Debian Codegraph @

llvm/unittests/ADT/DenseMapTest.cpp

raw
1 //===- llvm/unittest/ADT/DenseMapMap.cpp - DenseMap unit tests --*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "llvm/ADT/DenseMap.h"
10 #include "CountCopyAndMove.h"
11 #include "llvm/ADT/DenseMapInfo.h"
12 #include "llvm/ADT/DenseMapInfoVariant.h"
13 #include "llvm/ADT/SmallSet.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "gmock/gmock.h"
16 #include "gtest/gtest.h"
17 #include <map>
18 #include <optional>
19 #include <set>
20 #include <utility>
21 #include <variant>
22
23 using namespace llvm;
24
25 namespace {
26 uint32_t getTestKey(int i, uint32_t *) { return i; }
27 uint32_t getTestValue(int i, uint32_t *) { return 42 + i; }
28
29 uint32_t *getTestKey(int i, uint32_t **) {
30 static uint32_t dummy_arr1[8192];
31 assert(i < 8192 && "Only support 8192 dummy keys.");
32 return &dummy_arr1[i];
33 }
34 uint32_t *getTestValue(int i, uint32_t **) {
35 static uint32_t dummy_arr1[8192];
36 assert(i < 8192 && "Only support 8192 dummy keys.");
37 return &dummy_arr1[i];
38 }
39
40 enum class EnumClass { Val };
41
42 EnumClass getTestKey(int i, EnumClass *) {
43 // We can't possibly support 100 values for the swap test, so just return an
44 // invalid EnumClass for testing.
45 return static_cast<EnumClass>(i);
46 }
47
48 /// A test class that tries to check that construction and destruction
49 /// occur correctly.
50 class CtorTester {
51 static std::set<CtorTester *> Constructed;
52 int Value;
53
54 public:
55 explicit CtorTester(int Value = 0) : Value(Value) {
56 EXPECT_TRUE(Constructed.insert(this).second);
57 }
58 CtorTester(uint32_t Value) : Value(Value) {
59 EXPECT_TRUE(Constructed.insert(this).second);
60 }
61 CtorTester(const CtorTester &Arg) : Value(Arg.Value) {
62 EXPECT_TRUE(Constructed.insert(this).second);
63 }
64 CtorTester &operator=(const CtorTester &) = default;
65 ~CtorTester() {
66 EXPECT_EQ(1u, Constructed.erase(this));
67 }
68 operator uint32_t() const { return Value; }
69
70 int getValue() const { return Value; }
71 bool operator==(const CtorTester &RHS) const { return Value == RHS.Value; }
72 };
73
74 std::set<CtorTester *> CtorTester::Constructed;
75
76 struct CtorTesterMapInfo {
77 static inline CtorTester getEmptyKey() { return CtorTester(-1); }
78 static inline CtorTester getTombstoneKey() { return CtorTester(-2); }
79 static unsigned getHashValue(const CtorTester &Val) {
80 return Val.getValue() * 37u;
81 }
82 static bool isEqual(const CtorTester &LHS, const CtorTester &RHS) {
83 return LHS == RHS;
84 }
85 };
86
87 CtorTester getTestKey(int i, CtorTester *) { return CtorTester(i); }
88 CtorTester getTestValue(int i, CtorTester *) { return CtorTester(42 + i); }
89
90 std::optional<uint32_t> getTestKey(int i, std::optional<uint32_t> *) {
91 return i;
92 }
93
94 // Test fixture, with helper functions implemented by forwarding to global
95 // function overloads selected by component types of the type parameter. This
96 // allows all of the map implementations to be tested with shared
97 // implementations of helper routines.
98 template <typename T>
99 class DenseMapTest : public ::testing::Test {
100 protected:
101 T Map;
102
103 static typename T::key_type *const dummy_key_ptr;
104 static typename T::mapped_type *const dummy_value_ptr;
105
106 typename T::key_type getKey(int i = 0) {
107 return getTestKey(i, dummy_key_ptr);
108 }
109 typename T::mapped_type getValue(int i = 0) {
110 return getTestValue(i, dummy_value_ptr);
111 }
112 };
113
114 template <typename T>
115 typename T::key_type *const DenseMapTest<T>::dummy_key_ptr = nullptr;
116 template <typename T>
117 typename T::mapped_type *const DenseMapTest<T>::dummy_value_ptr = nullptr;
118
119 // Register these types for testing.
120 // clang-format off
121 typedef ::testing::Types<DenseMap<uint32_t, uint32_t>,
122 DenseMap<uint32_t *, uint32_t *>,
123 DenseMap<CtorTester, CtorTester, CtorTesterMapInfo>,
124 DenseMap<EnumClass, uint32_t>,
125 DenseMap<std::optional<uint32_t>, uint32_t>,
126 SmallDenseMap<uint32_t, uint32_t>,
127 SmallDenseMap<uint32_t *, uint32_t *>,
128 SmallDenseMap<CtorTester, CtorTester, 4,
129 CtorTesterMapInfo>,
130 SmallDenseMap<EnumClass, uint32_t>,
131 SmallDenseMap<std::optional<uint32_t>, uint32_t>
132 > DenseMapTestTypes;
133 // clang-format on
134
135 TYPED_TEST_SUITE(DenseMapTest, DenseMapTestTypes, );
136
137 // Empty map tests
138 TYPED_TEST(DenseMapTest, EmptyIntMapTest) {
139 // Size tests
140 EXPECT_EQ(0u, this->Map.size());
141 EXPECT_TRUE(this->Map.empty());
142
143 // Iterator tests
144 EXPECT_TRUE(this->Map.begin() == this->Map.end());
145
146 // Lookup tests
147 EXPECT_FALSE(this->Map.count(this->getKey()));
148 EXPECT_FALSE(this->Map.contains(this->getKey()));
149 EXPECT_TRUE(this->Map.find(this->getKey()) == this->Map.end());
150 EXPECT_EQ(typename TypeParam::mapped_type(),
151 this->Map.lookup(this->getKey()));
152 }
153
154 // Constant map tests
155 TYPED_TEST(DenseMapTest, ConstEmptyMapTest) {
156 const TypeParam &ConstMap = this->Map;
157 EXPECT_EQ(0u, ConstMap.size());
158 EXPECT_TRUE(ConstMap.empty());
159 EXPECT_TRUE(ConstMap.begin() == ConstMap.end());
160 }
161
162 // A map with a single entry
163 TYPED_TEST(DenseMapTest, SingleEntryMapTest) {
164 this->Map[this->getKey()] = this->getValue();
165
166 // Size tests
167 EXPECT_EQ(1u, this->Map.size());
168 EXPECT_FALSE(this->Map.begin() == this->Map.end());
169 EXPECT_FALSE(this->Map.empty());
170
171 // Iterator tests
172 typename TypeParam::iterator it = this->Map.begin();
173 EXPECT_EQ(this->getKey(), it->first);
174 EXPECT_EQ(this->getValue(), it->second);
175 ++it;
176 EXPECT_TRUE(it == this->Map.end());
177
178 // Lookup tests
179 EXPECT_TRUE(this->Map.count(this->getKey()));
180 EXPECT_TRUE(this->Map.contains(this->getKey()));
181 EXPECT_TRUE(this->Map.find(this->getKey()) == this->Map.begin());
182 EXPECT_EQ(this->getValue(), this->Map.lookup(this->getKey()));
183 EXPECT_EQ(this->getValue(), this->Map[this->getKey()]);
184 }
185
186 TYPED_TEST(DenseMapTest, AtTest) {
187 this->Map[this->getKey(0)] = this->getValue(0);
188 this->Map[this->getKey(1)] = this->getValue(1);
189 this->Map[this->getKey(2)] = this->getValue(2);
190 EXPECT_EQ(this->getValue(0), this->Map.at(this->getKey(0)));
191 EXPECT_EQ(this->getValue(1), this->Map.at(this->getKey(1)));
192 EXPECT_EQ(this->getValue(2), this->Map.at(this->getKey(2)));
193 }
194
195 // Test clear() method
196 TYPED_TEST(DenseMapTest, ClearTest) {
197 this->Map[this->getKey()] = this->getValue();
198 this->Map.clear();
199
200 EXPECT_EQ(0u, this->Map.size());
201 EXPECT_TRUE(this->Map.empty());
202 EXPECT_TRUE(this->Map.begin() == this->Map.end());
203 }
204
205 // Test erase(iterator) method
206 TYPED_TEST(DenseMapTest, EraseTest) {
207 this->Map[this->getKey()] = this->getValue();
208 this->Map.erase(this->Map.begin());
209
210 EXPECT_EQ(0u, this->Map.size());
211 EXPECT_TRUE(this->Map.empty());
212 EXPECT_TRUE(this->Map.begin() == this->Map.end());
213 }
214
215 // Test erase(value) method
216 TYPED_TEST(DenseMapTest, EraseTest2) {
217 this->Map[this->getKey()] = this->getValue();
218 this->Map.erase(this->getKey());
219
220 EXPECT_EQ(0u, this->Map.size());
221 EXPECT_TRUE(this->Map.empty());
222 EXPECT_TRUE(this->Map.begin() == this->Map.end());
223 }
224
225 // Test insert() method
226 TYPED_TEST(DenseMapTest, InsertTest) {
227 this->Map.insert(std::make_pair(this->getKey(), this->getValue()));
228 EXPECT_EQ(1u, this->Map.size());
229 EXPECT_EQ(this->getValue(), this->Map[this->getKey()]);
230 }
231
232 // Test copy constructor method
233 TYPED_TEST(DenseMapTest, CopyConstructorTest) {
234 this->Map[this->getKey()] = this->getValue();
235 TypeParam copyMap(this->Map);
236
237 EXPECT_EQ(1u, copyMap.size());
238 EXPECT_EQ(this->getValue(), copyMap[this->getKey()]);
239 }
240
241 // Test copy constructor method where SmallDenseMap isn't small.
242 TYPED_TEST(DenseMapTest, CopyConstructorNotSmallTest) {
243 for (int Key = 0; Key < 5; ++Key)
244 this->Map[this->getKey(Key)] = this->getValue(Key);
245 TypeParam copyMap(this->Map);
246
247 EXPECT_EQ(5u, copyMap.size());
248 for (int Key = 0; Key < 5; ++Key)
249 EXPECT_EQ(this->getValue(Key), copyMap[this->getKey(Key)]);
250 }
251
252 // Test copying from a default-constructed map.
253 TYPED_TEST(DenseMapTest, CopyConstructorFromDefaultTest) {
254 TypeParam copyMap(this->Map);
255
256 EXPECT_TRUE(copyMap.empty());
257 }
258
259 // Test copying from an empty map where SmallDenseMap isn't small.
260 TYPED_TEST(DenseMapTest, CopyConstructorFromEmptyTest) {
261 for (int Key = 0; Key < 5; ++Key)
262 this->Map[this->getKey(Key)] = this->getValue(Key);
263 this->Map.clear();
264 TypeParam copyMap(this->Map);
265
266 EXPECT_TRUE(copyMap.empty());
267 }
268
269 // Test assignment operator method
270 TYPED_TEST(DenseMapTest, AssignmentTest) {
271 this->Map[this->getKey()] = this->getValue();
272 TypeParam copyMap = this->Map;
273
274 EXPECT_EQ(1u, copyMap.size());
275 EXPECT_EQ(this->getValue(), copyMap[this->getKey()]);
276
277 // test self-assignment.
278 copyMap = static_cast<TypeParam &>(copyMap);
279 EXPECT_EQ(1u, copyMap.size());
280 EXPECT_EQ(this->getValue(), copyMap[this->getKey()]);
281 }
282
283 TYPED_TEST(DenseMapTest, AssignmentTestNotSmall) {
284 for (int Key = 0; Key < 5; ++Key)
285 this->Map[this->getKey(Key)] = this->getValue(Key);
286 TypeParam copyMap = this->Map;
287
288 EXPECT_EQ(5u, copyMap.size());
289 for (int Key = 0; Key < 5; ++Key)
290 EXPECT_EQ(this->getValue(Key), copyMap[this->getKey(Key)]);
291
292 // test self-assignment.
293 copyMap = static_cast<TypeParam &>(copyMap);
294 EXPECT_EQ(5u, copyMap.size());
295 for (int Key = 0; Key < 5; ++Key)
296 EXPECT_EQ(this->getValue(Key), copyMap[this->getKey(Key)]);
297 }
298
299 // Test swap method
300 TYPED_TEST(DenseMapTest, SwapTest) {
301 this->Map[this->getKey()] = this->getValue();
302 TypeParam otherMap;
303
304 this->Map.swap(otherMap);
305 EXPECT_EQ(0u, this->Map.size());
306 EXPECT_TRUE(this->Map.empty());
307 EXPECT_EQ(1u, otherMap.size());
308 EXPECT_EQ(this->getValue(), otherMap[this->getKey()]);
309
310 this->Map.swap(otherMap);
311 EXPECT_EQ(0u, otherMap.size());
312 EXPECT_TRUE(otherMap.empty());
313 EXPECT_EQ(1u, this->Map.size());
314 EXPECT_EQ(this->getValue(), this->Map[this->getKey()]);
315
316 // Make this more interesting by inserting 100 numbers into the map.
317 for (int i = 0; i < 100; ++i)
318 this->Map[this->getKey(i)] = this->getValue(i);
319
320 this->Map.swap(otherMap);
321 EXPECT_EQ(0u, this->Map.size());
322 EXPECT_TRUE(this->Map.empty());
323 EXPECT_EQ(100u, otherMap.size());
324 for (int i = 0; i < 100; ++i)
325 EXPECT_EQ(this->getValue(i), otherMap[this->getKey(i)]);
326
327 this->Map.swap(otherMap);
328 EXPECT_EQ(0u, otherMap.size());
329 EXPECT_TRUE(otherMap.empty());
330 EXPECT_EQ(100u, this->Map.size());
331 for (int i = 0; i < 100; ++i)
332 EXPECT_EQ(this->getValue(i), this->Map[this->getKey(i)]);
333 }
334
335 // A more complex iteration test
336 TYPED_TEST(DenseMapTest, IterationTest) {
337 bool visited[100];
338 std::map<typename TypeParam::key_type, unsigned> visitedIndex;
339
340 // Insert 100 numbers into the map
341 for (int i = 0; i < 100; ++i) {
342 visited[i] = false;
343 visitedIndex[this->getKey(i)] = i;
344
345 this->Map[this->getKey(i)] = this->getValue(i);
346 }
347
348 // Iterate over all numbers and mark each one found.
349 for (typename TypeParam::iterator it = this->Map.begin();
350 it != this->Map.end(); ++it)
351 visited[visitedIndex[it->first]] = true;
352
353 // Ensure every number was visited.
354 for (int i = 0; i < 100; ++i)
355 ASSERT_TRUE(visited[i]) << "Entry #" << i << " was never visited";
356 }
357
358 // const_iterator test
359 TYPED_TEST(DenseMapTest, ConstIteratorTest) {
360 // Check conversion from iterator to const_iterator.
361 typename TypeParam::iterator it = this->Map.begin();
362 typename TypeParam::const_iterator cit(it);
363 EXPECT_TRUE(it == cit);
364
365 // Check copying of const_iterators.
366 typename TypeParam::const_iterator cit2(cit);
367 EXPECT_TRUE(cit == cit2);
368 }
369
370 TYPED_TEST(DenseMapTest, KeysValuesIterator) {
371 SmallSet<typename TypeParam::key_type, 10> Keys;
372 SmallSet<typename TypeParam::mapped_type, 10> Values;
373 for (int I = 0; I < 10; ++I) {
374 auto K = this->getKey(I);
375 auto V = this->getValue(I);
376 Keys.insert(K);
377 Values.insert(V);
378 this->Map[K] = V;
379 }
380
381 SmallSet<typename TypeParam::key_type, 10> ActualKeys;
382 SmallSet<typename TypeParam::mapped_type, 10> ActualValues;
383 for (auto K : this->Map.keys())
384 ActualKeys.insert(K);
385 for (auto V : this->Map.values())
386 ActualValues.insert(V);
387
388 EXPECT_EQ(Keys, ActualKeys);
389 EXPECT_EQ(Values, ActualValues);
390 }
391
392 TYPED_TEST(DenseMapTest, ConstKeysValuesIterator) {
393 SmallSet<typename TypeParam::key_type, 10> Keys;
394 SmallSet<typename TypeParam::mapped_type, 10> Values;
395 for (int I = 0; I < 10; ++I) {
396 auto K = this->getKey(I);
397 auto V = this->getValue(I);
398 Keys.insert(K);
399 Values.insert(V);
400 this->Map[K] = V;
401 }
402
403 const TypeParam &ConstMap = this->Map;
404 SmallSet<typename TypeParam::key_type, 10> ActualKeys;
405 SmallSet<typename TypeParam::mapped_type, 10> ActualValues;
406 for (auto K : ConstMap.keys())
407 ActualKeys.insert(K);
408 for (auto V : ConstMap.values())
409 ActualValues.insert(V);
410
411 EXPECT_EQ(Keys, ActualKeys);
412 EXPECT_EQ(Values, ActualValues);
413 }
414
415 // Test initializer list construction.
416 TEST(DenseMapCustomTest, InitializerList) {
417 DenseMap<int, int> M({{0, 0}, {0, 1}, {1, 2}});
418 EXPECT_EQ(2u, M.size());
419 EXPECT_EQ(1u, M.count(0));
420 EXPECT_EQ(0, M[0]);
421 EXPECT_EQ(1u, M.count(1));
422 EXPECT_EQ(2, M[1]);
423 }
424
425 // Test initializer list construction.
426 TEST(DenseMapCustomTest, EqualityComparison) {
427 DenseMap<int, int> M1({{0, 0}, {1, 2}});
428 DenseMap<int, int> M2({{0, 0}, {1, 2}});
429 DenseMap<int, int> M3({{0, 0}, {1, 3}});
430
431 EXPECT_EQ(M1, M2);
432 EXPECT_NE(M1, M3);
433 }
434
435 TEST(DenseMapCustomTest, InsertRange) {
436 DenseMap<int, int> M;
437
438 std::pair<int, int> InputVals[3] = {{0, 0}, {0, 1}, {1, 2}};
439 M.insert_range(InputVals);
440
441 EXPECT_EQ(M.size(), 2u);
442 EXPECT_THAT(M, testing::UnorderedElementsAre(testing::Pair(0, 0),
443 testing::Pair(1, 2)));
444 }
445
446 TEST(SmallDenseMapCustomTest, InsertRange) {
447 SmallDenseMap<int, int> M;
448
449 std::pair<int, int> InputVals[3] = {{0, 0}, {0, 1}, {1, 2}};
450 M.insert_range(InputVals);
451
452 EXPECT_EQ(M.size(), 2u);
453 EXPECT_THAT(M, testing::UnorderedElementsAre(testing::Pair(0, 0),
454 testing::Pair(1, 2)));
455 }
456
457 // Test for the default minimum size of a DenseMap
458 TEST(DenseMapCustomTest, DefaultMinReservedSizeTest) {
459 // IF THIS VALUE CHANGE, please update InitialSizeTest, InitFromIterator, and
460 // ReserveTest as well!
461 const int ExpectedInitialBucketCount = 64;
462 // Formula from DenseMap::getMinBucketToReserveForEntries()
463 const int ExpectedMaxInitialEntries = ExpectedInitialBucketCount * 3 / 4 - 1;
464
465 DenseMap<int, CountCopyAndMove> Map;
466 // Will allocate 64 buckets
467 Map.reserve(1);
468 unsigned MemorySize = Map.getMemorySize();
469 CountCopyAndMove::ResetCounts();
470
471 for (int i = 0; i < ExpectedMaxInitialEntries; ++i)
472 Map.insert(std::pair<int, CountCopyAndMove>(std::piecewise_construct,
473 std::forward_as_tuple(i),
474 std::forward_as_tuple()));
475 // Check that we didn't grow
476 EXPECT_EQ(MemorySize, Map.getMemorySize());
477 // Check that move was called the expected number of times
478 EXPECT_EQ(ExpectedMaxInitialEntries, CountCopyAndMove::TotalMoves());
479 // Check that no copy occurred
480 EXPECT_EQ(0, CountCopyAndMove::TotalCopies());
481
482 // Adding one extra element should grow the map
483 Map.insert(std::pair<int, CountCopyAndMove>(
484 std::piecewise_construct,
485 std::forward_as_tuple(ExpectedMaxInitialEntries),
486 std::forward_as_tuple()));
487 // Check that we grew
488 EXPECT_NE(MemorySize, Map.getMemorySize());
489 // Check that move was called the expected number of times
490 // This relies on move-construction elision, and cannot be reliably tested.
491 // EXPECT_EQ(ExpectedMaxInitialEntries + 2, CountCopyAndMove::Move);
492 // Check that no copy occurred
493 EXPECT_EQ(0, CountCopyAndMove::TotalCopies());
494 }
495
496 // Make sure creating the map with an initial size of N actually gives us enough
497 // buckets to insert N items without increasing allocation size.
498 TEST(DenseMapCustomTest, InitialSizeTest) {
499 // Test a few different sizes, 48 is *not* a random choice: we need a value
500 // that is 2/3 of a power of two to stress the grow() condition, and the power
501 // of two has to be at least 64 because of minimum size allocation in the
502 // DenseMap (see DefaultMinReservedSizeTest). 66 is a value just above the
503 // 64 default init.
504 for (auto Size : {1, 2, 48, 66}) {
505 DenseMap<int, CountCopyAndMove> Map(Size);
506 unsigned MemorySize = Map.getMemorySize();
507 CountCopyAndMove::ResetCounts();
508
509 for (int i = 0; i < Size; ++i)
510 Map.insert(std::pair<int, CountCopyAndMove>(std::piecewise_construct,
511 std::forward_as_tuple(i),
512 std::forward_as_tuple()));
513 // Check that we didn't grow
514 EXPECT_EQ(MemorySize, Map.getMemorySize());
515 // Check that move was called the expected number of times
516 EXPECT_EQ(Size, CountCopyAndMove::TotalMoves());
517 // Check that no copy occurred
518 EXPECT_EQ(0, CountCopyAndMove::TotalCopies());
519 }
520 }
521
522 // Make sure creating the map with a iterator range does not trigger grow()
523 TEST(DenseMapCustomTest, InitFromIterator) {
524 std::vector<std::pair<int, CountCopyAndMove>> Values;
525 // The size is a random value greater than 64 (hardcoded DenseMap min init)
526 const int Count = 65;
527 Values.reserve(Count);
528 for (int i = 0; i < Count; i++)
529 Values.emplace_back(i, CountCopyAndMove(i));
530
531 CountCopyAndMove::ResetCounts();
532 DenseMap<int, CountCopyAndMove> Map(Values.begin(), Values.end());
533 // Check that no move occurred
534 EXPECT_EQ(0, CountCopyAndMove::TotalMoves());
535 // Check that copy was called the expected number of times
536 EXPECT_EQ(Count, CountCopyAndMove::TotalCopies());
537 }
538
539 // Make sure reserve actually gives us enough buckets to insert N items
540 // without increasing allocation size.
541 TEST(DenseMapCustomTest, ReserveTest) {
542 // Test a few different size, 48 is *not* a random choice: we need a value
543 // that is 2/3 of a power of two to stress the grow() condition, and the power
544 // of two has to be at least 64 because of minimum size allocation in the
545 // DenseMap (see DefaultMinReservedSizeTest). 66 is a value just above the
546 // 64 default init.
547 for (auto Size : {1, 2, 48, 66}) {
548 DenseMap<int, CountCopyAndMove> Map;
549 Map.reserve(Size);
550 unsigned MemorySize = Map.getMemorySize();
551 CountCopyAndMove::ResetCounts();
552 for (int i = 0; i < Size; ++i)
553 Map.insert(std::pair<int, CountCopyAndMove>(std::piecewise_construct,
554 std::forward_as_tuple(i),
555 std::forward_as_tuple()));
556 // Check that we didn't grow
557 EXPECT_EQ(MemorySize, Map.getMemorySize());
558 // Check that move was called the expected number of times
559 EXPECT_EQ(Size, CountCopyAndMove::TotalMoves());
560 // Check that no copy occurred
561 EXPECT_EQ(0, CountCopyAndMove::TotalCopies());
562 }
563 }
564
565 TEST(DenseMapCustomTest, InsertOrAssignTest) {
566 DenseMap<int, CountCopyAndMove> Map;
567
568 CountCopyAndMove val1(1);
569 CountCopyAndMove::ResetCounts();
570 auto try0 = Map.insert_or_assign(0, val1);
571 EXPECT_TRUE(try0.second);
572 EXPECT_EQ(0, CountCopyAndMove::TotalMoves());
573 EXPECT_EQ(1, CountCopyAndMove::CopyConstructions);
574 EXPECT_EQ(0, CountCopyAndMove::CopyAssignments);
575
576 CountCopyAndMove::ResetCounts();
577 auto try1 = Map.insert_or_assign(0, val1);
578 EXPECT_FALSE(try1.second);
579 EXPECT_EQ(0, CountCopyAndMove::TotalMoves());
580 EXPECT_EQ(0, CountCopyAndMove::CopyConstructions);
581 EXPECT_EQ(1, CountCopyAndMove::CopyAssignments);
582
583 int key2 = 2;
584 CountCopyAndMove val2(2);
585 CountCopyAndMove::ResetCounts();
586 auto try2 = Map.insert_or_assign(key2, std::move(val2));
587 EXPECT_TRUE(try2.second);
588 EXPECT_EQ(0, CountCopyAndMove::TotalCopies());
589 EXPECT_EQ(1, CountCopyAndMove::MoveConstructions);
590 EXPECT_EQ(0, CountCopyAndMove::MoveAssignments);
591
592 CountCopyAndMove val3(3);
593 CountCopyAndMove::ResetCounts();
594 auto try3 = Map.insert_or_assign(key2, std::move(val3));
595 EXPECT_FALSE(try3.second);
596 EXPECT_EQ(0, CountCopyAndMove::TotalCopies());
597 EXPECT_EQ(0, CountCopyAndMove::MoveConstructions);
598 EXPECT_EQ(1, CountCopyAndMove::MoveAssignments);
599 }
600
601 TEST(DenseMapCustomTest, EmplaceOrAssign) {
602 DenseMap<int, CountCopyAndMove> Map;
603
604 CountCopyAndMove::ResetCounts();
605 auto Try0 = Map.emplace_or_assign(3, 3);
606 EXPECT_TRUE(Try0.second);
607 EXPECT_EQ(0, CountCopyAndMove::TotalCopies());
608 EXPECT_EQ(0, CountCopyAndMove::TotalMoves());
609 EXPECT_EQ(1, CountCopyAndMove::ValueConstructions);
610
611 CountCopyAndMove::ResetCounts();
612 auto Try1 = Map.emplace_or_assign(3, 4);
613 EXPECT_FALSE(Try1.second);
614 EXPECT_EQ(0, CountCopyAndMove::TotalCopies());
615 EXPECT_EQ(1, CountCopyAndMove::ValueConstructions);
616 EXPECT_EQ(0, CountCopyAndMove::MoveConstructions);
617 EXPECT_EQ(1, CountCopyAndMove::MoveAssignments);
618
619 int Key = 5;
620 CountCopyAndMove::ResetCounts();
621 auto Try2 = Map.emplace_or_assign(Key, 3);
622 EXPECT_TRUE(Try2.second);
623 EXPECT_EQ(0, CountCopyAndMove::TotalCopies());
624 EXPECT_EQ(0, CountCopyAndMove::TotalMoves());
625 EXPECT_EQ(1, CountCopyAndMove::ValueConstructions);
626
627 CountCopyAndMove::ResetCounts();
628 auto Try3 = Map.emplace_or_assign(Key, 4);
629 EXPECT_FALSE(Try3.second);
630 EXPECT_EQ(0, CountCopyAndMove::TotalCopies());
631 EXPECT_EQ(1, CountCopyAndMove::ValueConstructions);
632 EXPECT_EQ(0, CountCopyAndMove::MoveConstructions);
633 EXPECT_EQ(1, CountCopyAndMove::MoveAssignments);
634 }
635
636 // Make sure DenseMap works with StringRef keys.
637 TEST(DenseMapCustomTest, StringRefTest) {
638 DenseMap<StringRef, int> M;
639
640 M["a"] = 1;
641 M["b"] = 2;
642 M["c"] = 3;
643
644 EXPECT_EQ(3u, M.size());
645 EXPECT_EQ(1, M.lookup("a"));
646 EXPECT_EQ(2, M.lookup("b"));
647 EXPECT_EQ(3, M.lookup("c"));
648
649 EXPECT_EQ(0, M.lookup("q"));
650
651 // Test the empty string, spelled various ways.
652 EXPECT_EQ(0, M.lookup(""));
653 EXPECT_EQ(0, M.lookup(StringRef()));
654 EXPECT_EQ(0, M.lookup(StringRef("a", 0)));
655 M[""] = 42;
656 EXPECT_EQ(42, M.lookup(""));
657 EXPECT_EQ(42, M.lookup(StringRef()));
658 EXPECT_EQ(42, M.lookup(StringRef("a", 0)));
659 }
660
661 struct NonDefaultConstructible {
662 unsigned V;
663 NonDefaultConstructible(unsigned V) : V(V) {};
664 bool operator==(const NonDefaultConstructible &Other) const {
665 return V == Other.V;
666 }
667 };
668
669 TEST(DenseMapCustomTest, LookupOr) {
670 DenseMap<int, NonDefaultConstructible> M;
671
672 M.insert_or_assign(0, 3u);
673 M.insert_or_assign(1, 2u);
674 M.insert_or_assign(1, 0u);
675
676 EXPECT_EQ(M.lookup_or(0, 4u), 3u);
677 EXPECT_EQ(M.lookup_or(1, 4u), 0u);
678 EXPECT_EQ(M.lookup_or(2, 4u), 4u);
679 }
680
681 TEST(DenseMapCustomTest, LookupOrConstness) {
682 DenseMap<int, unsigned *> M;
683 unsigned Default = 3u;
684 unsigned *Ret = M.lookup_or(0, &Default);
685 EXPECT_EQ(Ret, &Default);
686 }
687
688 // Key traits that allows lookup with either an unsigned or char* key;
689 // In the latter case, "a" == 0, "b" == 1 and so on.
690 struct TestDenseMapInfo {
691 static inline unsigned getEmptyKey() { return ~0; }
692 static inline unsigned getTombstoneKey() { return ~0U - 1; }
693 static unsigned getHashValue(const unsigned& Val) { return Val * 37U; }
694 static unsigned getHashValue(const char* Val) {
695 return (unsigned)(Val[0] - 'a') * 37U;
696 }
697 static bool isEqual(const unsigned& LHS, const unsigned& RHS) {
698 return LHS == RHS;
699 }
700 static bool isEqual(const char* LHS, const unsigned& RHS) {
701 return (unsigned)(LHS[0] - 'a') == RHS;
702 }
703 };
704
705 // find_as() tests
706 TEST(DenseMapCustomTest, FindAsTest) {
707 DenseMap<unsigned, unsigned, TestDenseMapInfo> map;
708 map[0] = 1;
709 map[1] = 2;
710 map[2] = 3;
711
712 // Size tests
713 EXPECT_EQ(3u, map.size());
714
715 // Normal lookup tests
716 EXPECT_EQ(1u, map.count(1));
717 EXPECT_EQ(1u, map.find(0)->second);
718 EXPECT_EQ(2u, map.find(1)->second);
719 EXPECT_EQ(3u, map.find(2)->second);
720 EXPECT_TRUE(map.find(3) == map.end());
721
722 // find_as() tests
723 EXPECT_EQ(1u, map.find_as("a")->second);
724 EXPECT_EQ(2u, map.find_as("b")->second);
725 EXPECT_EQ(3u, map.find_as("c")->second);
726 EXPECT_TRUE(map.find_as("d") == map.end());
727 }
728
729 TEST(DenseMapCustomTest, SmallDenseMapInitializerList) {
730 SmallDenseMap<int, int> M = {{0, 0}, {0, 1}, {1, 2}};
731 EXPECT_EQ(2u, M.size());
732 EXPECT_EQ(1u, M.count(0));
733 EXPECT_EQ(0, M[0]);
734 EXPECT_EQ(1u, M.count(1));
735 EXPECT_EQ(2, M[1]);
736 }
737
738 struct ContiguousDenseMapInfo {
739 static inline unsigned getEmptyKey() { return ~0; }
740 static inline unsigned getTombstoneKey() { return ~0U - 1; }
741 static unsigned getHashValue(const unsigned& Val) { return Val; }
742 static bool isEqual(const unsigned& LHS, const unsigned& RHS) {
743 return LHS == RHS;
744 }
745 };
746
747 // Test that filling a small dense map with exactly the number of elements in
748 // the map grows to have enough space for an empty bucket.
749 TEST(DenseMapCustomTest, SmallDenseMapGrowTest) {
750 SmallDenseMap<unsigned, unsigned, 32, ContiguousDenseMapInfo> map;
751 // Add some number of elements, then delete a few to leave us some tombstones.
752 // If we just filled the map with 32 elements we'd grow because of not enough
753 // tombstones which masks the issue here.
754 for (unsigned i = 0; i < 20; ++i)
755 map[i] = i + 1;
756 for (unsigned i = 0; i < 10; ++i)
757 map.erase(i);
758 for (unsigned i = 20; i < 32; ++i)
759 map[i] = i + 1;
760
761 // Size tests
762 EXPECT_EQ(22u, map.size());
763
764 // Try to find an element which doesn't exist. There was a bug in
765 // SmallDenseMap which led to a map with num elements == small capacity not
766 // having an empty bucket any more. Finding an element not in the map would
767 // therefore never terminate.
768 EXPECT_TRUE(map.find(32) == map.end());
769 }
770
771 TEST(DenseMapCustomTest, LargeSmallDenseMapCompaction) {
772 SmallDenseMap<unsigned, unsigned, 128, ContiguousDenseMapInfo> map;
773 // Fill to < 3/4 load.
774 for (unsigned i = 0; i < 95; ++i)
775 map[i] = i;
776 // And erase, leaving behind tombstones.
777 for (unsigned i = 0; i < 95; ++i)
778 map.erase(i);
779 // Fill further, so that less than 1/8 are empty, but still below 3/4 load.
780 for (unsigned i = 95; i < 128; ++i)
781 map[i] = i;
782
783 EXPECT_EQ(33u, map.size());
784 // Similar to the previous test, check for a non-existing element, as an
785 // indirect check that tombstones have been removed.
786 EXPECT_TRUE(map.find(0) == map.end());
787 }
788
789 TEST(DenseMapCustomTest, SmallDenseMapWithNumBucketsNonPowerOf2) {
790 // Is not power of 2.
791 const unsigned NumInitBuckets = 33;
792 // Power of 2 less then NumInitBuckets.
793 constexpr unsigned InlineBuckets = 4;
794 // Constructor should not trigger assert.
795 SmallDenseMap<int, int, InlineBuckets> map(NumInitBuckets);
796 }
797
798 TEST(DenseMapCustomTest, TryEmplaceTest) {
799 DenseMap<int, std::unique_ptr<int>> Map;
800 std::unique_ptr<int> P(new int(2));
801 auto Try1 = Map.try_emplace(0, new int(1));
802 EXPECT_TRUE(Try1.second);
803 auto Try2 = Map.try_emplace(0, std::move(P));
804 EXPECT_FALSE(Try2.second);
805 EXPECT_EQ(Try1.first, Try2.first);
806 EXPECT_NE(nullptr, P);
807 }
808
809 TEST(DenseMapCustomTest, ConstTest) {
810 // Test that const pointers work okay for count and find, even when the
811 // underlying map is a non-const pointer.
812 DenseMap<int *, int> Map;
813 int A;
814 int *B = &A;
815 const int *C = &A;
816 Map.insert({B, 0});
817 EXPECT_EQ(Map.count(B), 1u);
818 EXPECT_EQ(Map.count(C), 1u);
819 EXPECT_NE(Map.find(B), Map.end());
820 EXPECT_NE(Map.find(C), Map.end());
821 }
822
823 struct IncompleteStruct;
824
825 TEST(DenseMapCustomTest, OpaquePointerKey) {
826 // Test that we can use a pointer to an incomplete type as a DenseMap key.
827 // This is an important build time optimization, since many classes have
828 // DenseMap members.
829 DenseMap<IncompleteStruct *, int> Map;
830 int Keys[3] = {0, 0, 0};
831 IncompleteStruct *K1 = reinterpret_cast<IncompleteStruct *>(&Keys[0]);
832 IncompleteStruct *K2 = reinterpret_cast<IncompleteStruct *>(&Keys[1]);
833 IncompleteStruct *K3 = reinterpret_cast<IncompleteStruct *>(&Keys[2]);
834 Map.insert({K1, 1});
835 Map.insert({K2, 2});
836 Map.insert({K3, 3});
837 EXPECT_EQ(Map.count(K1), 1u);
838 EXPECT_EQ(Map[K1], 1);
839 EXPECT_EQ(Map[K2], 2);
840 EXPECT_EQ(Map[K3], 3);
841 Map.clear();
842 EXPECT_EQ(Map.find(K1), Map.end());
843 EXPECT_EQ(Map.find(K2), Map.end());
844 EXPECT_EQ(Map.find(K3), Map.end());
845 }
846 } // namespace
847
848 namespace {
849 struct A {
850 A(int value) : value(value) {}
851 int value;
852 };
853 struct B : public A {
854 using A::A;
855 };
856
857 struct AlwaysEqType {
858 bool operator==(const AlwaysEqType &RHS) const { return true; }
859 };
860 } // namespace
861
862 namespace llvm {
863 template <typename T>
864 struct DenseMapInfo<T, std::enable_if_t<std::is_base_of_v<A, T>>> {
865 static inline T getEmptyKey() { return {static_cast<int>(~0)}; }
866 static inline T getTombstoneKey() { return {static_cast<int>(~0U - 1)}; }
867 static unsigned getHashValue(const T &Val) { return Val.value; }
868 static bool isEqual(const T &LHS, const T &RHS) {
869 return LHS.value == RHS.value;
870 }
871 };
872
873 template <> struct DenseMapInfo<AlwaysEqType> {
874 using T = AlwaysEqType;
875 static inline T getEmptyKey() { return {}; }
876 static inline T getTombstoneKey() { return {}; }
877 static unsigned getHashValue(const T &Val) { return 0; }
878 static bool isEqual(const T &LHS, const T &RHS) {
879 return false;
880 }
881 };
882 } // namespace llvm
883
884 namespace {
885 TEST(DenseMapCustomTest, SFINAEMapInfo) {
886 // Test that we can use a pointer to an incomplete type as a DenseMap key.
887 // This is an important build time optimization, since many classes have
888 // DenseMap members.
889 DenseMap<B, int> Map;
890 B Keys[3] = {{0}, {1}, {2}};
891 Map.insert({Keys[0], 1});
892 Map.insert({Keys[1], 2});
893 Map.insert({Keys[2], 3});
894 EXPECT_EQ(Map.count(Keys[0]), 1u);
895 EXPECT_EQ(Map[Keys[0]], 1);
896 EXPECT_EQ(Map[Keys[1]], 2);
897 EXPECT_EQ(Map[Keys[2]], 3);
898 Map.clear();
899 EXPECT_EQ(Map.find(Keys[0]), Map.end());
900 EXPECT_EQ(Map.find(Keys[1]), Map.end());
901 EXPECT_EQ(Map.find(Keys[2]), Map.end());
902 }
903
904 TEST(DenseMapCustomTest, VariantSupport) {
905 using variant = std::variant<int, int, AlwaysEqType>;
906 DenseMap<variant, int> Map;
907 variant Keys[] = {
908 variant(std::in_place_index<0>, 1),
909 variant(std::in_place_index<1>, 1),
910 variant(std::in_place_index<2>),
911 };
912 Map.try_emplace(Keys[0], 0);
913 Map.try_emplace(Keys[1], 1);
914 EXPECT_THAT(Map, testing::SizeIs(2));
915 EXPECT_NE(DenseMapInfo<variant>::getHashValue(Keys[0]),
916 DenseMapInfo<variant>::getHashValue(Keys[1]));
917 // Check that isEqual dispatches to isEqual of underlying type, and not to
918 // operator==.
919 EXPECT_FALSE(DenseMapInfo<variant>::isEqual(Keys[2], Keys[2]));
920 }
921
922 // Test that gTest prints map entries as pairs instead of opaque objects.
923 // See third-party/unittest/googletest/internal/custom/gtest-printers.h
924 TEST(DenseMapCustomTest, PairPrinting) {
925 DenseMap<int, StringRef> Map = {{1, "one"}, {2, "two"}};
926 EXPECT_EQ(R"({ (1, "one"), (2, "two") })", ::testing::PrintToString(Map));
927 }
928
929 } // namespace