From 13f48f94bd2c8ca1f651fdbaa5cf819e7f9c22da Mon Sep 17 00:00:00 2001 From: Matthew Suozzo Date: Wed, 11 Nov 2026 14:02:53 +0000 Subject: [PATCH] Provide SWAR memcmp implementation when SIMD not enabled Without SIMD, memcmp compares one byte per iteration. Add a path for n >= 8 that compares 8-byte words and locates the first differing byte with ctz on their XOR. Calls shorter than 8 bytes go straight to the existing byte loop. ns per call, old loop -> new, Clang trunk at -O3, AMD EPYC 7B13: n first difference Wasmtime 50 V8 (Node 22) 4 none 4.2 -> 3.5 4.3 -> 4.1 8 byte 0 2.2 -> 2.2 3.2 -> 3.2 8 none 6.6 -> 3.2 7.5 -> 3.6 16 none 12.6 -> 4.4 11.2 -> 4.2 64 byte 0 2.2 -> 2.2 3.2 -> 3.2 64 none 46.9 -> 11.9 33.2 -> 8.3 1024 none 642 -> 167 502 -> 89 The function grows from 74->311 bytes at -O3 and from 66->185 at -Oz. --- libc-top-half/musl/src/string/memcmp.c | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/libc-top-half/musl/src/string/memcmp.c b/libc-top-half/musl/src/string/memcmp.c index ce313049a..ea8b971ce 100644 --- a/libc-top-half/musl/src/string/memcmp.c +++ b/libc-top-half/musl/src/string/memcmp.c @@ -1,4 +1,5 @@ #include +#include #ifdef __wasm_simd128__ #include @@ -6,6 +7,8 @@ int memcmp(const void *vl, const void *vr, size_t n) { + const unsigned char *l=vl, *r=vr; + #if defined(__wasm_simd128__) && defined(__wasilibc_simd_string) if (n >= sizeof(v128_t)) { // memcmp is allowed to read up to n bytes from each object. @@ -35,9 +38,25 @@ int memcmp(const void *vl, const void *vr, size_t n) } return 0; } +#else + // Compare 8 bytes at a time. + if (n >= sizeof(uint64_t)) { + do { + uint64_t a, b; + __builtin_memcpy(&a, l, sizeof(a)); + __builtin_memcpy(&b, r, sizeof(b)); + if (a != b) { + // The lowest set bit is in the first byte that differs. + int shift = __builtin_ctzll(a ^ b) & ~7; + return (int)((a >> shift) & 0xff) - (int)((b >> shift) & 0xff); + } + l += sizeof(a); + r += sizeof(b); + n -= sizeof(a); + } while (n >= sizeof(uint64_t)); + } #endif - const unsigned char *l=vl, *r=vr; for (; n && *l == *r; n--, l++, r++); return n ? *l-*r : 0; }