hashing_test.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  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. #include "common/hashing.h"
  5. #include <gmock/gmock.h>
  6. #include <gtest/gtest.h>
  7. #include <type_traits>
  8. #include "llvm/ADT/Sequence.h"
  9. #include "llvm/ADT/StringExtras.h"
  10. #include "llvm/Support/FormatVariadic.h"
  11. #include "llvm/Support/TypeName.h"
  12. namespace Carbon {
  13. namespace {
  14. using ::testing::Eq;
  15. using ::testing::Le;
  16. using ::testing::Ne;
  17. TEST(HashingTest, HashCodeAPI) {
  18. // Manually compute a few hash codes where we can exercise the underlying API.
  19. HashCode empty = HashValue("");
  20. HashCode a = HashValue("a");
  21. HashCode b = HashValue("b");
  22. ASSERT_THAT(HashValue(""), Eq(empty));
  23. ASSERT_THAT(HashValue("a"), Eq(a));
  24. ASSERT_THAT(HashValue("b"), Eq(b));
  25. ASSERT_THAT(empty, Ne(a));
  26. ASSERT_THAT(empty, Ne(b));
  27. ASSERT_THAT(a, Ne(b));
  28. // Exercise the methods in basic ways across a few sizes. This doesn't check
  29. // much beyond stability across re-computed values, crashing, or hitting UB.
  30. EXPECT_THAT(HashValue("a").ExtractIndex(2), Eq(a.ExtractIndex(2)));
  31. EXPECT_THAT(HashValue("a").ExtractIndex(4), Eq(a.ExtractIndex(4)));
  32. EXPECT_THAT(HashValue("a").ExtractIndex(8), Eq(a.ExtractIndex(8)));
  33. EXPECT_THAT(HashValue("a").ExtractIndex(1 << 10),
  34. Eq(a.ExtractIndex(1 << 10)));
  35. EXPECT_THAT(HashValue("a").ExtractIndex(1 << 20),
  36. Eq(a.ExtractIndex(1 << 20)));
  37. EXPECT_THAT(HashValue("a").ExtractIndex(1 << 30),
  38. Eq(a.ExtractIndex(1 << 30)));
  39. EXPECT_THAT(HashValue("a").ExtractIndex(1LL << 40),
  40. Eq(a.ExtractIndex(1LL << 40)));
  41. EXPECT_THAT(HashValue("a").ExtractIndex(1LL << 50),
  42. Eq(a.ExtractIndex(1LL << 50)));
  43. EXPECT_THAT(a.ExtractIndex(8), Ne(b.ExtractIndex(8)));
  44. EXPECT_THAT(a.ExtractIndex(8), Ne(empty.ExtractIndex(8)));
  45. // Note that the index produced with a tag may be different from the index
  46. // alone!
  47. EXPECT_THAT(HashValue("a").ExtractIndexAndTag<2>(2),
  48. Eq(a.ExtractIndexAndTag<2>(2)));
  49. EXPECT_THAT(HashValue("a").ExtractIndexAndTag<16>(4),
  50. Eq(a.ExtractIndexAndTag<16>(4)));
  51. EXPECT_THAT(HashValue("a").ExtractIndexAndTag<7>(8),
  52. Eq(a.ExtractIndexAndTag<7>(8)));
  53. EXPECT_THAT(HashValue("a").ExtractIndexAndTag<7>(1 << 10),
  54. Eq(a.ExtractIndexAndTag<7>(1 << 10)));
  55. EXPECT_THAT(HashValue("a").ExtractIndexAndTag<7>(1 << 20),
  56. Eq(a.ExtractIndexAndTag<7>(1 << 20)));
  57. EXPECT_THAT(HashValue("a").ExtractIndexAndTag<7>(1 << 30),
  58. Eq(a.ExtractIndexAndTag<7>(1 << 30)));
  59. EXPECT_THAT(HashValue("a").ExtractIndexAndTag<7>(1LL << 40),
  60. Eq(a.ExtractIndexAndTag<7>(1LL << 40)));
  61. EXPECT_THAT(HashValue("a").ExtractIndexAndTag<7>(1LL << 50),
  62. Eq(a.ExtractIndexAndTag<7>(1LL << 50)));
  63. const auto [a_index, a_tag] = a.ExtractIndexAndTag<4>(8);
  64. const auto [b_index, b_tag] = b.ExtractIndexAndTag<4>(8);
  65. EXPECT_THAT(a_index, Ne(b_index));
  66. EXPECT_THAT(a_tag, Ne(b_tag));
  67. }
  68. TEST(HashingTest, Integers) {
  69. for (int64_t i : {0, 1, 2, 3, 42, -1, -2, -3, -13}) {
  70. SCOPED_TRACE(llvm::formatv("Hashing: {0}", i).str());
  71. auto test_int_hash = [](auto i) {
  72. using T = decltype(i);
  73. SCOPED_TRACE(
  74. llvm::formatv("Hashing type: {0}", llvm::getTypeName<T>()).str());
  75. HashCode hash = HashValue(i);
  76. // Hashes should be stable within the execution.
  77. EXPECT_THAT(HashValue(i), Eq(hash));
  78. // Zero should match, and other integers shouldn't collide trivially.
  79. HashCode hash_zero = HashValue(static_cast<T>(0));
  80. if (i == 0) {
  81. EXPECT_THAT(hash, Eq(hash_zero));
  82. } else {
  83. EXPECT_THAT(hash, Ne(hash_zero));
  84. }
  85. };
  86. test_int_hash(i);
  87. test_int_hash(static_cast<int8_t>(i));
  88. test_int_hash(static_cast<uint8_t>(i));
  89. test_int_hash(static_cast<int16_t>(i));
  90. test_int_hash(static_cast<uint16_t>(i));
  91. test_int_hash(static_cast<int32_t>(i));
  92. test_int_hash(static_cast<uint32_t>(i));
  93. test_int_hash(static_cast<int64_t>(i));
  94. test_int_hash(static_cast<uint64_t>(i));
  95. }
  96. }
  97. TEST(HashingTest, Pointers) {
  98. int object1 = 42;
  99. std::string object2 =
  100. "Hello World! This is a long-ish string so it ends up on the heap!";
  101. HashCode hash_null = HashValue(nullptr);
  102. // Hashes should be stable.
  103. EXPECT_THAT(HashValue(nullptr), Eq(hash_null));
  104. // Hash other kinds of pointers without trivial collisions.
  105. HashCode hash1 = HashValue(&object1);
  106. HashCode hash2 = HashValue(&object2);
  107. HashCode hash3 = HashValue(object2.data());
  108. EXPECT_THAT(hash1, Ne(hash_null));
  109. EXPECT_THAT(hash2, Ne(hash_null));
  110. EXPECT_THAT(hash3, Ne(hash_null));
  111. EXPECT_THAT(hash1, Ne(hash2));
  112. EXPECT_THAT(hash1, Ne(hash3));
  113. EXPECT_THAT(hash2, Ne(hash3));
  114. // Hash values reflect the address and not the type.
  115. EXPECT_THAT(HashValue(static_cast<void*>(nullptr)), Eq(hash_null));
  116. EXPECT_THAT(HashValue(static_cast<int*>(nullptr)), Eq(hash_null));
  117. EXPECT_THAT(HashValue(static_cast<std::string*>(nullptr)), Eq(hash_null));
  118. EXPECT_THAT(HashValue(reinterpret_cast<void*>(&object1)), Eq(hash1));
  119. EXPECT_THAT(HashValue(reinterpret_cast<int*>(&object2)), Eq(hash2));
  120. EXPECT_THAT(HashValue(reinterpret_cast<std::string*>(object2.data())),
  121. Eq(hash3));
  122. }
  123. TEST(HashingTest, PairsAndTuples) {
  124. // Note that we can't compare hash codes across arity, or in general, compare
  125. // hash codes for different types as the type isn't part of the hash. These
  126. // hashes are targeted at use in hash tables which pick a single type that's
  127. // the basis of any comparison.
  128. HashCode hash_00 = HashValue(std::pair(0, 0));
  129. HashCode hash_01 = HashValue(std::pair(0, 1));
  130. HashCode hash_10 = HashValue(std::pair(1, 0));
  131. HashCode hash_11 = HashValue(std::pair(1, 1));
  132. EXPECT_THAT(hash_00, Ne(hash_01));
  133. EXPECT_THAT(hash_00, Ne(hash_10));
  134. EXPECT_THAT(hash_00, Ne(hash_11));
  135. EXPECT_THAT(hash_01, Ne(hash_10));
  136. EXPECT_THAT(hash_01, Ne(hash_11));
  137. EXPECT_THAT(hash_10, Ne(hash_11));
  138. HashCode hash_000 = HashValue(std::tuple(0, 0, 0));
  139. HashCode hash_001 = HashValue(std::tuple(0, 0, 1));
  140. HashCode hash_010 = HashValue(std::tuple(0, 1, 0));
  141. HashCode hash_011 = HashValue(std::tuple(0, 1, 1));
  142. HashCode hash_100 = HashValue(std::tuple(1, 0, 0));
  143. HashCode hash_101 = HashValue(std::tuple(1, 0, 1));
  144. HashCode hash_110 = HashValue(std::tuple(1, 1, 0));
  145. HashCode hash_111 = HashValue(std::tuple(1, 1, 1));
  146. EXPECT_THAT(hash_000, Ne(hash_001));
  147. EXPECT_THAT(hash_000, Ne(hash_010));
  148. EXPECT_THAT(hash_000, Ne(hash_011));
  149. EXPECT_THAT(hash_000, Ne(hash_100));
  150. EXPECT_THAT(hash_000, Ne(hash_101));
  151. EXPECT_THAT(hash_000, Ne(hash_110));
  152. EXPECT_THAT(hash_000, Ne(hash_111));
  153. EXPECT_THAT(hash_001, Ne(hash_010));
  154. EXPECT_THAT(hash_001, Ne(hash_011));
  155. EXPECT_THAT(hash_001, Ne(hash_100));
  156. EXPECT_THAT(hash_001, Ne(hash_101));
  157. EXPECT_THAT(hash_001, Ne(hash_110));
  158. EXPECT_THAT(hash_001, Ne(hash_111));
  159. EXPECT_THAT(hash_010, Ne(hash_011));
  160. EXPECT_THAT(hash_010, Ne(hash_100));
  161. EXPECT_THAT(hash_010, Ne(hash_101));
  162. EXPECT_THAT(hash_010, Ne(hash_110));
  163. EXPECT_THAT(hash_010, Ne(hash_111));
  164. EXPECT_THAT(hash_011, Ne(hash_100));
  165. EXPECT_THAT(hash_011, Ne(hash_101));
  166. EXPECT_THAT(hash_011, Ne(hash_110));
  167. EXPECT_THAT(hash_011, Ne(hash_111));
  168. EXPECT_THAT(hash_100, Ne(hash_101));
  169. EXPECT_THAT(hash_100, Ne(hash_110));
  170. EXPECT_THAT(hash_100, Ne(hash_111));
  171. EXPECT_THAT(hash_101, Ne(hash_110));
  172. EXPECT_THAT(hash_101, Ne(hash_111));
  173. EXPECT_THAT(hash_110, Ne(hash_111));
  174. // Hashing a 2-tuple and a pair should produce identical results, so pairs
  175. // are compatible with code using things like variadic tuple construction.
  176. EXPECT_THAT(HashValue(std::tuple(0, 0)), Eq(hash_00));
  177. EXPECT_THAT(HashValue(std::tuple(0, 1)), Eq(hash_01));
  178. EXPECT_THAT(HashValue(std::tuple(1, 0)), Eq(hash_10));
  179. EXPECT_THAT(HashValue(std::tuple(1, 1)), Eq(hash_11));
  180. // Integers in tuples should also work.
  181. for (int i : {0, 1, 2, 3, 42, -1, -2, -3, -13}) {
  182. SCOPED_TRACE(llvm::formatv("Hashing: ({0}, {0}, {0})", i).str());
  183. auto test_int_tuple_hash = [](auto i) {
  184. using T = decltype(i);
  185. SCOPED_TRACE(
  186. llvm::formatv("Hashing integer type: {0}", llvm::getTypeName<T>())
  187. .str());
  188. std::tuple v = {i, i, i};
  189. HashCode hash = HashValue(v);
  190. // Hashes should be stable within the execution.
  191. EXPECT_THAT(HashValue(v), Eq(hash));
  192. // Zero should match, and other integers shouldn't collide trivially.
  193. T zero = 0;
  194. std::tuple zero_tuple = {zero, zero, zero};
  195. HashCode hash_zero = HashValue(zero_tuple);
  196. if (i == 0) {
  197. EXPECT_THAT(hash, Eq(hash_zero));
  198. } else {
  199. EXPECT_THAT(hash, Ne(hash_zero));
  200. }
  201. };
  202. test_int_tuple_hash(i);
  203. test_int_tuple_hash(static_cast<int8_t>(i));
  204. test_int_tuple_hash(static_cast<uint8_t>(i));
  205. test_int_tuple_hash(static_cast<int16_t>(i));
  206. test_int_tuple_hash(static_cast<uint16_t>(i));
  207. test_int_tuple_hash(static_cast<int32_t>(i));
  208. test_int_tuple_hash(static_cast<uint32_t>(i));
  209. test_int_tuple_hash(static_cast<int64_t>(i));
  210. test_int_tuple_hash(static_cast<uint64_t>(i));
  211. // Heterogeneous integer types should also work, but we only support
  212. // comparing against hashes of tuples with the exact same type.
  213. using T1 = std::tuple<int8_t, uint32_t, int16_t>;
  214. using T2 = std::tuple<uint32_t, int16_t, uint64_t>;
  215. if (i == 0) {
  216. EXPECT_THAT(HashValue(T1{i, i, i}), Eq(HashValue(T1{0, 0, 0})));
  217. EXPECT_THAT(HashValue(T2{i, i, i}), Eq(HashValue(T2{0, 0, 0})));
  218. } else {
  219. EXPECT_THAT(HashValue(T1{i, i, i}), Ne(HashValue(T1{0, 0, 0})));
  220. EXPECT_THAT(HashValue(T2{i, i, i}), Ne(HashValue(T2{0, 0, 0})));
  221. }
  222. }
  223. // Hash values of pointers in pairs and tuples reflect the address and not the
  224. // type. Pairs and 2-tuples give the same hash values.
  225. HashCode hash_2null = HashValue(std::pair(nullptr, nullptr));
  226. EXPECT_THAT(HashValue(std::tuple(static_cast<int*>(nullptr),
  227. static_cast<double*>(nullptr))),
  228. Eq(hash_2null));
  229. // Hash other kinds of pointers without trivial collisions.
  230. int object1 = 42;
  231. std::string object2 = "Hello world!";
  232. HashCode hash_3ptr =
  233. HashValue(std::tuple(&object1, &object2, object2.data()));
  234. EXPECT_THAT(hash_3ptr, Ne(HashValue(std::tuple(nullptr, nullptr, nullptr))));
  235. // Hash values reflect the address and not the type.
  236. EXPECT_THAT(
  237. HashValue(std::tuple(reinterpret_cast<void*>(&object1),
  238. reinterpret_cast<int*>(&object2),
  239. reinterpret_cast<std::string*>(object2.data()))),
  240. Eq(hash_3ptr));
  241. }
  242. TEST(HashingTest, BasicStrings) {
  243. llvm::SmallVector<std::pair<std::string, HashCode>> hashes;
  244. for (int size : {0, 1, 2, 4, 16, 64, 256, 1024}) {
  245. std::string s(size, 'a');
  246. hashes.push_back({s, HashValue(s)});
  247. }
  248. for (const auto& [s1, hash1] : hashes) {
  249. EXPECT_THAT(HashValue(s1), Eq(hash1));
  250. // Also check that we get the same hashes even when using string-wrapping
  251. // types.
  252. EXPECT_THAT(HashValue(std::string_view(s1)), Eq(hash1));
  253. EXPECT_THAT(HashValue(llvm::StringRef(s1)), Eq(hash1));
  254. // And some basic tests that simple things don't collide.
  255. for (const auto& [s2, hash2] : hashes) {
  256. if (s1 != s2) {
  257. EXPECT_THAT(hash1, Ne(hash2))
  258. << "Matching hashes for '" << s1 << "' and '" << s2 << "'";
  259. }
  260. }
  261. }
  262. }
  263. struct HashableType {
  264. int x;
  265. int y;
  266. int ignored = 0;
  267. friend auto CarbonHashValue(const HashableType& value, uint64_t seed)
  268. -> HashCode {
  269. Hasher hasher(seed);
  270. hasher.Hash(value.x, value.y);
  271. return static_cast<HashCode>(hasher);
  272. }
  273. };
  274. TEST(HashingTest, CustomType) {
  275. HashableType a = {.x = 1, .y = 2};
  276. HashableType b = {.x = 3, .y = 4};
  277. EXPECT_THAT(HashValue(a), Eq(HashValue(a)));
  278. EXPECT_THAT(HashValue(a), Ne(HashValue(b)));
  279. // Differences in an ignored field have no impact.
  280. HashableType c = {.x = 3, .y = 4, .ignored = 42};
  281. EXPECT_THAT(HashValue(c), Eq(HashValue(b)));
  282. }
  283. // The only significantly bad seed is zero, so pick a non-zero seed with a tiny
  284. // amount of entropy to make sure that none of the testing relies on the entropy
  285. // from this.
  286. constexpr uint64_t TestSeed = 42ULL * 1024;
  287. auto ToHexBytes(llvm::StringRef s) -> std::string {
  288. std::string rendered;
  289. llvm::raw_string_ostream os(rendered);
  290. os << "{";
  291. llvm::ListSeparator sep(", ");
  292. for (const char c : s) {
  293. os << sep << llvm::formatv("{0:x2}", static_cast<uint8_t>(c));
  294. }
  295. os << "}";
  296. return rendered;
  297. }
  298. template <typename T>
  299. struct HashedValue {
  300. HashCode hash;
  301. T v;
  302. };
  303. using HashedString = HashedValue<std::string>;
  304. template <typename T>
  305. auto PrintFullWidthHex(llvm::raw_ostream& os, T value) {
  306. static_assert(sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4 ||
  307. sizeof(T) == 8);
  308. os << llvm::formatv(sizeof(T) == 1 ? "{0:x2}"
  309. : sizeof(T) == 2 ? "{0:x4}"
  310. : sizeof(T) == 4 ? "{0:x8}"
  311. : "{0:x16}",
  312. static_cast<uint64_t>(value));
  313. }
  314. template <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>
  315. auto operator<<(llvm::raw_ostream& os, HashedValue<T> hv)
  316. -> llvm::raw_ostream& {
  317. os << "hash " << hv.hash << " for value ";
  318. PrintFullWidthHex(os, hv.v);
  319. return os;
  320. }
  321. template <typename T, typename U,
  322. typename = std::enable_if_t<std::is_integral_v<T>>,
  323. typename = std::enable_if_t<std::is_integral_v<U>>>
  324. auto operator<<(llvm::raw_ostream& os, HashedValue<std::pair<T, U>> hv)
  325. -> llvm::raw_ostream& {
  326. os << "hash " << hv.hash << " for pair of ";
  327. PrintFullWidthHex(os, hv.v.first);
  328. os << " and ";
  329. PrintFullWidthHex(os, hv.v.second);
  330. return os;
  331. }
  332. struct Collisions {
  333. int total;
  334. int median;
  335. int max;
  336. };
  337. // Analyzes a list of hashed values to find all of the hash codes which collide
  338. // within a specific bit-range.
  339. //
  340. // With `BitBegin=0` and `BitEnd=64`, this is equivalent to finding full
  341. // collisions. But when the begin and end of the bit range are narrower than the
  342. // 64-bits of the hash code, it allows this function to analyze a specific
  343. // window of bits within the 64-bit hash code to understand how many collisions
  344. // emerge purely within that bit range.
  345. //
  346. // With narrow ranges (we often look at the first N and last N bits for small
  347. // N), collisions are common and so this function summarizes this with the total
  348. // number of collisions and the median number of collisions for an input value.
  349. template <int BitBegin, int BitEnd, typename T>
  350. auto FindBitRangeCollisions(llvm::ArrayRef<HashedValue<T>> hashes)
  351. -> Collisions {
  352. static_assert(BitBegin < BitEnd);
  353. constexpr int BitCount = BitEnd - BitBegin;
  354. static_assert(BitCount <= 32);
  355. constexpr int BitShift = BitBegin;
  356. constexpr uint64_t BitMask = ((1ULL << BitCount) - 1) << BitShift;
  357. // We collect counts of collisions in a vector. Initially, we just have a zero
  358. // and all inputs map to that collision count. As we discover collisions,
  359. // we'll create a dedicated counter for it and count how many inputs collide.
  360. llvm::SmallVector<int> collision_counts;
  361. collision_counts.push_back(0);
  362. // The "map" for collision counts. Each input hashed value has a corresponding
  363. // index stored here. That index is the index of the collision count in the
  364. // container above. We resize this to fill it with zeros to start as the zero
  365. // index above has a collision count of zero.
  366. //
  367. // The result of this is that the number of collisions for `hashes[i]` is
  368. // `collision_counts[collision_map[i]]`.
  369. llvm::SmallVector<int> collision_map;
  370. collision_map.resize(hashes.size());
  371. // First, we extract the bit subsequence we want to examine from each hash and
  372. // store it with an index back into the hashed values (or the collision map).
  373. //
  374. // The result is that, `bits_and_indices[i].bits` has the hash bits of
  375. // interest from `hashes[bits_and_indices[i].index]`.
  376. //
  377. // And because `collision_map` above uses the same indices as `hashes`,
  378. // `collision_counts[collision_map[bits_and_indices[i].index]]` is the number
  379. // of collisions for `bits_and_indices[i].bits`.
  380. struct BitSequenceAndHashIndex {
  381. // The bit subsequence of a hash input, adjusted into the low bits.
  382. uint32_t bits;
  383. // The index of the hash input corresponding to this bit sequence.
  384. int index;
  385. };
  386. llvm::SmallVector<BitSequenceAndHashIndex> bits_and_indices;
  387. bits_and_indices.reserve(hashes.size());
  388. for (const auto& [hash, v] : hashes) {
  389. CARBON_DCHECK(v == hashes[bits_and_indices.size()].v);
  390. auto hash_bits = (static_cast<uint64_t>(hash) & BitMask) >> BitShift;
  391. bits_and_indices.push_back(
  392. {.bits = static_cast<uint32_t>(hash_bits),
  393. .index = static_cast<int>(bits_and_indices.size())});
  394. }
  395. // Now we sort by the extracted bit sequence so we can efficiently scan for
  396. // colliding bit patterns.
  397. std::sort(
  398. bits_and_indices.begin(), bits_and_indices.end(),
  399. [](const auto& lhs, const auto& rhs) { return lhs.bits < rhs.bits; });
  400. // Scan the sorted bit sequences we've extracted looking for collisions. We
  401. // count the total collisions, but we also track the number of individual
  402. // inputs that collide with each specific bit pattern.
  403. uint32_t prev_hash_bits = bits_and_indices[0].bits;
  404. int prev_index = bits_and_indices[0].index;
  405. bool in_collision = false;
  406. int total = 0;
  407. for (const auto& [hash_bits, hash_index] :
  408. llvm::ArrayRef(bits_and_indices).slice(1)) {
  409. // Check if we've found a new hash (and thus a new value), reset everything.
  410. CARBON_CHECK(hashes[prev_index].v != hashes[hash_index].v);
  411. if (hash_bits != prev_hash_bits) {
  412. CARBON_CHECK(hashes[prev_index].hash != hashes[hash_index].hash);
  413. prev_hash_bits = hash_bits;
  414. prev_index = hash_index;
  415. in_collision = false;
  416. continue;
  417. }
  418. // Otherwise, we have a colliding bit sequence.
  419. ++total;
  420. // If we've already created a collision count to track this, just increment
  421. // it and map this hash to it.
  422. if (in_collision) {
  423. ++collision_counts.back();
  424. collision_map[hash_index] = collision_counts.size() - 1;
  425. continue;
  426. }
  427. // If this is a new collision, create a dedicated count to track it and
  428. // begin counting.
  429. in_collision = true;
  430. collision_map[prev_index] = collision_counts.size();
  431. collision_map[hash_index] = collision_counts.size();
  432. collision_counts.push_back(1);
  433. }
  434. // Sort by collision count for each hash.
  435. std::sort(bits_and_indices.begin(), bits_and_indices.end(),
  436. [&](const auto& lhs, const auto& rhs) {
  437. return collision_counts[collision_map[lhs.index]] <
  438. collision_counts[collision_map[rhs.index]];
  439. });
  440. // And compute the median and max.
  441. int median = collision_counts
  442. [collision_map[bits_and_indices[bits_and_indices.size() / 2].index]];
  443. int max = *std::max_element(collision_counts.begin(), collision_counts.end());
  444. CARBON_CHECK(max ==
  445. collision_counts[collision_map[bits_and_indices.back().index]]);
  446. return {.total = total, .median = median, .max = max};
  447. }
  448. auto CheckNoDuplicateValues(llvm::ArrayRef<HashedString> hashes) -> void {
  449. for (int i = 0, size = hashes.size(); i < size - 1; ++i) {
  450. const auto& [_, value] = hashes[i];
  451. CARBON_CHECK(value != hashes[i + 1].v) << "Duplicate value: " << value;
  452. }
  453. }
  454. template <int N>
  455. auto AllByteStringsHashedAndSorted() {
  456. static_assert(N < 5, "Can only generate all 4-byte strings or shorter.");
  457. llvm::SmallVector<HashedString> hashes;
  458. int64_t count = 1LL << (N * 8);
  459. for (int64_t i : llvm::seq(count)) {
  460. uint8_t bytes[N];
  461. for (int j : llvm::seq(N)) {
  462. bytes[j] = (static_cast<uint64_t>(i) >> (8 * j)) & 0xff;
  463. }
  464. std::string s(std::begin(bytes), std::end(bytes));
  465. hashes.push_back({HashValue(s, TestSeed), s});
  466. }
  467. std::sort(hashes.begin(), hashes.end(),
  468. [](const HashedString& lhs, const HashedString& rhs) {
  469. return static_cast<uint64_t>(lhs.hash) <
  470. static_cast<uint64_t>(rhs.hash);
  471. });
  472. CheckNoDuplicateValues(hashes);
  473. return hashes;
  474. }
  475. auto ExpectNoHashCollisions(llvm::ArrayRef<HashedString> hashes) -> void {
  476. HashCode prev_hash = hashes[0].hash;
  477. llvm::StringRef prev_s = hashes[0].v;
  478. for (const auto& [hash, s] : hashes.slice(1)) {
  479. if (hash != prev_hash) {
  480. prev_hash = hash;
  481. prev_s = s;
  482. continue;
  483. }
  484. FAIL() << "Colliding hash '" << hash << "' of strings "
  485. << ToHexBytes(prev_s) << " and " << ToHexBytes(s);
  486. }
  487. }
  488. TEST(HashingTest, Collisions1ByteSized) {
  489. auto hashes_storage = AllByteStringsHashedAndSorted<1>();
  490. auto hashes = llvm::ArrayRef(hashes_storage);
  491. ExpectNoHashCollisions(hashes);
  492. auto low_32bit_collisions = FindBitRangeCollisions<0, 32>(hashes);
  493. EXPECT_THAT(low_32bit_collisions.total, Eq(0));
  494. auto high_32bit_collisions = FindBitRangeCollisions<32, 64>(hashes);
  495. EXPECT_THAT(high_32bit_collisions.total, Eq(0));
  496. // We expect collisions when only looking at 7-bits of the hash. However,
  497. // modern hash table designs need to use either the low or high 7 bits as tags
  498. // for faster searching. So we add some direct testing that the median and max
  499. // collisions for any given key stay within bounds. We express the bounds in
  500. // terms of the minimum expected "perfect" rate of collisions if uniformly
  501. // distributed.
  502. int min_7bit_collisions = llvm::NextPowerOf2(hashes.size() - 1) / (1 << 7);
  503. auto low_7bit_collisions = FindBitRangeCollisions<0, 7>(hashes);
  504. EXPECT_THAT(low_7bit_collisions.median, Le(2 * min_7bit_collisions));
  505. EXPECT_THAT(low_7bit_collisions.max, Le(4 * min_7bit_collisions));
  506. auto high_7bit_collisions = FindBitRangeCollisions<64 - 7, 64>(hashes);
  507. EXPECT_THAT(high_7bit_collisions.median, Le(2 * min_7bit_collisions));
  508. EXPECT_THAT(high_7bit_collisions.max, Le(4 * min_7bit_collisions));
  509. }
  510. TEST(HashingTest, Collisions2ByteSized) {
  511. auto hashes_storage = AllByteStringsHashedAndSorted<2>();
  512. auto hashes = llvm::ArrayRef(hashes_storage);
  513. ExpectNoHashCollisions(hashes);
  514. auto low_32bit_collisions = FindBitRangeCollisions<0, 32>(hashes);
  515. EXPECT_THAT(low_32bit_collisions.total, Eq(0));
  516. auto high_32bit_collisions = FindBitRangeCollisions<32, 64>(hashes);
  517. EXPECT_THAT(high_32bit_collisions.total, Eq(0));
  518. // Similar to 1-byte keys, we do expect a certain rate of collisions here but
  519. // bound the median and max.
  520. int min_7bit_collisions = llvm::NextPowerOf2(hashes.size() - 1) / (1 << 7);
  521. auto low_7bit_collisions = FindBitRangeCollisions<0, 7>(hashes);
  522. EXPECT_THAT(low_7bit_collisions.median, Le(2 * min_7bit_collisions));
  523. EXPECT_THAT(low_7bit_collisions.max, Le(2 * min_7bit_collisions));
  524. auto high_7bit_collisions = FindBitRangeCollisions<64 - 7, 64>(hashes);
  525. EXPECT_THAT(high_7bit_collisions.median, Le(2 * min_7bit_collisions));
  526. EXPECT_THAT(high_7bit_collisions.max, Le(2 * min_7bit_collisions));
  527. }
  528. // Generate and hash all strings of of [BeginByteCount, EndByteCount) bytes,
  529. // with [BeginSetBitCount, EndSetBitCount) contiguous bits at each possible bit
  530. // offset set to one and all other bits set to zero.
  531. template <int BeginByteCount, int EndByteCount, int BeginSetBitCount,
  532. int EndSetBitCount>
  533. struct SparseHashTestParamRanges {
  534. static_assert(BeginByteCount >= 0);
  535. static_assert(BeginByteCount < EndByteCount);
  536. static_assert(BeginSetBitCount >= 0);
  537. static_assert(BeginSetBitCount < EndSetBitCount);
  538. // Note that we intentionally allow the end-set-bit-count to result in more
  539. // set bits than are available -- we truncate the number of set bits to fit
  540. // within the byte string.
  541. static_assert(BeginSetBitCount <= BeginByteCount * 8);
  542. struct ByteCount {
  543. static constexpr int Begin = BeginByteCount;
  544. static constexpr int End = EndByteCount;
  545. };
  546. struct SetBitCount {
  547. static constexpr int Begin = BeginSetBitCount;
  548. static constexpr int End = EndSetBitCount;
  549. };
  550. };
  551. template <typename ParamRanges>
  552. struct SparseHashTest : ::testing::Test {
  553. using ByteCount = typename ParamRanges::ByteCount;
  554. using SetBitCount = typename ParamRanges::SetBitCount;
  555. static auto GetHashedByteStrings() {
  556. llvm::SmallVector<HashedString> hashes;
  557. for (int byte_count :
  558. llvm::seq_inclusive(ByteCount::Begin, ByteCount::End)) {
  559. int bits = byte_count * 8;
  560. for (int set_bit_count : llvm::seq_inclusive(
  561. SetBitCount::Begin, std::min(bits, SetBitCount::End))) {
  562. if (set_bit_count == 0) {
  563. std::string s(byte_count, '\0');
  564. hashes.push_back({HashValue(s, TestSeed), std::move(s)});
  565. continue;
  566. }
  567. for (int begin_set_bit : llvm::seq_inclusive(0, bits - set_bit_count)) {
  568. std::string s(byte_count, '\0');
  569. int begin_set_bit_byte_index = begin_set_bit / 8;
  570. int begin_set_bit_bit_index = begin_set_bit % 8;
  571. int end_set_bit_byte_index = (begin_set_bit + set_bit_count) / 8;
  572. int end_set_bit_bit_index = (begin_set_bit + set_bit_count) % 8;
  573. // We build a begin byte and end byte. We set the begin byte, set
  574. // subsequent bytes up to *and including* the end byte to all ones,
  575. // and then mask the end byte. For multi-byte runs, the mask just sets
  576. // the end byte and for single-byte runs the mask computes the
  577. // intersecting bits.
  578. //
  579. // Consider a 4-set-bit count, starting at bit 2. The begin bit index
  580. // is 2, and the end bit index is 6.
  581. //
  582. // Begin byte: 0b11111111 -(shl 2)-----> 0b11111100
  583. // End byte: 0b11111111 -(shr (8-6))-> 0b00111111
  584. // Masked byte: 0b00111100
  585. //
  586. // Or a 10-set-bit-count starting at bit 2. The begin bit index is 2,
  587. // the end byte index is (12 / 8) or 1, and the end bit index is (12 %
  588. // 8) or 4.
  589. //
  590. // Begin byte: 0b11111111 -(shl 2)-----> 0b11111100 -> 6 bits
  591. // End byte: 0b11111111 -(shr (8-4))-> 0b00001111 -> 4 bits
  592. // 10 total bits
  593. //
  594. uint8_t begin_set_bit_byte = 0xFFU << begin_set_bit_bit_index;
  595. uint8_t end_set_bit_byte = 0xFFU >> (8 - end_set_bit_bit_index);
  596. bool has_end_byte_bits = end_set_bit_byte != 0;
  597. s[begin_set_bit_byte_index] = begin_set_bit_byte;
  598. for (int i : llvm::seq(begin_set_bit_byte_index + 1,
  599. end_set_bit_byte_index + has_end_byte_bits)) {
  600. s[i] = '\xFF';
  601. }
  602. // If there are no bits set in the end byte, it may be past-the-end
  603. // and we can't even mask a zero byte safely.
  604. if (has_end_byte_bits) {
  605. s[end_set_bit_byte_index] &= end_set_bit_byte;
  606. }
  607. hashes.push_back({HashValue(s, TestSeed), std::move(s)});
  608. }
  609. }
  610. }
  611. std::sort(hashes.begin(), hashes.end(),
  612. [](const HashedString& lhs, const HashedString& rhs) {
  613. return static_cast<uint64_t>(lhs.hash) <
  614. static_cast<uint64_t>(rhs.hash);
  615. });
  616. CheckNoDuplicateValues(hashes);
  617. return hashes;
  618. }
  619. };
  620. using SparseHashTestParams = ::testing::Types<
  621. SparseHashTestParamRanges</*BeginByteCount=*/0, /*EndByteCount=*/256,
  622. /*BeginSetBitCount=*/0, /*EndSetBitCount=*/1>,
  623. SparseHashTestParamRanges</*BeginByteCount=*/1, /*EndByteCount=*/128,
  624. /*BeginSetBitCount=*/2, /*EndSetBitCount=*/4>,
  625. SparseHashTestParamRanges</*BeginByteCount=*/1, /*EndByteCount=*/64,
  626. /*BeginSetBitCount=*/4, /*EndSetBitCount=*/16>>;
  627. TYPED_TEST_SUITE(SparseHashTest, SparseHashTestParams);
  628. TYPED_TEST(SparseHashTest, Collisions) {
  629. auto hashes_storage = this->GetHashedByteStrings();
  630. auto hashes = llvm::ArrayRef(hashes_storage);
  631. ExpectNoHashCollisions(hashes);
  632. int min_7bit_collisions = llvm::NextPowerOf2(hashes.size() - 1) / (1 << 7);
  633. auto low_7bit_collisions = FindBitRangeCollisions<0, 7>(hashes);
  634. EXPECT_THAT(low_7bit_collisions.median, Le(2 * min_7bit_collisions));
  635. EXPECT_THAT(low_7bit_collisions.max, Le(2 * min_7bit_collisions));
  636. auto high_7bit_collisions = FindBitRangeCollisions<64 - 7, 64>(hashes);
  637. EXPECT_THAT(high_7bit_collisions.median, Le(2 * min_7bit_collisions));
  638. EXPECT_THAT(high_7bit_collisions.max, Le(2 * min_7bit_collisions));
  639. }
  640. } // namespace
  641. } // namespace Carbon