[Support] Add KnownBits::countMaxSignedBits(). Make KnownBits::countMinSignBits(...
authorCraig Topper <craig.topper@sifive.com>
Mon, 3 Jan 2022 07:20:32 +0000 (23:20 -0800)
committerCraig Topper <craig.topper@sifive.com>
Mon, 3 Jan 2022 07:27:16 +0000 (23:27 -0800)
Even if we don't have any known bits, we can assume that there is
at least 1 sign bit. This is consistent with ComputeNumSignBits
which always returns at least 1.

Add KnownBits::countMaxSignedBits() which computes the number of
bits needed to represent all signed values with those known bits.
This is the signed equivalent of countMaxActiveBits().

Split from D116469.

Reviewed By: lebedev.ri

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

llvm/include/llvm/Support/KnownBits.h
llvm/unittests/Support/KnownBitsTest.cpp

index 1f32760..1674bad 100644 (file)
@@ -249,7 +249,14 @@ public:
       return countMinLeadingZeros();
     if (isNegative())
       return countMinLeadingOnes();
-    return 0;
+    // Every value has at least 1 sign bit.
+    return 1;
+  }
+
+  /// Returns the maximum number of bits needed to represent all possible
+  /// signed values with these known bits.
+  unsigned countMaxSignedBits() const {
+    return getBitWidth() - countMinSignBits() + 1;
   }
 
   /// Returns the maximum number of trailing zero bits possible.
index f9631f2..d41402b 100644 (file)
@@ -442,6 +442,17 @@ TEST(KnownBitsTest, CountMaxActiveBits) {
   });
 }
 
+TEST(KnownBitsTest, CountMaxSignedBits) {
+  unsigned Bits = 4;
+  ForeachKnownBits(Bits, [&](const KnownBits &Known) {
+    unsigned Expected = 0;
+    ForeachNumInKnownBits(Known, [&](const APInt &N) {
+      Expected = std::max(Expected, N.getMinSignedBits());
+    });
+    EXPECT_EQ(Expected, Known.countMaxSignedBits());
+  });
+}
+
 TEST(KnownBitsTest, SExtOrTrunc) {
   const unsigned NarrowerSize = 4;
   const unsigned BaseSize = 6;