Commit Graph
4 Commits
Author SHA1 Message Date
Chandler Carruth 4729b4473b Provide optimized string equality for hashtable keys (#8143)
We shouldn't need to do this, and we should be able to rely on LLVM's
`StringRef::operator==` and similar routines to be efficient. But in
practice and after measuring, this seems to not be the case. =/

Both glibc and LLVM-libc have `bcmp` implementations significantly
slower than what we introduce here, and reaching into libc requires PLT
overhead and other challenges. I plan to send a PR to LLVM-libc of this
implementation to replace its `bcmp`. Until that lands and we can
reliably use it, having this makes a _dramatic_ impact on hashtable
performance for string keys, which happens to be the case we care very
much about in the compiler.

This implementation is somewhat based on the premise that hashtable keys
and other kinds of string comparisons are close enough in their expected
behavior and distribution of data sizes that we don't need to overly
specialize. We have data suggesting that _all_ string comparisons are
heavily biased towards short strings and latency-sensitive code paths,
much as hashtable keys are. This implementation specifically optimizes
for those two priorities: latency and short strings.

The overarching design of this string comparison has a few key ideas
that enable it to be efficient:

- Must be an efficient out-of-line function to allow callers to remain
good inline candidates. Also uses `preserve_most` to minimize register
pressure in the caller, and `pure` to avoid re-loading values from
memory.
- Avoid trying to pass `bool`, a defined `0` vs `1` value, or condition
flags across this out-of-line ABI boundary as they are not efficiently
represented and converting to these representations within the
implementation adds overhead. We want the caller to be able to have the
conditional branch that converts to a boolean state where it can be
fused and efficient. The out-of-line function needs to return an
efficient input to a caller's conditional branch. This motivates a
`uint64_t` result type which has the most flexibility for the
implementation.
- Overread for sizes up to 8 bytes when within the page -- we read 8
bytes and then mask off the bits that we were not allowed to read. This
has to be disabled when using sanitizers and we only support
little-endian masking, but is a _significant_ performance improvement
when available.
- Overlapping reads at the start and end: much like in hashing,
_duplicate_ reads are fine, and we can leverage this to handle a range
of sizes with common code, for example reading the first and last 8
bytes handles sizes 9 through 16 with identical code.
- Balance between branch-predictable returns of constants and returning
a computed non-zero value (via xor or other operation) for the caller to
branch on. Sometimes, it is useful to allow branch prediction to
early-exit the comparisons, other times it ends up better to compute the
data and let the caller's branch be predicted or not.
- Use relevant architecture and microarchitecture details when needed.
For example, we carefully select between vector operations and GPR
operations to minimize vector <-> GPR movement overhead.

The PR provides unit tests for the relevant size classes and various
boundary conditions.

We also provide benchmarks, both ones that measure _latency_ of the
comparison by causing each iteration to have a data dependency on the
prior iteration, and ones that measure _throughput_ by allowing each
iteration to run in parallel. Even though we optimize for latency first,
we want to have the best throughput we can.

Cycles per comparison (lower is better) vs. Linux glibc ("System") and
out-of-line LLVM-libc `inline_bcmp` ("LLVM"). "C++ ids" uses the C++
identifier length distribution. `System` and `LLVM` are relative to this
implementation: positive `%` and `>1x` mean this implementation is
faster; negative `%` and `<1x` mean it is slower; `~` is no significant
difference (p < 0.05).

AArch64 (armv8.2-a) on an Apple M1 P-core, cycles per comparison:

| Sizes    | Latency | System |   LLVM | Throughput | System |   LLVM |
| :------- | ------: | -----: | -----: | ---------: | -----: | -----: |
| C++ ids  |    21.3 |   +41% |   +40% |       12.5 |   +93% |  +100% |
| 1-3      |    14.4 |   +48% |   +64% |        5.0 |  3.99x |  3.83x |
| 4-8      |    14.5 |   +55% |   +46% |        5.0 |  2.30x |  3.02x |
| 9-16     |    14.6 |   +47% |   +29% |        4.0 |  2.22x |   +95% |
| 17-32    |    17.6 |   +20% |   +50% |        5.2 |   +38% |   -21% |
| 33-64    |    20.1 |   +40% |   +47% |        7.2 |  2.68x |   -16% |
| 65-256   |    36.9 |   +49% |   +17% |       30.0 |   +57% |    -3% |
| 257-1024 |   103.8 |   +38% |    +7% |       85.1 |   +58% |  +0.2% |

x86-64-v3 on an AMD Ryzen 9 9950X (Zen 5), cycles per comparison:

| Sizes    | Latency | System |   LLVM | Throughput | System |   LLVM |
| :------- | ------: | -----: | -----: | ---------: | -----: | -----: |
| C++ ids  |    24.0 |    +1% |   +75% |       18.1 |  0.39x |  2.36x |
| 1-3      |    14.4 |   +57% |  2.34x |        4.7 |    +7% |  7.24x |
| 4-8      |    14.4 |   +57% |  2.62x |        4.7 |    +7% |  8.36x |
| 9-16     |    15.0 |   +53% |    +5% |        5.9 |   -15% |      ~ |
| 17-32    |    22.8 |  +0.4% |   +10% |        7.0 |   -29% |   -21% |
| 33-64    |    25.8 |    -6% |    +6% |        7.1 |   -16% |    -5% |
| 65-256   |    45.1 |    +4% |   +25% |       28.3 |    -7% |   +50% |
| 257-1024 |    64.0 |   +17% |   +35% |       64.7 |   +10% |   +16% |

x86-64-v3 on an AMD EPYC 7B13 (Zen 3), cycles per comparison:

| Sizes    | Latency | System |   LLVM | Throughput | System |   LLVM |
| :------- | ------: | -----: | -----: | ---------: | -----: | -----: |
| C++ ids  |    24.1 |    N/A |   +54% |       16.9 |    +8% |  2.15x |
| 1-3      |    15.6 |    N/A |   +94% |        5.7 |  4.29x |  5.04x |
| 4-8      |    15.6 |    N/A |  2.12x |        5.7 |  2.56x |  5.87x |
| 9-16     |    15.8 |    N/A |   +11% |        7.1 |  2.03x |      ~ |
| 17-32    |    24.6 |    N/A |  +0.4% |        8.1 |   +74% |   -12% |
| 33-64    |    30.5 |    -6% |    -1% |       10.1 |    +9% |   -10% |
| 65-256   |    46.3 |   +12% |   +32% |       33.2 |    -8% |   +39% |
| 257-1024 |    78.8 |   +12% |   +26% |       82.3 |    -3% |      ~ |

x86-64-v2 on an AMD Ryzen 9 9950X (Zen 5), cycles per comparison:

| Sizes    | Latency | System |   LLVM | Throughput | System |   LLVM |
| :------- | ------: | -----: | -----: | ---------: | -----: | -----: |
| C++ ids  |    23.9 |    +2% |   +78% |       17.7 |  0.40x |  2.45x |
| 1-3      |    14.8 |   +53% |  2.28x |        5.0 |      ~ |  6.68x |
| 4-8      |    14.9 |   +55% |  2.54x |        5.0 |      ~ |  7.82x |
| 9-16     |    14.9 |   +53% |    +5% |        6.0 |   -17% |   -17% |
| 17-32    |    22.7 |  +0.4% |   +10% |        6.0 |   -17% |      ~ |
| 33-64    |    26.9 |   -10% |   +37% |        7.5 |   -20% |  3.35x |
| 65-256   |    47.7 |    -1% |   +20% |       38.2 |   -31% |   +30% |
| 257-1024 |    91.5 |   -18% |   +24% |       91.4 |   -22% |   +18% |

x86-64-v2 on an AMD EPYC 7B13 (Zen 3), cycles per comparison:

| Sizes    | Latency | System |   LLVM | Throughput | System |   LLVM |
| :------- | ------: | -----: | -----: | ---------: | -----: | -----: |
| C++ ids  |    24.1 |    N/A |   +55% |       16.5 |   +10% |  2.24x |
| 1-3      |    15.8 |    N/A |   +92% |        6.3 |  3.88x |  4.60x |
| 4-8      |    15.8 |    N/A |  2.10x |        6.3 |  2.32x |  5.34x |
| 9-16     |    15.8 |    N/A |   +11% |        7.1 |  2.03x |      ~ |
| 17-32    |    24.4 |    N/A |    +4% |        8.1 |   +74% |      ~ |
| 33-64    |    30.7 |    -7% |   +26% |       10.0 |   +11% |  2.70x |
| 65-256   |    48.5 |    +7% |   +31% |       45.8 |   -33% |   +19% |
| 257-1024 |   108.1 |   -21% |   +11% |      110.9 |   -29% |      ~ |

Note: Zen 3 `System` latency is `N/A` for `C++ ids` and 1-32 bytes
because glibc's AVX2 `memcmp` returns a constant `0` behind a predicted
branch for equal 2-31 byte strings, so the latency benchmark's select
doesn't wait on the comparison.

Assisted-by: Antigravity with Gemini, Fable, and other models
2026-11-21 22:35:59 +00:00
Chandler Carruth 13ecad24be Remove the hashtable seed (#7871)
Hashtables seed every hash with the address of a global,
`ComputeSeed()`, so that ASLR varies layout and iteration order between
runs. Debug builds already vary iteration order directly in `entries()`,
so the seed only matters in release builds. There it costs a register
and an XOR on the latency path of every integer or pointer hash, and it
redraws a table's collisions in each process.

Remove the seed from `HashValue`, `Hasher`, `CarbonHashValue`,
`CustomHashValue::Hash`, and `HashKey`. Hashing starts from a zero
buffer, so integer keys hash as `WeakMix(key)`. `global_addr_seed`
remains in debug builds to seed the iteration-order entropy.
`ClangDeclSignature` chained its hash through the seed, and now hashes
its fields with one `Hasher`.

The seed also kept some short-input paths from collapsing. Without it,
every `{i, 0, 0}` array of `int32_t` hashed the same, all-zero 4-8 byte
inputs lost their size, and the 17-32 byte path multiplied the size
sample by a byte-shifted copy of itself. Each `Mix` operand of the
short-input paths now XORs in a 32-bit constant from
`ImmediateRandomData` in place of a 64-bit chunk of `StaticRandomData`,
which they now only sample to encode sizes. `XorImmediate` keeps these
as `xor $imm32` on x86-64; without its `asm` barrier, a read feeding the
XOR is folded in instead and the constant ends up in a register that
loops hoist.

Cycles against trunk on Zen 5, from `bench_runner.py` with 48 runs per
side, each run at a random code layout, and table sizes of 64, 3584, and
57344:
- Integer and pointer hits: -3.0% to -5.7% in `Map`, -0.8% to -2.4% in
`Set`.
- Integer and pointer misses: up to -12.6%, except `Set<int*>` at +1.4%
(64) and +6.1% (3584).
- String keys: -2.8% to +2.1%, with `Map` updates at +1.1% to +1.6%.
- Hash latency, without layout randomization: integers and pointers
-9.8%, empty strings +5.4% (0.1 cycles), other strings not significant.

Same method on an Apple M1, with #7870 on both sides. Without it, this
change moves benchmark loop counters between `sp`- and `x29`-relative
stack slots, which alone makes `Set<int>` lookups up to 49% slower on
the M1.
- Integer and pointer hits: -1.0% to -10.3% in `Map`, -24.5% to +1.2% in
`Set`.
- Integer and pointer misses: -3.9% to -48.0%, except +7.2% to +59.3% at
3584, from longer probes (instructions +6.4% to +70.6%).
- Inserting 64 integer keys: +12.1% to +15.0%, from store memory-order
violations.
- String keys: -6.6% to +3.9%.
- Hash latency: integers and pointers -9.0% to -10.0%, empty strings
+48.8% (1 cycle).

Release builds now iterate a given table in the same order in every run.
Code that depends on that order still fails in debug builds.

Assisted-by: Claude Code
2026-10-06 15:13:10 +00:00
Chandler Carruth 95fc6fae22 common: Decouple LLVM hashing dependencies from common/hashing.h (#7646)
- Move formatted printing to `hashing.cpp` instead of `hashing.h`
- Separate APInt and APFloat hashing specializations into a new
`hashing_llvm.h`
- Update toolchain/base dependencies and include sites that hash LLVM
data types to include `hashing_llvm.h`

Combined, this reduces the transitive includes caused by `hashing.h`.

Assisted-by: Antigravity with Gemini
2026-08-26 00:41:51 +00:00
Chandler Carruth a8748f3e2d Key context improvements (#4095)
This injects a customization point for hashtable-specific equality
testing that the key context uses by default. While this is rarely
needed, there are LLVM types where it is necessary and it seems a good
general tool to have to avoid unnecessary complexity from custom key
contexts when a simple customization of equality is all that is
required.

This also adds a CRTP mixin for implementing a common pattern of key
contexts where the context provides translation of some key types into
another type, potentially using state. Rather than having to implement
the entire key context API, code can derive from this template and
simply provide a set of overloads for the types it wants to translate.
Any key types used which can be passed to one of those overloads will
get translated before following the same logic as the default key
context. While this updates the only usage so far of this pattern, a
subsequent PR will add several more users making the pattern worth
abstracting here.
2024-07-02 21:20:14 +00:00