[libc-commits] [libc] [llvm] [libc] Introduce a highly optimized `bcmp` implementation (PR #244952)
Chandler Carruth via libc-commits
libc-commits at lists.llvm.org
Sat Nov 21 14:33:44 PST 2026
https://github.com/chandlerc created https://github.com/llvm/llvm-project/pull/244952
The existing implementation of `bcmp` wasn't un-optimized, but it turns out there was a _lot_ of performance left on the table here, and a lot of important callers were suffering from this.
This PR reworks `bcmp`'s implementation from top to bottom and across all the architectures that I had a good idea of how to pursue performance. 32-bit architectures bias a bit towards small code size rather than runtime performance, while the most tuned runtime performance is in the 64-bit architecture implementations.
It optimizes (aggressively) for the distribution of string function operands we have seen in practice, re-using a bunch of benchmark machinery from the rest of llvm-libc for this. The notable bias is optimizing for very _short_ strings -- those end up dominating the distribution we observe in practice.
It covers Arm, x86, and RISC-V, both 64-bit and 32-bit, and the most widespread set of architecture variants for each. For 32-bit architectures and RISC-V, tested with QEMU and performance analysis with `llvm-mca` as I don't have enough representative hardware.
Key aspects of the optimized implementation strategy:
- Never read memory with size zero as some callers require that.
- Calling conventions don't propagate condition flags, so either conditionally return a constant (which can be predicted within `bcmp`), or return bits that the caller can compare with zero rather than doing the comparison within `bcmp`. The latter is especially important as it allows a single prediction in the caller and avoids materializing condition flags into the ABI.
- Avoid vector register -> GPR stalls. Some of the time this is by doing a comparison directly on vector registers when we can and want a predictable branch on that comparison. But the largest aspect is using GPRs aggressively so that we can compare and branch without the penalty.
- For small strings on architectures that support it and when it won't cross a page boundary, we use overread up to 8 bytes after necessary safety guards (no sanitizers, no page boundaries), and then mask off the bytes that were past the end.
- Beyond these small strings (or including them on architectures where we must), we use branched size classes and (potentially) overlapping reads and comparisons.
This adds some infrastructure we needed as well as benchmarks. We designing both a latency and throughput benchmark framework for the operation so we can measure both and ensure we don't compromise one for the sake of the other. A brief summary of the results (CPU ns, lower is better):
| Target / Benchmark | Base | New | Improvement |
| -------------------------------- | ----------: | ----------: | ------------: |
| Zen 5 BM_Bcmp Google A..W | 1.47-1.61 | 1.29-1.47 | 1.12x geomean |
| Zen 5 BM_BcmpLatency Google A..W | 5.06-8.76 | 4.70-7.10 | 1.19x geomean |
| Zen 5 RTput [1,3] / [4,8] | 5.14 / 5.84 | 1.10 / 1.14 | 4.67x / 5.12x |
| Zen 5 RTput [1,16] / [65,256] | 5.48 / 5.10 | 3.19 / 3.58 | 1.72x / 1.42x |
| Zen 5 Lat [1,3] / [4,8] | 6.26 / 6.98 | 2.74 / 2.74 | 2.28x / 2.55x |
| Zen 5 Lat [65,256] / [257,1024] | 9.10 / 11.5 | 5.46 / 8.80 | 1.67x / 1.31x |
| Zen 3 BM_Bcmp Google A..W | 2.76-3.72 | 2.61-3.53 | 1.10x geomean |
| Zen 3 BM_Bcmp 384..4096 | 37.2 | 28.5 | 1.31x |
| M1 BM_Bcmp 384..4096 | 51.4 | 41.4 | 1.24x |
| M1 BM_BcmpLatency Google A..W | 9.97-15.3 | 8.09-11.6 | 1.18x geomean |
| M1 RTput [1,3] / [4,8] | 5.62 / 4.00 | 1.67 / 1.67 | 3.37x / 2.40x |
| M1 RTput [9,16] / [1,16] | 2.30 / 6.52 | 1.34 / 4.17 | 1.72x / 1.56x |
| M1 Lat [17,32] / [33,64] | 10.4 / 11.5 | 6.67 / 5.52 | 1.56x / 2.08x |
| M1 Lat [65,256] / [257,1024] | 16.4 / 23.4 | 11.4 / 17.5 | 1.44x / 1.34x |
Assisted-by: Antigravity with Gemini and Fable
>From 8f99ef60430a1f37b6d8184a6c7a612a1429d967 Mon Sep 17 00:00:00 2001
From: Chandler Carruth <chandlerc at gmail.com>
Date: Mon, 16 Nov 2026 09:26:50 +0000
Subject: [PATCH] [libc] Introduce a highly optimized `bcmp` implementation
The existing implementation of `bcmp` wasn't un-optimized, but it turns
out there was a _lot_ of performance left on the table here, and a lot
of important callers were suffering from this.
This PR reworks `bcmp`'s implementation from top to bottom and across
all the architectures that I had a good idea of how to pursue
performance. 32-bit architectures bias a bit towards small code size
rather than runtime performance, while the most tuned runtime
performance is in the 64-bit architecture implementations.
It optimizes (aggressively) for the distribution of string function
operands we have seen in practice, re-using a bunch of benchmark
machinery from the rest of llvm-libc for this. The notable bias is
optimizing for very _short_ strings -- those end up dominating the
distribution we observe in practice.
It covers Arm, x86, and RISC-V, both 64-bit and 32-bit, and the most
widespread set of architecture variants for each. For 32-bit
architectures and RISC-V, tested with QEMU and performance analysis with
`llvm-mca` as I don't have enough representative hardware.
Key aspects of the optimized implementation strategy:
- Never read memory with size zero as some callers require that.
- Calling conventions don't propagate condition flags, so either
conditionally return a constant (which can be predicted within
`bcmp`), or return bits that the caller can compare with zero rather
than doing the comparison within `bcmp`. The latter is especially
important as it allows a single prediction in the caller and avoids
materializing condition flags into the ABI.
- Avoid vector register -> GPR stalls. Some of the time this is by doing
a comparison directly on vector registers when we can and want a
predictable branch on that comparison. But the largest aspect is using
GPRs aggressively so that we can compare and branch without the
penalty.
- For small strings on architectures that support it and when it won't
cross a page boundary, we use overread up to 8 bytes after necessary
safety guards (no sanitizers, no page boundaries), and then mask off
the bytes that were past the end.
- Beyond these small strings (or including them on architectures where
we must), we use branched size classes and (potentially) overlapping
reads and comparisons.
This adds some infrastructure we needed as well as benchmarks. We
designing both a latency and throughput benchmark framework for the
operation so we can measure both and ensure we don't compromise one for
the sake of the other. A brief summary of the results (CPU ns, lower is
better):
| Target / Benchmark | Base | New | Improvement |
| -------------------------------- | ----------: | ----------: | ------------: |
| Zen 5 BM_Bcmp Google A..W | 1.47-1.61 | 1.29-1.47 | 1.12x geomean |
| Zen 5 BM_BcmpLatency Google A..W | 5.06-8.76 | 4.70-7.10 | 1.19x geomean |
| Zen 5 RTput [1,3] / [4,8] | 5.14 / 5.84 | 1.10 / 1.14 | 4.67x / 5.12x |
| Zen 5 RTput [1,16] / [65,256] | 5.48 / 5.10 | 3.19 / 3.58 | 1.72x / 1.42x |
| Zen 5 Lat [1,3] / [4,8] | 6.26 / 6.98 | 2.74 / 2.74 | 2.28x / 2.55x |
| Zen 5 Lat [65,256] / [257,1024] | 9.10 / 11.5 | 5.46 / 8.80 | 1.67x / 1.31x |
| Zen 3 BM_Bcmp Google A..W | 2.76-3.72 | 2.61-3.53 | 1.10x geomean |
| Zen 3 BM_Bcmp 384..4096 | 37.2 | 28.5 | 1.31x |
| M1 BM_Bcmp 384..4096 | 51.4 | 41.4 | 1.24x |
| M1 BM_BcmpLatency Google A..W | 9.97-15.3 | 8.09-11.6 | 1.18x geomean |
| M1 RTput [1,3] / [4,8] | 5.62 / 4.00 | 1.67 / 1.67 | 3.37x / 2.40x |
| M1 RTput [9,16] / [1,16] | 2.30 / 6.52 | 1.34 / 4.17 | 1.72x / 1.56x |
| M1 Lat [17,32] / [33,64] | 10.4 / 11.5 | 6.67 / 5.52 | 1.56x / 2.08x |
| M1 Lat [65,256] / [257,1024] | 16.4 / 23.4 | 11.4 / 17.5 | 1.44x / 1.34x |
Assisted-by: Antigravity with Gemini
---
.../LibcMemoryGoogleBenchmarkMain.cpp | 160 ++++++++++++
libc/src/__support/macros/sanitizer.h | 14 ++
libc/src/string/memory_utils/CMakeLists.txt | 7 +
.../string/memory_utils/aarch64/inline_bcmp.h | 169 ++++++-------
.../memory_utils/generic/aligned_access.h | 114 ++++++---
.../string/memory_utils/generic/bcmp_utils.h | 236 ++++++++++++++++++
libc/src/string/memory_utils/inline_bcmp.h | 20 +-
.../string/memory_utils/riscv/inline_bcmp.h | 78 +++++-
.../string/memory_utils/x86_64/inline_bcmp.h | 234 ++++++++++++-----
libc/src/strings/bcmp.cpp | 11 +
libc/test/src/strings/bcmp_test.cpp | 135 +++++++++-
.../libc/src/string/memory_utils/BUILD.bazel | 3 +
.../libc/src/strings/BUILD.bazel | 2 +
.../libc/test/src/strings/BUILD.bazel | 8 +-
14 files changed, 993 insertions(+), 198 deletions(-)
create mode 100644 libc/src/string/memory_utils/generic/bcmp_utils.h
diff --git a/libc/benchmarks/LibcMemoryGoogleBenchmarkMain.cpp b/libc/benchmarks/LibcMemoryGoogleBenchmarkMain.cpp
index d5beb8aa55a370..4530fcae3ecc61 100644
--- a/libc/benchmarks/LibcMemoryGoogleBenchmarkMain.cpp
+++ b/libc/benchmarks/LibcMemoryGoogleBenchmarkMain.cpp
@@ -8,7 +8,10 @@
#endif
#include <chrono>
#include <cstdint>
+#include <cstdlib>
+#include <cstring>
#include <random>
+#include <string>
#include <vector>
using llvm::Align;
@@ -16,10 +19,12 @@ using llvm::ArrayRef;
#ifdef LIBC_BENCHMARKS_HAS_LLVM_SUPPORT
using llvm::Twine;
#endif
+using llvm::libc_benchmarks::AlignedBuffer;
using llvm::libc_benchmarks::BzeroConfiguration;
using llvm::libc_benchmarks::ComparisonSetup;
using llvm::libc_benchmarks::CopySetup;
using llvm::libc_benchmarks::MemcmpOrBcmpConfiguration;
+using llvm::libc_benchmarks::MemcmpOrBcmpFunction;
using llvm::libc_benchmarks::MemcpyConfiguration;
using llvm::libc_benchmarks::MemmoveConfiguration;
using llvm::libc_benchmarks::MemorySizeDistribution;
@@ -123,3 +128,158 @@ BENCHMARK_MEMORY_FUNCTION(BM_Memset, SetSetup, MemsetConfiguration,
extern llvm::ArrayRef<BzeroConfiguration> getBzeroConfigurations();
BENCHMARK_MEMORY_FUNCTION(BM_Bzero, SetSetup, BzeroConfiguration,
getBzeroConfigurations());
+
+namespace {
+
+// Large enough that modern branch predictors cannot memorize the repeating
+// sequence of comparison sizes within a batch.
+constexpr size_t kComparisonBatchSize = 64 * 1024;
+
+// Compact 8-byte descriptor (all benchmark sizes and buffer offsets fit in
+// uint16_t) for power-of-two indexing and smaller cache footprint.
+struct ComparisonPair {
+ uint16_t lhs_offset;
+ uint16_t rhs_offset;
+ uint16_t size;
+ uint16_t pad;
+};
+
+template <bool IsLatency>
+[[gnu::noinline]] void
+runComparisonLoop(benchmark::State &state, const char *lhs, const char *rhs,
+ ArrayRef<ComparisonPair> pairs, MemcmpOrBcmpFunction func) {
+ const size_t n = pairs.size();
+ while (state.KeepRunningBatch(n)) {
+ if constexpr (IsLatency) {
+ size_t count = 0;
+ for (size_t i = 0; i < n; ++count) {
+ const ComparisonPair &p = pairs[i];
+ // Feed the zero/non-zero result into the next index branchlessly so
+ // each comparison must resolve before the next begins, mirroring a
+ // caller's branch on the return value without letting comparisons
+ // overlap.
+ i += 1 + static_cast<size_t>(
+ func(lhs + p.lhs_offset, rhs + p.rhs_offset, p.size) != 0);
+ }
+ if (count != n)
+ std::abort();
+ } else {
+ for (const ComparisonPair &p : pairs) {
+ // Every pair is equal, so this branch is predicted and successive
+ // comparisons can overlap.
+ if (__builtin_expect(
+ func(lhs + p.lhs_offset, rhs + p.rhs_offset, p.size) != 0, 0))
+ std::abort();
+ }
+ }
+ }
+}
+
+template <bool IsLatency, typename SizeSampler>
+void runComparisonBatch(benchmark::State &state,
+ const MemcmpOrBcmpConfiguration &config,
+ size_t max_size, SizeSampler &&size_sampler,
+ const std::string &label) {
+ // Keep data buffers small enough to stay in L1 while varying alignment.
+ const size_t buffer_size = max_size + 256;
+ AlignedBuffer lhs_buffer(buffer_size);
+ AlignedBuffer rhs_buffer(buffer_size);
+ std::memset(lhs_buffer.begin(), 0x0F, buffer_size);
+ std::memset(rhs_buffer.begin(), 0x0F, buffer_size);
+
+ OffsetDistribution offset_sampler(buffer_size, max_size, kBenchmarkAlignment);
+ auto &gen = getGenerator();
+ std::vector<ComparisonPair> pairs;
+ pairs.reserve(kComparisonBatchSize);
+ uint64_t batch_bytes = 0;
+ for (size_t i = 0; i < kComparisonBatchSize; ++i) {
+ const size_t size = size_sampler(gen);
+ pairs.push_back({static_cast<uint16_t>(offset_sampler(gen)),
+ static_cast<uint16_t>(offset_sampler(gen)),
+ static_cast<uint16_t>(size), 0});
+ batch_bytes += size;
+ }
+
+ runComparisonLoop<IsLatency>(state, lhs_buffer.begin(), rhs_buffer.begin(),
+ pairs, config.function);
+
+ const uint64_t total_bytes =
+ (state.iterations() / kComparisonBatchSize) * batch_bytes;
+ state.SetBytesProcessed(total_bytes);
+ state.SetItemsProcessed(state.iterations());
+ state.SetLabel(label);
+ state.counters["bytes_per_cycle"] = benchmark::Counter(
+ total_bytes / benchmark::CPUInfo::Get().cycles_per_second,
+ benchmark::Counter::kIsRate);
+}
+
+void runDistributionLatencyBenchmark(
+ benchmark::State &state, ArrayRef<MemcmpOrBcmpConfiguration> configs) {
+ const MemorySizeDistribution dist =
+ ComparisonSetup::get_distributions()[state.range(0)];
+ const MemcmpOrBcmpConfiguration config = configs[state.range(1)];
+ std::discrete_distribution<size_t> size_sampler(dist.probabilities.begin(),
+ dist.probabilities.end());
+ runComparisonBatch<true>(state, config, dist.probabilities.size() - 1,
+ size_sampler,
+ config.name.str() + "," + dist.name.str());
+}
+
+template <bool IsLatency>
+void runSizeClassBenchmark(benchmark::State &state,
+ ArrayRef<MemcmpOrBcmpConfiguration> configs) {
+ const size_t min_size = static_cast<size_t>(state.range(0));
+ const size_t max_size = static_cast<size_t>(state.range(1));
+ const MemcmpOrBcmpConfiguration config = configs[state.range(2)];
+ std::uniform_int_distribution<size_t> size_sampler(min_size, max_size);
+ runComparisonBatch<IsLatency>(state, config, max_size, size_sampler,
+ config.name.str() + ",[" +
+ std::to_string(min_size) + "," +
+ std::to_string(max_size) + "]");
+}
+
+void applyComparisonDistributionArgs(benchmark::Benchmark *b,
+ int64_t conf_size) {
+ const int64_t dist_size =
+ static_cast<int64_t>(ComparisonSetup::get_distributions().size());
+ for (int64_t dist_index = 0; dist_index < dist_size; ++dist_index)
+ for (int64_t conf_index = 0; conf_index < conf_size; ++conf_index)
+ b->Args({dist_index, conf_index});
+}
+
+void applySizeClassArgs(benchmark::Benchmark *b, int64_t conf_size) {
+ static constexpr int64_t kSizeClasses[][2] = {
+ {1, 3}, {4, 8}, {9, 16}, {17, 32},
+ {33, 64}, {1, 16}, {65, 256}, {257, 1024},
+ };
+ b->ArgNames({"min", "max", "conf"});
+ for (const auto &range : kSizeClasses)
+ for (int64_t conf_index = 0; conf_index < conf_size; ++conf_index)
+ b->Args({range[0], range[1], conf_index});
+}
+
+} // namespace
+
+#define BENCHMARK_COMPARISON_SUITE(NAME, CONFIGS) \
+ void BM_##NAME##Latency(benchmark::State &S) { \
+ runDistributionLatencyBenchmark(S, CONFIGS); \
+ } \
+ BENCHMARK(BM_##NAME##Latency)->Apply([](benchmark::Benchmark *b) { \
+ applyComparisonDistributionArgs(b, (CONFIGS).size()); \
+ }); \
+ void BM_##NAME##SizeClassThroughput(benchmark::State &S) { \
+ runSizeClassBenchmark<false>(S, CONFIGS); \
+ } \
+ BENCHMARK(BM_##NAME##SizeClassThroughput) \
+ ->Apply([](benchmark::Benchmark *b) { \
+ applySizeClassArgs(b, (CONFIGS).size()); \
+ }); \
+ void BM_##NAME##SizeClassLatency(benchmark::State &S) { \
+ runSizeClassBenchmark<true>(S, CONFIGS); \
+ } \
+ BENCHMARK(BM_##NAME##SizeClassLatency)->Apply([](benchmark::Benchmark *b) { \
+ applySizeClassArgs(b, (CONFIGS).size()); \
+ })
+
+BENCHMARK_COMPARISON_SUITE(Memcmp, getMemcmpConfigurations());
+BENCHMARK_COMPARISON_SUITE(Bcmp, getBcmpConfigurations());
diff --git a/libc/src/__support/macros/sanitizer.h b/libc/src/__support/macros/sanitizer.h
index f92088ac245f3c..dd85d4ab395576 100644
--- a/libc/src/__support/macros/sanitizer.h
+++ b/libc/src/__support/macros/sanitizer.h
@@ -19,10 +19,24 @@
#define LIBC_HAS_ADDRESS_SANITIZER
#endif
+#if LIBC_HAS_FEATURE(hwaddress_sanitizer) || defined(__SANITIZE_HWADDRESS__)
+#define LIBC_HAS_HWADDRESS_SANITIZER
+#endif
+
#if LIBC_HAS_FEATURE(memory_sanitizer)
#define LIBC_HAS_MEMORY_SANITIZER
#endif
+#if LIBC_HAS_FEATURE(thread_sanitizer) || defined(__SANITIZE_THREAD__)
+#define LIBC_HAS_THREAD_SANITIZER
+#endif
+
+#if defined(LIBC_HAS_ADDRESS_SANITIZER) || \
+ defined(LIBC_HAS_HWADDRESS_SANITIZER) || \
+ defined(LIBC_HAS_MEMORY_SANITIZER) || defined(LIBC_HAS_THREAD_SANITIZER)
+#define LIBC_HAS_MEMORY_ACCESS_SANITIZER
+#endif
+
#ifdef LIBC_HAS_MEMORY_SANITIZER
// Only perform MSAN unpoison in non-constexpr context.
#include <sanitizer/msan_interface.h>
diff --git a/libc/src/string/memory_utils/CMakeLists.txt b/libc/src/string/memory_utils/CMakeLists.txt
index 510546d79988ae..94b44f4a953f89 100644
--- a/libc/src/string/memory_utils/CMakeLists.txt
+++ b/libc/src/string/memory_utils/CMakeLists.txt
@@ -11,6 +11,7 @@ add_header_library(
arm/inline_memcpy.h
arm/inline_memset.h
generic/aligned_access.h
+ generic/bcmp_utils.h
generic/byte_per_byte.h
inline_bcmp.h
inline_bzero.h
@@ -36,14 +37,20 @@ add_header_library(
DEPENDS
libc.hdr.stdint_proxy
libc.src.__support.common
+ libc.src.__support.CPP.array
libc.src.__support.CPP.bit
libc.src.__support.CPP.cstddef
libc.src.__support.CPP.type_traits
+ libc.src.__support.macros.attributes
libc.src.__support.macros.config
libc.src.__support.macros.is_defined
libc.src.__support.macros.optimization
libc.src.__support.macros.properties.architectures
libc.src.__support.macros.properties.compiler
+ libc.src.__support.macros.properties.cpu_features
+ libc.src.__support.macros.properties.os
+ libc.src.__support.macros.properties.types
+ libc.src.__support.macros.sanitizer
)
add_header_library(
diff --git a/libc/src/string/memory_utils/aarch64/inline_bcmp.h b/libc/src/string/memory_utils/aarch64/inline_bcmp.h
index 9c6821037ff1a7..cfb9d9ea2ec4c8 100644
--- a/libc/src/string/memory_utils/aarch64/inline_bcmp.h
+++ b/libc/src/string/memory_utils/aarch64/inline_bcmp.h
@@ -5,111 +5,106 @@
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
-#ifndef LIBC_SRC_STRING_MEMORY_UTILS_AARCH64_INLINE_BCMP_H
-#define LIBC_SRC_STRING_MEMORY_UTILS_AARCH64_INLINE_BCMP_H
+#ifndef LLVM_LIBC_SRC_STRING_MEMORY_UTILS_AARCH64_INLINE_BCMP_H
+#define LLVM_LIBC_SRC_STRING_MEMORY_UTILS_AARCH64_INLINE_BCMP_H
+#include "hdr/stdint_proxy.h"
#include "src/__support/macros/attributes.h" // LIBC_INLINE
#include "src/__support/macros/config.h" // LIBC_NAMESPACE_DECL
#include "src/__support/macros/optimization.h" // LIBC_UNLIKELY
-#include "src/string/memory_utils/op_aarch64.h"
-#include "src/string/memory_utils/op_generic.h"
-#include "src/string/memory_utils/utils.h" // Ptr, CPtr
+#include "src/string/memory_utils/generic/bcmp_utils.h"
+#include "src/string/memory_utils/utils.h" // CPtr, BcmpReturnType, load_unaligned
#include <stddef.h> // size_t
+#ifdef __ARM_NEON
+#include "src/__support/macros/properties/types.h" // LIBC_TYPES_HAS_INT128
+#include <arm_neon.h>
+#endif
+
namespace LIBC_NAMESPACE_DECL {
-[[maybe_unused]] LIBC_INLINE BcmpReturnType
-inline_bcmp_aarch64_no_fp(CPtr p1, CPtr p2, size_t count) {
- if (LIBC_LIKELY(count < 16)) {
- switch (count) {
- case 0:
- return BcmpReturnType::zero();
- case 1:
- return generic::Bcmp<uint8_t>::block(p1, p2);
- case 2:
- return generic::Bcmp<uint16_t>::block(p1, p2);
- case 3:
- return generic::Bcmp<uint16_t>::head_tail(p1, p2, count);
- case 4:
- return generic::Bcmp<uint32_t>::block(p1, p2);
- case 5:
- case 6:
- case 7:
- return generic::Bcmp<uint32_t>::head_tail(p1, p2, count);
- case 8:
- return generic::Bcmp<uint64_t>::block(p1, p2);
- case 9:
- case 10:
- case 11:
- case 12:
- case 13:
- case 14:
- case 15:
- return generic::Bcmp<uint64_t>::head_tail(p1, p2, count);
- }
- }
+#ifdef __ARM_NEON
+namespace internal {
- return generic::Bcmp<uint64_t>::loop_and_tail_align_above(256, p1, p2, count);
+// Comparing `__uint128_t` halves with `|` keeps 17..32 in GPRs (`ldp` + `cmp` +
+// `ccmp` + `cset`) without Neon-to-GPR transfer latency or branch mispredicts;
+// LLVM would otherwise vectorize 64-bit comparisons into Neon.
+LIBC_INLINE BcmpReturnType bcmp_aarch64_17_to_32(CPtr p1, CPtr p2,
+ size_t count) {
+#ifdef LIBC_TYPES_HAS_INT128
+ return static_cast<uint32_t>(
+ (bcmp_xor<__uint128_t>(p1, p2) |
+ bcmp_xor<__uint128_t>(p1 + count - 16, p2 + count - 16)) != 0);
+#else
+ return bcmp_17_to_32_64bit(p1, p2, count);
+#endif
}
-#ifdef __ARM_NEON
-[[maybe_unused]] LIBC_INLINE BcmpReturnType
-inline_bcmp_aarch64_with_fp(CPtr p1, CPtr p2, size_t count) {
- if (LIBC_LIKELY(count <= 32)) {
- if (LIBC_UNLIKELY(count >= 16)) {
- return aarch64::Bcmp<16>::head_tail(p1, p2, count);
- }
- switch (count) {
- case 0:
- return BcmpReturnType::zero();
- case 1:
- return generic::Bcmp<uint8_t>::block(p1, p2);
- case 2:
- return generic::Bcmp<uint16_t>::block(p1, p2);
- case 3:
- return generic::Bcmp<uint16_t>::head_tail(p1, p2, count);
- case 4:
- return generic::Bcmp<uint32_t>::block(p1, p2);
- case 5:
- case 6:
- case 7:
- return generic::Bcmp<uint32_t>::head_tail(p1, p2, count);
- case 8:
- return generic::Bcmp<uint64_t>::block(p1, p2);
- case 9:
- case 10:
- case 11:
- case 12:
- case 13:
- case 14:
- case 15:
- return generic::Bcmp<uint64_t>::head_tail(p1, p2, count);
- }
- }
+LIBC_INLINE uint8x16_t aarch64_xor16(CPtr p1, CPtr p2) {
+ return veorq_u8(load_unaligned<uint8x16_t>(p1),
+ load_unaligned<uint8x16_t>(p2));
+}
- if (count <= 64)
- return aarch64::Bcmp<32>::head_tail(p1, p2, count);
+LIBC_INLINE uint8x16_t aarch64_xor32(CPtr p1, CPtr p2) {
+ return vorrq_u8(aarch64_xor16(p1, p2), aarch64_xor16(p1 + 16, p2 + 16));
+}
- // Aligned loop if > 256, otherwise normal loop
- if (LIBC_UNLIKELY(count > 256)) {
- if (auto value = aarch64::Bcmp<32>::block(p1, p2))
- return value;
- align_to_next_boundary<16, Arg::P1>(p1, p2, count);
- }
- return aarch64::Bcmp<32>::loop_and_tail(p1, p2, count);
+LIBC_INLINE bool aarch64_neon_nonzero(uint8x16_t diff) {
+ return vmaxvq_u32(vreinterpretq_u32_u8(diff)) != 0;
+}
+
+LIBC_INLINE bool aarch64_neon_64_ne(CPtr p1, CPtr p2) {
+ return aarch64_neon_nonzero(
+ vorrq_u8(aarch64_xor32(p1, p2), aarch64_xor32(p1 + 32, p2 + 32)));
}
-#endif
-LIBC_FLATTEN LIBC_INLINE BcmpReturnType
-inline_bcmp_aarch64_dispatch(CPtr p1, CPtr p2, size_t count) {
-#if defined(__ARM_NEON)
- return inline_bcmp_aarch64_with_fp(p1, p2, count);
+} // namespace internal
+#endif // __ARM_NEON
+
+// Sizes > 32 pair Neon early-exit checks with a GPR `[0, 4)` final return on
+// `33..128` (hiding Neon-to-GPR latency on equal inputs), while `> 128` checks
+// `[0, 4)` before looping so early mismatches exit immediately.
+[[maybe_unused]] LIBC_INLINE BcmpReturnType inline_bcmp_aarch64(CPtr p1,
+ CPtr p2,
+ size_t count) {
+#ifdef __ARM_NEON
+ if (count <= 8)
+ return internal::bcmp_0_to_8(p1, p2, count);
+ if (count <= 16)
+ return internal::bcmp_9_to_16(p1, p2, count);
+ if (count <= 32)
+ return internal::bcmp_aarch64_17_to_32(p1, p2, count);
+ const uint8x16_t head = vorrq_u8(internal::aarch64_xor16(p1 + 4, p2 + 4),
+ internal::aarch64_xor16(p1 + 16, p2 + 16));
+ if (count <= 64) {
+ if (LIBC_UNLIKELY(internal::aarch64_neon_nonzero(vorrq_u8(
+ head, internal::aarch64_xor32(p1 + count - 32, p2 + count - 32)))))
+ return BcmpReturnType::nonzero();
+ return internal::bcmp_xor<uint32_t>(p1, p2);
+ }
+ if (LIBC_UNLIKELY(internal::aarch64_neon_nonzero(
+ vorrq_u8(head, internal::aarch64_xor32(p1 + 32, p2 + 32)))))
+ return BcmpReturnType::nonzero();
+ if (count > 128) {
+ if (LIBC_UNLIKELY(internal::bcmp_xor<uint32_t>(p1, p2) != 0))
+ return BcmpReturnType::nonzero();
+ const size_t last = count - 64;
+ for (size_t i = 64 - static_cast<size_t>(distance_to_align_down<16>(p1));
+ i < last; i += 64) {
+ if (LIBC_UNLIKELY(internal::aarch64_neon_64_ne(p1 + i, p2 + i)))
+ return BcmpReturnType::nonzero();
+ }
+ }
+ if (LIBC_UNLIKELY(
+ internal::aarch64_neon_64_ne(p1 + count - 64, p2 + count - 64)))
+ return BcmpReturnType::nonzero();
+ return internal::bcmp_xor<uint32_t>(p1, p2);
#else
- return inline_bcmp_aarch64_no_fp(p1, p2, count);
-#endif
+ return inline_bcmp_unaligned_64bit(p1, p2, count);
+#endif // __ARM_NEON
}
} // namespace LIBC_NAMESPACE_DECL
-#endif // LIBC_SRC_STRING_MEMORY_UTILS_AARCH64_INLINE_BCMP_H
+#endif // LLVM_LIBC_SRC_STRING_MEMORY_UTILS_AARCH64_INLINE_BCMP_H
diff --git a/libc/src/string/memory_utils/generic/aligned_access.h b/libc/src/string/memory_utils/generic/aligned_access.h
index 49a318d9c8a954..672c2195dd3a2a 100644
--- a/libc/src/string/memory_utils/generic/aligned_access.h
+++ b/libc/src/string/memory_utils/generic/aligned_access.h
@@ -13,7 +13,10 @@
#ifndef LLVM_LIBC_SRC_STRING_MEMORY_UTILS_GENERIC_ALIGNED_ACCESS_H
#define LLVM_LIBC_SRC_STRING_MEMORY_UTILS_GENERIC_ALIGNED_ACCESS_H
-#include "src/__support/macros/attributes.h" // LIBC_INLINE
+#include "src/__support/endian_internal.h"
+#include "src/__support/macros/attributes.h" // LIBC_INLINE
+#include "src/__support/macros/optimization.h" // LIBC_LOOP_NOUNROLL
+#include "src/__support/macros/sanitizer.h" // LIBC_HAS_MEMORY_ACCESS_SANITIZER
#include "src/string/memory_utils/generic/byte_per_byte.h"
#include "src/string/memory_utils/op_generic.h" // generic::splat
#include "src/string/memory_utils/utils.h" // Ptr, CPtr
@@ -121,42 +124,91 @@ inline_memset_aligned_access_64bit(Ptr dst, uint8_t value, size_t count) {
// bcmp
///////////////////////////////////////////////////////////////////////////////
+template <typename Word>
+LIBC_INLINE BcmpReturnType inline_bcmp_aligned_access(CPtr p1, CPtr p2,
+ size_t count) {
+ constexpr size_t ALIGN = sizeof(Word);
+ if (count == 0)
+ return BcmpReturnType::zero();
+ if (count <= 3)
+ return cpp::to_integer<uint32_t>((p1[0] ^ p2[0]) |
+ (p1[count - 1] ^ p2[count - 1]) |
+ (p1[count >> 1] ^ p2[count >> 1]));
+ if (count >= ALIGN) {
+ if (const size_t head =
+ static_cast<size_t>(distance_to_align_up<ALIGN>(p1))) {
+ if (auto value = inline_bcmp_byte_per_byte(p1, p2, head))
+ return value;
+ p1 += head;
+ p2 += head;
+ count -= head;
+ }
+ if (count >= ALIGN) {
+ const size_t p2_align =
+ static_cast<size_t>(distance_to_align_down<ALIGN>(p2));
+ auto load_word = [](CPtr p) -> Word {
+ return load_unaligned<Word>(assume_aligned<ALIGN>(p));
+ };
+ if (p2_align == 0) {
+ if constexpr (ALIGN == 8) {
+ LIBC_LOOP_NOUNROLL
+ for (; count >= 32; p1 += 32, p2 += 32, count -= 32) {
+ if ((load_word(p1) ^ load_word(p2)) |
+ (load_word(p1 + 8) ^ load_word(p2 + 8)) |
+ (load_word(p1 + 16) ^ load_word(p2 + 16)) |
+ (load_word(p1 + 24) ^ load_word(p2 + 24)))
+ return BcmpReturnType::nonzero();
+ }
+ }
+ LIBC_LOOP_NOUNROLL
+ for (; count >= ALIGN; p1 += ALIGN, p2 += ALIGN, count -= ALIGN) {
+ if (load_word(p1) != load_word(p2))
+ return BcmpReturnType::nonzero();
+ }
+ } else {
+#ifndef LIBC_HAS_MEMORY_ACCESS_SANITIZER
+ // Shift-and-merge from naturally aligned `Word` loads around `p2`; each
+ // loaded granule contains at least one byte of `[p2, p2 + count)`.
+ CPtr p2_base = p2 - p2_align;
+ const unsigned sh_lo = static_cast<unsigned>(p2_align * 8);
+ const unsigned sh_hi = static_cast<unsigned>((ALIGN * 8) - sh_lo);
+ Word prev = load_word(p2_base);
+ LIBC_LOOP_NOUNROLL
+ for (; count >= ALIGN; p1 += ALIGN, p2_base += ALIGN, count -= ALIGN) {
+ const Word next = load_word(p2_base + ALIGN);
+ const Word w2 = Endian::IS_LITTLE ? (prev >> sh_lo) | (next << sh_hi)
+ : (prev << sh_lo) | (next >> sh_hi);
+ if (load_word(p1) != w2)
+ return BcmpReturnType::nonzero();
+ prev = next;
+ }
+ p2 = p2_base + p2_align;
+#else
+ LIBC_LOOP_NOUNROLL
+ for (; count >= ALIGN; p1 += ALIGN, p2 += ALIGN, count -= ALIGN) {
+ Word b;
+ if constexpr (ALIGN == 8)
+ b = load64_aligned(p2, 0, p2_align);
+ else
+ b = load32_aligned(p2, 0, p2_align);
+ if (load_word(p1) != b)
+ return BcmpReturnType::nonzero();
+ }
+#endif
+ }
+ }
+ }
+ return inline_bcmp_byte_per_byte(p1, p2, count);
+}
+
[[maybe_unused]] LIBC_INLINE BcmpReturnType
inline_bcmp_aligned_access_32bit(CPtr p1, CPtr p2, size_t count) {
- constexpr size_t kAlign = sizeof(uint32_t);
- if (count <= 2 * kAlign)
- return inline_bcmp_byte_per_byte(p1, p2, count);
- size_t bytes_to_p1_align = distance_to_align_up<kAlign>(p1);
- if (auto value = inline_bcmp_byte_per_byte(p1, p2, bytes_to_p1_align))
- return value;
- size_t offset = bytes_to_p1_align;
- size_t p2_alignment = distance_to_align_down<kAlign>(p2 + offset);
- for (; offset < count - kAlign; offset += kAlign) {
- uint32_t a = load32_aligned<uint32_t>(p1, offset);
- uint32_t b = load32_aligned(p2, offset, p2_alignment);
- if (a != b)
- return BcmpReturnType::nonzero();
- }
- return inline_bcmp_byte_per_byte(p1, p2, count, offset);
+ return inline_bcmp_aligned_access<uint32_t>(p1, p2, count);
}
[[maybe_unused]] LIBC_INLINE BcmpReturnType
inline_bcmp_aligned_access_64bit(CPtr p1, CPtr p2, size_t count) {
- constexpr size_t kAlign = sizeof(uint64_t);
- if (count <= 2 * kAlign)
- return inline_bcmp_byte_per_byte(p1, p2, count);
- size_t bytes_to_p1_align = distance_to_align_up<kAlign>(p1);
- if (auto value = inline_bcmp_byte_per_byte(p1, p2, bytes_to_p1_align))
- return value;
- size_t offset = bytes_to_p1_align;
- size_t p2_alignment = distance_to_align_down<kAlign>(p2 + offset);
- for (; offset < count - kAlign; offset += kAlign) {
- uint64_t a = load64_aligned<uint64_t>(p1, offset);
- uint64_t b = load64_aligned(p2, offset, p2_alignment);
- if (a != b)
- return BcmpReturnType::nonzero();
- }
- return inline_bcmp_byte_per_byte(p1, p2, count, offset);
+ return inline_bcmp_aligned_access<uint64_t>(p1, p2, count);
}
///////////////////////////////////////////////////////////////////////////////
diff --git a/libc/src/string/memory_utils/generic/bcmp_utils.h b/libc/src/string/memory_utils/generic/bcmp_utils.h
new file mode 100644
index 00000000000000..88c0afa82a6919
--- /dev/null
+++ b/libc/src/string/memory_utils/generic/bcmp_utils.h
@@ -0,0 +1,236 @@
+//===-- Shared bcmp building blocks -----------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SRC_STRING_MEMORY_UTILS_GENERIC_BCMP_UTILS_H
+#define LLVM_LIBC_SRC_STRING_MEMORY_UTILS_GENERIC_BCMP_UTILS_H
+
+#include "hdr/stdint_proxy.h"
+#include "src/__support/CPP/cstddef.h"
+#include "src/__support/endian_internal.h"
+#include "src/__support/macros/attributes.h" // LIBC_INLINE, LIBC_INLINE_VAR
+#include "src/__support/macros/config.h" // LIBC_NAMESPACE_DECL
+#include "src/__support/macros/optimization.h" // LIBC_LIKELY, LIBC_UNLIKELY, LIBC_LOOP_NOUNROLL
+#include "src/__support/macros/properties/architectures.h"
+#include "src/__support/macros/properties/os.h"
+#include "src/__support/macros/properties/types.h" // LIBC_TYPES_HAS_INT64
+#include "src/__support/macros/sanitizer.h" // LIBC_HAS_MEMORY_ACCESS_SANITIZER
+#include "src/string/memory_utils/utils.h" // CPtr, BcmpReturnType, load_unaligned
+
+#include <stddef.h> // size_t
+
+// Whether short comparisons (1..8 bytes) may read 8 bytes forward within a
+// 4 KiB page and discard trailing bytes (little-endian only). Disabled under
+// sanitizers, Arm MTE (16-byte granules), and baremetal/unknown OSes where
+// MPU/PMP regions may be smaller than 4 KiB.
+#if !defined(LIBC_HAS_MEMORY_ACCESS_SANITIZER) && \
+ !defined(__ARM_FEATURE_MEMORY_TAGGING) && \
+ !LIBC_HAS_FEATURE(memtag_stack) && \
+ !defined(LIBC_TARGET_OS_IS_BAREMETAL) && \
+ (defined(LIBC_TARGET_OS_IS_LINUX) || defined(LIBC_TARGET_OS_IS_ANDROID) || \
+ defined(LIBC_TARGET_OS_IS_FREEBSD) || \
+ defined(LIBC_TARGET_OS_IS_WINDOWS) || \
+ defined(LIBC_TARGET_OS_IS_FUCHSIA) || defined(__APPLE__)) && \
+ defined(LIBC_TYPES_HAS_INT64) && defined(__BYTE_ORDER__) && \
+ (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) && \
+ (defined(LIBC_TARGET_ARCH_IS_X86_64) || \
+ (defined(LIBC_TARGET_ARCH_IS_AARCH64) && \
+ (defined(__ARM_FEATURE_UNALIGNED) || defined(_M_ARM64))) || \
+ (defined(LIBC_TARGET_ARCH_IS_RISCV64) && \
+ defined(__riscv_misaligned_fast)))
+#define LIBC_BCMP_USE_OVERREAD 1
+#else
+#define LIBC_BCMP_USE_OVERREAD 0
+#endif
+
+#if LIBC_BCMP_USE_OVERREAD && defined(__BMI2__) && \
+ defined(LIBC_TARGET_ARCH_IS_X86_64)
+#include <immintrin.h>
+#endif
+
+namespace LIBC_NAMESPACE_DECL {
+namespace internal {
+
+template <typename T> LIBC_INLINE T bcmp_xor(CPtr p1, CPtr p2) {
+ return load_unaligned<T>(p1) ^ load_unaligned<T>(p2);
+}
+
+// Compares count bytes for count in 1..3 without reading outside [0, count).
+LIBC_INLINE BcmpReturnType bcmp_exact_1_to_3(CPtr p1, CPtr p2, size_t count) {
+ return cpp::to_integer<uint32_t>((p1[0] ^ p2[0]) |
+ (p1[count - 1] ^ p2[count - 1]) |
+ (p1[count >> 1] ^ p2[count >> 1]));
+}
+
+#if LIBC_BCMP_USE_OVERREAD
+
+// Rejects page offsets 4088..4095 so an 8-byte forward read stays within its
+// 4 KiB page (never rejects offset 0).
+LIBC_INLINE bool read8_stays_in_page(CPtr ptr) {
+ return ((reinterpret_cast<uintptr_t>(ptr) + 8) & 0xff8U) != 0;
+}
+
+// Single-cache-line little-endian masks for 1..8 bytes.
+#if defined(LIBC_TARGET_ARCH_IS_X86_64) && !defined(__BMI2__)
+// Indexed by `count - 1`: x86-64 folds `-8` into `testq -8(base, count, 8)`.
+alignas(64) LIBC_INLINE_VAR constexpr uint64_t SIZE_MASKS_8[8] = {
+ 0x00000000000000ffULL, 0x000000000000ffffULL, 0x0000000000ffffffULL,
+ 0x00000000ffffffffULL, 0x000000ffffffffffULL, 0x0000ffffffffffffULL,
+ 0x00ffffffffffffffULL, 0xffffffffffffffffULL,
+};
+#elif defined(LIBC_TARGET_ARCH_IS_AARCH64)
+// Indexed by `count & 7` (index 0 holds the 8-byte mask since `count == 0`
+// exits earlier): lets AArch64 compute the index in parallel with address
+// materialization and load via `[base, idx, lsl #3]`.
+alignas(64) LIBC_INLINE_VAR constexpr uint64_t SIZE_MASKS_8[8] = {
+ 0xffffffffffffffffULL, 0x00000000000000ffULL, 0x000000000000ffffULL,
+ 0x0000000000ffffffULL, 0x00000000ffffffffULL, 0x000000ffffffffffULL,
+ 0x0000ffffffffffffULL, 0x00ffffffffffffffULL,
+};
+#endif
+
+// Compares count in 1..8 without size branches by XORing 8-byte forward loads
+// and discarding bytes past count.
+LIBC_INLINE BcmpReturnType bcmp_overread_1_to_8(CPtr p1, CPtr p2,
+ size_t count) {
+ const uint64_t ne_bits = bcmp_xor<uint64_t>(p1, p2);
+#if defined(__BMI2__) && defined(LIBC_TARGET_ARCH_IS_X86_64)
+ return static_cast<uint32_t>(
+ _bzhi_u64(ne_bits, static_cast<unsigned int>(8 * count)) != 0);
+#elif defined(LIBC_TARGET_ARCH_IS_X86_64)
+ return static_cast<uint32_t>((ne_bits & SIZE_MASKS_8[count - 1]) != 0);
+#elif defined(LIBC_TARGET_ARCH_IS_AARCH64)
+ return static_cast<uint32_t>((ne_bits & SIZE_MASKS_8[count & 7]) != 0);
+#else
+ // On RISC-V (no scaled-register load), shifting avoids table materialization.
+ return static_cast<uint32_t>((ne_bits << ((8 - count) * 8)) != 0);
+#endif
+}
+
+#endif // LIBC_BCMP_USE_OVERREAD
+
+// Compares count bytes for count in 0..8.
+LIBC_INLINE BcmpReturnType bcmp_0_to_8(CPtr p1, CPtr p2, size_t count) {
+ if (count == 0)
+ return BcmpReturnType::zero();
+#if LIBC_BCMP_USE_OVERREAD
+ if (LIBC_LIKELY(read8_stays_in_page(p1) && read8_stays_in_page(p2)))
+ return bcmp_overread_1_to_8(p1, p2, count);
+#endif
+ if (count >= 4) {
+ const size_t tail = count - sizeof(uint32_t);
+ return bcmp_xor<uint32_t>(p1, p2) |
+ bcmp_xor<uint32_t>(p1 + tail, p2 + tail);
+ }
+ return bcmp_exact_1_to_3(p1, p2, count);
+}
+
+// Compares count in 9..16 using non-adjacent 32-bit loads so LLVM keeps all
+// loads in GPRs (avoiding NEON SLP `vmov` and unaligned `ldrd`/`ldm` on Arm).
+LIBC_INLINE BcmpReturnType bcmp_9_to_16_32bit(CPtr p1, CPtr p2, size_t count) {
+ if (LIBC_UNLIKELY((bcmp_xor<uint32_t>(p1 + 4, p2 + 4) |
+ bcmp_xor<uint32_t>(p1 + count - 8, p2 + count - 8)) != 0))
+ return BcmpReturnType::nonzero();
+ return bcmp_xor<uint32_t>(p1, p2) |
+ bcmp_xor<uint32_t>(p1 + count - 4, p2 + count - 4);
+}
+
+#ifdef LIBC_TYPES_HAS_INT64
+
+// Compares count in 9..16: predicted early exit on `[4, count)` and direct
+// 32-bit XOR return on `[0, 4)` (no `setne`/`cset` or `count`-indexed AGU).
+LIBC_INLINE BcmpReturnType bcmp_9_to_16(CPtr p1, CPtr p2, size_t count) {
+ if (LIBC_UNLIKELY((bcmp_xor<uint32_t>(p1 + 4, p2 + 4) |
+ bcmp_xor<uint64_t>(p1 + count - 8, p2 + count - 8)) != 0))
+ return BcmpReturnType::nonzero();
+ return bcmp_xor<uint32_t>(p1, p2);
+}
+
+// Branchless 17..32 comparison using 64-bit loads. Interleaving head and tail
+// pairs prevents LLVM from SLP-vectorizing adjacent loads on RVV targets.
+LIBC_INLINE BcmpReturnType bcmp_17_to_32_64bit(CPtr p1, CPtr p2, size_t count) {
+ const uint64_t d0 = bcmp_xor<uint64_t>(p1, p2) |
+ bcmp_xor<uint64_t>(p1 + count - 16, p2 + count - 16);
+ const uint64_t d1 = bcmp_xor<uint64_t>(p1 + 8, p2 + 8) |
+ bcmp_xor<uint64_t>(p1 + count - 8, p2 + count - 8);
+ return static_cast<uint32_t>((d0 | d1) != 0);
+}
+
+LIBC_INLINE bool bcmp_32_64bit_ne(CPtr p1, CPtr p2) {
+ return (bcmp_xor<uint64_t>(p1, p2) | bcmp_xor<uint64_t>(p1 + 8, p2 + 8) |
+ bcmp_xor<uint64_t>(p1 + 16, p2 + 16) |
+ bcmp_xor<uint64_t>(p1 + 24, p2 + 24)) != 0;
+}
+
+#endif // LIBC_TYPES_HAS_INT64
+
+} // namespace internal
+
+// Generic unaligned 32-bit scalar `bcmp` (32-bit Arm with unaligned support,
+// x86-32 without SSE2, RV32 with `__riscv_misaligned_fast`). Stride-8 pairing
+// keeps all loads in GPRs (no NEON SLP `vmov` or unaligned `ldrd`/`ldm`).
+[[maybe_unused]] LIBC_INLINE BcmpReturnType
+inline_bcmp_unaligned_32bit(CPtr p1, CPtr p2, size_t count) {
+ if (count <= 8)
+ return internal::bcmp_0_to_8(p1, p2, count);
+ if (count <= 16)
+ return internal::bcmp_9_to_16_32bit(p1, p2, count);
+ LIBC_LOOP_NOUNROLL
+ for (size_t i = 0; i < count - 16; i += 16) {
+ if (LIBC_UNLIKELY((internal::bcmp_xor<uint32_t>(p1 + i, p2 + i) |
+ internal::bcmp_xor<uint32_t>(p1 + i + 8, p2 + i + 8)) !=
+ 0))
+ return BcmpReturnType::nonzero();
+ if (LIBC_UNLIKELY(
+ (internal::bcmp_xor<uint32_t>(p1 + i + 4, p2 + i + 4) |
+ internal::bcmp_xor<uint32_t>(p1 + i + 12, p2 + i + 12)) != 0))
+ return BcmpReturnType::nonzero();
+ }
+ const CPtr tail1 = p1 + count - 16;
+ const CPtr tail2 = p2 + count - 16;
+ if (LIBC_UNLIKELY((internal::bcmp_xor<uint32_t>(tail1 + 4, tail2 + 4) |
+ internal::bcmp_xor<uint32_t>(tail1 + 12, tail2 + 12)) !=
+ 0))
+ return BcmpReturnType::nonzero();
+ return internal::bcmp_xor<uint32_t>(tail1, tail2) |
+ internal::bcmp_xor<uint32_t>(tail1 + 8, tail2 + 8);
+}
+
+#ifdef LIBC_TYPES_HAS_INT64
+
+// Generic unaligned 64-bit scalar `bcmp` (x86-64 without SSE2, AArch64
+// `-mgeneral-regs-only`, RV64 with `__riscv_misaligned_fast`).
+[[maybe_unused]] LIBC_INLINE BcmpReturnType
+inline_bcmp_unaligned_64bit(CPtr p1, CPtr p2, size_t count) {
+ if (count <= 8)
+ return internal::bcmp_0_to_8(p1, p2, count);
+ if (count <= 16)
+ return internal::bcmp_9_to_16(p1, p2, count);
+ if (count <= 32)
+ return internal::bcmp_17_to_32_64bit(p1, p2, count);
+ if (LIBC_UNLIKELY(internal::bcmp_32_64bit_ne(p1, p2)))
+ return BcmpReturnType::nonzero();
+ if (count > 64) {
+ const size_t last = count - 32;
+ LIBC_LOOP_NOUNROLL
+ for (size_t i = 32 - static_cast<size_t>(distance_to_align_down<8>(p1));
+ i < last; i += 32) {
+ if (LIBC_UNLIKELY(internal::bcmp_32_64bit_ne(p1 + i, p2 + i)))
+ return BcmpReturnType::nonzero();
+ }
+ }
+ return static_cast<uint32_t>(
+ internal::bcmp_32_64bit_ne(p1 + count - 32, p2 + count - 32));
+}
+
+#endif // LIBC_TYPES_HAS_INT64
+
+} // namespace LIBC_NAMESPACE_DECL
+
+#undef LIBC_BCMP_USE_OVERREAD
+
+#endif // LLVM_LIBC_SRC_STRING_MEMORY_UTILS_GENERIC_BCMP_UTILS_H
diff --git a/libc/src/string/memory_utils/inline_bcmp.h b/libc/src/string/memory_utils/inline_bcmp.h
index b241e999a6aae1..e484eaf3d76c46 100644
--- a/libc/src/string/memory_utils/inline_bcmp.h
+++ b/libc/src/string/memory_utils/inline_bcmp.h
@@ -9,10 +9,10 @@
#ifndef LLVM_LIBC_SRC_STRING_MEMORY_UTILS_INLINE_BCMP_H
#define LLVM_LIBC_SRC_STRING_MEMORY_UTILS_INLINE_BCMP_H
-#include "src/__support/common.h"
-#include "src/__support/macros/attributes.h" // LIBC_INLINE
+#include "src/__support/macros/attributes.h" // LIBC_ALWAYS_INLINE, LIBC_FLATTEN
#include "src/__support/macros/config.h" // LIBC_NAMESPACE_DECL
#include "src/__support/macros/properties/architectures.h" // LIBC_TARGET_ARCH_IS_
+#include "src/string/memory_utils/utils.h" // CPtr
#include <stddef.h> // size_t
@@ -24,7 +24,15 @@
#define LIBC_SRC_STRING_MEMORY_UTILS_BCMP inline_bcmp_x86
#elif defined(LIBC_TARGET_ARCH_IS_AARCH64)
#include "src/string/memory_utils/aarch64/inline_bcmp.h"
-#define LIBC_SRC_STRING_MEMORY_UTILS_BCMP inline_bcmp_aarch64_dispatch
+#define LIBC_SRC_STRING_MEMORY_UTILS_BCMP inline_bcmp_aarch64
+#elif defined(LIBC_TARGET_ARCH_IS_ARM)
+#if defined(__ARM_FEATURE_UNALIGNED)
+#include "src/string/memory_utils/generic/bcmp_utils.h"
+#define LIBC_SRC_STRING_MEMORY_UTILS_BCMP inline_bcmp_unaligned_32bit
+#else
+#include "src/string/memory_utils/generic/aligned_access.h"
+#define LIBC_SRC_STRING_MEMORY_UTILS_BCMP inline_bcmp_aligned_access_32bit
+#endif
#elif defined(LIBC_TARGET_ARCH_IS_ANY_RISCV)
#include "src/string/memory_utils/riscv/inline_bcmp.h"
#define LIBC_SRC_STRING_MEMORY_UTILS_BCMP inline_bcmp_riscv
@@ -35,8 +43,10 @@
namespace LIBC_NAMESPACE_DECL {
-LIBC_FLATTEN LIBC_INLINE int inline_bcmp(const void *p1, const void *p2,
- size_t count) {
+// Always inline so `bcmp` (aligned to 64 bytes) does not emit a tail-call stub
+// to an unaligned out-of-line `inline_bcmp`.
+LIBC_FLATTEN LIBC_ALWAYS_INLINE int inline_bcmp(const void *p1, const void *p2,
+ size_t count) {
return static_cast<int>(LIBC_SRC_STRING_MEMORY_UTILS_BCMP(
reinterpret_cast<CPtr>(p1), reinterpret_cast<CPtr>(p2), count));
}
diff --git a/libc/src/string/memory_utils/riscv/inline_bcmp.h b/libc/src/string/memory_utils/riscv/inline_bcmp.h
index 666ad6382412e5..300ca980596874 100644
--- a/libc/src/string/memory_utils/riscv/inline_bcmp.h
+++ b/libc/src/string/memory_utils/riscv/inline_bcmp.h
@@ -5,30 +5,84 @@
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
-#ifndef LIBC_SRC_STRING_MEMORY_UTILS_RISCV_INLINE_BCMP_H
-#define LIBC_SRC_STRING_MEMORY_UTILS_RISCV_INLINE_BCMP_H
+#ifndef LLVM_LIBC_SRC_STRING_MEMORY_UTILS_RISCV_INLINE_BCMP_H
+#define LLVM_LIBC_SRC_STRING_MEMORY_UTILS_RISCV_INLINE_BCMP_H
-#include "src/__support/macros/attributes.h" // LIBC_INLINE
-#include "src/__support/macros/config.h" // LIBC_NAMESPACE_DECL
-#include "src/__support/macros/properties/architectures.h" // LIBC_TARGET_ARCH_IS_RISCV64
-#include "src/string/memory_utils/generic/aligned_access.h"
-#include "src/string/memory_utils/utils.h" // Ptr, CPtr
+#include "hdr/stdint_proxy.h"
+#include "src/__support/macros/attributes.h" // LIBC_INLINE
+#include "src/__support/macros/config.h" // LIBC_NAMESPACE_DECL
+#include "src/__support/macros/optimization.h" // LIBC_UNLIKELY
+#include "src/__support/macros/properties/architectures.h"
+#include "src/string/memory_utils/generic/bcmp_utils.h"
+#include "src/string/memory_utils/utils.h" // CPtr, BcmpReturnType
#include <stddef.h> // size_t
+#if !defined(LIBC_TARGET_ARCH_IS_RISCV64) && \
+ !defined(LIBC_TARGET_ARCH_IS_RISCV32)
+#error "Unimplemented"
+#endif
+
+#if defined(__riscv_vector) && defined(__riscv_v_intrinsic) && \
+ (__riscv_v_intrinsic >= 11000)
+#include <riscv_vector.h>
+#define LIBC_RISCV_HAS_RVV
+#elif !defined(__riscv_misaligned_fast)
+#include "src/string/memory_utils/generic/aligned_access.h"
+#endif
+
namespace LIBC_NAMESPACE_DECL {
[[maybe_unused]] LIBC_INLINE BcmpReturnType inline_bcmp_riscv(CPtr p1, CPtr p2,
size_t count) {
-#if defined(LIBC_TARGET_ARCH_IS_RISCV64)
+#ifdef LIBC_RISCV_HAS_RVV
+#ifdef __riscv_misaligned_fast
+ if (count <= 8)
+ return internal::bcmp_0_to_8(p1, p2, count);
+#ifdef LIBC_TARGET_ARCH_IS_RISCV64
+ if (count <= 16)
+ return internal::bcmp_9_to_16(p1, p2, count);
+ if (count <= 32)
+ return internal::bcmp_17_to_32_64bit(p1, p2, count);
+#else
+ if (count <= 16)
+ return internal::bcmp_9_to_16_32bit(p1, p2, count);
+#endif
+#else
+ if (count == 0)
+ return BcmpReturnType::zero();
+ if (count <= 3)
+ return internal::bcmp_exact_1_to_3(p1, p2, count);
+#endif
+ // VLA RVV 1.0 loop (LMUL=4); `do..while` avoids a loop-back branch on
+ // single-chunk inputs after short sizes exit above.
+ do {
+ const size_t vl = __riscv_vsetvl_e8m4(count);
+ const vuint8m4_t v1 =
+ __riscv_vle8_v_u8m4(reinterpret_cast<const uint8_t *>(p1), vl);
+ const vuint8m4_t v2 =
+ __riscv_vle8_v_u8m4(reinterpret_cast<const uint8_t *>(p2), vl);
+ const vbool2_t ne = __riscv_vmsne_vv_u8m4_b2(v1, v2, vl);
+ if (LIBC_UNLIKELY(__riscv_vfirst_m_b2(ne, vl) >= 0))
+ return BcmpReturnType::nonzero();
+ p1 += vl;
+ p2 += vl;
+ count -= vl;
+ } while (count > 0);
+ return BcmpReturnType::zero();
+#elif defined(__riscv_misaligned_fast) && defined(LIBC_TARGET_ARCH_IS_RISCV64)
+ return inline_bcmp_unaligned_64bit(p1, p2, count);
+#elif defined(__riscv_misaligned_fast)
+ return inline_bcmp_unaligned_32bit(p1, p2, count);
+#elif defined(LIBC_TARGET_ARCH_IS_RISCV64)
return inline_bcmp_aligned_access_64bit(p1, p2, count);
-#elif defined(LIBC_TARGET_ARCH_IS_RISCV32)
- return inline_bcmp_aligned_access_32bit(p1, p2, count);
#else
-#error "Unimplemented"
+ return inline_bcmp_aligned_access_32bit(p1, p2, count);
#endif
}
} // namespace LIBC_NAMESPACE_DECL
-#endif // LIBC_SRC_STRING_MEMORY_UTILS_RISCV_INLINE_BCMP_H
+#undef LIBC_RISCV_HAS_RVV
+
+#endif // LLVM_LIBC_SRC_STRING_MEMORY_UTILS_RISCV_INLINE_BCMP_H
diff --git a/libc/src/string/memory_utils/x86_64/inline_bcmp.h b/libc/src/string/memory_utils/x86_64/inline_bcmp.h
index 0eaf968f2f78db..791701e50d6867 100644
--- a/libc/src/string/memory_utils/x86_64/inline_bcmp.h
+++ b/libc/src/string/memory_utils/x86_64/inline_bcmp.h
@@ -1,4 +1,4 @@
-//===-- Bcmp implementation for x86_64 --------------------------*- C++ -*-===//
+//===-- Bcmp implementation for x86 -----------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
@@ -8,84 +8,198 @@
#ifndef LLVM_LIBC_SRC_STRING_MEMORY_UTILS_X86_64_INLINE_BCMP_H
#define LLVM_LIBC_SRC_STRING_MEMORY_UTILS_X86_64_INLINE_BCMP_H
+#include "hdr/stdint_proxy.h"
#include "src/__support/macros/attributes.h" // LIBC_INLINE
#include "src/__support/macros/config.h" // LIBC_NAMESPACE_DECL
-#include "src/string/memory_utils/op_generic.h"
-#include "src/string/memory_utils/op_x86.h"
-#include "src/string/memory_utils/utils.h" // Ptr, CPtr
+#include "src/__support/macros/optimization.h" // LIBC_UNLIKELY, LIBC_LOOP_NOUNROLL
+#include "src/__support/macros/properties/architectures.h"
+#include "src/__support/macros/properties/cpu_features.h" // LIBC_TARGET_CPU_HAS_SSE2
+#include "src/string/memory_utils/generic/bcmp_utils.h"
+#include "src/string/memory_utils/utils.h" // CPtr, BcmpReturnType, load_unaligned
#include <stddef.h> // size_t
+#if defined(LIBC_TARGET_CPU_HAS_SSE2)
+#include <immintrin.h>
+#endif
+
namespace LIBC_NAMESPACE_DECL {
-[[maybe_unused]] LIBC_INLINE BcmpReturnType
-inline_bcmp_generic_gt16(CPtr p1, CPtr p2, size_t count) {
- return generic::Bcmp<uint64_t>::loop_and_tail_align_above(256, p1, p2, count);
+#if defined(LIBC_TARGET_CPU_HAS_SSE2)
+namespace internal {
+
+LIBC_INLINE __m128i sse2_eq_16(CPtr a, CPtr b) {
+ return _mm_cmpeq_epi8(load_unaligned<__m128i>(a), load_unaligned<__m128i>(b));
}
-#if defined(__SSE4_1__)
-[[maybe_unused]] LIBC_INLINE BcmpReturnType
-inline_bcmp_x86_sse41_gt16(CPtr p1, CPtr p2, size_t count) {
- if (count <= 32)
- return generic::Bcmp<__m128i>::head_tail(p1, p2, count);
- return generic::Bcmp<__m128i>::loop_and_tail_align_above(256, p1, p2, count);
+LIBC_INLINE __m128i sse2_eq_32(CPtr a, CPtr b) {
+ return _mm_and_si128(sse2_eq_16(a, b), sse2_eq_16(a + 16, b + 16));
}
-#endif // __SSE4_1__
-#if defined(__AVX__)
-[[maybe_unused]] LIBC_INLINE BcmpReturnType
-inline_bcmp_x86_avx_gt16(CPtr p1, CPtr p2, size_t count) {
- if (count <= 32)
- return generic::Bcmp<__m128i>::head_tail(p1, p2, count);
- if (count <= 64)
- return generic::Bcmp<__m256i>::head_tail(p1, p2, count);
- return generic::Bcmp<__m256i>::loop_and_tail_align_above(256, p1, p2, count);
+LIBC_INLINE uint32_t sse2_mismatch_mask(__m128i eq) {
+ return static_cast<uint32_t>(_mm_movemask_epi8(eq)) ^ 0xffffU;
}
-#endif // __AVX__
-#if defined(__AVX512BW__)
-[[maybe_unused]] LIBC_INLINE BcmpReturnType
-inline_bcmp_x86_avx512bw_gt16(CPtr p1, CPtr p2, size_t count) {
- if (count <= 32)
- return generic::Bcmp<__m128i>::head_tail(p1, p2, count);
- if (count <= 64)
- return generic::Bcmp<__m256i>::head_tail(p1, p2, count);
- if (count <= 128)
- return generic::Bcmp<__m512i>::head_tail(p1, p2, count);
- return generic::Bcmp<__m512i>::loop_and_tail_align_above(256, p1, p2, count);
+// 17..32 and 33..64 return a 16- or 32-bit mismatch bitmask directly in `int`
+// (avoiding `ptest` + `setcc`). With AVX-512VL+BW, `_mm*_cmpneq_epi8_mask` runs
+// both comparisons in parallel and combines with `kor` instead of LLVM lowering
+// `and(cmpeq, cmpeq)` to a serialized masked `vpcmpeqb %k0{%k1}`.
+LIBC_INLINE BcmpReturnType bcmp_x86_17_to_32(CPtr p1, CPtr p2, size_t count) {
+#if defined(__AVX512VL__) && defined(__AVX512BW__)
+ const __mmask16 head_ne = _mm_cmpneq_epi8_mask(load_unaligned<__m128i>(p1),
+ load_unaligned<__m128i>(p2));
+ const __mmask16 tail_ne =
+ _mm_cmpneq_epi8_mask(load_unaligned<__m128i>(p1 + count - 16),
+ load_unaligned<__m128i>(p2 + count - 16));
+ return static_cast<uint32_t>(head_ne | tail_ne);
+#else
+ return sse2_mismatch_mask(_mm_and_si128(
+ sse2_eq_16(p1, p2), sse2_eq_16(p1 + count - 16, p2 + count - 16)));
+#endif
+}
+
+#if defined(LIBC_TARGET_ARCH_IS_X86_32)
+
+// Compact 32-byte SSE2 loop + tail for 32-bit x86 (low GPR count & code size).
+LIBC_INLINE BcmpReturnType bcmp_x86_32_gt32(CPtr p1, CPtr p2, size_t count) {
+ LIBC_LOOP_NOUNROLL
+ for (size_t i = 0; i < count - 32; i += 32) {
+ if (LIBC_UNLIKELY(_mm_movemask_epi8(sse2_eq_32(p1 + i, p2 + i)) != 0xffff))
+ return BcmpReturnType::nonzero();
+ }
+ return sse2_mismatch_mask(sse2_eq_32(p1 + count - 32, p2 + count - 32));
+}
+
+#else // x86-64
+
+LIBC_INLINE BcmpReturnType bcmp_x86_33_to_64(CPtr p1, CPtr p2, size_t count) {
+#if defined(__AVX512VL__) && defined(__AVX512BW__)
+ const __mmask32 head_ne = _mm256_cmpneq_epi8_mask(
+ load_unaligned<__m256i>(p1), load_unaligned<__m256i>(p2));
+ const __mmask32 tail_ne =
+ _mm256_cmpneq_epi8_mask(load_unaligned<__m256i>(p1 + count - 32),
+ load_unaligned<__m256i>(p2 + count - 32));
+ return static_cast<uint32_t>(head_ne | tail_ne);
+#elif defined(__AVX2__)
+ const __m256i eq = _mm256_and_si256(
+ _mm256_cmpeq_epi8(load_unaligned<__m256i>(p1),
+ load_unaligned<__m256i>(p2)),
+ _mm256_cmpeq_epi8(load_unaligned<__m256i>(p1 + count - 32),
+ load_unaligned<__m256i>(p2 + count - 32)));
+ return ~static_cast<uint32_t>(_mm256_movemask_epi8(eq));
+#else
+ return sse2_mismatch_mask(_mm_and_si128(
+ sse2_eq_32(p1, p2), sse2_eq_32(p1 + count - 32, p2 + count - 32)));
+#endif
+}
+
+// Medium sizes (`65..256` AVX2 / `65..128` SSE2) return the mismatch mask of
+// the first block directly while checking the remaining bytes with predicted
+// early-exit branches, hiding tail load latency on equal inputs. Larger sizes
+// check the head before entering the 128-byte loop so early mismatches exit
+// immediately.
+#if defined(__AVX2__)
+LIBC_INLINE BcmpReturnType bcmp_x86_over_64(CPtr p1, CPtr p2, size_t count) {
+ auto xor_32 = [](CPtr a, CPtr b) -> __m256i {
+ return _mm256_xor_si256(load_unaligned<__m256i>(a),
+ load_unaligned<__m256i>(b));
+ };
+ auto xor_128 = [&](CPtr a, CPtr b) -> __m256i {
+ return _mm256_or_si256(
+ _mm256_or_si256(xor_32(a, b), xor_32(a + 32, b + 32)),
+ _mm256_or_si256(xor_32(a + 64, b + 64), xor_32(a + 96, b + 96)));
+ };
+ const __m256i head_eq = _mm256_cmpeq_epi8(load_unaligned<__m256i>(p1),
+ load_unaligned<__m256i>(p2));
+ const __m256i second_xor = xor_32(p1 + 32, p2 + 32);
+ if (count <= 128) {
+ const __m256i rest_xor = _mm256_or_si256(
+ _mm256_or_si256(second_xor, xor_32(p1 + count - 64, p2 + count - 64)),
+ xor_32(p1 + count - 32, p2 + count - 32));
+ if (LIBC_UNLIKELY(!_mm256_testz_si256(rest_xor, rest_xor)))
+ return BcmpReturnType::nonzero();
+ return ~static_cast<uint32_t>(_mm256_movemask_epi8(head_eq));
+ }
+ const __m256i head_rest =
+ _mm256_or_si256(second_xor, _mm256_or_si256(xor_32(p1 + 64, p2 + 64),
+ xor_32(p1 + 96, p2 + 96)));
+ const size_t last = count - 128;
+ if (count <= 256) {
+ const __m256i rest_xor =
+ _mm256_or_si256(head_rest, xor_128(p1 + last, p2 + last));
+ if (LIBC_UNLIKELY(!_mm256_testz_si256(rest_xor, rest_xor)))
+ return BcmpReturnType::nonzero();
+ return ~static_cast<uint32_t>(_mm256_movemask_epi8(head_eq));
+ }
+ if (LIBC_UNLIKELY(~static_cast<uint32_t>(_mm256_movemask_epi8(head_eq)) !=
+ 0 ||
+ !_mm256_testz_si256(head_rest, head_rest)))
+ return BcmpReturnType::nonzero();
+ for (size_t i = 128 - static_cast<size_t>(distance_to_align_down<32>(p1));
+ i < last; i += 128) {
+ const __m256i block_xor = xor_128(p1 + i, p2 + i);
+ if (LIBC_UNLIKELY(!_mm256_testz_si256(block_xor, block_xor)))
+ return BcmpReturnType::nonzero();
+ }
+ const __m256i tail_xor = xor_128(p1 + last, p2 + last);
+ return ~static_cast<uint32_t>(_mm256_movemask_epi8(
+ _mm256_cmpeq_epi8(tail_xor, _mm256_setzero_si256())));
+}
+#else
+LIBC_INLINE BcmpReturnType bcmp_x86_over_64(CPtr p1, CPtr p2, size_t count) {
+ auto eq_64 = [](CPtr a, CPtr b) -> __m128i {
+ return _mm_and_si128(sse2_eq_32(a, b), sse2_eq_32(a + 32, b + 32));
+ };
+ const __m128i head_eq = sse2_eq_32(p1, p2);
+ const __m128i second_eq = sse2_eq_32(p1 + 32, p2 + 32);
+ const size_t last = count - 64;
+ if (count <= 128) {
+ if (LIBC_UNLIKELY(_mm_movemask_epi8(_mm_and_si128(
+ second_eq, eq_64(p1 + last, p2 + last))) != 0xffff))
+ return BcmpReturnType::nonzero();
+ return sse2_mismatch_mask(head_eq);
+ }
+ if (LIBC_UNLIKELY(_mm_movemask_epi8(_mm_and_si128(head_eq, second_eq)) !=
+ 0xffff))
+ return BcmpReturnType::nonzero();
+ for (size_t i = 64 - static_cast<size_t>(distance_to_align_down<16>(p1));
+ i < last; i += 64) {
+ if (LIBC_UNLIKELY(_mm_movemask_epi8(eq_64(p1 + i, p2 + i)) != 0xffff))
+ return BcmpReturnType::nonzero();
+ }
+ return sse2_mismatch_mask(eq_64(p1 + last, p2 + last));
}
-#endif // __AVX512BW__
+#endif // __AVX2__ / SSE2
+
+#endif // LIBC_TARGET_ARCH_IS_X86_32
+
+} // namespace internal
+#endif // LIBC_TARGET_CPU_HAS_SSE2
[[maybe_unused]] LIBC_INLINE BcmpReturnType inline_bcmp_x86(CPtr p1, CPtr p2,
size_t count) {
- if (count == 0)
- return BcmpReturnType::zero();
- if (count == 1)
- return generic::Bcmp<uint8_t>::block(p1, p2);
- if (count == 2)
- return generic::Bcmp<uint16_t>::block(p1, p2);
- if (count == 3)
- return generic::BcmpSequence<uint16_t, uint8_t>::block(p1, p2);
- if (count == 4)
- return generic::Bcmp<uint32_t>::block(p1, p2);
- if (count == 5)
- return generic::BcmpSequence<uint32_t, uint8_t>::block(p1, p2);
- if (count == 6)
- return generic::BcmpSequence<uint32_t, uint16_t>::block(p1, p2);
- if (count == 7)
- return generic::BcmpSequence<uint32_t, uint16_t, uint8_t>::block(p1, p2);
- if (count == 8)
- return generic::Bcmp<uint64_t>::block(p1, p2);
+#if defined(LIBC_TARGET_CPU_HAS_SSE2)
+ if (count <= 8)
+ return internal::bcmp_0_to_8(p1, p2, count);
+#if defined(LIBC_TARGET_ARCH_IS_X86_32)
+ if (count <= 16)
+ return internal::bcmp_9_to_16_32bit(p1, p2, count);
+ if (count <= 32)
+ return internal::bcmp_x86_17_to_32(p1, p2, count);
+ return internal::bcmp_x86_32_gt32(p1, p2, count);
+#else
if (count <= 16)
- return generic::Bcmp<uint64_t>::head_tail(p1, p2, count);
-#if defined(__AVX512BW__)
- return inline_bcmp_x86_avx512bw_gt16(p1, p2, count);
-#elif defined(__AVX__)
- return inline_bcmp_x86_avx_gt16(p1, p2, count);
-#elif defined(__SSE4_1__)
- return inline_bcmp_x86_sse41_gt16(p1, p2, count);
+ return internal::bcmp_9_to_16(p1, p2, count);
+ if (count <= 32)
+ return internal::bcmp_x86_17_to_32(p1, p2, count);
+ if (count <= 64)
+ return internal::bcmp_x86_33_to_64(p1, p2, count);
+ return internal::bcmp_x86_over_64(p1, p2, count);
+#endif
+#elif defined(LIBC_TARGET_ARCH_IS_X86_32)
+ return inline_bcmp_unaligned_32bit(p1, p2, count);
#else
- return inline_bcmp_generic_gt16(p1, p2, count);
+ return inline_bcmp_unaligned_64bit(p1, p2, count);
#endif
}
diff --git a/libc/src/strings/bcmp.cpp b/libc/src/strings/bcmp.cpp
index 083f13d3f95d3a..152ae5380d9d9c 100644
--- a/libc/src/strings/bcmp.cpp
+++ b/libc/src/strings/bcmp.cpp
@@ -8,11 +8,22 @@
#include "src/strings/bcmp.h"
#include "src/__support/common.h"
+#include "src/__support/macros/attributes.h"
#include "src/__support/macros/config.h"
+#include "src/__support/macros/properties/architectures.h"
#include "src/string/memory_utils/inline_bcmp.h"
namespace LIBC_NAMESPACE_DECL {
+// Align to a 64-byte cache line on 64-bit targets so the 0..8 byte fast path
+// fits within a single cache line and avoids alignment-sensitive latency
+// swings.
+#if __has_cpp_attribute(gnu::aligned) && \
+ (defined(LIBC_TARGET_ARCH_IS_X86_64) || \
+ defined(LIBC_TARGET_ARCH_IS_AARCH64) || \
+ defined(LIBC_TARGET_ARCH_IS_RISCV64))
+[[gnu::aligned(64)]]
+#endif
LLVM_LIBC_FUNCTION(int, bcmp,
(const void *lhs, const void *rhs, size_t count)) {
return inline_bcmp(lhs, rhs, count);
diff --git a/libc/test/src/strings/bcmp_test.cpp b/libc/test/src/strings/bcmp_test.cpp
index 794f9a1b8bd9de..d0d7db80f06235 100644
--- a/libc/test/src/strings/bcmp_test.cpp
+++ b/libc/test/src/strings/bcmp_test.cpp
@@ -7,11 +7,16 @@
//===----------------------------------------------------------------------===//
#include "src/__support/macros/config.h"
+#include "src/__support/macros/properties/os.h" // LIBC_TARGET_OS_IS_LINUX
#include "src/strings/bcmp.h"
#include "test/UnitTest/Test.h"
#include "test/UnitTest/TestLogger.h"
#include "test/src/string/memory_utils/memory_check_utils.h"
+#if !defined(LIBC_FULL_BUILD) && defined(LIBC_TARGET_OS_IS_LINUX)
+#include "test/src/string/memory_utils/protected_pages.h"
+#endif // !defined(LIBC_FULL_BUILD) && defined(LIBC_TARGET_OS_IS_LINUX)
+
namespace LIBC_NAMESPACE_DECL {
TEST(LlvmLibcBcmpTest, CmpZeroByte) {
@@ -44,11 +49,11 @@ static inline int Adaptor(cpp::span<char> p1, cpp::span<char> p2, size_t size) {
}
TEST(LlvmLibcBcmpTest, SizeSweep) {
- static constexpr size_t kMaxSize = 400;
+ static constexpr size_t kMaxSize = 600;
Buffer Buffer1(kMaxSize);
Buffer Buffer2(kMaxSize);
Randomize(Buffer1.span());
- for (size_t size = 0; size < kMaxSize; ++size) {
+ for (size_t size = 0; size <= kMaxSize; ++size) {
auto span1 = Buffer1.span().subspan(0, size);
auto span2 = Buffer2.span().subspan(0, size);
const bool OK = CheckBcmp<Adaptor>(span1, span2, size);
@@ -58,4 +63,130 @@ TEST(LlvmLibcBcmpTest, SizeSweep) {
}
}
+static inline void check_flipped_byte(const char *a, char *b, size_t size,
+ size_t idx) {
+ b[idx] ^= 1;
+ ASSERT_NE(LIBC_NAMESPACE::bcmp(a, b, size), 0);
+ ASSERT_NE(LIBC_NAMESPACE::bcmp(b, a, size), 0);
+ b[idx] ^= 1;
+}
+
+// Offsets lhs across every alignment modulo 64 so aligned loops and unaligned
+// tails are exercised for all size classes.
+TEST(LlvmLibcBcmpTest, AlignmentSweep) {
+ static constexpr size_t MAX_OFFSET = 64;
+ static constexpr size_t MAX_SIZE = 600;
+ Buffer buffer1(MAX_OFFSET + MAX_SIZE);
+ Buffer buffer2(MAX_SIZE);
+ Randomize(buffer1.span());
+
+ auto check_size = [&](size_t size) {
+ for (size_t offset = 0; offset < MAX_OFFSET; ++offset) {
+ auto span1 = buffer1.span().subspan(offset, size);
+ auto span2 = buffer2.span().subspan(0, size);
+ if (size <= 72) {
+ ASSERT_TRUE(CheckBcmp<Adaptor>(span1, span2, size));
+ ASSERT_EQ(LIBC_NAMESPACE::bcmp(span2.data(), span1.data(), size), 0);
+ } else {
+ ReferenceCopy(span2, span1);
+ ASSERT_EQ(LIBC_NAMESPACE::bcmp(span1.data(), span2.data(), size), 0);
+ ASSERT_EQ(LIBC_NAMESPACE::bcmp(span2.data(), span1.data(), size), 0);
+ const size_t positions[] = {0, 1, 31, 32, 63, 64, size / 2, size - 1};
+ for (size_t i : positions)
+ check_flipped_byte(span1.data(), span2.data(), size, i);
+ }
+ }
+ };
+
+ for (size_t size = 0; size <= 72; ++size)
+ check_size(size);
+ const size_t bases[] = {126, 254, 510};
+ for (size_t base : bases)
+ for (size_t size = base; size <= base + 8; ++size)
+ check_size(size);
+ check_size(MAX_SIZE);
+}
+
+// Verify that bytes outside [0, size) never affect the result.
+TEST(LlvmLibcBcmpTest, IgnoresSurroundingBytes) {
+ static constexpr size_t PAD = 64;
+ static constexpr size_t MAX_SIZE = 64;
+ char lhs[PAD + MAX_SIZE + PAD];
+ char rhs[PAD + MAX_SIZE + PAD];
+
+ for (size_t size = 0; size <= MAX_SIZE; ++size) {
+ for (size_t i = 0; i < PAD; ++i) {
+ lhs[i] = lhs[PAD + size + i] = 'x';
+ rhs[i] = rhs[PAD + size + i] = 'y';
+ }
+ for (size_t i = 0; i < size; ++i)
+ lhs[PAD + i] = rhs[PAD + i] = static_cast<char>('a' + (i % 26));
+
+ ASSERT_EQ(LIBC_NAMESPACE::bcmp(lhs + PAD, rhs + PAD, size), 0);
+ if (size == 0)
+ continue;
+
+ for (size_t i = 0; i < PAD; ++i)
+ rhs[i] = rhs[PAD + size + i] = 'x';
+ check_flipped_byte(lhs + PAD, rhs + PAD, size, size - 1);
+ check_flipped_byte(lhs + PAD, rhs + PAD, size, 0);
+ }
+}
+
+#if !defined(LIBC_FULL_BUILD) && defined(LIBC_TARGET_OS_IS_LINUX)
+
+// Places buffers against inaccessible guard pages so out-of-page reads fault.
+TEST(LlvmLibcBcmpTest, CheckAccess) {
+ static constexpr size_t MAX_SIZE = 600;
+ LIBC_ASSERT(MAX_SIZE < GetPageSize());
+ ProtectedPages pages;
+ const Page page_a = pages.GetPageA().WithAccess(PROT_READ | PROT_WRITE);
+ const Page page_b = pages.GetPageB().WithAccess(PROT_READ | PROT_WRITE);
+ const size_t page_size = page_a.page_size;
+ Randomize(
+ cpp::span<char>(reinterpret_cast<char *>(page_a.page_ptr), page_size));
+
+ const void *inaccessible[] = {
+ nullptr,
+ page_a.page_ptr - 1,
+ page_a.page_ptr + page_size,
+ };
+ for (const void *bad : inaccessible) {
+ ASSERT_EQ(LIBC_NAMESPACE::bcmp(bad, bad, 0), 0);
+ ASSERT_EQ(LIBC_NAMESPACE::bcmp(page_a.page_ptr, bad, 0), 0);
+ ASSERT_EQ(LIBC_NAMESPACE::bcmp(bad, page_a.page_ptr, 0), 0);
+ }
+
+ for (size_t size = 1; size <= 64; ++size) {
+ for (size_t offset = 0; offset < 16; ++offset) {
+ cpp::span<char> rhs(reinterpret_cast<char *>(page_b.top(size) - offset),
+ size);
+ uint8_t *a_ptrs[] = {page_a.bottom(size) + offset,
+ page_a.top(size) - offset};
+ for (uint8_t *a_raw : a_ptrs) {
+ cpp::span<char> lhs(reinterpret_cast<char *>(a_raw), size);
+ ASSERT_TRUE(CheckBcmp<Adaptor>(lhs, rhs, size));
+ ASSERT_EQ(LIBC_NAMESPACE::bcmp(rhs.data(), lhs.data(), size), 0);
+ }
+ }
+ }
+
+ for (size_t size = 65; size <= MAX_SIZE; ++size) {
+ uint8_t *a_ptrs[] = {page_a.bottom(size), page_a.top(size)};
+ uint8_t *b_ptrs[] = {page_b.bottom(size), page_b.top(size)};
+ for (uint8_t *a_raw : a_ptrs) {
+ for (uint8_t *b_raw : b_ptrs) {
+ cpp::span<char> a(reinterpret_cast<char *>(a_raw), size);
+ cpp::span<char> b(reinterpret_cast<char *>(b_raw), size);
+ ReferenceCopy(b, a);
+ ASSERT_EQ(LIBC_NAMESPACE::bcmp(a.data(), b.data(), size), 0);
+ check_flipped_byte(a.data(), b.data(), size, 0);
+ check_flipped_byte(a.data(), b.data(), size, size - 1);
+ }
+ }
+ }
+}
+
+#endif // !defined(LIBC_FULL_BUILD) && defined(LIBC_TARGET_OS_IS_LINUX)
+
} // namespace LIBC_NAMESPACE_DECL
diff --git a/utils/bazel/llvm-project-overlay/libc/src/string/memory_utils/BUILD.bazel b/utils/bazel/llvm-project-overlay/libc/src/string/memory_utils/BUILD.bazel
index e5e8c5bed7c4ce..3610af94934d93 100644
--- a/utils/bazel/llvm-project-overlay/libc/src/string/memory_utils/BUILD.bazel
+++ b/utils/bazel/llvm-project-overlay/libc/src/string/memory_utils/BUILD.bazel
@@ -36,6 +36,7 @@ libc_support_library(
"arm/inline_memcpy.h",
"arm/inline_memset.h",
"generic/aligned_access.h",
+ "generic/bcmp_utils.h",
"generic/byte_per_byte.h",
"generic/inline_strlen.h",
"inline_bcmp.h",
@@ -71,9 +72,11 @@ libc_support_library(
"//libc/src/__support/macros:config",
"//libc/src/__support/macros:is_defined",
"//libc/src/__support/macros:optimization",
+ "//libc/src/__support/macros:sanitizer",
"//libc/src/__support/macros/properties:architectures",
"//libc/src/__support/macros/properties:compiler",
"//libc/src/__support/macros/properties:cpu_features",
+ "//libc/src/__support/macros/properties:os",
"//libc/src/__support/macros/properties:types",
],
)
diff --git a/utils/bazel/llvm-project-overlay/libc/src/strings/BUILD.bazel b/utils/bazel/llvm-project-overlay/libc/src/strings/BUILD.bazel
index faf6edb6adb2d7..8e59c99d883133 100644
--- a/utils/bazel/llvm-project-overlay/libc/src/strings/BUILD.bazel
+++ b/utils/bazel/llvm-project-overlay/libc/src/strings/BUILD.bazel
@@ -55,7 +55,9 @@ libc_function(
hdrs = ["bcmp.h"],
deps = [
"//libc/src/__support:common",
+ "//libc/src/__support/macros:attributes",
"//libc/src/__support/macros:config",
+ "//libc/src/__support/macros/properties:architectures",
"//libc/src/string/memory_utils",
],
)
diff --git a/utils/bazel/llvm-project-overlay/libc/test/src/strings/BUILD.bazel b/utils/bazel/llvm-project-overlay/libc/test/src/strings/BUILD.bazel
index 37ab5e139ae55f..b7c6c419f15b33 100644
--- a/utils/bazel/llvm-project-overlay/libc/test/src/strings/BUILD.bazel
+++ b/utils/bazel/llvm-project-overlay/libc/test/src/strings/BUILD.bazel
@@ -25,10 +25,16 @@ libc_test(
name = "bcmp_test",
srcs = ["bcmp_test.cpp"],
deps = [
+ "//libc/src/__support/macros/properties:os",
"//libc/src/strings:bcmp",
"//libc/test/UnitTest:test_logger",
"//libc/test/src/string:memory_check_utils",
- ],
+ ] + select({
+ "//libc:full_build": [],
+ "//conditions:default": [
+ "//libc/test/src/string:protected_pages",
+ ],
+ }),
)
libc_test(
More information about the libc-commits
mailing list