[llvm] cbdb81e - Fix DenseMap with APInt keys

via llvm-commits llvm-commits at lists.llvm.org
Tue Nov 1 16:50:11 PDT 2022


Author: Weverything
Date: 2022-11-01T16:23:32-07:00
New Revision: cbdb81e60b45e90996541f2661bad99606bfda06

URL: https://github.com/llvm/llvm-project/commit/cbdb81e60b45e90996541f2661bad99606bfda06
DIFF: https://github.com/llvm/llvm-project/commit/cbdb81e60b45e90996541f2661bad99606bfda06.diff

LOG: Fix DenseMap with APInt keys

The empty key value for APInt was colliding with a valid zero-width
APInt.  Change the internal value of empty key and tombstone values
for APInt to avoid this collision.

Fixes: https://github.com/llvm/llvm-project/issues/58013

Differential Revision: https://reviews.llvm.org/D135741

Added: 
    

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

Removed: 
    


################################################################################
diff  --git a/llvm/include/llvm/ADT/APInt.h b/llvm/include/llvm/ADT/APInt.h
index d3e645d30094d..2e2f9ef4d1207 100644
--- a/llvm/include/llvm/ADT/APInt.h
+++ b/llvm/include/llvm/ADT/APInt.h
@@ -2287,13 +2287,13 @@ void LoadIntFromMemory(APInt &IntVal, const uint8_t *Src, unsigned LoadBytes);
 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;
   }
 

diff  --git a/llvm/unittests/ADT/APIntTest.cpp b/llvm/unittests/ADT/APIntTest.cpp
index 0af294c609698..3dba0fa0fded9 100644
--- a/llvm/unittests/ADT/APIntTest.cpp
+++ b/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 @@ TEST(APIntTest, ScaleBitMask) {
   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


        


More information about the llvm-commits mailing list