DenseMap: make .resize() do the intuitive thing
authorFiona Glaser <escha@apple.com>
Tue, 15 Mar 2016 01:50:46 +0000 (01:50 +0000)
committerFiona Glaser <escha@apple.com>
Tue, 15 Mar 2016 01:50:46 +0000 (01:50 +0000)
In some places, like InstCombine, we resize a DenseMap to fit the elements
we intend to put in it, then insert those elements (to avoid continual
reallocations as it grows). But .resize(foo) doesn't actually do what
people think; it resizes to foo buckets (which is really an
implementation detail the user of DenseMap probably shouldn't care about),
not the space required to fit foo elements. DenseMap grows if 3/4 of its
buckets are full, so this actually causes one forced reallocation every
time instead of avoiding a reallocation.

This patch makes .resize(foo) do the intuitive thing: it grows to the size
necessary to fit foo elements without new allocations.

Also include a test to verify that .resize() actually does what we think it
does.

llvm-svn: 263522

llvm/include/llvm/ADT/DenseMap.h
llvm/unittests/ADT/DenseMapTest.cpp

index 4cf0d6d..4dee41f 100644 (file)
@@ -81,8 +81,12 @@ public:
   }
   unsigned size() const { return getNumEntries(); }
 
-  /// Grow the densemap so that it has at least Size buckets. Does not shrink
+  /// Grow the densemap so that it can contain at least Size items before
+  /// resizing again. This means somewhat more than Size buckets because
+  /// densemap resizes upon reaching 3/4 full.
   void resize(size_type Size) {
+    // Size *= (4/3), rounding up.
+    Size = (Size * 4 + 2) / 3;
     incrementEpoch();
     if (Size > getNumBuckets())
       grow(Size);
index f3dcf95..0fda2c6 100644 (file)
@@ -339,6 +339,19 @@ TYPED_TEST(DenseMapTest, ConstIteratorTest) {
   EXPECT_TRUE(cit == cit2);
 }
 
+// Make sure resize actually gives us enough buckets to insert N items
+// without increasing allocation size.
+TEST(DenseMapCustomTest, ResizeTest) {
+  for (unsigned Size = 16; Size < 32; ++Size) {
+    DenseMap<unsigned, unsigned> Map;
+    Map.resize(Size);
+    unsigned MemorySize = Map.getMemorySize();
+    for (unsigned i = 0; i < Size; ++i)
+      Map[i] = i;
+    EXPECT_TRUE(Map.getMemorySize() == MemorySize);
+  }
+}
+
 // Make sure DenseMap works with StringRef keys.
 TEST(DenseMapCustomTest, StringRefTest) {
   DenseMap<StringRef, int> M;