1//===-- llvm/ADT/Hashing.h - Utilities for hashing --------------*- C++ -*-===//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//===----------------------------------------------------------------------===//
9// This file implements the newly proposed standard C++ interfaces for hashing
10// arbitrary data and building hash functions for user-defined types. This
11// interface was originally proposed in N3333[1] and is currently under review
12// for inclusion in a future TR and/or standard.
14// The primary interfaces provide are comprised of one type and three functions:
16// -- 'hash_code' class is an opaque type representing the hash code for some
17// data. It is the intended product of hashing, and can be used to implement
18// hash tables, checksumming, and other common uses of hashes. It is not an
19// integer type (although it can be converted to one) because it is risky
20// to assume much about the internals of a hash_code. In particular, each
21// execution of the program has a high probability of producing a different
22// hash_code for a given input. Thus their values are not stable to save or
23// persist, and should only be used during the execution for the
24// construction of hashing datastructures.
26// -- 'hash_value' is a function designed to be overloaded for each
27// user-defined type which wishes to be used within a hashing context. It
28// should be overloaded within the user-defined type's namespace and found
29// via ADL. Overloads for primitive types are provided by this library.
31// -- 'hash_combine' and 'hash_combine_range' are functions designed to aid
32// programmers in easily and intuitively combining a set of data into
33// a single hash_code for their object. They should only logically be used
34// within the implementation of a 'hash_value' routine or similar context.
36// Note that 'hash_combine_range' contains very special logic for hashing
37// a contiguous array of integers or pointers. This logic is *extremely* fast,
38// on a modern Intel "Gainestown" Xeon (Nehalem uarch) @2.2 GHz, these were
39// benchmarked at over 6.5 GiB/s for large keys, and <20 cycles/hash for keys
42//===----------------------------------------------------------------------===//
44#ifndef LLVM_ADT_HASHING_H
45#define LLVM_ADT_HASHING_H
48#include "llvm/Config/abi-breaking.h"
62template <
typename T,
typename Enable>
struct DenseMapInfo;
64/// An opaque object representing a hash code.
66/// This object represents the result of hashing some entity. It is intended to
67/// be used to implement hashtables or other hashing-based data structures.
68/// While it wraps and exposes a numeric value, this value should not be
69/// trusted to be stable or predictable across processes or executions.
71/// In order to obtain the hash_code for an object 'x':
73/// using llvm::hash_value;
74/// llvm::hash_code code = hash_value(x);
80 /// Default construct a hash_code.
81 /// Note that this leaves the value uninitialized.
84 /// Form a hash code directly from a numerical value.
87 /// Convert the hash code to its numerical value for use.
88 /*explicit*/ operator size_t()
const {
return value; }
91 return lhs.value == rhs.value;
94 return lhs.value != rhs.value;
97 /// Allow a hash_code to be directly run through hash_value.
101/// Compute a hash_code for any integer value.
103/// Note that this function is intended to compute the same hash_code for
104/// a particular value without regard to the pre-promotion type. This is in
105/// contrast to hash_combine which may produce different hash_codes for
106/// differing argument types even if they would implicit promote to a common
107/// type without changing the value.
109std::enable_if_t<is_integral_or_enum<T>::value, hash_code>
hash_value(
T value);
111/// Compute a hash_code for a pointer's address.
113/// N.B.: This hashes the *address*. Not the value and not the type.
114template <
typename T> hash_code
hash_value(
const T *ptr);
116/// Compute a hash_code for a pair of objects.
117template <
typename T,
typename U>
118hash_code
hash_value(
const std::pair<T, U> &arg);
120/// Compute a hash_code for a tuple.
121template <
typename... Ts>
122hash_code
hash_value(
const std::tuple<Ts...> &arg);
124/// Compute a hash_code for a standard string.
126hash_code
hash_value(
const std::basic_string<T> &arg);
128/// Compute a hash_code for a standard string.
129template <
typename T> hash_code
hash_value(
const std::optional<T> &arg);
131// All of the implementation details of actually computing the various hash
132// code values are held within this namespace. These routines are included in
133// the header file mainly to allow inlining and constant propagation.
139 std::memcpy(&result, p,
sizeof(result));
147 std::memcpy(&result, p,
sizeof(result));
153/// Some primes between 2^63 and 2^64 for various uses.
159/// Bitwise right rotate.
160/// Normally this will compile to a single instruction, especially if the
161/// shift is a manifest constant.
163 // Avoid shifting by 64: doing so yields an undefined result.
164 return shift == 0 ? val : ((val >> shift) | (val << (64 - shift)));
168 return val ^ (val >> 47);
172 // Murmur-inspired hashing.
173 const uint64_t kMul = 0x9ddfea08eb382d69ULL;
236 if (length >= 4 && length <= 8)
238 if (length > 8 && length <= 16)
240 if (length > 16 && length <= 32)
250/// The intermediate state used during hashing.
251/// Currently, the algorithm for computing hash codes is based on CityHash and
252/// keeps 56 bytes of arbitrary state.
256 /// Create a new hash_state structure and initialize it based on the
257 /// seed and the first 64-byte chunk.
258 /// This effectively performs the initial mix.
272 /// Mix 32-bytes from the input sequence into the 16-bytes of 'a'
273 /// and 'b', including whatever is already in 'a' and 'b'.
284 /// Mix in a 64-byte buffer of data.
285 /// We mix all 64 bytes even when the chunk length is smaller, but we
286 /// record the actual length.
302 /// Compute the final 64-bit hash code value based on the current
303 /// state and the length of bytes hashed.
310/// In LLVM_ENABLE_ABI_BREAKING_CHECKS builds, the seed is non-deterministic
311/// per process (address of a function in LLVMSupport) to prevent having users
312/// depend on the particular hash values. On platforms without ASLR, this is
313/// still likely non-deterministic per build.
315#if LLVM_ENABLE_ABI_BREAKING_CHECKS
319 return 0xff51afd7ed558ccdULL;
324/// Trait to indicate whether a type's bits can be hashed directly.
326/// A type trait which is true if we want to combine values for hashing by
327/// reading the underlying data. It is false if values of this type must
328/// first be passed to hash_value, and the resulting hash_codes combined.
330// FIXME: We want to replace is_integral_or_enum and is_pointer here with
331// a predicate which asserts that comparing the underlying storage of two
332// values of the type for equality is equivalent to comparing the two values
333// for equality. For all the platforms we care about, this holds for integers
334// and pointers, but there are platforms where it doesn't and we would like to
335// support user-defined types which happen to satisfy this property.
338 std::is_pointer<T>::value) &&
339 64 % sizeof(T) == 0)> {};
341// Special case std::pair to detect when both types are viable and when there
342// is no alignment-derived padding in the pair. This is a bit of a lie because
343// std::pair isn't truly POD, but it's close enough in all reasonable
344// implementations for our use case of hashing the underlying data.
345template <
typename T,
typename U>
347 : std::bool_constant<(is_hashable_data<T>::value &&
348 is_hashable_data<U>::value &&
349 (sizeof(T) + sizeof(U)) == sizeof(std::pair<T, U>))> {
352/// Helper to get the hashable data representation for a type.
355 // This variant is enabled when the type itself can be used.
358 // This variant is enabled when we must first call hash_value and use the
359 // result as our data.
361 return static_cast<size_t>(
hash_value(value));
365/// Helper to store data from a value into a buffer and advance the
366/// pointer into that buffer.
368/// This routine first checks whether there is enough space in the provided
369/// buffer, and if not immediately returns false. If there is space, it
370/// copies the underlying bytes of value into the buffer, advances the
371/// buffer_ptr past the copied bytes, and returns true.
375 size_t store_size =
sizeof(value) - offset;
376 if (buffer_ptr + store_size > buffer_end)
378 const char *value_data =
reinterpret_cast<const char *
>(&value);
379 std::memcpy(buffer_ptr, value_data + offset, store_size);
380 buffer_ptr += store_size;
384/// Implement the combining of integral values into a hash_code.
386/// This overload is selected when the value type of the iterator is
387/// integral. Rather than computing a hash_code for each object and then
388/// combining them, this (as an optimization) directly combines the integers.
389template <
typename InputIteratorT>
392 char buffer[64], *buffer_ptr = buffer;
393 char *
const buffer_end = std::end(buffer);
398 return hash_short(buffer, buffer_ptr - buffer, seed);
399 assert(buffer_ptr == buffer_end);
403 while (first != last) {
404 // Fill up the buffer. We don't clear it, which re-mixes the last round
405 // when only a partial 64-byte chunk is left.
411 // Rotate the buffer if we did a partial fill in order to simulate doing
412 // a mix of the last 64-bytes. That is how the algorithm works when we
413 // have a contiguous byte sequence, and we want to emulate that here.
414 std::rotate(buffer, buffer_ptr, buffer_end);
416 // Mix this chunk into the current state.
418 length += buffer_ptr - buffer;
424/// Implement the combining of integral values into a hash_code.
426/// This overload is selected when the value type of the iterator is integral
427/// and when the input iterator is actually a pointer. Rather than computing
428/// a hash_code for each object and then combining them, this (as an
429/// optimization) directly combines the integers. Also, because the integers
430/// are stored in contiguous memory, this routine avoids copying each value
431/// and directly reads from the underlying memory.
432template <
typename ValueT>
433std::enable_if_t<is_hashable_data<ValueT>::value,
hash_code>
436 const char *s_begin =
reinterpret_cast<const char *
>(first);
437 const char *s_end =
reinterpret_cast<const char *
>(last);
438 const size_t length = std::distance(s_begin, s_end);
442 const char *s_aligned_end = s_begin + (length & ~63);
445 while (s_begin != s_aligned_end) {
450 state.mix(s_end - 64);
452 return state.finalize(length);
456}
// namespace hashing
459/// Compute a hash_code for a sequence of values.
461/// This hashes a sequence of values. It produces the same hash_code as
462/// 'hash_combine(a, b, c, ...)', but can run over arbitrary sized sequences
463/// and is significantly faster given pointers and types which can be hashed as
464/// a sequence of bytes.
465template <
typename InputIteratorT>
467 return ::llvm::hashing::detail::hash_combine_range_impl(first, last);
470// A wrapper for hash_combine_range above.
475// Implementation details for hash_combine.
479/// Helper class to manage the recursive combining of hash_combine
482/// This class exists to manage the state and various calls involved in the
483/// recursive combining of arguments used in hash_combine. It is particularly
484/// useful at minimizing the code in the recursive calls to ease the pain
485/// caused by a lack of variadic functions.
492 /// Construct a recursive hash combining helper.
494 /// This sets up the state for a recursive hash combine, including getting
495 /// the seed and buffer setup.
499 /// Combine one chunk of data into the current in-flight hash.
501 /// This merges one chunk of data into the hash. First it tries to buffer
502 /// the data. If the buffer is full, it hashes the buffer into its
503 /// hash_state, empties it, and then merges the new chunk in. This also
504 /// handles cases where the data straddles the end of the buffer.
505 template <
typename T>
508 // Check for skew which prevents the buffer from being packed, and do
509 // a partial store into the buffer to fill it. This is only a concern
510 // with the variadic combine because that formation can have varying
512 size_t partial_store_size = buffer_end - buffer_ptr;
513 std::memcpy(buffer_ptr, &
data, partial_store_size);
515 // If the store fails, our buffer is full and ready to hash. We have to
516 // either initialize the hash state (on the first full buffer) or mix
517 // this buffer into the existing hash state. Length tracks the *hashed*
518 // length, not the buffered length.
523 // Mix this chunk into the current state and bump length up by 64.
527 // Reset the buffer_ptr to the head of the buffer for the next chunk of
531 // Try again to store into the buffer -- this cannot fail as we only
532 // store types smaller than the buffer.
540 /// Recursive, variadic combining method.
542 /// This function recurses through each argument, combining that argument
543 /// into a single hash.
544 template <
typename T,
typename ...Ts>
546 const T &arg,
const Ts &...
args) {
549 // Recurse to the next argument.
550 return combine(length, buffer_ptr, buffer_end,
args...);
553 /// Base case for recursive, variadic combining.
555 /// The base case when combining arguments recursively is reached when all
556 /// arguments have been handled. It flushes the remaining buffer and
557 /// constructs a hash_code.
559 // Check whether the entire set of values fit in the buffer. If so, we'll
560 // use the optimized short hashing routine and skip state entirely.
564 // Mix the final buffer, rotating it if we did a partial fill in order to
565 // simulate doing a mix of the last 64-bytes. That is how the algorithm
566 // works when we have a contiguous byte sequence, and we want to emulate
568 std::rotate(
buffer, buffer_ptr, buffer_end);
570 // Mix this chunk into the current state.
572 length += buffer_ptr -
buffer;
574 return state.finalize(length);
579}
// namespace hashing
581/// Combine values into a single hash_code.
583/// This routine accepts a varying number of arguments of any type. It will
584/// attempt to combine them into a single hash_code. For user-defined types it
585/// attempts to call a \see hash_value overload (via ADL) for the type. For
586/// integer and pointer types it directly combines their data into the
587/// resulting hash_code.
589/// The result is suitable for returning from a user's hash_value
590/// *implementation* for their user-defined type. Consumers of a type should
591/// *not* call this routine, they should instead call 'hash_value'.
593 // Recursively hash each argument using a helper class.
598// Implementation details for implementations of hash_value overloads provided
603/// Helper to hash the value of a single integer.
605/// Overloads for smaller integer types are not provided to ensure consistent
606/// behavior in the presence of integral promotions. Essentially,
607/// "hash_value('4')" and "hash_value('0' + 4)" should be the same.
609 // Similar to hash_4to8_bytes but using a seed instead of length.
611 const char *s =
reinterpret_cast<const char *
>(&value);
617}
// namespace hashing
619// Declared and documented above, but defined here so that any of the hashing
620// infrastructure is available.
623 return ::llvm::hashing::detail::hash_integer_value(
627// Declared and documented above, but defined here so that any of the hashing
628// infrastructure is available.
630 return ::llvm::hashing::detail::hash_integer_value(
631 reinterpret_cast<uintptr_t
>(ptr));
634// Declared and documented above, but defined here so that any of the hashing
635// infrastructure is available.
636template <
typename T,
typename U>
642 return std::apply([](
const auto &...xs) {
return hash_combine(xs...); }, arg);
645// Declared and documented above, but defined here so that any of the hashing
646// infrastructure is available.
660 return static_cast<unsigned>(size_t(val));
667/// Implement std::hash so that hash_code can be used in STL containers.
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
An opaque object representing a hash code.
friend size_t hash_value(const hash_code &code)
Allow a hash_code to be directly run through hash_value.
friend bool operator==(const hash_code &lhs, const hash_code &rhs)
friend bool operator!=(const hash_code &lhs, const hash_code &rhs)
hash_code(size_t value)
Form a hash code directly from a numerical value.
hash_code()=default
Default construct a hash_code.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
uint64_t hash_1to3_bytes(const char *s, size_t len, uint64_t seed)
bool store_and_advance(char *&buffer_ptr, char *buffer_end, const T &value, size_t offset=0)
Helper to store data from a value into a buffer and advance the pointer into that buffer.
uint64_t hash_9to16_bytes(const char *s, size_t len, uint64_t seed)
uint64_t hash_4to8_bytes(const char *s, size_t len, uint64_t seed)
hash_code hash_combine_range_impl(InputIteratorT first, InputIteratorT last)
Implement the combining of integral values into a hash_code.
hash_code hash_integer_value(uint64_t value)
Helper to hash the value of a single integer.
uint64_t rotate(uint64_t val, size_t shift)
Bitwise right rotate.
static constexpr uint64_t k2
auto get_hashable_data(const T &value)
Helper to get the hashable data representation for a type.
uint64_t fetch64(const char *p)
uint64_t hash_17to32_bytes(const char *s, size_t len, uint64_t seed)
static constexpr uint64_t k1
uint64_t get_execution_seed()
In LLVM_ENABLE_ABI_BREAKING_CHECKS builds, the seed is non-deterministic per process (address of a fu...
uint32_t fetch32(const char *p)
static constexpr uint64_t k3
uint64_t hash_short(const char *s, size_t length, uint64_t seed)
static constexpr uint64_t k0
Some primes between 2^63 and 2^64 for various uses.
uint64_t shift_mix(uint64_t val)
uint64_t hash_33to64_bytes(const char *s, size_t len, uint64_t seed)
uint64_t hash_16_bytes(uint64_t low, uint64_t high)
constexpr bool IsBigEndianHost
void swapByteOrder(T &Value)
This is an optimization pass for GlobalISel generic memory operations.
constexpr T rotr(T V, int R)
hash_code hash_value(const FixedPointSemantics &Val)
constexpr auto adl_begin(RangeT &&range) -> decltype(adl_detail::begin_impl(std::forward< RangeT >(range)))
Returns the begin iterator to range using std::begin and function found through Argument-Dependent Lo...
LLVM_ABI void install_fatal_error_handler(fatal_error_handler_t handler, void *user_data=nullptr)
install_fatal_error_handler - Installs a new error handler to be used whenever a serious (non-recover...
constexpr auto adl_end(RangeT &&range) -> decltype(adl_detail::end_impl(std::forward< RangeT >(range)))
Returns the end iterator to range using std::end and functions found through Argument-Dependent Looku...
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Implement std::hash so that hash_code can be used in STL containers.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
static bool isEqual(hash_code LHS, hash_code RHS)
static hash_code getEmptyKey()
static unsigned getHashValue(hash_code val)
static hash_code getTombstoneKey()
An information struct used to provide DenseMap with the various necessary components for a given valu...
Helper class to manage the recursive combining of hash_combine arguments.
hash_code combine(size_t length, char *buffer_ptr, char *buffer_end)
Base case for recursive, variadic combining.
char * combine_data(size_t &length, char *buffer_ptr, char *buffer_end, T data)
Combine one chunk of data into the current in-flight hash.
hash_code combine(size_t length, char *buffer_ptr, char *buffer_end, const T &arg, const Ts &...args)
Recursive, variadic combining method.
hash_combine_recursive_helper()
Construct a recursive hash combining helper.
The intermediate state used during hashing.
static hash_state create(const char *s, uint64_t seed)
Create a new hash_state structure and initialize it based on the seed and the first 64-byte chunk.
uint64_t finalize(size_t length)
Compute the final 64-bit hash code value based on the current state and the length of bytes hashed.
static void mix_32_bytes(const char *s, uint64_t &a, uint64_t &b)
Mix 32-bytes from the input sequence into the 16-bytes of 'a' and 'b', including whatever is already ...
void mix(const char *s)
Mix in a 64-byte buffer of data.
Trait to indicate whether a type's bits can be hashed directly.
size_t operator()(llvm::hash_code const &Val) const