Hashing.h 25 KB

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