[libc-commits] [libc] [llvm] [libc] Introduce a highly optimized `bcmp` implementation (PR #244952)

via libc-commits libc-commits at lists.llvm.org
Sat Nov 21 14:34:15 PST 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-backend-risc-v

Author: Chandler Carruth (chandlerc)

<details>
<summary>Changes</summary>

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

---

Patch is 61.75 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/244952.diff


14 Files Affected:

- (modified) libc/benchmarks/LibcMemoryGoogleBenchmarkMain.cpp (+160) 
- (modified) libc/src/__support/macros/sanitizer.h (+14) 
- (modified) libc/src/string/memory_utils/CMakeLists.txt (+7) 
- (modified) libc/src/string/memory_utils/aarch64/inline_bcmp.h (+82-87) 
- (modified) libc/src/string/memory_utils/generic/aligned_access.h (+83-31) 
- (added) libc/src/string/memory_utils/generic/bcmp_utils.h (+236) 
- (modified) libc/src/string/memory_utils/inline_bcmp.h (+15-5) 
- (modified) libc/src/string/memory_utils/riscv/inline_bcmp.h (+66-12) 
- (modified) libc/src/string/memory_utils/x86_64/inline_bcmp.h (+174-60) 
- (modified) libc/src/strings/bcmp.cpp (+11) 
- (modified) libc/test/src/strings/bcmp_test.cpp (+133-2) 
- (modified) utils/bazel/llvm-project-overlay/libc/src/string/memory_utils/BUILD.bazel (+3) 
- (modified) utils/bazel/llvm-project-overlay/libc/src/strings/BUILD.bazel (+2) 
- (modified) utils/bazel/llvm-project-overlay/libc/test/src/strings/BUILD.bazel (+7-1) 


``````````diff
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)...
[truncated]

``````````

</details>


https://github.com/llvm/llvm-project/pull/244952


More information about the libc-commits mailing list