LLVM API Documentation

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