LCOV - code coverage report
Current view: top level - include/llvm/ADT - Hashing.h (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 183 184 99.5 %
Date: 2017-09-14 15:23:50 Functions: 533 639 83.4 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===-- llvm/ADT/Hashing.h - Utilities for hashing --------------*- C++ -*-===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This file implements the newly proposed standard C++ interfaces for hashing
      11             : // arbitrary data and building hash functions for user-defined types. This
      12             : // interface was originally proposed in N3333[1] and is currently under review
      13             : // for inclusion in a future TR and/or standard.
      14             : //
      15             : // The primary interfaces provide are comprised of one type and three functions:
      16             : //
      17             : //  -- 'hash_code' class is an opaque type representing the hash code for some
      18             : //     data. It is the intended product of hashing, and can be used to implement
      19             : //     hash tables, checksumming, and other common uses of hashes. It is not an
      20             : //     integer type (although it can be converted to one) because it is risky
      21             : //     to assume much about the internals of a hash_code. In particular, each
      22             : //     execution of the program has a high probability of producing a different
      23             : //     hash_code for a given input. Thus their values are not stable to save or
      24             : //     persist, and should only be used during the execution for the
      25             : //     construction of hashing datastructures.
      26             : //
      27             : //  -- 'hash_value' is a function designed to be overloaded for each
      28             : //     user-defined type which wishes to be used within a hashing context. It
      29             : //     should be overloaded within the user-defined type's namespace and found
      30             : //     via ADL. Overloads for primitive types are provided by this library.
      31             : //
      32             : //  -- 'hash_combine' and 'hash_combine_range' are functions designed to aid
      33             : //      programmers in easily and intuitively combining a set of data into
      34             : //      a single hash_code for their object. They should only logically be used
      35             : //      within the implementation of a 'hash_value' routine or similar context.
      36             : //
      37             : // Note that 'hash_combine_range' contains very special logic for hashing
      38             : // a contiguous array of integers or pointers. This logic is *extremely* fast,
      39             : // on a modern Intel "Gainestown" Xeon (Nehalem uarch) @2.2 GHz, these were
      40             : // benchmarked at over 6.5 GiB/s for large keys, and <20 cycles/hash for keys
      41             : // under 32-bytes.
      42             : //
      43             : //===----------------------------------------------------------------------===//
      44             : 
      45             : #ifndef LLVM_ADT_HASHING_H
      46             : #define LLVM_ADT_HASHING_H
      47             : 
      48             : #include "llvm/Support/DataTypes.h"
      49             : #include "llvm/Support/Host.h"
      50             : #include "llvm/Support/SwapByteOrder.h"
      51             : #include "llvm/Support/type_traits.h"
      52             : #include <algorithm>
      53             : #include <cassert>
      54             : #include <cstring>
      55             : #include <string>
      56             : #include <utility>
      57             : 
      58             : namespace llvm {
      59             : 
      60             : /// \brief An opaque object representing a hash code.
      61             : ///
      62             : /// This object represents the result of hashing some entity. It is intended to
      63             : /// be used to implement hashtables or other hashing-based data structures.
      64             : /// While it wraps and exposes a numeric value, this value should not be
      65             : /// trusted to be stable or predictable across processes or executions.
      66             : ///
      67             : /// In order to obtain the hash_code for an object 'x':
      68             : /// \code
      69             : ///   using llvm::hash_value;
      70             : ///   llvm::hash_code code = hash_value(x);
      71             : /// \endcode
      72             : class hash_code {
      73             :   size_t value;
      74             : 
      75             : public:
      76             :   /// \brief Default construct a hash_code.
      77             :   /// Note that this leaves the value uninitialized.
      78             :   hash_code() = default;
      79             : 
      80             :   /// \brief Form a hash code directly from a numerical value.
      81        4497 :   hash_code(size_t value) : value(value) {}
      82             : 
      83             :   /// \brief Convert the hash code to its numerical value for use.
      84   107461893 :   /*explicit*/ operator size_t() const { return value; }
      85             : 
      86             :   friend bool operator==(const hash_code &lhs, const hash_code &rhs) {
      87          69 :     return lhs.value == rhs.value;
      88             :   }
      89             :   friend bool operator!=(const hash_code &lhs, const hash_code &rhs) {
      90          30 :     return lhs.value != rhs.value;
      91             :   }
      92             : 
      93             :   /// \brief Allow a hash_code to be directly run through hash_value.
      94    31394758 :   friend size_t hash_value(const hash_code &code) { return code.value; }
      95             : };
      96             : 
      97             : /// \brief Compute a hash_code for any integer value.
      98             : ///
      99             : /// Note that this function is intended to compute the same hash_code for
     100             : /// a particular value without regard to the pre-promotion type. This is in
     101             : /// contrast to hash_combine which may produce different hash_codes for
     102             : /// differing argument types even if they would implicit promote to a common
     103             : /// type without changing the value.
     104             : template <typename T>
     105             : typename std::enable_if<is_integral_or_enum<T>::value, hash_code>::type
     106             : hash_value(T value);
     107             : 
     108             : /// \brief Compute a hash_code for a pointer's address.
     109             : ///
     110             : /// N.B.: This hashes the *address*. Not the value and not the type.
     111             : template <typename T> hash_code hash_value(const T *ptr);
     112             : 
     113             : /// \brief Compute a hash_code for a pair of objects.
     114             : template <typename T, typename U>
     115             : hash_code hash_value(const std::pair<T, U> &arg);
     116             : 
     117             : /// \brief Compute a hash_code for a standard string.
     118             : template <typename T>
     119             : hash_code hash_value(const std::basic_string<T> &arg);
     120             : 
     121             : 
     122             : /// \brief Override the execution seed with a fixed value.
     123             : ///
     124             : /// This hashing library uses a per-execution seed designed to change on each
     125             : /// run with high probability in order to ensure that the hash codes are not
     126             : /// attackable and to ensure that output which is intended to be stable does
     127             : /// not rely on the particulars of the hash codes produced.
     128             : ///
     129             : /// That said, there are use cases where it is important to be able to
     130             : /// reproduce *exactly* a specific behavior. To that end, we provide a function
     131             : /// which will forcibly set the seed to a fixed value. This must be done at the
     132             : /// start of the program, before any hashes are computed. Also, it cannot be
     133             : /// undone. This makes it thread-hostile and very hard to use outside of
     134             : /// immediately on start of a simple program designed for reproducible
     135             : /// behavior.
     136             : void set_fixed_execution_hash_seed(size_t fixed_value);
     137             : 
     138             : 
     139             : // All of the implementation details of actually computing the various hash
     140             : // code values are held within this namespace. These routines are included in
     141             : // the header file mainly to allow inlining and constant propagation.
     142             : namespace hashing {
     143             : namespace detail {
     144             : 
     145             : inline uint64_t fetch64(const char *p) {
     146             :   uint64_t result;
     147  1447325632 :   memcpy(&result, p, sizeof(result));
     148             :   if (sys::IsBigEndianHost)
     149             :     sys::swapByteOrder(result);
     150             :   return result;
     151             : }
     152             : 
     153             : inline uint32_t fetch32(const char *p) {
     154             :   uint32_t result;
     155   114995868 :   memcpy(&result, p, sizeof(result));
     156             :   if (sys::IsBigEndianHost)
     157             :     sys::swapByteOrder(result);
     158             :   return result;
     159             : }
     160             : 
     161             : /// Some primes between 2^63 and 2^64 for various uses.
     162             : static const uint64_t k0 = 0xc3a5c85c97cb3127ULL;
     163             : static const uint64_t k1 = 0xb492b66fbe98f273ULL;
     164             : static const uint64_t k2 = 0x9ae16a3b2f90404fULL;
     165             : static const uint64_t k3 = 0xc949d7c7509e6557ULL;
     166             : 
     167             : /// \brief Bitwise right rotate.
     168             : /// Normally this will compile to a single instruction, especially if the
     169             : /// shift is a manifest constant.
     170             : inline uint64_t rotate(uint64_t val, size_t shift) {
     171             :   // Avoid shifting by 64: doing so yields an undefined result.
     172   989427593 :   return shift == 0 ? val : ((val >> shift) | (val << (64 - shift)));
     173             : }
     174             : 
     175             : inline uint64_t shift_mix(uint64_t val) {
     176   106544367 :   return val ^ (val >> 47);
     177             : }
     178             : 
     179             : inline uint64_t hash_16_bytes(uint64_t low, uint64_t high) {
     180             :   // Murmur-inspired hashing.
     181   292247885 :   const uint64_t kMul = 0x9ddfea08eb382d69ULL;
     182   292247885 :   uint64_t a = (low ^ high) * kMul;
     183   292247885 :   a ^= (a >> 47);
     184   292247885 :   uint64_t b = (high ^ a) * kMul;
     185   292247885 :   b ^= (b >> 47);
     186   292247885 :   b *= kMul;
     187             :   return b;
     188             : }
     189             : 
     190             : inline uint64_t hash_1to3_bytes(const char *s, size_t len, uint64_t seed) {
     191       29124 :   uint8_t a = s[0];
     192       29124 :   uint8_t b = s[len >> 1];
     193       29124 :   uint8_t c = s[len - 1];
     194       29124 :   uint32_t y = static_cast<uint32_t>(a) + (static_cast<uint32_t>(b) << 8);
     195       29124 :   uint32_t z = len + (static_cast<uint32_t>(c) << 2);
     196       58248 :   return shift_mix(y * k2 ^ z * k3 ^ seed) * k2;
     197             : }
     198             : 
     199             : inline uint64_t hash_4to8_bytes(const char *s, size_t len, uint64_t seed) {
     200    57497421 :   uint64_t a = fetch32(s);
     201   172492263 :   return hash_16_bytes(len + (a << 3), seed ^ fetch32(s + len - 4));
     202             : }
     203             : 
     204             : inline uint64_t hash_9to16_bytes(const char *s, size_t len, uint64_t seed) {
     205    71653021 :   uint64_t a = fetch64(s);
     206   143306042 :   uint64_t b = fetch64(s + len - 8);
     207   214959063 :   return hash_16_bytes(seed ^ a, rotate(b + len, len)) ^ b;
     208             : }
     209             : 
     210   103072317 : inline uint64_t hash_17to32_bytes(const char *s, size_t len, uint64_t seed) {
     211   103072317 :   uint64_t a = fetch64(s) * k1;
     212   206144634 :   uint64_t b = fetch64(s + 8);
     213   206144634 :   uint64_t c = fetch64(s + len - 8) * k2;
     214   206144634 :   uint64_t d = fetch64(s + len - 16) * k0;
     215   309216951 :   return hash_16_bytes(rotate(a - b, 43) + rotate(c ^ seed, 30) + d,
     216   309216951 :                        a + rotate(b ^ k3, 20) - c + len + seed);
     217             : }
     218             : 
     219    35251013 : inline uint64_t hash_33to64_bytes(const char *s, size_t len, uint64_t seed) {
     220    70502026 :   uint64_t z = fetch64(s + 24);
     221    70502026 :   uint64_t a = fetch64(s) + (len + fetch64(s + len - 16)) * k0;
     222    70502026 :   uint64_t b = rotate(a + z, 52);
     223    35251013 :   uint64_t c = rotate(a, 37);
     224    70502026 :   a += fetch64(s + 8);
     225    35251013 :   c += rotate(a, 7);
     226    70502026 :   a += fetch64(s + 16);
     227    35251013 :   uint64_t vf = a + z;
     228    35251013 :   uint64_t vs = b + rotate(a, 31) + c;
     229   105753039 :   a = fetch64(s + 16) + fetch64(s + len - 32);
     230    70502026 :   z = fetch64(s + len - 8);
     231    70502026 :   b = rotate(a + z, 52);
     232    35251013 :   c = rotate(a, 37);
     233    70502026 :   a += fetch64(s + len - 24);
     234    35251013 :   c += rotate(a, 7);
     235    70502026 :   a += fetch64(s + len - 16);
     236    35251013 :   uint64_t wf = a + z;
     237    35251013 :   uint64_t ws = b + rotate(a, 31) + c;
     238    70502026 :   uint64_t r = shift_mix((vf + ws) * k2 + (wf + vs) * k0);
     239    70502026 :   return shift_mix((seed ^ (r * k0)) + vs) * k2;
     240             : }
     241             : 
     242   280479719 : inline uint64_t hash_short(const char *s, size_t length, uint64_t seed) {
     243   280479719 :   if (length >= 4 && length <= 8)
     244    57497421 :     return hash_4to8_bytes(s, length, seed);
     245   222982298 :   if (length > 8 && length <= 16)
     246    71653021 :     return hash_9to16_bytes(s, length, seed);
     247   151329277 :   if (length > 16 && length <= 32)
     248   103072317 :     return hash_17to32_bytes(s, length, seed);
     249    48256960 :   if (length > 32)
     250    35251012 :     return hash_33to64_bytes(s, length, seed);
     251    13005948 :   if (length != 0)
     252       29124 :     return hash_1to3_bytes(s, length, seed);
     253             : 
     254    12976824 :   return k2 ^ seed;
     255             : }
     256             : 
     257             : /// \brief The intermediate state used during hashing.
     258             : /// Currently, the algorithm for computing hash codes is based on CityHash and
     259             : /// keeps 56 bytes of arbitrary state.
     260             : struct hash_state {
     261             :   uint64_t h0, h1, h2, h3, h4, h5, h6;
     262             : 
     263             :   /// \brief Create a new hash_state structure and initialize it based on the
     264             :   /// seed and the first 64-byte chunk.
     265             :   /// This effectively performs the initial mix.
     266    12004405 :   static hash_state create(const char *s, uint64_t seed) {
     267    12004405 :     hash_state state = {
     268    36013215 :       0, seed, hash_16_bytes(seed, k1), rotate(seed ^ k1, 49),
     269    48017620 :       seed * k1, shift_mix(seed), 0 };
     270    24008810 :     state.h6 = hash_16_bytes(state.h4, state.h5);
     271    12004405 :     state.mix(s);
     272    12004405 :     return state;
     273             :   }
     274             : 
     275             :   /// \brief Mix 32-bytes from the input sequence into the 16-bytes of 'a'
     276             :   /// and 'b', including whatever is already in 'a' and 'b'.
     277             :   static void mix_32_bytes(const char *s, uint64_t &a, uint64_t &b) {
     278    89870032 :     a += fetch64(s);
     279   179740064 :     uint64_t c = fetch64(s + 24);
     280   179740064 :     b = rotate(b + a + c, 21);
     281    89870032 :     uint64_t d = a;
     282   269610096 :     a += fetch64(s + 8) + fetch64(s + 16);
     283   179740064 :     b += rotate(a, 44) + d;
     284    89870032 :     a += c;
     285             :   }
     286             : 
     287             :   /// \brief Mix in a 64-byte buffer of data.
     288             :   /// We mix all 64 bytes even when the chunk length is smaller, but we
     289             :   /// record the actual length.
     290    44935016 :   void mix(const char *s) {
     291   134805048 :     h0 = rotate(h0 + h1 + h3 + fetch64(s + 8), 37) * k1;
     292   134805048 :     h1 = rotate(h1 + h4 + fetch64(s + 48), 42) * k1;
     293    44935016 :     h0 ^= h6;
     294    89870032 :     h1 += h3 + fetch64(s + 40);
     295    89870032 :     h2 = rotate(h2 + h5, 33) * k1;
     296    44935016 :     h3 = h4 * k1;
     297    44935016 :     h4 = h0 + h5;
     298    89870032 :     mix_32_bytes(s, h3, h4);
     299    44935016 :     h5 = h2 + h6;
     300    89870032 :     h6 = h1 + fetch64(s + 16);
     301    89870032 :     mix_32_bytes(s + 32, h5, h6);
     302    89870032 :     std::swap(h2, h0);
     303    44935016 :   }
     304             : 
     305             :   /// \brief Compute the final 64-bit hash code value based on the current
     306             :   /// state and the length of bytes hashed.
     307    12004406 :   uint64_t finalize(size_t length) {
     308    36013218 :     return hash_16_bytes(hash_16_bytes(h3, h5) + shift_mix(h1) * k1 + h2,
     309    48017624 :                          hash_16_bytes(h4, h6) + shift_mix(length) * k1 + h0);
     310             :   }
     311             : };
     312             : 
     313             : 
     314             : /// \brief A global, fixed seed-override variable.
     315             : ///
     316             : /// This variable can be set using the \see llvm::set_fixed_execution_seed
     317             : /// function. See that function for details. Do not, under any circumstances,
     318             : /// set or read this variable.
     319             : extern size_t fixed_seed_override;
     320             : 
     321   292484637 : inline size_t get_execution_seed() {
     322             :   // FIXME: This needs to be a per-execution seed. This is just a placeholder
     323             :   // implementation. Switching to a per-execution seed is likely to flush out
     324             :   // instability bugs and so will happen as its own commit.
     325             :   //
     326             :   // However, if there is a fixed seed override set the first time this is
     327             :   // called, return that instead of the per-execution seed.
     328   292484637 :   const uint64_t seed_prime = 0xff51afd7ed558ccdULL;
     329       51417 :   static size_t seed = fixed_seed_override ? fixed_seed_override
     330   292536054 :                                            : (size_t)seed_prime;
     331   292484637 :   return seed;
     332             : }
     333             : 
     334             : 
     335             : /// \brief Trait to indicate whether a type's bits can be hashed directly.
     336             : ///
     337             : /// A type trait which is true if we want to combine values for hashing by
     338             : /// reading the underlying data. It is false if values of this type must
     339             : /// first be passed to hash_value, and the resulting hash_codes combined.
     340             : //
     341             : // FIXME: We want to replace is_integral_or_enum and is_pointer here with
     342             : // a predicate which asserts that comparing the underlying storage of two
     343             : // values of the type for equality is equivalent to comparing the two values
     344             : // for equality. For all the platforms we care about, this holds for integers
     345             : // and pointers, but there are platforms where it doesn't and we would like to
     346             : // support user-defined types which happen to satisfy this property.
     347             : template <typename T> struct is_hashable_data
     348             :   : std::integral_constant<bool, ((is_integral_or_enum<T>::value ||
     349             :                                    std::is_pointer<T>::value) &&
     350             :                                   64 % sizeof(T) == 0)> {};
     351             : 
     352             : // Special case std::pair to detect when both types are viable and when there
     353             : // is no alignment-derived padding in the pair. This is a bit of a lie because
     354             : // std::pair isn't truly POD, but it's close enough in all reasonable
     355             : // implementations for our use case of hashing the underlying data.
     356             : template <typename T, typename U> struct is_hashable_data<std::pair<T, U> >
     357             :   : std::integral_constant<bool, (is_hashable_data<T>::value &&
     358             :                                   is_hashable_data<U>::value &&
     359             :                                   (sizeof(T) + sizeof(U)) ==
     360             :                                    sizeof(std::pair<T, U>))> {};
     361             : 
     362             : /// \brief Helper to get the hashable data representation for a type.
     363             : /// This variant is enabled when the type itself can be used.
     364             : template <typename T>
     365             : typename std::enable_if<is_hashable_data<T>::value, T>::type
     366             : get_hashable_data(const T &value) {
     367          16 :   return value;
     368             : }
     369             : /// \brief Helper to get the hashable data representation for a type.
     370             : /// This variant is enabled when we must first call hash_value and use the
     371             : /// result as our data.
     372             : template <typename T>
     373             : typename std::enable_if<!is_hashable_data<T>::value, size_t>::type
     374             : get_hashable_data(const T &value) {
     375             :   using ::llvm::hash_value;
     376    34387084 :   return hash_value(value);
     377             : }
     378             : 
     379             : /// \brief Helper to store data from a value into a buffer and advance the
     380             : /// pointer into that buffer.
     381             : ///
     382             : /// This routine first checks whether there is enough space in the provided
     383             : /// buffer, and if not immediately returns false. If there is space, it
     384             : /// copies the underlying bytes of value into the buffer, advances the
     385             : /// buffer_ptr past the copied bytes, and returns true.
     386             : template <typename T>
     387             : bool store_and_advance(char *&buffer_ptr, char *buffer_end, const T& value,
     388             :                        size_t offset = 0) {
     389   301140363 :   size_t store_size = sizeof(value) - offset;
     390   301140363 :   if (buffer_ptr + store_size > buffer_end)
     391             :     return false;
     392   297017646 :   const char *value_data = reinterpret_cast<const char *>(&value);
     393   297017646 :   memcpy(buffer_ptr, value_data + offset, store_size);
     394   297017646 :   buffer_ptr += store_size;
     395             :   return true;
     396             : }
     397             : 
     398             : /// \brief Implement the combining of integral values into a hash_code.
     399             : ///
     400             : /// This overload is selected when the value type of the iterator is
     401             : /// integral. Rather than computing a hash_code for each object and then
     402             : /// combining them, this (as an optimization) directly combines the integers.
     403             : template <typename InputIteratorT>
     404     1315909 : hash_code hash_combine_range_impl(InputIteratorT first, InputIteratorT last) {
     405     1315909 :   const size_t seed = get_execution_seed();
     406     1315909 :   char buffer[64], *buffer_ptr = buffer;
     407     1315909 :   char *const buffer_end = std::end(buffer);
     408    11254865 :   while (first != last && store_and_advance(buffer_ptr, buffer_end,
     409     4954294 :                                             get_hashable_data(*first)))
     410       89960 :     ++first;
     411     1315909 :   if (first == last)
     412     1286113 :     return hash_short(buffer, buffer_ptr - buffer, seed);
     413             :   assert(buffer_ptr == buffer_end);
     414             : 
     415       29796 :   hash_state state = state.create(buffer, seed);
     416       29796 :   size_t length = 64;
     417     8275196 :   while (first != last) {
     418             :     // Fill up the buffer. We don't clear it, which re-mixes the last round
     419             :     // when only a partial 64-byte chunk is left.
     420             :     buffer_ptr = buffer;
     421   103712663 :     while (first != last && store_and_advance(buffer_ptr, buffer_end,
     422    37510936 :                                               get_hashable_data(*first)))
     423    32753899 :       ++first;
     424             : 
     425             :     // Rotate the buffer if we did a partial fill in order to simulate doing
     426             :     // a mix of the last 64-bytes. That is how the algorithm works when we
     427             :     // have a contiguous byte sequence, and we want to emulate that here.
     428     8245400 :     std::rotate(buffer, buffer_ptr, buffer_end);
     429             : 
     430             :     // Mix this chunk into the current state.
     431     4122700 :     state.mix(buffer);
     432     4122700 :     length += buffer_ptr - buffer;
     433             :   };
     434             : 
     435       29796 :   return state.finalize(length);
     436             : }
     437             : 
     438             : /// \brief Implement the combining of integral values into a hash_code.
     439             : ///
     440             : /// This overload is selected when the value type of the iterator is integral
     441             : /// and when the input iterator is actually a pointer. Rather than computing
     442             : /// a hash_code for each object and then combining them, this (as an
     443             : /// optimization) directly combines the integers. Also, because the integers
     444             : /// are stored in contiguous memory, this routine avoids copying each value
     445             : /// and directly reads from the underlying memory.
     446             : template <typename ValueT>
     447             : typename std::enable_if<is_hashable_data<ValueT>::value, hash_code>::type
     448   186634269 : hash_combine_range_impl(ValueT *first, ValueT *last) {
     449   186634269 :   const size_t seed = get_execution_seed();
     450   186634268 :   const char *s_begin = reinterpret_cast<const char *>(first);
     451   186634268 :   const char *s_end = reinterpret_cast<const char *>(last);
     452   186634268 :   const size_t length = std::distance(s_begin, s_end);
     453   186634268 :   if (length <= 64)
     454   174659670 :     return hash_short(s_begin, length, seed);
     455             : 
     456    11974598 :   const char *s_aligned_end = s_begin + (length & ~63);
     457    11974598 :   hash_state state = state.create(s_begin, seed);
     458    11974598 :   s_begin += 64;
     459    45921932 :   while (s_begin != s_aligned_end) {
     460    16973667 :     state.mix(s_begin);
     461    16973667 :     s_begin += 64;
     462             :   }
     463    11974598 :   if (length & 63)
     464    11834229 :     state.mix(s_end - 64);
     465             : 
     466    11974598 :   return state.finalize(length);
     467             : }
     468             : 
     469             : } // namespace detail
     470             : } // namespace hashing
     471             : 
     472             : 
     473             : /// \brief Compute a hash_code for a sequence of values.
     474             : ///
     475             : /// This hashes a sequence of values. It produces the same hash_code as
     476             : /// 'hash_combine(a, b, c, ...)', but can run over arbitrary sized sequences
     477             : /// and is significantly faster given pointers and types which can be hashed as
     478             : /// a sequence of bytes.
     479             : template <typename InputIteratorT>
     480             : hash_code hash_combine_range(InputIteratorT first, InputIteratorT last) {
     481   187950178 :   return ::llvm::hashing::detail::hash_combine_range_impl(first, last);
     482             : }
     483             : 
     484             : 
     485             : // Implementation details for hash_combine.
     486             : namespace hashing {
     487             : namespace detail {
     488             : 
     489             : /// \brief Helper class to manage the recursive combining of hash_combine
     490             : /// arguments.
     491             : ///
     492             : /// This class exists to manage the state and various calls involved in the
     493             : /// recursive combining of arguments used in hash_combine. It is particularly
     494             : /// useful at minimizing the code in the recursive calls to ease the pain
     495             : /// caused by a lack of variadic functions.
     496             : struct hash_combine_recursive_helper {
     497             :   char buffer[64];
     498             :   hash_state state;
     499             :   const size_t seed;
     500             : 
     501             : public:
     502             :   /// \brief Construct a recursive hash combining helper.
     503             :   ///
     504             :   /// This sets up the state for a recursive hash combine, including getting
     505             :   /// the seed and buffer setup.
     506             :   hash_combine_recursive_helper()
     507   104533947 :     : seed(get_execution_seed()) {}
     508             : 
     509             :   /// \brief Combine one chunk of data into the current in-flight hash.
     510             :   ///
     511             :   /// This merges one chunk of data into the hash. First it tries to buffer
     512             :   /// the data. If the buffer is full, it hashes the buffer into its
     513             :   /// hash_state, empties it, and then merges the new chunk in. This also
     514             :   /// handles cases where the data straddles the end of the buffer.
     515             :   template <typename T>
     516   258675117 :   char *combine_data(size_t &length, char *buffer_ptr, char *buffer_end, T data) {
     517   258675117 :     if (!store_and_advance(buffer_ptr, buffer_end, data)) {
     518             :       // Check for skew which prevents the buffer from being packed, and do
     519             :       // a partial store into the buffer to fill it. This is only a concern
     520             :       // with the variadic combine because that formation can have varying
     521             :       // argument types.
     522          16 :       size_t partial_store_size = buffer_end - buffer_ptr;
     523          16 :       memcpy(buffer_ptr, &data, partial_store_size);
     524             : 
     525             :       // If the store fails, our buffer is full and ready to hash. We have to
     526             :       // either initialize the hash state (on the first full buffer) or mix
     527             :       // this buffer into the existing hash state. Length tracks the *hashed*
     528             :       // length, not the buffered length.
     529          16 :       if (length == 0) {
     530          11 :         state = state.create(buffer, seed);
     531          11 :         length = 64;
     532             :       } else {
     533             :         // Mix this chunk into the current state and bump length up by 64.
     534           5 :         state.mix(buffer);
     535           5 :         length += 64;
     536             :       }
     537             :       // Reset the buffer_ptr to the head of the buffer for the next chunk of
     538             :       // data.
     539          16 :       buffer_ptr = buffer;
     540             : 
     541             :       // Try again to store into the buffer -- this cannot fail as we only
     542             :       // store types smaller than the buffer.
     543          16 :       if (!store_and_advance(buffer_ptr, buffer_end, data,
     544             :                              partial_store_size))
     545           0 :         abort();
     546             :     }
     547   258675117 :     return buffer_ptr;
     548             :   }
     549             : 
     550             :   /// \brief Recursive, variadic combining method.
     551             :   ///
     552             :   /// This function recurses through each argument, combining that argument
     553             :   /// into a single hash.
     554             :   template <typename T, typename ...Ts>
     555   258675117 :   hash_code combine(size_t length, char *buffer_ptr, char *buffer_end,
     556             :                     const T &arg, const Ts &...args) {
     557   258675117 :     buffer_ptr = combine_data(length, buffer_ptr, buffer_end, get_hashable_data(arg));
     558             : 
     559             :     // Recurse to the next argument.
     560   258675116 :     return combine(length, buffer_ptr, buffer_end, args...);
     561             :   }
     562             : 
     563             :   /// \brief Base case for recursive, variadic combining.
     564             :   ///
     565             :   /// The base case when combining arguments recursively is reached when all
     566             :   /// arguments have been handled. It flushes the remaining buffer and
     567             :   /// constructs a hash_code.
     568   104533947 :   hash_code combine(size_t length, char *buffer_ptr, char *buffer_end) {
     569             :     // Check whether the entire set of values fit in the buffer. If so, we'll
     570             :     // use the optimized short hashing routine and skip state entirely.
     571   104533947 :     if (length == 0)
     572   104533936 :       return hash_short(buffer, buffer_ptr - buffer, seed);
     573             : 
     574             :     // Mix the final buffer, rotating it if we did a partial fill in order to
     575             :     // simulate doing a mix of the last 64-bytes. That is how the algorithm
     576             :     // works when we have a contiguous byte sequence, and we want to emulate
     577             :     // that here.
     578          22 :     std::rotate(buffer, buffer_ptr, buffer_end);
     579             : 
     580             :     // Mix this chunk into the current state.
     581          11 :     state.mix(buffer);
     582          11 :     length += buffer_ptr - buffer;
     583             : 
     584          11 :     return state.finalize(length);
     585             :   }
     586             : };
     587             : 
     588             : } // namespace detail
     589             : } // namespace hashing
     590             : 
     591             : /// \brief Combine values into a single hash_code.
     592             : ///
     593             : /// This routine accepts a varying number of arguments of any type. It will
     594             : /// attempt to combine them into a single hash_code. For user-defined types it
     595             : /// attempts to call a \see hash_value overload (via ADL) for the type. For
     596             : /// integer and pointer types it directly combines their data into the
     597             : /// resulting hash_code.
     598             : ///
     599             : /// The result is suitable for returning from a user's hash_value
     600             : /// *implementation* for their user-defined type. Consumers of a type should
     601             : /// *not* call this routine, they should instead call 'hash_value'.
     602   104533947 : template <typename ...Ts> hash_code hash_combine(const Ts &...args) {
     603             :   // Recursively hash each argument using a helper class.
     604   104533947 :   ::llvm::hashing::detail::hash_combine_recursive_helper helper;
     605   104533947 :   return helper.combine(0, helper.buffer, helper.buffer + 64, args...);
     606             : }
     607             : 
     608             : // Implementation details for implementations of hash_value overloads provided
     609             : // here.
     610             : namespace hashing {
     611             : namespace detail {
     612             : 
     613             : /// \brief Helper to hash the value of a single integer.
     614             : ///
     615             : /// Overloads for smaller integer types are not provided to ensure consistent
     616             : /// behavior in the presence of integral promotions. Essentially,
     617             : /// "hash_value('4')" and "hash_value('0' + 4)" should be the same.
     618         513 : inline hash_code hash_integer_value(uint64_t value) {
     619             :   // Similar to hash_4to8_bytes but using a seed instead of length.
     620         513 :   const uint64_t seed = get_execution_seed();
     621         513 :   const char *s = reinterpret_cast<const char *>(&value);
     622         513 :   const uint64_t a = fetch32(s);
     623        1539 :   return hash_16_bytes(seed + (a << 3), fetch32(s + 4));
     624             : }
     625             : 
     626             : } // namespace detail
     627             : } // namespace hashing
     628             : 
     629             : // Declared and documented above, but defined here so that any of the hashing
     630             : // infrastructure is available.
     631             : template <typename T>
     632             : typename std::enable_if<is_integral_or_enum<T>::value, hash_code>::type
     633             : hash_value(T value) {
     634           3 :   return ::llvm::hashing::detail::hash_integer_value(
     635          22 :       static_cast<uint64_t>(value));
     636             : }
     637             : 
     638             : // Declared and documented above, but defined here so that any of the hashing
     639             : // infrastructure is available.
     640             : template <typename T> hash_code hash_value(const T *ptr) {
     641         489 :   return ::llvm::hashing::detail::hash_integer_value(
     642         491 :     reinterpret_cast<uintptr_t>(ptr));
     643             : }
     644             : 
     645             : // Declared and documented above, but defined here so that any of the hashing
     646             : // infrastructure is available.
     647             : template <typename T, typename U>
     648             : hash_code hash_value(const std::pair<T, U> &arg) {
     649          12 :   return hash_combine(arg.first, arg.second);
     650             : }
     651             : 
     652             : // Declared and documented above, but defined here so that any of the hashing
     653             : // infrastructure is available.
     654             : template <typename T>
     655           3 : hash_code hash_value(const std::basic_string<T> &arg) {
     656       78627 :   return hash_combine_range(arg.begin(), arg.end());
     657             : }
     658             : 
     659             : } // namespace llvm
     660             : 
     661             : #endif

Generated by: LCOV version 1.13