Files
carbon-lang/common/hashtable_key_context.h
T
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

300 lines
12 KiB
C++

// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#ifndef CARBON_COMMON_HASHTABLE_KEY_CONTEXT_H_
#define CARBON_COMMON_HASHTABLE_KEY_CONTEXT_H_
#include <concepts>
#include "common/hashing.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/APInt.h"
namespace Carbon {
// The equality comparison used by the the hashtable key contexts in this file,
// and suitable for using in other hashtable key contexts.
//
// This provides a hashtable-specific extension point to implement equality
// comparison within a hashtable key context. By default, it will use
// `operator==` on the LHS and RHS operands if they are of the identical type.
// However, types can provide a dedicated customization point by implementing a
// free function that can be found by ADL for your type called
// `CarbonHashtableEq` with the following signature:
//
// ```cpp
// auto CarbonHashtableEq(const YourType& lhs, const YourType& rhs) -> bool;
// ```
//
// Any such overload will be able to override the default we provide for types
// that can compare with `==`. This overload may only compare two objects equal
// if the hash of those two objects are identical.
//
// This library also provides any customization points for LLVM or standard
// library types either lacking `operator==` or where that operator is not
// suitable for hashtables. For example, `llvm::APInt` and `llvm::APFloat` have
// custom equality comparisons provided through this extension point.
template <typename LeftT, typename RightT>
auto HashtableEq(const LeftT& lhs, const RightT& rhs) -> bool;
// Customizable context for keys in hashtables.
//
// This type or customizations matching its API are used with the data
// structures in `map.h` and `set.h`. By providing a custom version of the
// `KeyContext` type parameter to those data structures, users can provide
// either stateless or stateful customization of the two core hashtable key
// operations: hashing and comparison.
//
// The default for hashing uses Carbon's `hashing.h`. Customizations must still
// return a `HashCode` as defined there, and it needs to have the same core
// properties of hashes produced by the `hashing.h` infrastructure.
//
// The default for comparison is `operator==`. The `KeyEq` method is always
// called with a key *stored in the hashtable* as the second or "Rhs" parameter.
// This is to allow simplifying the set of overloads needed for heterogeneous
// contexts: only the first, LHS, parameter needs to support different lookup
// key types.
//
// Custom KeyContext types should have the the same API as the default type.
// They can choose to use templates to support heterogeneous key types or not as
// appropriate. The default context can also be used as a base class with only
// one or the other APIs customized.
//
// An important consideration is how the key context is constructed. When the
// key context can be default constructed, hashtable APIs trafficking in keys
// will have overloads that provide a default constructed key context. When the
// context is *not* default constructible, every API that accepts a key will
// also require a context argument to be called, and that argument will be used
// throughout that operation. The intent is to allow callers to provide stateful
// contexts to each API where it would be needed, while managing that state
// outside the hashtable. Often the needed state is trivially part of the
// caller's existing state and needn't be stored separately.
//
// Example for a stateful, customized key context for interned strings:
// ```cpp
// class InternedStringIndexKeyContext {
// public:
// InternedStringIndexKeyContext(
// llvm::ArrayRef<llvm::StringRef> interned_strings)
// : interned_strings_(interned_strings) {}
//
// auto HashKey(llvm::StringRef s) const -> HashCode {
// return HashValue(s);
// }
// auto HashKey(int index_key) const -> HashCode {
// return HashKey(interned_strings_[index_key]);
// }
//
// auto KeyEq(llvm::StringRef lhs, int rhs_index) const -> bool {
// return lhs == interned_strings_[rhs_index];
// }
// auto KeyEq(int lhs_index, int rhs_index) const -> bool {
// return KeyEq(interned_strings_[lhs_index], rhs_index);
// }
//
// private:
// llvm::ArrayRef<llvm::StringRef> interned_strings_;
// };
// ```
struct DefaultKeyContext {
template <typename AnyKeyT>
auto HashKey(const AnyKeyT& key) const -> HashCode;
template <typename AnyKeyT, typename TableKeyT>
auto KeyEq(const AnyKeyT& lhs_key, const TableKeyT& rhs_key) const -> bool;
};
// A CRTP mixin for a custom key context type that first translates keys to a
// different type, possibly using some state.
//
// Derived types should publicly inherit from this mixin and define overloads of
// the `TranslateKey` method as indicated below in its comment.
template <typename DerivedT>
class TranslatingKeyContext {
public:
// Derived types should provide one or more overloads that hide this function
// and perform translation for the key types which need it.
//
// For any key type, the context will check if there exists a callable
// `TranslateKey` function on the derived type. If so, that function will be
// called and the result used for hashing or comparison. If not, the key will
// be used directly. The derived type doesn't need to and shouldn't provide a
// default no-op overload. Instead, for any types that need no translation, it
// should ensure no overload is viable.
//
// Note that this function should be *hidden* by the derived overloads. It is
// provided here to help detect typos or misspellings or cases where no
// overload is provided at all.
template <typename TranslateKeyT>
auto TranslateKey(const TranslateKeyT& /*key*/) const -> int {
// A static_assert that will fail on any actual instantiation (it can't be
// instantiated with a void type). We have to make this dependent as
// Clang-16 will fail to compile even when the definition is never
// instantiated otherwise.
static_assert(
std::same_as<TranslateKeyT, void>,
"No `TranslateKey` overload was provided by the derived type!");
}
template <typename AnyKeyT>
auto HashKey(const AnyKeyT& key) const -> HashCode;
template <typename AnyKeyT, typename TableKeyT>
auto KeyEq(const AnyKeyT& lhs_key, const TableKeyT& rhs_key) const -> bool;
};
////////////////////////////////////////////////////////////////////////////////
//
// Only implementation details below this point.
//
////////////////////////////////////////////////////////////////////////////////
namespace InternalHashtableEqDispatch {
inline auto CarbonHashtableEq(const llvm::APInt& lhs, const llvm::APInt& rhs)
-> bool {
return lhs.getBitWidth() == rhs.getBitWidth() && lhs == rhs;
}
inline auto CarbonHashtableEq(const llvm::APFloat& lhs,
const llvm::APFloat& rhs) -> bool {
return lhs.bitwiseIsEqual(rhs);
}
// The calling convention of `StringBytesNe`. Where it's available, a call
// preserves more of the caller's registers than the default convention does:
// every general register but the result's and one scratch register on x86-64,
// and seven more of them on AArch64. Callers then don't have to save and
// restore that much of their own state around each comparison.
#if defined(__x86_64__) || defined(__aarch64__)
#define CARBON_STRING_BYTES_NE_CC [[clang::preserve_most]]
#else
#define CARBON_STRING_BYTES_NE_CC
#endif
// Returns zero if the `size` bytes at `lhs` and `rhs` are equal, and a non-zero
// value otherwise. Which non-zero value is unspecified, so callers may only
// compare the result with zero. It's like `bcmp`, but faster for short and
// medium sizes. It's out of line, which keeps callers small enough to inline,
// and `pure`, which lets callers keep values loaded from memory in registers
// across the call.
[[gnu::pure]] CARBON_STRING_BYTES_NE_CC auto StringBytesNe(const std::byte* lhs,
const std::byte* rhs,
size_t size)
-> uint64_t;
inline auto CarbonHashtableEq(llvm::StringRef lhs, llvm::StringRef rhs)
-> bool {
return lhs.size() == rhs.size() &&
StringBytesNe(reinterpret_cast<const std::byte*>(lhs.data()),
reinterpret_cast<const std::byte*>(rhs.data()),
lhs.size()) == 0;
}
inline auto CarbonHashtableEq(llvm::StringRef lhs, const std::string& rhs)
-> bool {
return CarbonHashtableEq(lhs, llvm::StringRef(rhs));
}
inline auto CarbonHashtableEq(const std::string& lhs, const std::string& rhs)
-> bool {
return CarbonHashtableEq(llvm::StringRef(lhs), llvm::StringRef(rhs));
}
template <typename T>
inline auto CarbonHashtableEq(llvm::MutableArrayRef<T> lhs,
llvm::ArrayRef<T> rhs) -> bool {
return lhs == rhs;
}
template <typename LHS, typename RHS>
inline auto CarbonHashtableEq(const LHS& lhs, const RHS& rhs) -> bool
requires(requires {
{ CarbonHashtableEq(rhs, lhs) } -> std::convertible_to<bool>;
})
{
return CarbonHashtableEq(rhs, lhs);
}
// Provides symmetric equality so the `CarbonHashtableEq` operands aren't
// ordered.
//
// If this template proves problematic in any way, we can revisit it - the
// `CarbonHashtableEq` functions don't really need to be symmetric, since they
// generally represent an implicit conversion which is often only one-way (eg:
// MutableArrayRef converts to ArrayRef, but not the other way around) - but
// documenting/describing that asymmetry felt a little awkward too - so maybe
// this template is an OK solution for now.
template <typename T>
inline auto CarbonHashtableEq(const T& lhs, const T& rhs) -> bool
requires(requires {
{ lhs == rhs } -> std::convertible_to<bool>;
})
{
return lhs == rhs;
}
template <typename LeftT, typename RightT>
inline auto DispatchImpl(const LeftT& lhs, const RightT& rhs) -> bool {
// This unqualified call will find both the overloads in our internal
// namespace above and ADL-found functions within an associated namespace for
// either `LeftT` or `RightT`.
return CarbonHashtableEq(lhs, rhs);
}
} // namespace InternalHashtableEqDispatch
template <typename LeftT, typename RightT>
inline auto HashtableEq(const LeftT& lhs, const RightT& rhs) -> bool {
return InternalHashtableEqDispatch::DispatchImpl(lhs, rhs);
}
template <typename AnyKeyT>
auto DefaultKeyContext::HashKey(const AnyKeyT& key) const -> HashCode {
return HashValue(key);
}
template <typename AnyKeyT, typename TableKeyT>
auto DefaultKeyContext::KeyEq(const AnyKeyT& lhs_key,
const TableKeyT& rhs_key) const -> bool {
return HashtableEq(lhs_key, rhs_key);
}
template <typename DerivedT>
template <typename AnyKeyT>
auto TranslatingKeyContext<DerivedT>::HashKey(const AnyKeyT& key) const
-> HashCode {
const DerivedT& self = *static_cast<const DerivedT*>(this);
if constexpr (requires { self.TranslateKey(key); }) {
return HashValue(self.TranslateKey(key));
} else {
return HashValue(key);
}
}
template <typename DerivedT>
template <typename AnyKeyT, typename TableKeyT>
auto TranslatingKeyContext<DerivedT>::KeyEq(const AnyKeyT& lhs_key,
const TableKeyT& rhs_key) const
-> bool {
const DerivedT& self = *static_cast<const DerivedT*>(this);
// Because we don't want to make no-op calls and potentially struggle with
// temporary lifetimes at runtime we have to fully expand the 4 states.
constexpr bool TranslateLhs = requires { self.TranslateKey(lhs_key); };
constexpr bool TranslateRhs = requires { self.TranslateKey(rhs_key); };
if constexpr (TranslateLhs && TranslateRhs) {
return HashtableEq(self.TranslateKey(lhs_key), self.TranslateKey(rhs_key));
} else if constexpr (TranslateLhs) {
return HashtableEq(self.TranslateKey(lhs_key), rhs_key);
} else if constexpr (TranslateRhs) {
return HashtableEq(lhs_key, self.TranslateKey(rhs_key));
} else {
return HashtableEq(lhs_key, rhs_key);
}
}
} // namespace Carbon
#endif // CARBON_COMMON_HASHTABLE_KEY_CONTEXT_H_