Hashing.h 26 KB

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