hashing.h 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef CARBON_COMMON_HASHING_H_
  5. #define CARBON_COMMON_HASHING_H_
  6. #include <concepts>
  7. #include <string>
  8. #include <tuple>
  9. #include <type_traits>
  10. #include <utility>
  11. #include "common/check.h"
  12. #include "common/ostream.h"
  13. #include "llvm/ADT/APFloat.h"
  14. #include "llvm/ADT/APInt.h"
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/StringRef.h"
  18. #include "llvm/Support/FormatVariadic.h"
  19. #ifdef __ARM_ACLE
  20. #include <arm_acle.h>
  21. #endif
  22. namespace Carbon {
  23. // A 64-bit hash code produced by `Carbon::HashValue`.
  24. //
  25. // This provides methods for extracting high-quality bits from the hash code
  26. // quickly.
  27. //
  28. // This class can also be a hashing input when recursively hashing more complex
  29. // data structures.
  30. class HashCode : public Printable<HashCode> {
  31. public:
  32. HashCode() = default;
  33. constexpr explicit HashCode(uint64_t value) : value_(value) {}
  34. friend constexpr auto operator==(HashCode lhs, HashCode rhs) -> bool {
  35. return lhs.value_ == rhs.value_;
  36. }
  37. friend constexpr auto operator!=(HashCode lhs, HashCode rhs) -> bool {
  38. return lhs.value_ != rhs.value_;
  39. }
  40. // Extracts an index from the hash code as a `ssize_t`. This index covers the
  41. // full range of that type, and may even be negative. Typical usage will
  42. // involve masking this down to some positive range using a bitand with a mask
  43. // computed from a power-of-two size. This routine doesn't do any masking to
  44. // ensure a positive index to avoid redundant computations with the typical
  45. // user of the index.
  46. constexpr auto ExtractIndex() -> ssize_t;
  47. // Extracts an index and a fixed `N`-bit tag from the hash code.
  48. //
  49. // This extracts these values from the position of the hash code which
  50. // maximizes the entropy in the tag and the low bits of the index, as typical
  51. // indices will be further masked down to fall in a smaller range.
  52. //
  53. // `N` must be in the range [1, 32]. The returned index will be in the range
  54. // [0, 2**(64-N)).
  55. template <int N>
  56. constexpr auto ExtractIndexAndTag() -> std::pair<ssize_t, uint32_t>;
  57. // Extract the full 64-bit hash code as an integer.
  58. //
  59. // The methods above should be preferred rather than directly manipulating
  60. // this integer. This is provided primarily to enable Merkle-tree hashing or
  61. // other recursive hashing where that is needed or more efficient.
  62. explicit operator uint64_t() const { return value_; }
  63. auto Print(llvm::raw_ostream& out) const -> void {
  64. out << llvm::formatv("{0:x16}", value_);
  65. }
  66. private:
  67. uint64_t value_ = 0;
  68. };
  69. // Computes a hash code for the provided value, incorporating the provided seed.
  70. //
  71. // The seed doesn't need to be of any particular high quality, but a zero seed
  72. // has bad effects in several places. Prefer the unseeded routine rather than
  73. // providing a zero here.
  74. //
  75. // This **not** a cryptographically secure or stable hash -- it is only designed
  76. // for use with in-memory hash table style data structures. Being fast and
  77. // effective for that use case is the guiding principle of its design.
  78. //
  79. // There is no guarantee that the values produced are stable from execution to
  80. // execution. For speed and quality reasons, the implementation does not
  81. // introduce any variance to defend against accidental dependencies. As a
  82. // consequence, it is strongly encouraged to use a seed that varies from
  83. // execution to execution to avoid depending on specific values produced.
  84. //
  85. // The algorithm used is most heavily based on [Abseil's hashing algorithm][1],
  86. // with some additional ideas and inspiration from the fallback hashing
  87. // algorithm in [Rust's AHash][2] and the [FxHash][3] function. However, there
  88. // are also *significant* changes introduced here.
  89. //
  90. // [1]: https://github.com/abseil/abseil-cpp/tree/master/absl/hash/internal
  91. // [2]: https://github.com/tkaitchuck/aHash/wiki/AHash-fallback-algorithm
  92. // [3]: https://docs.rs/fxhash/latest/fxhash/
  93. //
  94. // This hash algorithm does *not* defend against hash flooding. While it can be
  95. // viewed as "keyed" on the seed, it is expected to be possible to craft inputs
  96. // for some data types that cancel out the seed used and manufacture endlessly
  97. // colliding sets of keys. In general, this function works to be *fast* for hash
  98. // tables. If you need to defend against hash flooding, either directly use a
  99. // data structure with strong worst-case guarantees, or a hash table which
  100. // detects catastrophic collisions and falls back to such a data structure.
  101. //
  102. // This hash function is heavily optimized for *latency* over *quality*. Modern
  103. // hash tables designs can efficiently handle reasonable collision rates,
  104. // including using extra bits from the hash to avoid all efficiency coming from
  105. // the same low bits. Because of this, low-latency is significantly more
  106. // important for performance than high-quality, and this is heavily leveraged.
  107. // The result is that the hash codes produced *do* have significant avalanche
  108. // problems for small keys. The upside is that the latency for hashing integers,
  109. // pointers, and small byte strings (up to 32-bytes) is exceptionally low, and
  110. // essentially a small constant time instruction sequence.
  111. //
  112. // No exotic instruction set extensions are required, and the state used is
  113. // small. It does rely on being able to get the low- and high-64-bit results of
  114. // a 64-bit multiply efficiently.
  115. //
  116. // The function supports many typical data types such as primitives, string-ish
  117. // views, and types composing primitives transparently like pairs, tuples, and
  118. // array-ish views. It is also extensible to support user-defined types.
  119. //
  120. // The builtin support for string-like types include:
  121. // - `std::string_view`
  122. // - `std::string`
  123. // - `llvm::StringRef`
  124. // - `llvm::SmallString`
  125. //
  126. // This function supports heterogeneous lookup between all of the string-like
  127. // types. It also supports heterogeneous lookup between pointer types regardless
  128. // of pointee type and `nullptr`.
  129. //
  130. // However, these are the only heterogeneous lookup support including for the
  131. // builtin in, standard, and LLVM types. Notably, each different size and
  132. // signedness integer type may hash differently for efficiency reasons. Hash
  133. // tables should pick a single integer type in which to manage keys and do
  134. // lookups.
  135. //
  136. // To add support for your type, you need to implement a customization point --
  137. // a free function that can be found by ADL for your type -- called
  138. // `CarbonHashValue` with the following signature:
  139. //
  140. // ```cpp
  141. // auto CarbonHashValue(const YourType& value, uint64_t seed) -> HashCode;
  142. // ```
  143. //
  144. // The extension point needs to ensure that values that compare equal (including
  145. // any comparisons with different types that might be used with a hash table of
  146. // `YourType` keys) produce the same `HashCode` values.
  147. //
  148. // `HashCode` values should typically be produced using the `Hasher` helper type
  149. // below. See its documentation for more details about implementing these
  150. // customization points and how best to incorporate the value's state into a
  151. // `HashCode`.
  152. //
  153. // For two input values that are almost but not quite equal, the extension
  154. // point should maximize the probability of each bit of their resulting
  155. // `HashCode`s differing. More formally, `HashCode`s should exhibit an
  156. // [avalanche effect][4]. However, while this is desirable, it should be
  157. // **secondary** to low latency. The intended use case of these functions is not
  158. // cryptography but in-memory hashtables where the latency and overhead of
  159. // computing the `HashCode` is *significantly* more important than achieving a
  160. // particularly high quality. The goal is to have "just enough" avalanche
  161. // effect, but there is not a fixed criteria for how much is enough. That should
  162. // be determined through practical experimentation with a hashtable and
  163. // distribution of keys.
  164. //
  165. // [4]: https://en.wikipedia.org/wiki/Avalanche_effect
  166. template <typename T>
  167. inline auto HashValue(const T& value, uint64_t seed) -> HashCode;
  168. // The same as the seeded version of `HashValue` but without callers needing to
  169. // provide a seed.
  170. //
  171. // Generally prefer the seeded version, but this is available if there is no
  172. // reasonable seed. In particular, this will behave better than using a seed of
  173. // `0`. One important use case is for recursive hashing of sub-objects where
  174. // appropriate or needed.
  175. template <typename T>
  176. inline auto HashValue(const T& value) -> HashCode;
  177. // Object and APIs that eventually produce a hash code.
  178. //
  179. // This type is primarily used by types to implement a customization point
  180. // `CarbonHashValue` that will in turn be used by the `HashValue` function. See
  181. // the `HashValue` function for details of that extension point.
  182. //
  183. // The methods on this type can be used to incorporate data from your
  184. // user-defined type into its internal state which can be converted to a
  185. // `HashCode` at any time. These methods will only produce the same `HashCode`
  186. // if they are called in the exact same order with the same arguments -- there
  187. // are no guaranteed equivalences between calling different methods.
  188. //
  189. // Example usage:
  190. // ```cpp
  191. // auto CarbonHashValue(const MyType& value, uint64_t seed) -> HashCode {
  192. // Hasher hasher(seed);
  193. // hasher.HashTwo(value.x, value.y);
  194. // return static_cast<HashCode>(hasher);
  195. // }
  196. // ```
  197. //
  198. // This type's API also reflects the reality that high-performance hash tables
  199. // are used with keys that are generally small and cheap to hash.
  200. //
  201. // To ensure this type's code is optimized effectively, it should typically be
  202. // used as a local variable and not passed across function boundaries
  203. // unnecessarily.
  204. //
  205. // The type also provides a number of static helper functions and static data
  206. // members that may be used by authors of `CarbonHashValue` implementations to
  207. // efficiently compute the inputs to the core `Hasher` methods, or even to
  208. // manually do some amounts of hashing in performance-tuned ways outside of the
  209. // methods provided.
  210. class Hasher {
  211. public:
  212. Hasher() = default;
  213. explicit Hasher(uint64_t seed) : buffer(seed) {}
  214. Hasher(Hasher&& arg) = default;
  215. Hasher(const Hasher& arg) = delete;
  216. auto operator=(Hasher&& rhs) -> Hasher& = default;
  217. // Extracts the current state as a `HashCode` for use.
  218. explicit operator HashCode() const { return HashCode(buffer); }
  219. // Incorporates a variable number of objects into the `hasher`s state.
  220. //
  221. // The `values` here can be anything hashable, and this routine handles
  222. // recursively hashing a single value as appropriate and then in turn
  223. // incorporating that. However, it is optimized for relatively small numbers
  224. // of values and/or small elements. A large tree structure will be better
  225. // handled by a dedicated Merkle-tree decomposition rather than the ad-hoc one
  226. // provided here. This routine's decomposition is mostly useful for combining
  227. // N small bits of data with one recursively hashed entity.
  228. //
  229. // There is no guaranteed correspondence between the behavior of a single call
  230. // with multiple parameters and multiple calls.
  231. template <typename... Ts>
  232. auto Hash(const Ts&... values) -> void;
  233. // Incorporates an array of objects into the hasher's state.
  234. //
  235. // Similar to the variadic `Hash`, this will handle recursively hashing if
  236. // necessary, but is optimized to avoid it when possible and is especially
  237. // efficient when hashing a raw array of bytes.
  238. //
  239. // Note that this is especially inefficient when it must recursively hash for
  240. // long arrays -- that pattern should be avoided if possible. It is usually
  241. // more effective to optimize that pattern at a higher level with a dedicated
  242. // hashing implementation.
  243. template <typename T>
  244. auto HashArray(llvm::ArrayRef<T> values) -> void;
  245. // Incorporates an object into the hasher's state by hashing its object
  246. // representation. Requires `value`'s type to have a unique object
  247. // representation. This is primarily useful for builtin and primitive types.
  248. //
  249. // This can be directly used for simple users combining some aggregation of
  250. // objects. However, when possible, prefer the variadic version below for
  251. // aggregating several primitive types into a hash.
  252. template <typename T>
  253. requires std::has_unique_object_representations_v<T>
  254. auto HashRaw(const T& value) -> void;
  255. // Simpler and more primitive functions to incorporate state represented in
  256. // `uint64_t` values into the hasher's state.
  257. //
  258. // These may be slightly less efficient than the `Hash` method above for a
  259. // typical application code `uint64_t`, but are designed to work well even
  260. // when relevant data has been packed into the `uint64_t` parameters densely.
  261. auto HashDense(uint64_t data) -> void;
  262. auto HashDense(uint64_t data0, uint64_t data1) -> void;
  263. // A heavily optimized routine for incorporating a dynamically sized sequence
  264. // of bytes into the hasher's state.
  265. //
  266. // This routine has carefully structured inline code paths for short byte
  267. // sequences and a reasonably high bandwidth code path for longer sequences.
  268. // The size of the byte sequence is always incorporated into the hasher's
  269. // state along with the contents.
  270. auto HashSizedBytes(llvm::ArrayRef<std::byte> bytes) -> void;
  271. // Incorporate a dynamically sized sequence of bytes represented as an array
  272. // of objects into the hasher's state.
  273. template <typename T>
  274. requires std::has_unique_object_representations_v<T>
  275. auto HashSizedBytes(llvm::ArrayRef<T> data) -> void {
  276. HashSizedBytes(llvm::ArrayRef<std::byte>(
  277. reinterpret_cast<const std::byte*>(data.data()),
  278. data.size() * sizeof(T)));
  279. }
  280. // An out-of-line, throughput-optimized routine for incorporating a
  281. // dynamically sized sequence when the sequence size is guaranteed to be >32.
  282. // The size is always incorporated into the state.
  283. auto HashSizedBytesLarge(llvm::ArrayRef<std::byte> bytes) -> void;
  284. // Utility functions to read data of various sizes efficiently into a
  285. // 64-bit value. These pointers need-not be aligned, and can alias other
  286. // objects. The representation of the read data in the `uint64_t` returned is
  287. // not stable or guaranteed.
  288. static auto Read1(const std::byte* data) -> uint64_t;
  289. static auto Read2(const std::byte* data) -> uint64_t;
  290. static auto Read4(const std::byte* data) -> uint64_t;
  291. static auto Read8(const std::byte* data) -> uint64_t;
  292. // Similar to the `ReadN` functions, but supports reading a range of different
  293. // bytes provided by the size *without branching on the size*. The lack of
  294. // branches is often key, and the code in these routines works to be efficient
  295. // in extracting a *dynamic* size of bytes into the returned `uint64_t`. There
  296. // may be overlap between different routines, because these routines are based
  297. // on different implementation techniques that do have some overlap in the
  298. // range of sizes they can support. Which routine is the most efficient for a
  299. // size in the overlap isn't trivial, and so these primitives are provided
  300. // as-is and should be selected based on the localized generated code and
  301. // benchmarked performance.
  302. static auto Read1To3(const std::byte* data, ssize_t size) -> uint64_t;
  303. static auto Read4To8(const std::byte* data, ssize_t size) -> uint64_t;
  304. static auto Read8To16(const std::byte* data, ssize_t size)
  305. -> std::pair<uint64_t, uint64_t>;
  306. // Reads the underlying object representation of a type into a 64-bit integer
  307. // efficiently. Only supports types with unique object representation and at
  308. // most 8-bytes large. This is typically used to read primitive types.
  309. template <typename T>
  310. requires std::has_unique_object_representations_v<T> && (sizeof(T) <= 8)
  311. static auto ReadSmall(const T& value) -> uint64_t;
  312. // The core of the hash algorithm is this mix function. The specific
  313. // operations are not guaranteed to be stable but are described here for
  314. // hashing authors to understand what to expect.
  315. //
  316. // Currently, this uses the same "mix" operation as in Abseil, AHash, and
  317. // several other hashing algorithms. It takes two 64-bit integers, and
  318. // multiplies them, capturing both the high 64-bit result and the low 64-bit
  319. // result, and then XOR-ing those two halves together.
  320. //
  321. // A consequence of this operation is that a zero on either side will fail to
  322. // incorporate any bits from the other side. Often, this is an acceptable rate
  323. // of collision in practice. But it is worth being aware of and working to
  324. // avoid common paths encountering this. For example, naively used this might
  325. // cause different length all-zero byte strings to hash the same, essentially
  326. // losing the length in the composition of the hash for a likely important
  327. // case of byte sequence.
  328. //
  329. // Another consequence of the particular implementation is that it is useful
  330. // to have a reasonable distribution of bits throughout both sides of the
  331. // multiplication. However, it is not *necessary* as we do capture the
  332. // complete 128-bit result. Where reasonable, the caller should XOR random
  333. // data into operands before calling `Mix` to try and increase the
  334. // distribution of bits feeding the multiply.
  335. static auto Mix(uint64_t lhs, uint64_t rhs) -> uint64_t;
  336. // An alternative to `Mix` that is significantly weaker but also lower
  337. // latency. It should not be used when the input `uint64_t` is densely packed
  338. // with data, but is a good option for hashing a single integer or pointer
  339. // where the full 64-bits are sparsely populated and especially the high bits
  340. // are often invariant between interestingly different values.
  341. //
  342. // This uses just the low 64-bit result of a multiply. It ensures the operand
  343. // is good at diffusing bits, but inherently the high bits of the input will
  344. // be (significantly) less often represented in the output. It also does some
  345. // reversal to ensure the *low* bits of the result are the most useful ones.
  346. static auto WeakMix(uint64_t value) -> uint64_t;
  347. // We have a 64-byte random data pool designed to fit on a single cache line.
  348. // This routine allows sampling it at byte indices, which allows getting 64 -
  349. // 8 different random 64-bit results. The offset must be in the range [0, 56).
  350. static auto SampleRandomData(ssize_t offset) -> uint64_t {
  351. CARBON_DCHECK(offset + sizeof(uint64_t) < sizeof(StaticRandomData));
  352. uint64_t data;
  353. memcpy(&data,
  354. reinterpret_cast<const unsigned char*>(&StaticRandomData) + offset,
  355. sizeof(data));
  356. return data;
  357. }
  358. // Random data taken from the hexadecimal digits of Pi's fractional component,
  359. // written in lexical order for convenience of reading. The resulting
  360. // byte-stream will be different due to little-endian integers. These can be
  361. // used directly for convenience rather than calling `SampleRandomData`, but
  362. // be aware that this is the underlying pool. The goal is to reuse the same
  363. // single cache-line of constant data.
  364. //
  365. // The initializers here can be generated with the following shell script,
  366. // which will generate 8 64-bit values and one more digit. The `bc` command's
  367. // decimal based scaling means that without getting at least some extra hex
  368. // digits rendered there will be rounding that we don't want so the script
  369. // below goes on to produce one more hex digit ensuring the 8 initializers
  370. // aren't rounded in any way. Using a higher scale won't cause the 8
  371. // initializers here to change further.
  372. //
  373. // ```sh
  374. // echo 'obase=16; scale=155; 4*a(1)' | env BC_LINE_LENGTH=500 bc -l \
  375. // | cut -c 3- | tr '[:upper:]' '[:lower:]' \
  376. // | sed -e "s/.\{4\}/&'/g" \
  377. // | sed -e "s/\(.\{4\}'.\{4\}'.\{4\}'.\{4\}\)'/0x\1,\n/g"
  378. // ```
  379. static constexpr std::array<uint64_t, 8> StaticRandomData = {
  380. 0x243f'6a88'85a3'08d3, 0x1319'8a2e'0370'7344, 0xa409'3822'299f'31d0,
  381. 0x082e'fa98'ec4e'6c89, 0x4528'21e6'38d0'1377, 0xbe54'66cf'34e9'0c6c,
  382. 0xc0ac'29b7'c97c'50dd, 0x3f84'd5b5'b547'0917,
  383. };
  384. // We need a multiplicative hashing constant for both 64-bit multiplicative
  385. // hashing fast paths and some other 128-bit folded multiplies. We use an
  386. // empirically better constant compared to Knuth's, Rust's FxHash, and others
  387. // we've tried. It was found by a search of uniformly distributed odd numbers
  388. // and examining them for desirable properties when used as a multiplicative
  389. // hash, however our search seems largely to have been lucky rather than
  390. // having a highly effective set of criteria. We evaluated this constant by
  391. // integrating this hash function with a hashtable and looking at the
  392. // collision rates of several different but very fundamental patterns of keys:
  393. // integers counting from 0, pointers allocated on the heap, and strings with
  394. // character and size distributions matching C-style ASCII identifiers.
  395. // Different constants found with this search worked better or less well, but
  396. // fairly consistently across the different types of keys. At the end, far and
  397. // away the best behaved constant we found was one of the first ones in the
  398. // search and is what we use here.
  399. //
  400. // For reference, some other constants include one derived by diving 2^64 by
  401. // Phi: 0x9e37'79b9'7f4a'7c15U -- see these sites for details:
  402. // https://probablydance.com/2018/06/16/fibonacci-hashing-the-optimization-that-the-world-forgot-or-a-better-alternative-to-integer-modulo/
  403. // https://book.huihoo.com/data-structures-and-algorithms-with-object-oriented-design-patterns-in-c++/html/page214.html
  404. //
  405. // Another very good constant derived by minimizing repeating bit patterns is
  406. // 0xdcb2'2ca6'8cb1'34edU and its bit-reversed form. However, this constant
  407. // has observed frequent issues at roughly 4k pointer keys, connected to a
  408. // common hashtable seed also being a pointer. These issues appear to occur
  409. // both more often and have a larger impact relative to the number of keys
  410. // than the rare cases where some combinations of pointer seeds and pointer
  411. // keys create minor quality issues with the constant we use.
  412. static constexpr uint64_t MulConstant = 0x7924'f9e0'de1e'8cf5U;
  413. private:
  414. uint64_t buffer;
  415. };
  416. // A dedicated namespace for `CarbonHashValue` overloads that are not found by
  417. // ADL with their associated types. For example, primitive type overloads or
  418. // overloads for types in LLVM's libraries.
  419. //
  420. // Note that these are internal implementation details and **not** part of the
  421. // public API. They should not be used directly by client code.
  422. namespace InternalHashDispatch {
  423. template <typename T>
  424. inline auto CarbonHashValue(llvm::ArrayRef<T> values, uint64_t seed)
  425. -> HashCode {
  426. Hasher hasher(seed);
  427. hasher.HashArray(values);
  428. return static_cast<HashCode>(hasher);
  429. }
  430. inline auto CarbonHashValue(llvm::ArrayRef<std::byte> bytes, uint64_t seed)
  431. -> HashCode {
  432. Hasher hasher(seed);
  433. hasher.HashSizedBytes(bytes);
  434. return static_cast<HashCode>(hasher);
  435. }
  436. // Hashing implementation for `llvm::StringRef`. We forward all the other
  437. // string-like types that support heterogeneous lookup to this one.
  438. inline auto CarbonHashValue(llvm::StringRef value, uint64_t seed) -> HashCode {
  439. return CarbonHashValue(
  440. llvm::ArrayRef(reinterpret_cast<const std::byte*>(value.data()),
  441. value.size()),
  442. seed);
  443. }
  444. inline auto CarbonHashValue(std::string_view value, uint64_t seed) -> HashCode {
  445. return CarbonHashValue(llvm::StringRef(value.data(), value.size()), seed);
  446. }
  447. inline auto CarbonHashValue(const std::string& value, uint64_t seed)
  448. -> HashCode {
  449. return CarbonHashValue(llvm::StringRef(value.data(), value.size()), seed);
  450. }
  451. template <unsigned Length>
  452. inline auto CarbonHashValue(const llvm::SmallString<Length>& value,
  453. uint64_t seed) -> HashCode {
  454. return CarbonHashValue(llvm::StringRef(value.data(), value.size()), seed);
  455. }
  456. // Support types that are array-like by building an `llvm::ArrayRef` out of
  457. // them. We can't do this by accepting any type convertible to an `ArrayRef`
  458. // because that type supports building a synthetic array out of any single
  459. // element.
  460. template <typename T>
  461. inline auto CarbonHashValue(const std::vector<T>& arg, uint64_t seed)
  462. -> HashCode {
  463. return CarbonHashValue(llvm::ArrayRef(arg), seed);
  464. }
  465. template <typename T>
  466. inline auto CarbonHashValue(const llvm::SmallVectorImpl<T>& arg, uint64_t seed)
  467. -> HashCode {
  468. return CarbonHashValue(llvm::ArrayRef(arg), seed);
  469. }
  470. template <typename T, size_t N>
  471. inline auto CarbonHashValue(const std::array<T, N>& arg, uint64_t seed)
  472. -> HashCode {
  473. return CarbonHashValue(llvm::ArrayRef(arg), seed);
  474. }
  475. template <typename T, size_t N>
  476. inline auto CarbonHashValue(const T (&arg)[N], uint64_t seed) -> HashCode {
  477. return CarbonHashValue(llvm::ArrayRef(arg), seed);
  478. }
  479. inline auto CarbonHashValue(llvm::APInt value, uint64_t seed) -> HashCode {
  480. Hasher hasher(seed);
  481. if (LLVM_LIKELY(value.isSingleWord())) {
  482. hasher.Hash(value.getBitWidth(), value.getZExtValue());
  483. } else {
  484. hasher.HashRaw(value.getBitWidth());
  485. hasher.HashSizedBytes(
  486. llvm::ArrayRef(value.getRawData(), value.getNumWords()));
  487. }
  488. return static_cast<HashCode>(hasher);
  489. }
  490. inline auto CarbonHashValue(llvm::APFloat value, uint64_t seed) -> HashCode {
  491. Hasher hasher(seed);
  492. // Hashing floating point numbers is complex and depends on the specific
  493. // internal semantics of `APFloat`, so delegate to the LLVM hashing framework
  494. // here. We re-hash the result to mix in our seed. All of this is a bit
  495. // inefficient, and we can revisit this to provide a dedicated implementation
  496. // if it becomes a bottleneck.
  497. using llvm::hash_value;
  498. hasher.HashRaw(hash_value(value));
  499. return static_cast<HashCode>(hasher);
  500. }
  501. template <typename... Ts>
  502. inline auto CarbonHashValue(const std::tuple<Ts...>& value, uint64_t seed)
  503. -> HashCode {
  504. Hasher hasher(seed);
  505. std::apply([&](const auto&... args) { hasher.Hash(args...); }, value);
  506. return static_cast<HashCode>(hasher);
  507. }
  508. template <typename T, typename U>
  509. inline auto CarbonHashValue(const std::pair<T, U>& value, uint64_t seed)
  510. -> HashCode {
  511. Hasher hasher(seed);
  512. hasher.Hash(value.first, value.second);
  513. return static_cast<HashCode>(hasher);
  514. }
  515. // Implementation detail predicate to detect if there is a `CarbonHashValue`
  516. // overload available for a particular type, either in this namespace or found
  517. // via ADL. Note that this should not be moved above any overloads.
  518. template <typename T>
  519. concept HasCarbonHashValue = requires(const T& value, uint64_t seed) {
  520. { CarbonHashValue(value, seed) } -> std::same_as<HashCode>;
  521. };
  522. // C++ guarantees this is true for the unsigned variants, but we require it for
  523. // signed variants and pointers.
  524. static_assert(std::has_unique_object_representations_v<int8_t>);
  525. static_assert(std::has_unique_object_representations_v<int16_t>);
  526. static_assert(std::has_unique_object_representations_v<int32_t>);
  527. static_assert(std::has_unique_object_representations_v<int64_t>);
  528. static_assert(std::has_unique_object_representations_v<void*>);
  529. // Overloaded function to provide mappings or conversions required to types that
  530. // should be hashed as plain data but where can't directly examine the storage.
  531. //
  532. // For example, C++ uses `std::nullptr_t` but unfortunately doesn't make it have
  533. // a unique object representation. To address that, we need a function that
  534. // converts `nullptr` back into a `void*` that will have a unique object
  535. // representation. And this needs to be done by-value as we need to build a
  536. // temporary object to return, which requires a separate overload rather than
  537. // just using a type function that could be used in parallel in the predicate
  538. // below. Instead, we build the predicate independently of the mapping overload,
  539. // but together they should produce the correct result.
  540. template <typename T>
  541. inline auto MapToRawDataType(const T& value) -> const T& {
  542. // This overload should never be selected for `std::nullptr_t`, so
  543. // static_assert to get some better compiler error messages.
  544. static_assert(!std::same_as<T, std::nullptr_t>);
  545. return value;
  546. }
  547. inline auto MapToRawDataType(std::nullptr_t /*value*/) -> const void* {
  548. return nullptr;
  549. }
  550. // Implementation detail predicate to detect if we can hash as a raw data type.
  551. // When used, it should be combined with our mapping function `MapToRawDataType`
  552. // to handle any necessary edge cases that don't directly work.
  553. template <typename T>
  554. concept CanHashAsRawDataType = std::same_as<T, std::nullptr_t> ||
  555. std::has_unique_object_representations_v<T>;
  556. // Implementation of the unqualified dispatch to any provided `CarbonHashValue`
  557. // overloads, either here, or via ADL. Note that similar to
  558. // `HasCarbonHashValue`, this must not be moved above any of those overloads.
  559. template <typename T>
  560. inline auto DispatchImpl(const T& value, uint64_t seed) -> HashCode {
  561. // If we have an explicit overload for `CarbonHashValue`, call it. This may be
  562. // provided above or via ADL, and is preferred as it represents an explicit
  563. // request for how the type is hashed.
  564. if constexpr (HasCarbonHashValue<T>) {
  565. return CarbonHashValue(value, seed);
  566. } else if constexpr (CanHashAsRawDataType<T>) {
  567. // There was no explicit overload to call, but the type allows us to hash it
  568. // as raw data, do so.
  569. Hasher hasher(seed);
  570. hasher.HashRaw(MapToRawDataType(value));
  571. return static_cast<HashCode>(hasher);
  572. } else {
  573. // We can only synthesize hashing for types that are hashable as raw data.
  574. // This type isn't so fail a static assert due to the lack of an overload.
  575. // We use the concept here to try and get the best diagnostics we can about
  576. // candidates.
  577. static_assert(HasCarbonHashValue<T>,
  578. "Attempted to hash a type which does not have a "
  579. "`CarbonHashValue` overload.");
  580. }
  581. }
  582. } // namespace InternalHashDispatch
  583. template <typename T>
  584. inline auto HashValue(const T& value, uint64_t seed) -> HashCode {
  585. return InternalHashDispatch::DispatchImpl(value, seed);
  586. }
  587. template <typename T>
  588. inline auto HashValue(const T& value) -> HashCode {
  589. // When a seed isn't provided, use the last 64-bit chunk of random data. Other
  590. // chunks (especially the first) are more often XOR-ed with the seed and risk
  591. // cancelling each other out and feeding a zero to a `Mix` call in a way that
  592. // sharply increasing collisions.
  593. return HashValue(value, Hasher::StaticRandomData[7]);
  594. }
  595. constexpr auto HashCode::ExtractIndex() -> ssize_t { return value_; }
  596. template <int N>
  597. constexpr auto HashCode::ExtractIndexAndTag() -> std::pair<ssize_t, uint32_t> {
  598. static_assert(N >= 1);
  599. static_assert(N < 32);
  600. return {static_cast<ssize_t>(value_ >> N),
  601. static_cast<uint32_t>(value_ & ((1U << N) - 1))};
  602. }
  603. // Building with `-DCARBON_MCA_MARKERS` will enable `llvm-mca` annotations in
  604. // the source code. These can interfere with optimization, but allows analyzing
  605. // the generated `.s` file with the `llvm-mca` tool. Documentation for these
  606. // markers is here:
  607. // https://llvm.org/docs/CommandGuide/llvm-mca.html#using-markers-to-analyze-specific-code-blocks
  608. #if CARBON_MCA_MARKERS
  609. #define CARBON_MCA_BEGIN(NAME) \
  610. __asm volatile("# LLVM-MCA-BEGIN " NAME "" ::: "memory");
  611. #define CARBON_MCA_END(NAME) \
  612. __asm volatile("# LLVM-MCA-END " NAME "" ::: "memory");
  613. #else
  614. #define CARBON_MCA_BEGIN(NAME)
  615. #define CARBON_MCA_END(NAME)
  616. #endif
  617. inline auto Hasher::Read1(const std::byte* data) -> uint64_t {
  618. uint8_t result;
  619. std::memcpy(&result, data, sizeof(result));
  620. return result;
  621. }
  622. inline auto Hasher::Read2(const std::byte* data) -> uint64_t {
  623. uint16_t result;
  624. std::memcpy(&result, data, sizeof(result));
  625. return result;
  626. }
  627. inline auto Hasher::Read4(const std::byte* data) -> uint64_t {
  628. uint32_t result;
  629. std::memcpy(&result, data, sizeof(result));
  630. return result;
  631. }
  632. inline auto Hasher::Read8(const std::byte* data) -> uint64_t {
  633. uint64_t result;
  634. std::memcpy(&result, data, sizeof(result));
  635. return result;
  636. }
  637. inline auto Hasher::Read1To3(const std::byte* data, ssize_t size) -> uint64_t {
  638. // Use carefully crafted indexing to avoid branches on the exact size while
  639. // reading.
  640. uint64_t byte0 = static_cast<uint8_t>(data[0]);
  641. uint64_t byte1 = static_cast<uint8_t>(data[size - 1]);
  642. uint64_t byte2 = static_cast<uint8_t>(data[size >> 1]);
  643. return byte0 | (byte1 << 16) | (byte2 << 8);
  644. }
  645. inline auto Hasher::Read4To8(const std::byte* data, ssize_t size) -> uint64_t {
  646. uint32_t low;
  647. std::memcpy(&low, data, sizeof(low));
  648. uint32_t high;
  649. std::memcpy(&high, data + size - sizeof(high), sizeof(high));
  650. return low | (static_cast<uint64_t>(high) << 32);
  651. }
  652. inline auto Hasher::Read8To16(const std::byte* data, ssize_t size)
  653. -> std::pair<uint64_t, uint64_t> {
  654. uint64_t low;
  655. std::memcpy(&low, data, sizeof(low));
  656. uint64_t high;
  657. std::memcpy(&high, data + size - sizeof(high), sizeof(high));
  658. return {low, high};
  659. }
  660. inline auto Hasher::Mix(uint64_t lhs, uint64_t rhs) -> uint64_t {
  661. // Use the C23 extended integer support that Clang provides as a general
  662. // language extension.
  663. using U128 = unsigned _BitInt(128);
  664. U128 result = static_cast<U128>(lhs) * static_cast<U128>(rhs);
  665. return static_cast<uint64_t>(result) ^ static_cast<uint64_t>(result >> 64);
  666. }
  667. inline auto Hasher::WeakMix(uint64_t value) -> uint64_t {
  668. value *= MulConstant;
  669. #ifdef __ARM_ACLE
  670. // Arm has a fast bit-reversal that gives us the optimal distribution.
  671. value = __rbitll(value);
  672. #else
  673. // Otherwise, assume an optimized BSWAP such as x86's. That's close enough.
  674. value = __builtin_bswap64(value);
  675. #endif
  676. return value;
  677. }
  678. inline auto Hasher::HashDense(uint64_t data) -> void {
  679. // When hashing exactly one 64-bit entity use the Phi-derived constant as this
  680. // is just multiplicative hashing. The initial buffer is mixed on input to
  681. // pipeline with materializing the constant.
  682. buffer = Mix(data ^ buffer, MulConstant);
  683. }
  684. inline auto Hasher::HashDense(uint64_t data0, uint64_t data1) -> void {
  685. // When hashing two chunks of data at the same time, we XOR it with random
  686. // data to avoid common inputs from having especially bad multiplicative
  687. // effects. We also XOR in the starting buffer as seed or to chain. Note that
  688. // we don't use *consecutive* random data 64-bit values to avoid a common
  689. // compiler "optimization" of loading both 64-bit chunks into a 128-bit vector
  690. // and doing the XOR in the vector unit. The latency of extracting the data
  691. // afterward eclipses any benefit. Callers will routinely have two consecutive
  692. // data values here, but using non-consecutive keys avoids any vectorization
  693. // being tempting.
  694. //
  695. // XOR-ing both the incoming state and a random word over the second data is
  696. // done to pipeline with materializing the constants and is observed to have
  697. // better performance than XOR-ing after the mix.
  698. //
  699. // This roughly matches the mix pattern used in the larger mixing routines
  700. // from Abseil, which is a more minimal form than used in other algorithms
  701. // such as AHash and seems adequate for latency-optimized use cases.
  702. buffer =
  703. Mix(data0 ^ StaticRandomData[1], data1 ^ StaticRandomData[3] ^ buffer);
  704. }
  705. template <typename T>
  706. requires std::has_unique_object_representations_v<T> && (sizeof(T) <= 8)
  707. inline auto Hasher::ReadSmall(const T& value) -> uint64_t {
  708. const auto* storage = reinterpret_cast<const std::byte*>(&value);
  709. if constexpr (sizeof(T) == 1) {
  710. return Read1(storage);
  711. } else if constexpr (sizeof(T) == 2) {
  712. return Read2(storage);
  713. } else if constexpr (sizeof(T) == 3) {
  714. return Read2(storage) | (Read1(&storage[2]) << 16);
  715. } else if constexpr (sizeof(T) == 4) {
  716. return Read4(storage);
  717. } else if constexpr (sizeof(T) == 5) {
  718. return Read4(storage) | (Read1(&storage[4]) << 32);
  719. } else if constexpr (sizeof(T) == 6 || sizeof(T) == 7) {
  720. // Use overlapping 4-byte reads for 6 and 7 bytes.
  721. return Read4(storage) | (Read4(&storage[sizeof(T) - 4]) << 32);
  722. } else if constexpr (sizeof(T) == 8) {
  723. return Read8(storage);
  724. } else {
  725. static_assert(sizeof(T) <= 8);
  726. }
  727. }
  728. template <typename... Ts>
  729. inline auto Hasher::Hash(const Ts&... values) -> void {
  730. if constexpr (sizeof...(Ts) == 0) {
  731. buffer ^= StaticRandomData[0];
  732. return;
  733. }
  734. using InternalHashDispatch::CanHashAsRawDataType;
  735. using InternalHashDispatch::HasCarbonHashValue;
  736. using InternalHashDispatch::MapToRawDataType;
  737. // Special-case a single element tuple that we will hash as raw data.
  738. if constexpr (sizeof...(Ts) == 1 && (... && (!HasCarbonHashValue<Ts> &&
  739. CanHashAsRawDataType<Ts>))) {
  740. HashRaw(MapToRawDataType(values)...);
  741. return;
  742. }
  743. // Map each value into a uint64_t, either by hashing it using any custom hash
  744. // function required, reading its data into a 64-bit value, or if large
  745. // hashing it as raw data and using that hash code as the 64-bit data. This
  746. // mirrors the logic in `InternalHashDispatch::DispatchImpl`, but minimizes
  747. // early hashing of anything small we can just read as data. While this may be
  748. // a little bit wasteful in some cases, collapsing down to a flat array of
  749. // 64-bit integers is more efficient to hash.
  750. auto map_value = []<typename T>(const T& value) -> uint64_t {
  751. if constexpr (HasCarbonHashValue<T>) {
  752. // Use the top-level `HashValue` to re-dispatch to the custom
  753. // implementation with a fixed seed.
  754. return static_cast<uint64_t>(HashValue(value));
  755. } else if constexpr (CanHashAsRawDataType<T>) {
  756. auto raw_value = MapToRawDataType(value);
  757. if constexpr (sizeof(raw_value) <= 8) {
  758. return ReadSmall(raw_value);
  759. } else {
  760. // Use the top-level `HashValue` to pick up a good fixed seed and hash
  761. // this large object as raw data.
  762. return static_cast<uint64_t>(HashValue(raw_value));
  763. }
  764. } else {
  765. // We can only synthesize hashing for types that are hashable as raw data.
  766. // This type isn't so fail a static assert due to the lack of an overload.
  767. // We use the concept here to try and get the best diagnostics we can
  768. // about candidates.
  769. static_assert(HasCarbonHashValue<T>,
  770. "Attempted to hash a type which does not have a "
  771. "`CarbonHashValue` overload.");
  772. }
  773. };
  774. const uint64_t data[] = {map_value(values)...};
  775. if constexpr (sizeof...(Ts) == 2) {
  776. HashDense(data[0], data[1]);
  777. return;
  778. }
  779. HashRaw(data);
  780. }
  781. template <typename T>
  782. inline auto Hasher::HashArray(llvm::ArrayRef<T> values) -> void {
  783. using InternalHashDispatch::CanHashAsRawDataType;
  784. using InternalHashDispatch::HasCarbonHashValue;
  785. // This logic similarly mirrors `InternalHashDispatch::DispatchImpl`, but is
  786. // specialized here to allow us to efficiently process the array when it
  787. // *doesn't* require recursive hashing.
  788. if constexpr (HasCarbonHashValue<T>) {
  789. // Use a trivial loop to give consistent behavior for arrays requiring
  790. // recursive hashing. This isn't terribly efficient, but if clients care
  791. // they should specialize the entire hashing operation. For simple, tiny
  792. // cases, this avoids an awkward functionality cliff.
  793. for (const T& value : values) {
  794. HashDense(static_cast<uint64_t>(HashValue(value)));
  795. }
  796. HashRaw(values.size());
  797. } else if constexpr (std::has_unique_object_representations_v<T>) {
  798. // This code is a narrow special case for `CanHashAsRawDataType` that we can
  799. // further hash the underlying storage directly. We check that it is a
  800. // subset.
  801. static_assert(CanHashAsRawDataType<T>);
  802. HashSizedBytes(values);
  803. } else {
  804. // We can only synthesize hashing for types that are hashable as raw data.
  805. // This type isn't so fail a static assert due to the lack of an overload.
  806. // We use the concept here to try and get the best diagnostics we can
  807. // about candidates.
  808. static_assert(HasCarbonHashValue<T>,
  809. "Attempted to hash a type which does not have a "
  810. "`CarbonHashValue` overload.");
  811. }
  812. }
  813. template <typename T>
  814. requires std::has_unique_object_representations_v<T>
  815. inline auto Hasher::HashRaw(const T& value) -> void {
  816. if constexpr (sizeof(T) <= 8) {
  817. // For types size 8-bytes and smaller directly being hashed (as opposed to
  818. // 8-bytes potentially bit-packed with data), we rarely expect the incoming
  819. // data to fully and densely populate all 8 bytes. For these cases we have a
  820. // `WeakMix` routine that is lower latency but lower quality.
  821. CARBON_MCA_BEGIN("fixed-8b");
  822. buffer = WeakMix(buffer ^ ReadSmall(value));
  823. CARBON_MCA_END("fixed-8b");
  824. return;
  825. }
  826. const auto* data_ptr = reinterpret_cast<const std::byte*>(&value);
  827. if constexpr (8 < sizeof(T) && sizeof(T) <= 16) {
  828. CARBON_MCA_BEGIN("fixed-16b");
  829. auto values = Read8To16(data_ptr, sizeof(T));
  830. HashDense(values.first, values.second);
  831. CARBON_MCA_END("fixed-16b");
  832. return;
  833. }
  834. if constexpr (16 < sizeof(T) && sizeof(T) <= 32) {
  835. CARBON_MCA_BEGIN("fixed-32b");
  836. // Essentially the same technique used for dynamically sized byte sequences
  837. // of this size, but we start with a fixed XOR of random data.
  838. buffer ^= StaticRandomData[0];
  839. uint64_t m0 = Mix(Read8(data_ptr) ^ StaticRandomData[1],
  840. Read8(data_ptr + 8) ^ buffer);
  841. const std::byte* tail_16b_ptr = data_ptr + (sizeof(T) - 16);
  842. uint64_t m1 = Mix(Read8(tail_16b_ptr) ^ StaticRandomData[3],
  843. Read8(tail_16b_ptr + 8) ^ buffer);
  844. buffer = m0 ^ m1;
  845. CARBON_MCA_END("fixed-32b");
  846. return;
  847. }
  848. // Hashing the size isn't relevant here, but is harmless, so fall back to a
  849. // common code path.
  850. HashSizedBytesLarge(llvm::ArrayRef<std::byte>(data_ptr, sizeof(T)));
  851. }
  852. inline auto Hasher::HashSizedBytes(llvm::ArrayRef<std::byte> bytes) -> void {
  853. const std::byte* data_ptr = bytes.data();
  854. const ssize_t size = bytes.size();
  855. // First handle short sequences under 8 bytes. We distribute the branches a
  856. // bit for short strings.
  857. if (size <= 8) {
  858. if (size >= 4) {
  859. CARBON_MCA_BEGIN("dynamic-8b");
  860. uint64_t data = Read4To8(data_ptr, size);
  861. // We optimize for latency on short strings by hashing both the data and
  862. // size in a single multiply here, using the small nature of size to
  863. // sample a specific sequence of bytes with well distributed bits into one
  864. // side of the multiply. This results in a *statistically* weak hash
  865. // function, but one with very low latency.
  866. //
  867. // Note that we don't drop to the `WeakMix` routine here because we want
  868. // to use sampled random data to encode the size, which may not be as
  869. // effective without the full 128-bit folded result.
  870. buffer = Mix(data ^ buffer, SampleRandomData(size));
  871. CARBON_MCA_END("dynamic-8b");
  872. return;
  873. }
  874. // When we only have 0-3 bytes of string, we can avoid the cost of `Mix`.
  875. // Instead, for empty strings we can just XOR some of our data against the
  876. // existing buffer. For 1-3 byte lengths we do 3 one-byte reads adjusted to
  877. // always read in-bounds without branching. Then we OR the size into the 4th
  878. // byte and use `WeakMix`.
  879. CARBON_MCA_BEGIN("dynamic-4b");
  880. if (size == 0) {
  881. buffer ^= StaticRandomData[0];
  882. } else {
  883. uint64_t data = Read1To3(data_ptr, size) | size << 24;
  884. buffer = WeakMix(data);
  885. }
  886. CARBON_MCA_END("dynamic-4b");
  887. return;
  888. }
  889. if (size <= 16) {
  890. CARBON_MCA_BEGIN("dynamic-16b");
  891. // Similar to the above, we optimize primarily for latency here and spread
  892. // the incoming data across both ends of the multiply. Note that this does
  893. // have a drawback -- any time one half of the mix function becomes zero it
  894. // will fail to incorporate any bits from the other half. However, there is
  895. // exactly 1 in 2^64 values for each side that achieve this, and only when
  896. // the size is exactly 16 -- for smaller sizes there is an overlapping byte
  897. // that makes this impossible unless the seed is *also* incredibly unlucky.
  898. //
  899. // Because this hash function makes no attempt to defend against hash
  900. // flooding, we accept this risk in order to keep the latency low. If this
  901. // becomes a non-flooding problem, we can restrict the size to <16 and send
  902. // the 16-byte case down the next tier of cost.
  903. uint64_t size_hash = SampleRandomData(size);
  904. auto data = Read8To16(data_ptr, size);
  905. buffer = Mix(data.first ^ size_hash, data.second ^ buffer);
  906. CARBON_MCA_END("dynamic-16b");
  907. return;
  908. }
  909. if (size <= 32) {
  910. CARBON_MCA_BEGIN("dynamic-32b");
  911. // Do two mixes of overlapping 16-byte ranges in parallel to minimize
  912. // latency. We also incorporate the size by sampling random data into the
  913. // seed before both.
  914. buffer ^= SampleRandomData(size);
  915. uint64_t m0 = Mix(Read8(data_ptr) ^ StaticRandomData[1],
  916. Read8(data_ptr + 8) ^ buffer);
  917. const std::byte* tail_16b_ptr = data_ptr + (size - 16);
  918. uint64_t m1 = Mix(Read8(tail_16b_ptr) ^ StaticRandomData[3],
  919. Read8(tail_16b_ptr + 8) ^ buffer);
  920. // Just an XOR mix at the end is quite weak here, but we prefer that for
  921. // latency over a more robust approach. Doing another mix with the size (the
  922. // way longer string hashing does) increases the latency on x86-64
  923. // significantly (approx. 20%).
  924. buffer = m0 ^ m1;
  925. CARBON_MCA_END("dynamic-32b");
  926. return;
  927. }
  928. HashSizedBytesLarge(bytes);
  929. }
  930. } // namespace Carbon
  931. #endif // CARBON_COMMON_HASHING_H_