xref: /llvm-project/llvm/unittests/ADT/DenseMapTest.cpp (revision 05eca80cb8c9d22e5faa24c1758cf82fcd801e23)
1 //===- llvm/unittest/ADT/DenseMapMap.cpp - DenseMap unit tests --*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "gtest/gtest.h"
11 #include "llvm/ADT/DenseMap.h"
12 #include <map>
13 #include <set>
14 
15 using namespace llvm;
16 
17 namespace {
18 
19 uint32_t getTestKey(int i, uint32_t *) { return i; }
20 uint32_t getTestValue(int i, uint32_t *) { return 42 + i; }
21 
22 uint32_t *getTestKey(int i, uint32_t **) {
23   static uint32_t dummy_arr1[8192];
24   assert(i < 8192 && "Only support 8192 dummy keys.");
25   return &dummy_arr1[i];
26 }
27 uint32_t *getTestValue(int i, uint32_t **) {
28   static uint32_t dummy_arr1[8192];
29   assert(i < 8192 && "Only support 8192 dummy keys.");
30   return &dummy_arr1[i];
31 }
32 
33 /// \brief A test class that tries to check that construction and destruction
34 /// occur correctly.
35 class CtorTester {
36   static std::set<CtorTester *> Constructed;
37   int Value;
38 
39 public:
40   explicit CtorTester(int Value = 0) : Value(Value) {
41     EXPECT_TRUE(Constructed.insert(this).second);
42   }
43   CtorTester(uint32_t Value) : Value(Value) {
44     EXPECT_TRUE(Constructed.insert(this).second);
45   }
46   CtorTester(const CtorTester &Arg) : Value(Arg.Value) {
47     EXPECT_TRUE(Constructed.insert(this).second);
48   }
49   CtorTester &operator=(const CtorTester &) = default;
50   ~CtorTester() {
51     EXPECT_EQ(1u, Constructed.erase(this));
52   }
53   operator uint32_t() const { return Value; }
54 
55   int getValue() const { return Value; }
56   bool operator==(const CtorTester &RHS) const { return Value == RHS.Value; }
57 };
58 
59 std::set<CtorTester *> CtorTester::Constructed;
60 
61 struct CtorTesterMapInfo {
62   static inline CtorTester getEmptyKey() { return CtorTester(-1); }
63   static inline CtorTester getTombstoneKey() { return CtorTester(-2); }
64   static unsigned getHashValue(const CtorTester &Val) {
65     return Val.getValue() * 37u;
66   }
67   static bool isEqual(const CtorTester &LHS, const CtorTester &RHS) {
68     return LHS == RHS;
69   }
70 };
71 
72 CtorTester getTestKey(int i, CtorTester *) { return CtorTester(i); }
73 CtorTester getTestValue(int i, CtorTester *) { return CtorTester(42 + i); }
74 
75 // Test fixture, with helper functions implemented by forwarding to global
76 // function overloads selected by component types of the type parameter. This
77 // allows all of the map implementations to be tested with shared
78 // implementations of helper routines.
79 template <typename T>
80 class DenseMapTest : public ::testing::Test {
81 protected:
82   T Map;
83 
84   static typename T::key_type *const dummy_key_ptr;
85   static typename T::mapped_type *const dummy_value_ptr;
86 
87   typename T::key_type getKey(int i = 0) {
88     return getTestKey(i, dummy_key_ptr);
89   }
90   typename T::mapped_type getValue(int i = 0) {
91     return getTestValue(i, dummy_value_ptr);
92   }
93 };
94 
95 template <typename T>
96 typename T::key_type *const DenseMapTest<T>::dummy_key_ptr = nullptr;
97 template <typename T>
98 typename T::mapped_type *const DenseMapTest<T>::dummy_value_ptr = nullptr;
99 
100 // Register these types for testing.
101 typedef ::testing::Types<DenseMap<uint32_t, uint32_t>,
102                          DenseMap<uint32_t *, uint32_t *>,
103                          DenseMap<CtorTester, CtorTester, CtorTesterMapInfo>,
104                          SmallDenseMap<uint32_t, uint32_t>,
105                          SmallDenseMap<uint32_t *, uint32_t *>,
106                          SmallDenseMap<CtorTester, CtorTester, 4,
107                                        CtorTesterMapInfo>
108                          > DenseMapTestTypes;
109 TYPED_TEST_CASE(DenseMapTest, DenseMapTestTypes);
110 
111 // Empty map tests
112 TYPED_TEST(DenseMapTest, EmptyIntMapTest) {
113   // Size tests
114   EXPECT_EQ(0u, this->Map.size());
115   EXPECT_TRUE(this->Map.empty());
116 
117   // Iterator tests
118   EXPECT_TRUE(this->Map.begin() == this->Map.end());
119 
120   // Lookup tests
121   EXPECT_FALSE(this->Map.count(this->getKey()));
122   EXPECT_TRUE(this->Map.find(this->getKey()) == this->Map.end());
123 #if !defined(_MSC_VER) || defined(__clang__)
124   EXPECT_EQ(typename TypeParam::mapped_type(),
125             this->Map.lookup(this->getKey()));
126 #else
127   // MSVC, at least old versions, cannot parse the typename to disambiguate
128   // TypeParam::mapped_type as a type. However, because MSVC doesn't implement
129   // two-phase name lookup, it also doesn't require the typename. Deal with
130   // this mutual incompatibility through specialized code.
131   EXPECT_EQ(TypeParam::mapped_type(),
132             this->Map.lookup(this->getKey()));
133 #endif
134 }
135 
136 // Constant map tests
137 TYPED_TEST(DenseMapTest, ConstEmptyMapTest) {
138   const TypeParam &ConstMap = this->Map;
139   EXPECT_EQ(0u, ConstMap.size());
140   EXPECT_TRUE(ConstMap.empty());
141   EXPECT_TRUE(ConstMap.begin() == ConstMap.end());
142 }
143 
144 // A map with a single entry
145 TYPED_TEST(DenseMapTest, SingleEntryMapTest) {
146   this->Map[this->getKey()] = this->getValue();
147 
148   // Size tests
149   EXPECT_EQ(1u, this->Map.size());
150   EXPECT_FALSE(this->Map.begin() == this->Map.end());
151   EXPECT_FALSE(this->Map.empty());
152 
153   // Iterator tests
154   typename TypeParam::iterator it = this->Map.begin();
155   EXPECT_EQ(this->getKey(), it->first);
156   EXPECT_EQ(this->getValue(), it->second);
157   ++it;
158   EXPECT_TRUE(it == this->Map.end());
159 
160   // Lookup tests
161   EXPECT_TRUE(this->Map.count(this->getKey()));
162   EXPECT_TRUE(this->Map.find(this->getKey()) == this->Map.begin());
163   EXPECT_EQ(this->getValue(), this->Map.lookup(this->getKey()));
164   EXPECT_EQ(this->getValue(), this->Map[this->getKey()]);
165 }
166 
167 // Test clear() method
168 TYPED_TEST(DenseMapTest, ClearTest) {
169   this->Map[this->getKey()] = this->getValue();
170   this->Map.clear();
171 
172   EXPECT_EQ(0u, this->Map.size());
173   EXPECT_TRUE(this->Map.empty());
174   EXPECT_TRUE(this->Map.begin() == this->Map.end());
175 }
176 
177 // Test erase(iterator) method
178 TYPED_TEST(DenseMapTest, EraseTest) {
179   this->Map[this->getKey()] = this->getValue();
180   this->Map.erase(this->Map.begin());
181 
182   EXPECT_EQ(0u, this->Map.size());
183   EXPECT_TRUE(this->Map.empty());
184   EXPECT_TRUE(this->Map.begin() == this->Map.end());
185 }
186 
187 // Test erase(value) method
188 TYPED_TEST(DenseMapTest, EraseTest2) {
189   this->Map[this->getKey()] = this->getValue();
190   this->Map.erase(this->getKey());
191 
192   EXPECT_EQ(0u, this->Map.size());
193   EXPECT_TRUE(this->Map.empty());
194   EXPECT_TRUE(this->Map.begin() == this->Map.end());
195 }
196 
197 // Test insert() method
198 TYPED_TEST(DenseMapTest, InsertTest) {
199   this->Map.insert(std::make_pair(this->getKey(), this->getValue()));
200   EXPECT_EQ(1u, this->Map.size());
201   EXPECT_EQ(this->getValue(), this->Map[this->getKey()]);
202 }
203 
204 // Test copy constructor method
205 TYPED_TEST(DenseMapTest, CopyConstructorTest) {
206   this->Map[this->getKey()] = this->getValue();
207   TypeParam copyMap(this->Map);
208 
209   EXPECT_EQ(1u, copyMap.size());
210   EXPECT_EQ(this->getValue(), copyMap[this->getKey()]);
211 }
212 
213 // Test copy constructor method where SmallDenseMap isn't small.
214 TYPED_TEST(DenseMapTest, CopyConstructorNotSmallTest) {
215   for (int Key = 0; Key < 5; ++Key)
216     this->Map[this->getKey(Key)] = this->getValue(Key);
217   TypeParam copyMap(this->Map);
218 
219   EXPECT_EQ(5u, copyMap.size());
220   for (int Key = 0; Key < 5; ++Key)
221     EXPECT_EQ(this->getValue(Key), copyMap[this->getKey(Key)]);
222 }
223 
224 // Test copying from a default-constructed map.
225 TYPED_TEST(DenseMapTest, CopyConstructorFromDefaultTest) {
226   TypeParam copyMap(this->Map);
227 
228   EXPECT_TRUE(copyMap.empty());
229 }
230 
231 // Test copying from an empty map where SmallDenseMap isn't small.
232 TYPED_TEST(DenseMapTest, CopyConstructorFromEmptyTest) {
233   for (int Key = 0; Key < 5; ++Key)
234     this->Map[this->getKey(Key)] = this->getValue(Key);
235   this->Map.clear();
236   TypeParam copyMap(this->Map);
237 
238   EXPECT_TRUE(copyMap.empty());
239 }
240 
241 // Test assignment operator method
242 TYPED_TEST(DenseMapTest, AssignmentTest) {
243   this->Map[this->getKey()] = this->getValue();
244   TypeParam copyMap = this->Map;
245 
246   EXPECT_EQ(1u, copyMap.size());
247   EXPECT_EQ(this->getValue(), copyMap[this->getKey()]);
248 
249   // test self-assignment.
250   copyMap = copyMap;
251   EXPECT_EQ(1u, copyMap.size());
252   EXPECT_EQ(this->getValue(), copyMap[this->getKey()]);
253 }
254 
255 TYPED_TEST(DenseMapTest, AssignmentTestNotSmall) {
256   for (int Key = 0; Key < 5; ++Key)
257     this->Map[this->getKey(Key)] = this->getValue(Key);
258   TypeParam copyMap = this->Map;
259 
260   EXPECT_EQ(5u, copyMap.size());
261   for (int Key = 0; Key < 5; ++Key)
262     EXPECT_EQ(this->getValue(Key), copyMap[this->getKey(Key)]);
263 
264   // test self-assignment.
265   copyMap = copyMap;
266   EXPECT_EQ(5u, copyMap.size());
267   for (int Key = 0; Key < 5; ++Key)
268     EXPECT_EQ(this->getValue(Key), copyMap[this->getKey(Key)]);
269 }
270 
271 // Test swap method
272 TYPED_TEST(DenseMapTest, SwapTest) {
273   this->Map[this->getKey()] = this->getValue();
274   TypeParam otherMap;
275 
276   this->Map.swap(otherMap);
277   EXPECT_EQ(0u, this->Map.size());
278   EXPECT_TRUE(this->Map.empty());
279   EXPECT_EQ(1u, otherMap.size());
280   EXPECT_EQ(this->getValue(), otherMap[this->getKey()]);
281 
282   this->Map.swap(otherMap);
283   EXPECT_EQ(0u, otherMap.size());
284   EXPECT_TRUE(otherMap.empty());
285   EXPECT_EQ(1u, this->Map.size());
286   EXPECT_EQ(this->getValue(), this->Map[this->getKey()]);
287 
288   // Make this more interesting by inserting 100 numbers into the map.
289   for (int i = 0; i < 100; ++i)
290     this->Map[this->getKey(i)] = this->getValue(i);
291 
292   this->Map.swap(otherMap);
293   EXPECT_EQ(0u, this->Map.size());
294   EXPECT_TRUE(this->Map.empty());
295   EXPECT_EQ(100u, otherMap.size());
296   for (int i = 0; i < 100; ++i)
297     EXPECT_EQ(this->getValue(i), otherMap[this->getKey(i)]);
298 
299   this->Map.swap(otherMap);
300   EXPECT_EQ(0u, otherMap.size());
301   EXPECT_TRUE(otherMap.empty());
302   EXPECT_EQ(100u, this->Map.size());
303   for (int i = 0; i < 100; ++i)
304     EXPECT_EQ(this->getValue(i), this->Map[this->getKey(i)]);
305 }
306 
307 // A more complex iteration test
308 TYPED_TEST(DenseMapTest, IterationTest) {
309   bool visited[100];
310   std::map<typename TypeParam::key_type, unsigned> visitedIndex;
311 
312   // Insert 100 numbers into the map
313   for (int i = 0; i < 100; ++i) {
314     visited[i] = false;
315     visitedIndex[this->getKey(i)] = i;
316 
317     this->Map[this->getKey(i)] = this->getValue(i);
318   }
319 
320   // Iterate over all numbers and mark each one found.
321   for (typename TypeParam::iterator it = this->Map.begin();
322        it != this->Map.end(); ++it)
323     visited[visitedIndex[it->first]] = true;
324 
325   // Ensure every number was visited.
326   for (int i = 0; i < 100; ++i)
327     ASSERT_TRUE(visited[i]) << "Entry #" << i << " was never visited";
328 }
329 
330 // const_iterator test
331 TYPED_TEST(DenseMapTest, ConstIteratorTest) {
332   // Check conversion from iterator to const_iterator.
333   typename TypeParam::iterator it = this->Map.begin();
334   typename TypeParam::const_iterator cit(it);
335   EXPECT_TRUE(it == cit);
336 
337   // Check copying of const_iterators.
338   typename TypeParam::const_iterator cit2(cit);
339   EXPECT_TRUE(cit == cit2);
340 }
341 
342 namespace {
343 // Simple class that counts how many moves and copy happens when growing a map
344 struct CountCopyAndMove {
345   static int Move;
346   static int Copy;
347   CountCopyAndMove() {}
348 
349   CountCopyAndMove(const CountCopyAndMove &) { Copy++; }
350   CountCopyAndMove &operator=(const CountCopyAndMove &) {
351     Copy++;
352     return *this;
353   }
354   CountCopyAndMove(CountCopyAndMove &&) { Move++; }
355   CountCopyAndMove &operator=(const CountCopyAndMove &&) {
356     Move++;
357     return *this;
358   }
359 };
360 int CountCopyAndMove::Copy = 0;
361 int CountCopyAndMove::Move = 0;
362 
363 } // anonymous namespace
364 
365 // Test for the default minimum size of a DenseMap
366 TEST(DenseMapCustomTest, DefaultMinReservedSizeTest) {
367   // IF THIS VALUE CHANGE, please update InitialSizeTest, InitFromIterator, and
368   // ReserveTest as well!
369   const int ExpectedInitialBucketCount = 64;
370   // Formula from DenseMap::getMinBucketToReserveForEntries()
371   const int ExpectedMaxInitialEntries = ExpectedInitialBucketCount * 3 / 4 - 1;
372 
373   DenseMap<int, CountCopyAndMove> Map;
374   // Will allocate 64 buckets
375   Map.reserve(1);
376   unsigned MemorySize = Map.getMemorySize();
377   CountCopyAndMove::Copy = 0;
378   CountCopyAndMove::Move = 0;
379   for (int i = 0; i < ExpectedMaxInitialEntries; ++i)
380     Map.insert(std::make_pair(i, CountCopyAndMove()));
381   // Check that we didn't grow
382   EXPECT_EQ(MemorySize, Map.getMemorySize());
383   // Check that move was called the expected number of times
384   EXPECT_EQ(ExpectedMaxInitialEntries * 2, CountCopyAndMove::Move);
385   // Check that no copy occured
386   EXPECT_EQ(0, CountCopyAndMove::Copy);
387 
388   // Adding one extra element should grow the map
389   CountCopyAndMove::Copy = 0;
390   CountCopyAndMove::Move = 0;
391   Map.insert(std::make_pair(ExpectedMaxInitialEntries, CountCopyAndMove()));
392   // Check that we grew
393   EXPECT_NE(MemorySize, Map.getMemorySize());
394   // Check that move was called the expected number of times
395   EXPECT_EQ(ExpectedMaxInitialEntries + 2, CountCopyAndMove::Move);
396   // Check that no copy occured
397   EXPECT_EQ(0, CountCopyAndMove::Copy);
398 }
399 
400 // Make sure creating the map with an initial size of N actually gives us enough
401 // buckets to insert N items without increasing allocation size.
402 TEST(DenseMapCustomTest, InitialSizeTest) {
403   // Test a few different sizes, 48 is *not* a random choice: we need a value
404   // that is 2/3 of a power of two to stress the grow() condition, and the power
405   // of two has to be at least 64 because of minimum size allocation in the
406   // DenseMap (see DefaultMinReservedSizeTest). 66 is a value just above the
407   // 64 default init.
408   for (auto Size : {1, 2, 48, 66}) {
409     DenseMap<int, CountCopyAndMove> Map(Size);
410     unsigned MemorySize = Map.getMemorySize();
411     CountCopyAndMove::Copy = 0;
412     CountCopyAndMove::Move = 0;
413     for (int i = 0; i < Size; ++i)
414       Map.insert(std::make_pair(i, CountCopyAndMove()));
415     // Check that we didn't grow
416     EXPECT_EQ(MemorySize, Map.getMemorySize());
417     // Check that move was called the expected number of times
418     EXPECT_EQ(Size * 2, CountCopyAndMove::Move);
419     // Check that no copy occured
420     EXPECT_EQ(0, CountCopyAndMove::Copy);
421   }
422 }
423 
424 // Make sure creating the map with a iterator range does not trigger grow()
425 TEST(DenseMapCustomTest, InitFromIterator) {
426   std::vector<std::pair<int, CountCopyAndMove>> Values;
427   // The size is a random value greater than 64 (hardcoded DenseMap min init)
428   const int Count = 65;
429   for (int i = 0; i < Count; i++)
430     Values.emplace_back(i, CountCopyAndMove());
431 
432   CountCopyAndMove::Move = 0;
433   CountCopyAndMove::Copy = 0;
434   DenseMap<int, CountCopyAndMove> Map(Values.begin(), Values.end());
435   // Check that no move occured
436   EXPECT_EQ(0, CountCopyAndMove::Move);
437   // Check that copy was called the expected number of times
438   EXPECT_EQ(Count, CountCopyAndMove::Copy);
439 }
440 
441 // Make sure reserve actually gives us enough buckets to insert N items
442 // without increasing allocation size.
443 TEST(DenseMapCustomTest, ReserveTest) {
444   // Test a few different size, 48 is *not* a random choice: we need a value
445   // that is 2/3 of a power of two to stress the grow() condition, and the power
446   // of two has to be at least 64 because of minimum size allocation in the
447   // DenseMap (see DefaultMinReservedSizeTest). 66 is a value just above the
448   // 64 default init.
449   for (auto Size : {1, 2, 48, 66}) {
450     DenseMap<int, CountCopyAndMove> Map;
451     Map.reserve(Size);
452     unsigned MemorySize = Map.getMemorySize();
453     CountCopyAndMove::Copy = 0;
454     CountCopyAndMove::Move = 0;
455     for (int i = 0; i < Size; ++i)
456       Map.insert(std::make_pair(i, CountCopyAndMove()));
457     // Check that we didn't grow
458     EXPECT_EQ(MemorySize, Map.getMemorySize());
459     // Check that move was called the expected number of times
460     EXPECT_EQ(Size * 2, CountCopyAndMove::Move);
461     // Check that no copy occured
462     EXPECT_EQ(0, CountCopyAndMove::Copy);
463   }
464 }
465 
466 // Make sure DenseMap works with StringRef keys.
467 TEST(DenseMapCustomTest, StringRefTest) {
468   DenseMap<StringRef, int> M;
469 
470   M["a"] = 1;
471   M["b"] = 2;
472   M["c"] = 3;
473 
474   EXPECT_EQ(3u, M.size());
475   EXPECT_EQ(1, M.lookup("a"));
476   EXPECT_EQ(2, M.lookup("b"));
477   EXPECT_EQ(3, M.lookup("c"));
478 
479   EXPECT_EQ(0, M.lookup("q"));
480 
481   // Test the empty string, spelled various ways.
482   EXPECT_EQ(0, M.lookup(""));
483   EXPECT_EQ(0, M.lookup(StringRef()));
484   EXPECT_EQ(0, M.lookup(StringRef("a", 0)));
485   M[""] = 42;
486   EXPECT_EQ(42, M.lookup(""));
487   EXPECT_EQ(42, M.lookup(StringRef()));
488   EXPECT_EQ(42, M.lookup(StringRef("a", 0)));
489 }
490 
491 // Key traits that allows lookup with either an unsigned or char* key;
492 // In the latter case, "a" == 0, "b" == 1 and so on.
493 struct TestDenseMapInfo {
494   static inline unsigned getEmptyKey() { return ~0; }
495   static inline unsigned getTombstoneKey() { return ~0U - 1; }
496   static unsigned getHashValue(const unsigned& Val) { return Val * 37U; }
497   static unsigned getHashValue(const char* Val) {
498     return (unsigned)(Val[0] - 'a') * 37U;
499   }
500   static bool isEqual(const unsigned& LHS, const unsigned& RHS) {
501     return LHS == RHS;
502   }
503   static bool isEqual(const char* LHS, const unsigned& RHS) {
504     return (unsigned)(LHS[0] - 'a') == RHS;
505   }
506 };
507 
508 // find_as() tests
509 TEST(DenseMapCustomTest, FindAsTest) {
510   DenseMap<unsigned, unsigned, TestDenseMapInfo> map;
511   map[0] = 1;
512   map[1] = 2;
513   map[2] = 3;
514 
515   // Size tests
516   EXPECT_EQ(3u, map.size());
517 
518   // Normal lookup tests
519   EXPECT_EQ(1u, map.count(1));
520   EXPECT_EQ(1u, map.find(0)->second);
521   EXPECT_EQ(2u, map.find(1)->second);
522   EXPECT_EQ(3u, map.find(2)->second);
523   EXPECT_TRUE(map.find(3) == map.end());
524 
525   // find_as() tests
526   EXPECT_EQ(1u, map.find_as("a")->second);
527   EXPECT_EQ(2u, map.find_as("b")->second);
528   EXPECT_EQ(3u, map.find_as("c")->second);
529   EXPECT_TRUE(map.find_as("d") == map.end());
530 }
531 
532 struct ContiguousDenseMapInfo {
533   static inline unsigned getEmptyKey() { return ~0; }
534   static inline unsigned getTombstoneKey() { return ~0U - 1; }
535   static unsigned getHashValue(const unsigned& Val) { return Val; }
536   static bool isEqual(const unsigned& LHS, const unsigned& RHS) {
537     return LHS == RHS;
538   }
539 };
540 
541 // Test that filling a small dense map with exactly the number of elements in
542 // the map grows to have enough space for an empty bucket.
543 TEST(DenseMapCustomTest, SmallDenseMapGrowTest) {
544   SmallDenseMap<unsigned, unsigned, 32, ContiguousDenseMapInfo> map;
545   // Add some number of elements, then delete a few to leave us some tombstones.
546   // If we just filled the map with 32 elements we'd grow because of not enough
547   // tombstones which masks the issue here.
548   for (unsigned i = 0; i < 20; ++i)
549     map[i] = i + 1;
550   for (unsigned i = 0; i < 10; ++i)
551     map.erase(i);
552   for (unsigned i = 20; i < 32; ++i)
553     map[i] = i + 1;
554 
555   // Size tests
556   EXPECT_EQ(22u, map.size());
557 
558   // Try to find an element which doesn't exist.  There was a bug in
559   // SmallDenseMap which led to a map with num elements == small capacity not
560   // having an empty bucket any more.  Finding an element not in the map would
561   // therefore never terminate.
562   EXPECT_TRUE(map.find(32) == map.end());
563 }
564 
565 }
566