LLVM  mainline
Hashing.h
Go to the documentation of this file.
00001 //===-- llvm/ADT/Hashing.h - Utilities for hashing --------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the newly proposed standard C++ interfaces for hashing
00011 // arbitrary data and building hash functions for user-defined types. This
00012 // interface was originally proposed in N3333[1] and is currently under review
00013 // for inclusion in a future TR and/or standard.
00014 //
00015 // The primary interfaces provide are comprised of one type and three functions:
00016 //
00017 //  -- 'hash_code' class is an opaque type representing the hash code for some
00018 //     data. It is the intended product of hashing, and can be used to implement
00019 //     hash tables, checksumming, and other common uses of hashes. It is not an
00020 //     integer type (although it can be converted to one) because it is risky
00021 //     to assume much about the internals of a hash_code. In particular, each
00022 //     execution of the program has a high probability of producing a different
00023 //     hash_code for a given input. Thus their values are not stable to save or
00024 //     persist, and should only be used during the execution for the
00025 //     construction of hashing datastructures.
00026 //
00027 //  -- 'hash_value' is a function designed to be overloaded for each
00028 //     user-defined type which wishes to be used within a hashing context. It
00029 //     should be overloaded within the user-defined type's namespace and found
00030 //     via ADL. Overloads for primitive types are provided by this library.
00031 //
00032 //  -- 'hash_combine' and 'hash_combine_range' are functions designed to aid
00033 //      programmers in easily and intuitively combining a set of data into
00034 //      a single hash_code for their object. They should only logically be used
00035 //      within the implementation of a 'hash_value' routine or similar context.
00036 //
00037 // Note that 'hash_combine_range' contains very special logic for hashing
00038 // a contiguous array of integers or pointers. This logic is *extremely* fast,
00039 // on a modern Intel "Gainestown" Xeon (Nehalem uarch) @2.2 GHz, these were
00040 // benchmarked at over 6.5 GiB/s for large keys, and <20 cycles/hash for keys
00041 // under 32-bytes.
00042 //
00043 //===----------------------------------------------------------------------===//
00044 
00045 #ifndef LLVM_ADT_HASHING_H
00046 #define LLVM_ADT_HASHING_H
00047 
00048 #include "llvm/Support/DataTypes.h"
00049 #include "llvm/Support/Host.h"
00050 #include "llvm/Support/SwapByteOrder.h"
00051 #include "llvm/Support/type_traits.h"
00052 #include <algorithm>
00053 #include <cassert>
00054 #include <cstring>
00055 #include <iterator>
00056 #include <string>
00057 #include <utility>
00058 
00059 namespace llvm {
00060 
00061 /// \brief An opaque object representing a hash code.
00062 ///
00063 /// This object represents the result of hashing some entity. It is intended to
00064 /// be used to implement hashtables or other hashing-based data structures.
00065 /// While it wraps and exposes a numeric value, this value should not be
00066 /// trusted to be stable or predictable across processes or executions.
00067 ///
00068 /// In order to obtain the hash_code for an object 'x':
00069 /// \code
00070 ///   using llvm::hash_value;
00071 ///   llvm::hash_code code = hash_value(x);
00072 /// \endcode
00073 class hash_code {
00074   size_t value;
00075 
00076 public:
00077   /// \brief Default construct a hash_code.
00078   /// Note that this leaves the value uninitialized.
00079   hash_code() = default;
00080 
00081   /// \brief Form a hash code directly from a numerical value.
00082   hash_code(size_t value) : value(value) {}
00083 
00084   /// \brief Convert the hash code to its numerical value for use.
00085   /*explicit*/ operator size_t() const { return value; }
00086 
00087   friend bool operator==(const hash_code &lhs, const hash_code &rhs) {
00088     return lhs.value == rhs.value;
00089   }
00090   friend bool operator!=(const hash_code &lhs, const hash_code &rhs) {
00091     return lhs.value != rhs.value;
00092   }
00093 
00094   /// \brief Allow a hash_code to be directly run through hash_value.
00095   friend size_t hash_value(const hash_code &code) { return code.value; }
00096 };
00097 
00098 /// \brief Compute a hash_code for any integer value.
00099 ///
00100 /// Note that this function is intended to compute the same hash_code for
00101 /// a particular value without regard to the pre-promotion type. This is in
00102 /// contrast to hash_combine which may produce different hash_codes for
00103 /// differing argument types even if they would implicit promote to a common
00104 /// type without changing the value.
00105 template <typename T>
00106 typename std::enable_if<is_integral_or_enum<T>::value, hash_code>::type
00107 hash_value(T value);
00108 
00109 /// \brief Compute a hash_code for a pointer's address.
00110 ///
00111 /// N.B.: This hashes the *address*. Not the value and not the type.
00112 template <typename T> hash_code hash_value(const T *ptr);
00113 
00114 /// \brief Compute a hash_code for a pair of objects.
00115 template <typename T, typename U>
00116 hash_code hash_value(const std::pair<T, U> &arg);
00117 
00118 /// \brief Compute a hash_code for a standard string.
00119 template <typename T>
00120 hash_code hash_value(const std::basic_string<T> &arg);
00121 
00122 
00123 /// \brief Override the execution seed with a fixed value.
00124 ///
00125 /// This hashing library uses a per-execution seed designed to change on each
00126 /// run with high probability in order to ensure that the hash codes are not
00127 /// attackable and to ensure that output which is intended to be stable does
00128 /// not rely on the particulars of the hash codes produced.
00129 ///
00130 /// That said, there are use cases where it is important to be able to
00131 /// reproduce *exactly* a specific behavior. To that end, we provide a function
00132 /// which will forcibly set the seed to a fixed value. This must be done at the
00133 /// start of the program, before any hashes are computed. Also, it cannot be
00134 /// undone. This makes it thread-hostile and very hard to use outside of
00135 /// immediately on start of a simple program designed for reproducible
00136 /// behavior.
00137 void set_fixed_execution_hash_seed(size_t fixed_value);
00138 
00139 
00140 // All of the implementation details of actually computing the various hash
00141 // code values are held within this namespace. These routines are included in
00142 // the header file mainly to allow inlining and constant propagation.
00143 namespace hashing {
00144 namespace detail {
00145 
00146 inline uint64_t fetch64(const char *p) {
00147   uint64_t result;
00148   memcpy(&result, p, sizeof(result));
00149   if (sys::IsBigEndianHost)
00150     sys::swapByteOrder(result);
00151   return result;
00152 }
00153 
00154 inline uint32_t fetch32(const char *p) {
00155   uint32_t result;
00156   memcpy(&result, p, sizeof(result));
00157   if (sys::IsBigEndianHost)
00158     sys::swapByteOrder(result);
00159   return result;
00160 }
00161 
00162 /// Some primes between 2^63 and 2^64 for various uses.
00163 static const uint64_t k0 = 0xc3a5c85c97cb3127ULL;
00164 static const uint64_t k1 = 0xb492b66fbe98f273ULL;
00165 static const uint64_t k2 = 0x9ae16a3b2f90404fULL;
00166 static const uint64_t k3 = 0xc949d7c7509e6557ULL;
00167 
00168 /// \brief Bitwise right rotate.
00169 /// Normally this will compile to a single instruction, especially if the
00170 /// shift is a manifest constant.
00171 inline uint64_t rotate(uint64_t val, size_t shift) {
00172   // Avoid shifting by 64: doing so yields an undefined result.
00173   return shift == 0 ? val : ((val >> shift) | (val << (64 - shift)));
00174 }
00175 
00176 inline uint64_t shift_mix(uint64_t val) {
00177   return val ^ (val >> 47);
00178 }
00179 
00180 inline uint64_t hash_16_bytes(uint64_t low, uint64_t high) {
00181   // Murmur-inspired hashing.
00182   const uint64_t kMul = 0x9ddfea08eb382d69ULL;
00183   uint64_t a = (low ^ high) * kMul;
00184   a ^= (a >> 47);
00185   uint64_t b = (high ^ a) * kMul;
00186   b ^= (b >> 47);
00187   b *= kMul;
00188   return b;
00189 }
00190 
00191 inline uint64_t hash_1to3_bytes(const char *s, size_t len, uint64_t seed) {
00192   uint8_t a = s[0];
00193   uint8_t b = s[len >> 1];
00194   uint8_t c = s[len - 1];
00195   uint32_t y = static_cast<uint32_t>(a) + (static_cast<uint32_t>(b) << 8);
00196   uint32_t z = len + (static_cast<uint32_t>(c) << 2);
00197   return shift_mix(y * k2 ^ z * k3 ^ seed) * k2;
00198 }
00199 
00200 inline uint64_t hash_4to8_bytes(const char *s, size_t len, uint64_t seed) {
00201   uint64_t a = fetch32(s);
00202   return hash_16_bytes(len + (a << 3), seed ^ fetch32(s + len - 4));
00203 }
00204 
00205 inline uint64_t hash_9to16_bytes(const char *s, size_t len, uint64_t seed) {
00206   uint64_t a = fetch64(s);
00207   uint64_t b = fetch64(s + len - 8);
00208   return hash_16_bytes(seed ^ a, rotate(b + len, len)) ^ b;
00209 }
00210 
00211 inline uint64_t hash_17to32_bytes(const char *s, size_t len, uint64_t seed) {
00212   uint64_t a = fetch64(s) * k1;
00213   uint64_t b = fetch64(s + 8);
00214   uint64_t c = fetch64(s + len - 8) * k2;
00215   uint64_t d = fetch64(s + len - 16) * k0;
00216   return hash_16_bytes(rotate(a - b, 43) + rotate(c ^ seed, 30) + d,
00217                        a + rotate(b ^ k3, 20) - c + len + seed);
00218 }
00219 
00220 inline uint64_t hash_33to64_bytes(const char *s, size_t len, uint64_t seed) {
00221   uint64_t z = fetch64(s + 24);
00222   uint64_t a = fetch64(s) + (len + fetch64(s + len - 16)) * k0;
00223   uint64_t b = rotate(a + z, 52);
00224   uint64_t c = rotate(a, 37);
00225   a += fetch64(s + 8);
00226   c += rotate(a, 7);
00227   a += fetch64(s + 16);
00228   uint64_t vf = a + z;
00229   uint64_t vs = b + rotate(a, 31) + c;
00230   a = fetch64(s + 16) + fetch64(s + len - 32);
00231   z = fetch64(s + len - 8);
00232   b = rotate(a + z, 52);
00233   c = rotate(a, 37);
00234   a += fetch64(s + len - 24);
00235   c += rotate(a, 7);
00236   a += fetch64(s + len - 16);
00237   uint64_t wf = a + z;
00238   uint64_t ws = b + rotate(a, 31) + c;
00239   uint64_t r = shift_mix((vf + ws) * k2 + (wf + vs) * k0);
00240   return shift_mix((seed ^ (r * k0)) + vs) * k2;
00241 }
00242 
00243 inline uint64_t hash_short(const char *s, size_t length, uint64_t seed) {
00244   if (length >= 4 && length <= 8)
00245     return hash_4to8_bytes(s, length, seed);
00246   if (length > 8 && length <= 16)
00247     return hash_9to16_bytes(s, length, seed);
00248   if (length > 16 && length <= 32)
00249     return hash_17to32_bytes(s, length, seed);
00250   if (length > 32)
00251     return hash_33to64_bytes(s, length, seed);
00252   if (length != 0)
00253     return hash_1to3_bytes(s, length, seed);
00254 
00255   return k2 ^ seed;
00256 }
00257 
00258 /// \brief The intermediate state used during hashing.
00259 /// Currently, the algorithm for computing hash codes is based on CityHash and
00260 /// keeps 56 bytes of arbitrary state.
00261 struct hash_state {
00262   uint64_t h0, h1, h2, h3, h4, h5, h6;
00263 
00264   /// \brief Create a new hash_state structure and initialize it based on the
00265   /// seed and the first 64-byte chunk.
00266   /// This effectively performs the initial mix.
00267   static hash_state create(const char *s, uint64_t seed) {
00268     hash_state state = {
00269       0, seed, hash_16_bytes(seed, k1), rotate(seed ^ k1, 49),
00270       seed * k1, shift_mix(seed), 0 };
00271     state.h6 = hash_16_bytes(state.h4, state.h5);
00272     state.mix(s);
00273     return state;
00274   }
00275 
00276   /// \brief Mix 32-bytes from the input sequence into the 16-bytes of 'a'
00277   /// and 'b', including whatever is already in 'a' and 'b'.
00278   static void mix_32_bytes(const char *s, uint64_t &a, uint64_t &b) {
00279     a += fetch64(s);
00280     uint64_t c = fetch64(s + 24);
00281     b = rotate(b + a + c, 21);
00282     uint64_t d = a;
00283     a += fetch64(s + 8) + fetch64(s + 16);
00284     b += rotate(a, 44) + d;
00285     a += c;
00286   }
00287 
00288   /// \brief Mix in a 64-byte buffer of data.
00289   /// We mix all 64 bytes even when the chunk length is smaller, but we
00290   /// record the actual length.
00291   void mix(const char *s) {
00292     h0 = rotate(h0 + h1 + h3 + fetch64(s + 8), 37) * k1;
00293     h1 = rotate(h1 + h4 + fetch64(s + 48), 42) * k1;
00294     h0 ^= h6;
00295     h1 += h3 + fetch64(s + 40);
00296     h2 = rotate(h2 + h5, 33) * k1;
00297     h3 = h4 * k1;
00298     h4 = h0 + h5;
00299     mix_32_bytes(s, h3, h4);
00300     h5 = h2 + h6;
00301     h6 = h1 + fetch64(s + 16);
00302     mix_32_bytes(s + 32, h5, h6);
00303     std::swap(h2, h0);
00304   }
00305 
00306   /// \brief Compute the final 64-bit hash code value based on the current
00307   /// state and the length of bytes hashed.
00308   uint64_t finalize(size_t length) {
00309     return hash_16_bytes(hash_16_bytes(h3, h5) + shift_mix(h1) * k1 + h2,
00310                          hash_16_bytes(h4, h6) + shift_mix(length) * k1 + h0);
00311   }
00312 };
00313 
00314 
00315 /// \brief A global, fixed seed-override variable.
00316 ///
00317 /// This variable can be set using the \see llvm::set_fixed_execution_seed
00318 /// function. See that function for details. Do not, under any circumstances,
00319 /// set or read this variable.
00320 extern size_t fixed_seed_override;
00321 
00322 inline size_t get_execution_seed() {
00323   // FIXME: This needs to be a per-execution seed. This is just a placeholder
00324   // implementation. Switching to a per-execution seed is likely to flush out
00325   // instability bugs and so will happen as its own commit.
00326   //
00327   // However, if there is a fixed seed override set the first time this is
00328   // called, return that instead of the per-execution seed.
00329   const uint64_t seed_prime = 0xff51afd7ed558ccdULL;
00330   static size_t seed = fixed_seed_override ? fixed_seed_override
00331                                            : (size_t)seed_prime;
00332   return seed;
00333 }
00334 
00335 
00336 /// \brief Trait to indicate whether a type's bits can be hashed directly.
00337 ///
00338 /// A type trait which is true if we want to combine values for hashing by
00339 /// reading the underlying data. It is false if values of this type must
00340 /// first be passed to hash_value, and the resulting hash_codes combined.
00341 //
00342 // FIXME: We want to replace is_integral_or_enum and is_pointer here with
00343 // a predicate which asserts that comparing the underlying storage of two
00344 // values of the type for equality is equivalent to comparing the two values
00345 // for equality. For all the platforms we care about, this holds for integers
00346 // and pointers, but there are platforms where it doesn't and we would like to
00347 // support user-defined types which happen to satisfy this property.
00348 template <typename T> struct is_hashable_data
00349   : std::integral_constant<bool, ((is_integral_or_enum<T>::value ||
00350                                    std::is_pointer<T>::value) &&
00351                                   64 % sizeof(T) == 0)> {};
00352 
00353 // Special case std::pair to detect when both types are viable and when there
00354 // is no alignment-derived padding in the pair. This is a bit of a lie because
00355 // std::pair isn't truly POD, but it's close enough in all reasonable
00356 // implementations for our use case of hashing the underlying data.
00357 template <typename T, typename U> struct is_hashable_data<std::pair<T, U> >
00358   : std::integral_constant<bool, (is_hashable_data<T>::value &&
00359                                   is_hashable_data<U>::value &&
00360                                   (sizeof(T) + sizeof(U)) ==
00361                                    sizeof(std::pair<T, U>))> {};
00362 
00363 /// \brief Helper to get the hashable data representation for a type.
00364 /// This variant is enabled when the type itself can be used.
00365 template <typename T>
00366 typename std::enable_if<is_hashable_data<T>::value, T>::type
00367 get_hashable_data(const T &value) {
00368   return value;
00369 }
00370 /// \brief Helper to get the hashable data representation for a type.
00371 /// This variant is enabled when we must first call hash_value and use the
00372 /// result as our data.
00373 template <typename T>
00374 typename std::enable_if<!is_hashable_data<T>::value, size_t>::type
00375 get_hashable_data(const T &value) {
00376   using ::llvm::hash_value;
00377   return hash_value(value);
00378 }
00379 
00380 /// \brief Helper to store data from a value into a buffer and advance the
00381 /// pointer into that buffer.
00382 ///
00383 /// This routine first checks whether there is enough space in the provided
00384 /// buffer, and if not immediately returns false. If there is space, it
00385 /// copies the underlying bytes of value into the buffer, advances the
00386 /// buffer_ptr past the copied bytes, and returns true.
00387 template <typename T>
00388 bool store_and_advance(char *&buffer_ptr, char *buffer_end, const T& value,
00389                        size_t offset = 0) {
00390   size_t store_size = sizeof(value) - offset;
00391   if (buffer_ptr + store_size > buffer_end)
00392     return false;
00393   const char *value_data = reinterpret_cast<const char *>(&value);
00394   memcpy(buffer_ptr, value_data + offset, store_size);
00395   buffer_ptr += store_size;
00396   return true;
00397 }
00398 
00399 /// \brief Implement the combining of integral values into a hash_code.
00400 ///
00401 /// This overload is selected when the value type of the iterator is
00402 /// integral. Rather than computing a hash_code for each object and then
00403 /// combining them, this (as an optimization) directly combines the integers.
00404 template <typename InputIteratorT>
00405 hash_code hash_combine_range_impl(InputIteratorT first, InputIteratorT last) {
00406   const size_t seed = get_execution_seed();
00407   char buffer[64], *buffer_ptr = buffer;
00408   char *const buffer_end = std::end(buffer);
00409   while (first != last && store_and_advance(buffer_ptr, buffer_end,
00410                                             get_hashable_data(*first)))
00411     ++first;
00412   if (first == last)
00413     return hash_short(buffer, buffer_ptr - buffer, seed);
00414   assert(buffer_ptr == buffer_end);
00415 
00416   hash_state state = state.create(buffer, seed);
00417   size_t length = 64;
00418   while (first != last) {
00419     // Fill up the buffer. We don't clear it, which re-mixes the last round
00420     // when only a partial 64-byte chunk is left.
00421     buffer_ptr = buffer;
00422     while (first != last && store_and_advance(buffer_ptr, buffer_end,
00423                                               get_hashable_data(*first)))
00424       ++first;
00425 
00426     // Rotate the buffer if we did a partial fill in order to simulate doing
00427     // a mix of the last 64-bytes. That is how the algorithm works when we
00428     // have a contiguous byte sequence, and we want to emulate that here.
00429     std::rotate(buffer, buffer_ptr, buffer_end);
00430 
00431     // Mix this chunk into the current state.
00432     state.mix(buffer);
00433     length += buffer_ptr - buffer;
00434   };
00435 
00436   return state.finalize(length);
00437 }
00438 
00439 /// \brief Implement the combining of integral values into a hash_code.
00440 ///
00441 /// This overload is selected when the value type of the iterator is integral
00442 /// and when the input iterator is actually a pointer. Rather than computing
00443 /// a hash_code for each object and then combining them, this (as an
00444 /// optimization) directly combines the integers. Also, because the integers
00445 /// are stored in contiguous memory, this routine avoids copying each value
00446 /// and directly reads from the underlying memory.
00447 template <typename ValueT>
00448 typename std::enable_if<is_hashable_data<ValueT>::value, hash_code>::type
00449 hash_combine_range_impl(ValueT *first, ValueT *last) {
00450   const size_t seed = get_execution_seed();
00451   const char *s_begin = reinterpret_cast<const char *>(first);
00452   const char *s_end = reinterpret_cast<const char *>(last);
00453   const size_t length = std::distance(s_begin, s_end);
00454   if (length <= 64)
00455     return hash_short(s_begin, length, seed);
00456 
00457   const char *s_aligned_end = s_begin + (length & ~63);
00458   hash_state state = state.create(s_begin, seed);
00459   s_begin += 64;
00460   while (s_begin != s_aligned_end) {
00461     state.mix(s_begin);
00462     s_begin += 64;
00463   }
00464   if (length & 63)
00465     state.mix(s_end - 64);
00466 
00467   return state.finalize(length);
00468 }
00469 
00470 } // namespace detail
00471 } // namespace hashing
00472 
00473 
00474 /// \brief Compute a hash_code for a sequence of values.
00475 ///
00476 /// This hashes a sequence of values. It produces the same hash_code as
00477 /// 'hash_combine(a, b, c, ...)', but can run over arbitrary sized sequences
00478 /// and is significantly faster given pointers and types which can be hashed as
00479 /// a sequence of bytes.
00480 template <typename InputIteratorT>
00481 hash_code hash_combine_range(InputIteratorT first, InputIteratorT last) {
00482   return ::llvm::hashing::detail::hash_combine_range_impl(first, last);
00483 }
00484 
00485 
00486 // Implementation details for hash_combine.
00487 namespace hashing {
00488 namespace detail {
00489 
00490 /// \brief Helper class to manage the recursive combining of hash_combine
00491 /// arguments.
00492 ///
00493 /// This class exists to manage the state and various calls involved in the
00494 /// recursive combining of arguments used in hash_combine. It is particularly
00495 /// useful at minimizing the code in the recursive calls to ease the pain
00496 /// caused by a lack of variadic functions.
00497 struct hash_combine_recursive_helper {
00498   char buffer[64];
00499   hash_state state;
00500   const size_t seed;
00501 
00502 public:
00503   /// \brief Construct a recursive hash combining helper.
00504   ///
00505   /// This sets up the state for a recursive hash combine, including getting
00506   /// the seed and buffer setup.
00507   hash_combine_recursive_helper()
00508     : seed(get_execution_seed()) {}
00509 
00510   /// \brief Combine one chunk of data into the current in-flight hash.
00511   ///
00512   /// This merges one chunk of data into the hash. First it tries to buffer
00513   /// the data. If the buffer is full, it hashes the buffer into its
00514   /// hash_state, empties it, and then merges the new chunk in. This also
00515   /// handles cases where the data straddles the end of the buffer.
00516   template <typename T>
00517   char *combine_data(size_t &length, char *buffer_ptr, char *buffer_end, T data) {
00518     if (!store_and_advance(buffer_ptr, buffer_end, data)) {
00519       // Check for skew which prevents the buffer from being packed, and do
00520       // a partial store into the buffer to fill it. This is only a concern
00521       // with the variadic combine because that formation can have varying
00522       // argument types.
00523       size_t partial_store_size = buffer_end - buffer_ptr;
00524       memcpy(buffer_ptr, &data, partial_store_size);
00525 
00526       // If the store fails, our buffer is full and ready to hash. We have to
00527       // either initialize the hash state (on the first full buffer) or mix
00528       // this buffer into the existing hash state. Length tracks the *hashed*
00529       // length, not the buffered length.
00530       if (length == 0) {
00531         state = state.create(buffer, seed);
00532         length = 64;
00533       } else {
00534         // Mix this chunk into the current state and bump length up by 64.
00535         state.mix(buffer);
00536         length += 64;
00537       }
00538       // Reset the buffer_ptr to the head of the buffer for the next chunk of
00539       // data.
00540       buffer_ptr = buffer;
00541 
00542       // Try again to store into the buffer -- this cannot fail as we only
00543       // store types smaller than the buffer.
00544       if (!store_and_advance(buffer_ptr, buffer_end, data,
00545                              partial_store_size))
00546         abort();
00547     }
00548     return buffer_ptr;
00549   }
00550 
00551   /// \brief Recursive, variadic combining method.
00552   ///
00553   /// This function recurses through each argument, combining that argument
00554   /// into a single hash.
00555   template <typename T, typename ...Ts>
00556   hash_code combine(size_t length, char *buffer_ptr, char *buffer_end,
00557                     const T &arg, const Ts &...args) {
00558     buffer_ptr = combine_data(length, buffer_ptr, buffer_end, get_hashable_data(arg));
00559 
00560     // Recurse to the next argument.
00561     return combine(length, buffer_ptr, buffer_end, args...);
00562   }
00563 
00564   /// \brief Base case for recursive, variadic combining.
00565   ///
00566   /// The base case when combining arguments recursively is reached when all
00567   /// arguments have been handled. It flushes the remaining buffer and
00568   /// constructs a hash_code.
00569   hash_code combine(size_t length, char *buffer_ptr, char *buffer_end) {
00570     // Check whether the entire set of values fit in the buffer. If so, we'll
00571     // use the optimized short hashing routine and skip state entirely.
00572     if (length == 0)
00573       return hash_short(buffer, buffer_ptr - buffer, seed);
00574 
00575     // Mix the final buffer, rotating it if we did a partial fill in order to
00576     // simulate doing a mix of the last 64-bytes. That is how the algorithm
00577     // works when we have a contiguous byte sequence, and we want to emulate
00578     // that here.
00579     std::rotate(buffer, buffer_ptr, buffer_end);
00580 
00581     // Mix this chunk into the current state.
00582     state.mix(buffer);
00583     length += buffer_ptr - buffer;
00584 
00585     return state.finalize(length);
00586   }
00587 };
00588 
00589 } // namespace detail
00590 } // namespace hashing
00591 
00592 /// \brief Combine values into a single hash_code.
00593 ///
00594 /// This routine accepts a varying number of arguments of any type. It will
00595 /// attempt to combine them into a single hash_code. For user-defined types it
00596 /// attempts to call a \see hash_value overload (via ADL) for the type. For
00597 /// integer and pointer types it directly combines their data into the
00598 /// resulting hash_code.
00599 ///
00600 /// The result is suitable for returning from a user's hash_value
00601 /// *implementation* for their user-defined type. Consumers of a type should
00602 /// *not* call this routine, they should instead call 'hash_value'.
00603 template <typename ...Ts> hash_code hash_combine(const Ts &...args) {
00604   // Recursively hash each argument using a helper class.
00605   ::llvm::hashing::detail::hash_combine_recursive_helper helper;
00606   return helper.combine(0, helper.buffer, helper.buffer + 64, args...);
00607 }
00608 
00609 // Implementation details for implementations of hash_value overloads provided
00610 // here.
00611 namespace hashing {
00612 namespace detail {
00613 
00614 /// \brief Helper to hash the value of a single integer.
00615 ///
00616 /// Overloads for smaller integer types are not provided to ensure consistent
00617 /// behavior in the presence of integral promotions. Essentially,
00618 /// "hash_value('4')" and "hash_value('0' + 4)" should be the same.
00619 inline hash_code hash_integer_value(uint64_t value) {
00620   // Similar to hash_4to8_bytes but using a seed instead of length.
00621   const uint64_t seed = get_execution_seed();
00622   const char *s = reinterpret_cast<const char *>(&value);
00623   const uint64_t a = fetch32(s);
00624   return hash_16_bytes(seed + (a << 3), fetch32(s + 4));
00625 }
00626 
00627 } // namespace detail
00628 } // namespace hashing
00629 
00630 // Declared and documented above, but defined here so that any of the hashing
00631 // infrastructure is available.
00632 template <typename T>
00633 typename std::enable_if<is_integral_or_enum<T>::value, hash_code>::type
00634 hash_value(T value) {
00635   return ::llvm::hashing::detail::hash_integer_value(value);
00636 }
00637 
00638 // Declared and documented above, but defined here so that any of the hashing
00639 // infrastructure is available.
00640 template <typename T> hash_code hash_value(const T *ptr) {
00641   return ::llvm::hashing::detail::hash_integer_value(
00642     reinterpret_cast<uintptr_t>(ptr));
00643 }
00644 
00645 // Declared and documented above, but defined here so that any of the hashing
00646 // infrastructure is available.
00647 template <typename T, typename U>
00648 hash_code hash_value(const std::pair<T, U> &arg) {
00649   return hash_combine(arg.first, arg.second);
00650 }
00651 
00652 // Declared and documented above, but defined here so that any of the hashing
00653 // infrastructure is available.
00654 template <typename T>
00655 hash_code hash_value(const std::basic_string<T> &arg) {
00656   return hash_combine_range(arg.begin(), arg.end());
00657 }
00658 
00659 } // namespace llvm
00660 
00661 #endif