7fbe5bb0ca275c901aaee8f059d7028e871f3929
[oota-llvm.git] / include / llvm / ADT / Hashing.h
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/ADT/STLExtras.h"
49 #include "llvm/Support/DataTypes.h"
50 #include "llvm/Support/type_traits.h"
51 #include <algorithm>
52 #include <cassert>
53 #include <cstring>
54 #include <iterator>
55 #include <utility>
56
57 // Allow detecting C++11 feature availability when building with Clang without
58 // breaking other compilers.
59 #ifndef __has_feature
60 # define __has_feature(x) 0
61 #endif
62
63 namespace llvm {
64
65 /// \brief An opaque object representing a hash code.
66 ///
67 /// This object represents the result of hashing some entity. It is intended to
68 /// be used to implement hashtables or other hashing-based data structures.
69 /// While it wraps and exposes a numeric value, this value should not be
70 /// trusted to be stable or predictable across processes or executions.
71 ///
72 /// In order to obtain the hash_code for an object 'x':
73 /// \code
74 ///   using llvm::hash_value;
75 ///   llvm::hash_code code = hash_value(x);
76 /// \endcode
77 ///
78 /// Also note that there are two numerical values which are reserved, and the
79 /// implementation ensures will never be produced for real hash_codes. These
80 /// can be used as sentinels within hashing data structures.
81 class hash_code {
82   size_t value;
83
84 public:
85   /// \brief Default construct a hash_code.
86   /// Note that this leaves the value uninitialized.
87   hash_code() {}
88
89   /// \brief Form a hash code directly from a numerical value.
90   hash_code(size_t value) : value(value) {}
91
92   /// \brief Convert the hash code to its numerical value for use.
93   /*explicit*/ operator size_t() const { return value; }
94
95   friend bool operator==(const hash_code &lhs, const hash_code &rhs) {
96     return lhs.value == rhs.value;
97   }
98   friend bool operator!=(const hash_code &lhs, const hash_code &rhs) {
99     return lhs.value != rhs.value;
100   }
101
102   /// \brief Allow a hash_code to be directly run through hash_value.
103   friend size_t hash_value(const hash_code &code) { return code.value; }
104 };
105
106 /// \brief Compute a hash_code for any integer value.
107 ///
108 /// Note that this function is intended to compute the same hash_code for
109 /// a particular value without regard to the pre-promotion type. This is in
110 /// contrast to hash_combine which may produce different hash_codes for
111 /// differing argument types even if they would implicit promote to a common
112 /// type without changing the value.
113 template <typename T>
114 typename enable_if<is_integral<T>, hash_code>::type hash_value(T value);
115
116 /// \brief Compute a hash_code for a pointer's address.
117 ///
118 /// N.B.: This hashes the *address*. Not the value and not the type.
119 template <typename T> hash_code hash_value(const T *ptr);
120
121 /// \brief Compute a hash_code for a pair of objects.
122 template <typename T, typename U>
123 hash_code hash_value(const std::pair<T, U> &arg);
124
125
126 /// \brief Override the execution seed with a fixed value.
127 ///
128 /// This hashing library uses a per-execution seed designed to change on each
129 /// run with high probability in order to ensure that the hash codes are not
130 /// attackable and to ensure that output which is intended to be stable does
131 /// not rely on the particulars of the hash codes produced.
132 ///
133 /// That said, there are use cases where it is important to be able to
134 /// reproduce *exactly* a specific behavior. To that end, we provide a function
135 /// which will forcibly set the seed to a fixed value. This must be done at the
136 /// start of the program, before any hashes are computed. Also, it cannot be
137 /// undone. This makes it thread-hostile and very hard to use outside of
138 /// immediately on start of a simple program designed for reproducible
139 /// behavior.
140 void set_fixed_execution_hash_seed(size_t fixed_value);
141
142
143 // All of the implementation details of actually computing the various hash
144 // code values are held within this namespace. These routines are included in
145 // the header file mainly to allow inlining and constant propagation.
146 namespace hashing {
147 namespace detail {
148
149 inline uint64_t fetch64(const char *p) {
150   uint64_t result;
151   memcpy(&result, p, sizeof(result));
152   return result;
153 }
154
155 inline uint32_t fetch32(const char *p) {
156   uint32_t result;
157   memcpy(&result, p, sizeof(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, unsigned shift) {
171   // Avoid shifting by 64: doing so yields an undefined result.
172   return shift == 0 ? val : ((val >> shift) | (val << (64 - shift)));
173 }
174
175 inline uint64_t shift_mix(uint64_t val) {
176   return val ^ (val >> 47);
177 }
178
179 inline uint64_t hash_16_bytes(uint64_t low, uint64_t high) {
180   // Murmur-inspired hashing.
181   const uint64_t kMul = 0x9ddfea08eb382d69ULL;
182   uint64_t a = (low ^ high) * kMul;
183   a ^= (a >> 47);
184   uint64_t b = (high ^ a) * kMul;
185   b ^= (b >> 47);
186   b *= kMul;
187   return b;
188 }
189
190 inline uint64_t hash_1to3_bytes(const char *s, size_t len, uint64_t seed) {
191   uint8_t a = s[0];
192   uint8_t b = s[len >> 1];
193   uint8_t c = s[len - 1];
194   uint32_t y = static_cast<uint32_t>(a) + (static_cast<uint32_t>(b) << 8);
195   uint32_t z = len + (static_cast<uint32_t>(c) << 2);
196   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   uint64_t a = fetch32(s);
201   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     uint64_t a = fetch64(s);
206     uint64_t b = fetch64(s + len - 8);
207     return hash_16_bytes(seed ^ a, rotate(b + len, len)) ^ b;
208 }
209
210 inline uint64_t hash_17to32_bytes(const char *s, size_t len, uint64_t seed) {
211   uint64_t a = fetch64(s) * k1;
212   uint64_t b = fetch64(s + 8);
213   uint64_t c = fetch64(s + len - 8) * k2;
214   uint64_t d = fetch64(s + len - 16) * k0;
215   return hash_16_bytes(rotate(a - b, 43) + rotate(c ^ seed, 30) + d,
216                        a + rotate(b ^ k3, 20) - c + len + seed);
217 }
218
219 inline uint64_t hash_33to64_bytes(const char *s, size_t len, uint64_t seed) {
220   uint64_t z = fetch64(s + 24);
221   uint64_t a = fetch64(s) + (len + fetch64(s + len - 16)) * k0;
222   uint64_t b = rotate(a + z, 52);
223   uint64_t c = rotate(a, 37);
224   a += fetch64(s + 8);
225   c += rotate(a, 7);
226   a += fetch64(s + 16);
227   uint64_t vf = a + z;
228   uint64_t vs = b + rotate(a, 31) + c;
229   a = fetch64(s + 16) + fetch64(s + len - 32);
230   z = fetch64(s + len - 8);
231   b = rotate(a + z, 52);
232   c = rotate(a, 37);
233   a += fetch64(s + len - 24);
234   c += rotate(a, 7);
235   a += fetch64(s + len - 16);
236   uint64_t wf = a + z;
237   uint64_t ws = b + rotate(a, 31) + c;
238   uint64_t r = shift_mix((vf + ws) * k2 + (wf + vs) * k0);
239   return shift_mix((seed ^ (r * k0)) + vs) * k2;
240 }
241
242 inline uint64_t hash_short(const char *s, size_t length, uint64_t seed) {
243   if (length >= 4 && length <= 8)
244     return hash_4to8_bytes(s, length, seed);
245   if (length > 8 && length <= 16)
246     return hash_9to16_bytes(s, length, seed);
247   if (length > 16 && length <= 32)
248     return hash_17to32_bytes(s, length, seed);
249   if (length > 32)
250     return hash_33to64_bytes(s, length, seed);
251   if (length != 0)
252     return hash_1to3_bytes(s, length, seed);
253
254   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   uint64_t seed;
263
264   /// \brief Create a new hash_state structure and initialize it based on the
265   /// seed and the first 64-byte chunk.
266   /// This effectively performs the initial mix.
267   static hash_state create(const char *s, uint64_t seed) {
268     hash_state state = {
269       0, seed, hash_16_bytes(seed, k1), rotate(seed ^ k1, 49),
270       seed * k1, shift_mix(seed), hash_16_bytes(state.h4, state.h5),
271       seed
272     };
273     state.mix(s);
274     return state;
275   }
276
277   /// \brief Mix 32-bytes from the input sequence into the 16-bytes of 'a'
278   /// and 'b', including whatever is already in 'a' and 'b'.
279   static void mix_32_bytes(const char *s, uint64_t &a, uint64_t &b) {
280     a += fetch64(s);
281     uint64_t c = fetch64(s + 24);
282     b = rotate(b + a + c, 21);
283     uint64_t d = a;
284     a += fetch64(s + 8) + fetch64(s + 16);
285     b += rotate(a, 44) + d;
286     a += c;
287   }
288
289   /// \brief Mix in a 64-byte buffer of data.
290   /// We mix all 64 bytes even when the chunk length is smaller, but we
291   /// record the actual length.
292   void mix(const char *s) {
293     h0 = rotate(h0 + h1 + h3 + fetch64(s + 8), 37) * k1;
294     h1 = rotate(h1 + h4 + fetch64(s + 48), 42) * k1;
295     h0 ^= h6;
296     h1 += h3 + fetch64(s + 40);
297     h2 = rotate(h2 + h5, 33) * k1;
298     h3 = h4 * k1;
299     h4 = h0 + h5;
300     mix_32_bytes(s, h3, h4);
301     h5 = h2 + h6;
302     h6 = h1 + fetch64(s + 16);
303     mix_32_bytes(s + 32, h5, h6);
304     std::swap(h2, h0);
305   }
306
307   /// \brief Compute the final 64-bit hash code value based on the current
308   /// state and the length of bytes hashed.
309   uint64_t finalize(size_t length) {
310     return hash_16_bytes(hash_16_bytes(h3, h5) + shift_mix(h1) * k1 + h2,
311                          hash_16_bytes(h4, h6) + shift_mix(length) * k1 + h0);
312   }
313 };
314
315
316 /// \brief A global, fixed seed-override variable.
317 ///
318 /// This variable can be set using the \see llvm::set_fixed_execution_seed
319 /// function. See that function for details. Do not, under any circumstances,
320 /// set or read this variable.
321 extern size_t fixed_seed_override;
322
323 inline size_t get_execution_seed() {
324   // FIXME: This needs to be a per-execution seed. This is just a placeholder
325   // implementation. Switching to a per-execution seed is likely to flush out
326   // instability bugs and so will happen as its own commit.
327   //
328   // However, if there is a fixed seed override set the first time this is
329   // called, return that instead of the per-execution seed.
330   const uint64_t seed_prime = 0xff51afd7ed558ccdULL;
331   static size_t seed = fixed_seed_override ? fixed_seed_override
332                                            : static_cast<size_t>(seed_prime);
333   return seed;
334 }
335
336
337 /// \brief Trait to indicate whether a type's bits can be hashed directly.
338 ///
339 /// A type trait which is true if we want to combine values for hashing by
340 /// reading the underlying data. It is false if values of this type must
341 /// first be passed to hash_value, and the resulting hash_codes combined.
342 //
343 // FIXME: We want to replace is_integral and is_pointer here with a predicate
344 // which asserts that comparing the underlying storage of two values of the
345 // type for equality is equivalent to comparing the two values for equality.
346 // For all the platforms we care about, this holds for integers and pointers,
347 // but there are platforms where it doesn't and we would like to support
348 // user-defined types which happen to satisfy this property.
349 template <typename T> struct is_hashable_data
350   : integral_constant<bool, ((is_integral<T>::value || is_pointer<T>::value) &&
351                              64 % sizeof(T) == 0)> {};
352
353 // Special case std::pair to detect when both types are viable and when there
354 // is no alignment-derived padding in the pair. This is a bit of a lie because
355 // std::pair isn't truly POD, but it's close enough in all reasonable
356 // implementations for our use case of hashing the underlying data.
357 template <typename T, typename U> struct is_hashable_data<std::pair<T, U> >
358   : integral_constant<bool, (is_hashable_data<T>::value &&
359                              is_hashable_data<U>::value &&
360                              (sizeof(T) + sizeof(U)) ==
361                               sizeof(std::pair<T, U>))> {};
362
363 /// \brief Helper to get the hashable data representation for a type.
364 /// This variant is enabled when the type itself can be used.
365 template <typename T>
366 typename enable_if<is_hashable_data<T>, T>::type
367 get_hashable_data(const T &value) {
368   return value;
369 }
370 /// \brief Helper to get the hashable data representation for a type.
371 /// This variant is enabled when we must first call hash_value and use the
372 /// result as our data.
373 template <typename T>
374 typename enable_if_c<!is_hashable_data<T>::value, size_t>::type
375 get_hashable_data(const T &value) {
376   using ::llvm::hash_value;
377   return hash_value(value);
378 }
379
380 /// \brief Helper to store data from a value into a buffer and advance the
381 /// pointer into that buffer.
382 ///
383 /// This routine first checks whether there is enough space in the provided
384 /// buffer, and if not immediately returns false. If there is space, it
385 /// copies the underlying bytes of value into the buffer, advances the
386 /// buffer_ptr past the copied bytes, and returns true.
387 template <typename T>
388 bool store_and_advance(char *&buffer_ptr, char *buffer_end, const T& value,
389                        size_t offset = 0) {
390   size_t store_size = sizeof(value) - offset;
391   if (buffer_ptr + store_size > buffer_end)
392     return false;
393   const char *value_data = reinterpret_cast<const char *>(&value);
394   memcpy(buffer_ptr, value_data + offset, store_size);
395   buffer_ptr += store_size;
396   return true;
397 }
398
399 /// \brief Implement the combining of integral values into a hash_code.
400 ///
401 /// This overload is selected when the value type of the iterator is
402 /// integral. Rather than computing a hash_code for each object and then
403 /// combining them, this (as an optimization) directly combines the integers.
404 template <typename InputIteratorT>
405 hash_code hash_combine_range_impl(InputIteratorT first, InputIteratorT last) {
406   typedef typename std::iterator_traits<InputIteratorT>::value_type ValueT;
407   const size_t seed = get_execution_seed();
408   char buffer[64], *buffer_ptr = buffer;
409   char *const buffer_end = buffer_ptr + array_lengthof(buffer);
410   while (first != last && store_and_advance(buffer_ptr, buffer_end,
411                                             get_hashable_data(*first)))
412     ++first;
413 /// \brief Metafunction that determines whether the given type is an integral
414 /// type.
415   if (first == last)
416     return hash_short(buffer, buffer_ptr - buffer, seed);
417   assert(buffer_ptr == buffer_end);
418
419   hash_state state = state.create(buffer, seed);
420   size_t length = 64;
421   while (first != last) {
422     // Fill up the buffer. We don't clear it, which re-mixes the last round
423     // when only a partial 64-byte chunk is left.
424     buffer_ptr = buffer;
425     while (first != last && store_and_advance(buffer_ptr, buffer_end,
426                                               get_hashable_data(*first)))
427       ++first;
428
429     // Rotate the buffer if we did a partial fill in order to simulate doing
430     // a mix of the last 64-bytes. That is how the algorithm works when we
431     // have a contiguous byte sequence, and we want to emulate that here.
432     std::rotate(buffer, buffer_ptr, buffer_end);
433
434     // Mix this chunk into the current state.
435     state.mix(buffer);
436     length += buffer_ptr - buffer;
437   };
438
439   return state.finalize(length);
440 }
441
442 /// \brief Implement the combining of integral values into a hash_code.
443 ///
444 /// This overload is selected when the value type of the iterator is integral
445 /// and when the input iterator is actually a pointer. Rather than computing
446 /// a hash_code for each object and then combining them, this (as an
447 /// optimization) directly combines the integers. Also, because the integers
448 /// are stored in contiguous memory, this routine avoids copying each value
449 /// and directly reads from the underlying memory.
450 template <typename ValueT>
451 typename enable_if<is_hashable_data<ValueT>, hash_code>::type
452 hash_combine_range_impl(const ValueT *first, const ValueT *last) {
453   const size_t seed = get_execution_seed();
454   const char *s_begin = reinterpret_cast<const char *>(first);
455   const char *s_end = reinterpret_cast<const char *>(last);
456   const size_t length = std::distance(s_begin, s_end);
457   if (length <= 64)
458     return hash_short(s_begin, length, seed);
459
460   const char *s_aligned_end = s_begin + (length & ~63);
461   hash_state state = state.create(s_begin, seed);
462   s_begin += 64;
463   while (s_begin != s_aligned_end) {
464     state.mix(s_begin);
465     s_begin += 64;
466   }
467   if (length & 63)
468     state.mix(s_end - 64);
469
470   return state.finalize(length);
471 }
472
473 } // namespace detail
474 } // namespace hashing
475
476
477 /// \brief Compute a hash_code for a sequence of values.
478 ///
479 /// This hashes a sequence of values. It produces the same hash_code as
480 /// 'hash_combine(a, b, c, ...)', but can run over arbitrary sized sequences
481 /// and is significantly faster given pointers and types which can be hashed as
482 /// a sequence of bytes.
483 template <typename InputIteratorT>
484 hash_code hash_combine_range(InputIteratorT first, InputIteratorT last) {
485   return ::llvm::hashing::detail::hash_combine_range_impl(first, last);
486 }
487
488
489 // Implementation details for hash_combine.
490 namespace hashing {
491 namespace detail {
492
493 /// \brief Helper class to manage the recursive combining of hash_combine
494 /// arguments.
495 ///
496 /// This class exists to manage the state and various calls involved in the
497 /// recursive combining of arguments used in hash_combine. It is particularly
498 /// useful at minimizing the code in the recursive calls to ease the pain
499 /// caused by a lack of variadic functions.
500 class hash_combine_recursive_helper {
501   const size_t seed;
502   char buffer[64];
503   char *const buffer_end;
504   char *buffer_ptr;
505   size_t length;
506   hash_state state;
507
508 public:
509   /// \brief Construct a recursive hash combining helper.
510   ///
511   /// This sets up the state for a recursive hash combine, including getting
512   /// the seed and buffer setup.
513   hash_combine_recursive_helper()
514     : seed(get_execution_seed()),
515       buffer_end(buffer + array_lengthof(buffer)),
516       buffer_ptr(buffer),
517       length(0) {}
518
519   /// \brief Combine one chunk of data into the current in-flight hash.
520   ///
521   /// This merges one chunk of data into the hash. First it tries to buffer
522   /// the data. If the buffer is full, it hashes the buffer into its
523   /// hash_state, empties it, and then merges the new chunk in. This also
524   /// handles cases where the data straddles the end of the buffer.
525   template <typename T> void combine_data(T data) {
526     if (!store_and_advance(buffer_ptr, buffer_end, data)) {
527       // Check for skew which prevents the buffer from being packed, and do
528       // a partial store into the buffer to fill it. This is only a concern
529       // with the variadic combine because that formation can have varying
530       // argument types.
531       size_t partial_store_size = buffer_end - buffer_ptr;
532       memcpy(buffer_ptr, &data, partial_store_size);
533
534       // If the store fails, our buffer is full and ready to hash. We have to
535       // either initialize the hash state (on the first full buffer) or mix
536       // this buffer into the existing hash state. Length tracks the *hashed*
537       // length, not the buffered length.
538       if (length == 0) {
539         state = state.create(buffer, seed);
540         length = 64;
541       } else {
542         // Mix this chunk into the current state and bump length up by 64.
543         state.mix(buffer);
544         length += 64;
545       }
546       // Reset the buffer_ptr to the head of the buffer for the next chunk of
547       // data.
548       buffer_ptr = buffer;
549
550       // Try again to store into the buffer -- this cannot fail as we only
551       // store types smaller than the buffer.
552       if (!store_and_advance(buffer_ptr, buffer_end, data,
553                              partial_store_size))
554         abort();
555     }
556   }
557
558 #if defined(__has_feature) && __has_feature(__cxx_variadic_templates__)
559
560   /// \brief Recursive, variadic combining method.
561   ///
562   /// This function recurses through each argument, combining that argument
563   /// into a single hash.
564   template <typename T, typename ...Ts>
565   hash_code combine(const T &arg, const Ts &...args) {
566     combine_data( get_hashable_data(arg));
567
568     // Recurse to the next argument.
569     return combine(args...);
570   }
571
572 #else
573   // Manually expanded recursive combining methods. See variadic above for
574   // documentation.
575
576   template <typename T1, typename T2, typename T3, typename T4, typename T5,
577             typename T6>
578   hash_code combine(const T1 &arg1, const T2 &arg2, const T3 &arg3,
579                     const T4 &arg4, const T5 &arg5, const T6 &arg6) {
580     combine_data(get_hashable_data(arg1));
581     return combine(arg2, arg3, arg4, arg5, arg6);
582   }
583   template <typename T1, typename T2, typename T3, typename T4, typename T5>
584   hash_code combine(const T1 &arg1, const T2 &arg2, const T3 &arg3,
585                     const T4 &arg4, const T5 &arg5) {
586     combine_data(get_hashable_data(arg1));
587     return combine(arg2, arg3, arg4, arg5);
588   }
589   template <typename T1, typename T2, typename T3, typename T4>
590   hash_code combine(const T1 &arg1, const T2 &arg2, const T3 &arg3,
591                     const T4 &arg4) {
592     combine_data(get_hashable_data(arg1));
593     return combine(arg2, arg3, arg4);
594   }
595   template <typename T1, typename T2, typename T3>
596   hash_code combine(const T1 &arg1, const T2 &arg2, const T3 &arg3) {
597     combine_data(get_hashable_data(arg1));
598     return combine(arg2, arg3);
599   }
600   template <typename T1, typename T2>
601   hash_code combine(const T1 &arg1, const T2 &arg2) {
602     combine_data(get_hashable_data(arg1));
603     return combine(arg2);
604   }
605   template <typename T1>
606   hash_code combine(const T1 &arg1) {
607     combine_data(get_hashable_data(arg1));
608     return combine();
609   }
610
611 #endif
612
613   /// \brief Base case for recursive, variadic combining.
614   ///
615   /// The base case when combining arguments recursively is reached when all
616   /// arguments have been handled. It flushes the remaining buffer and
617   /// constructs a hash_code.
618   hash_code combine() {
619     // Check whether the entire set of values fit in the buffer. If so, we'll
620     // use the optimized short hashing routine and skip state entirely.
621     if (length == 0)
622       return hash_short(buffer, buffer_ptr - buffer, seed);
623
624     // Mix the final buffer, rotating it if we did a partial fill in order to
625     // simulate doing a mix of the last 64-bytes. That is how the algorithm
626     // works when we have a contiguous byte sequence, and we want to emulate
627     // that here.
628     std::rotate(buffer, buffer_ptr, buffer_end);
629
630     // Mix this chunk into the current state.
631     state.mix(buffer);
632     length += buffer_ptr - buffer;
633
634     return state.finalize(length);
635   }
636 };
637
638 } // namespace detail
639 } // namespace hashing
640
641
642 #if __has_feature(__cxx_variadic_templates__)
643
644 /// \brief Combine values into a single hash_code.
645 ///
646 /// This routine accepts a varying number of arguments of any type. It will
647 /// attempt to combine them into a single hash_code. For user-defined types it
648 /// attempts to call a \see hash_value overload (via ADL) for the type. For
649 /// integer and pointer types it directly combines their data into the
650 /// resulting hash_code.
651 ///
652 /// The result is suitable for returning from a user's hash_value
653 /// *implementation* for their user-defined type. Consumers of a type should
654 /// *not* call this routine, they should instead call 'hash_value'.
655 template <typename ...Ts> hash_code hash_combine(const Ts &...args) {
656   // Recursively hash each argument using a helper class.
657   ::llvm::hashing::detail::hash_combine_recursive_helper helper;
658   return helper.combine(args...);
659 }
660
661 #else
662
663 // What follows are manually exploded overloads for each argument width. See
664 // the above variadic definition for documentation and specification.
665
666 template <typename T1, typename T2, typename T3, typename T4, typename T5,
667           typename T6>
668 hash_code hash_combine(const T1 &arg1, const T2 &arg2, const T3 &arg3,
669                   const T4 &arg4, const T5 &arg5, const T6 &arg6) {
670   ::llvm::hashing::detail::hash_combine_recursive_helper helper;
671   return helper.combine(arg1, arg2, arg3, arg4, arg5, arg6);
672 }
673 template <typename T1, typename T2, typename T3, typename T4, typename T5>
674 hash_code hash_combine(const T1 &arg1, const T2 &arg2, const T3 &arg3,
675                   const T4 &arg4, const T5 &arg5) {
676   ::llvm::hashing::detail::hash_combine_recursive_helper helper;
677   return helper.combine(arg1, arg2, arg3, arg4, arg5);
678 }
679 template <typename T1, typename T2, typename T3, typename T4>
680 hash_code hash_combine(const T1 &arg1, const T2 &arg2, const T3 &arg3,
681                   const T4 &arg4) {
682   ::llvm::hashing::detail::hash_combine_recursive_helper helper;
683   return helper.combine(arg1, arg2, arg3, arg4);
684 }
685 template <typename T1, typename T2, typename T3>
686 hash_code hash_combine(const T1 &arg1, const T2 &arg2, const T3 &arg3) {
687   ::llvm::hashing::detail::hash_combine_recursive_helper helper;
688   return helper.combine(arg1, arg2, arg3);
689 }
690 template <typename T1, typename T2>
691 hash_code hash_combine(const T1 &arg1, const T2 &arg2) {
692   ::llvm::hashing::detail::hash_combine_recursive_helper helper;
693   return helper.combine(arg1, arg2);
694 }
695 template <typename T1>
696 hash_code hash_combine(const T1 &arg1) {
697   ::llvm::hashing::detail::hash_combine_recursive_helper helper;
698   return helper.combine(arg1);
699 }
700
701 #endif
702
703
704 // Implementation details for implementatinos of hash_value overloads provided
705 // here.
706 namespace hashing {
707 namespace detail {
708
709 /// \brief Helper to hash the value of a single integer.
710 ///
711 /// Overloads for smaller integer types are not provided to ensure consistent
712 /// behavior in the presence of integral promotions. Essentially,
713 /// "hash_value('4')" and "hash_value('0' + 4)" should be the same.
714 inline hash_code hash_integer_value(uint64_t value) {
715   // Similar to hash_4to8_bytes but using a seed instead of length.
716   const uint64_t seed = get_execution_seed();
717   const char *s = reinterpret_cast<const char *>(&value);
718   const uint64_t a = fetch32(s);
719   return hash_16_bytes(seed + (a << 3), fetch32(s + 4));
720 }
721
722 } // namespace detail
723 } // namespace hashing
724
725 // Declared and documented above, but defined here so that any of the hashing
726 // infrastructure is available.
727 template <typename T>
728 typename enable_if<is_integral<T>, hash_code>::type hash_value(T value) {
729   return ::llvm::hashing::detail::hash_integer_value(value);
730 }
731
732 // Declared and documented above, but defined here so that any of the hashing
733 // infrastructure is available.
734 template <typename T> hash_code hash_value(const T *ptr) {
735   return ::llvm::hashing::detail::hash_integer_value(
736     reinterpret_cast<uintptr_t>(ptr));
737 }
738
739 // Declared and documented above, but defined here so that any of the hashing
740 // infrastructure is available.
741 template <typename T, typename U>
742 hash_code hash_value(const std::pair<T, U> &arg) {
743   return hash_combine(arg.first, arg.second);
744 }
745
746 } // namespace llvm
747
748 #endif