[PATCH] D135741: Change DenseMap keys for APInt to avoid collision with valid APIint

Richard Trieu via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Tue Oct 11 20:44:05 PDT 2022


rtrieu created this revision.
Herald added a project: All.
rtrieu requested review of this revision.
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

An APInt that can fit into a single word stores the bitwidth and the value.  In the normal APInt constructor, bits outside the bitwidth are zeroed out.  For a zero-width APInt, the only valid value is zero.

DenseMap requires the use of two special keys, an empty key and a tombstone key.  APInt has specified that these keys APInt with bitwidth 0 and value either 0 or 1.  For a value of 0, this collides with a valid zero-width APInt.  Because of this, using a zero-width APInt with a DenseMap will not work.

This change updates the keys to use ~0 and ~1, which are non-valid for zero-width APInt.

Proposed fix for: https://github.com/llvm/llvm-project/issues/58013


https://reviews.llvm.org/D135741

Files:
  llvm/include/llvm/ADT/APInt.h
  llvm/unittests/ADT/APIntTest.cpp


Index: llvm/unittests/ADT/APIntTest.cpp
===================================================================
--- llvm/unittests/ADT/APIntTest.cpp
+++ llvm/unittests/ADT/APIntTest.cpp
@@ -8,6 +8,7 @@
 
 #include "llvm/ADT/APInt.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/Twine.h"
 #include "gtest/gtest.h"
@@ -3126,4 +3127,11 @@
   EXPECT_EQ(APIntOps::ScaleBitMask(APInt(8, 0xE4), 4, true), APInt(4, 0x08));
 }
 
+TEST(APIntTest, DenseMap) {
+  DenseMap<APInt, int> Map;
+  APInt ZeroWidthInt(0, 0, false);
+  Map.insert({ZeroWidthInt, 0});
+  Map.find(ZeroWidthInt);
+}
+
 } // end anonymous namespace
Index: llvm/include/llvm/ADT/APInt.h
===================================================================
--- llvm/include/llvm/ADT/APInt.h
+++ llvm/include/llvm/ADT/APInt.h
@@ -2267,13 +2267,13 @@
 template <> struct DenseMapInfo<APInt, void> {
   static inline APInt getEmptyKey() {
     APInt V(nullptr, 0);
-    V.U.VAL = 0;
+    V.U.VAL = ~0ULL;
     return V;
   }
 
   static inline APInt getTombstoneKey() {
     APInt V(nullptr, 0);
-    V.U.VAL = 1;
+    V.U.VAL = ~1ULL;
     return V;
   }
 


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D135741.465561.patch
Type: text/x-patch
Size: 1183 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20221012/08bdb685/attachment-0001.bin>


More information about the llvm-commits mailing list