Hashing.h 26 KB

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