Add a ceilLogBase2 function to APInt.
authorDan Gohman <gohman@apple.com>
Tue, 13 Oct 2009 01:49:02 +0000 (01:49 +0000)
committerDan Gohman <gohman@apple.com>
Tue, 13 Oct 2009 01:49:02 +0000 (01:49 +0000)
git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@83932 91177308-0d34-0410-b5e6-96231b3b80d8

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

index 6c418bda62dc395dc4d884f281298fc7f1ca81f7..88aa9956d93216fdb894d7ca1b71a77e8d3343c4 100644 (file)
@@ -1234,6 +1234,11 @@ public:
     return BitWidth - 1 - countLeadingZeros();
   }
 
+  /// @returns the ceil log base 2 of this APInt.
+  unsigned ceilLogBase2() const {
+    return BitWidth - (*this - 1).countLeadingZeros();
+  }
+
   /// @returns the log base 2 of this APInt if its an exact power of two, -1
   /// otherwise
   int32_t exactLogBase2() const {
index 24a3d9b4ade8d2df3fa8c205f9363b1b8880bca6..7b03d0f00c843626fb0d986be09778bf90c984f7 100644 (file)
@@ -315,6 +315,17 @@ TEST(APIntTest, StringBitsNeeded16) {
   EXPECT_EQ(9U, APInt::getBitsNeeded("-20", 16));
 }
 
+TEST(APIntTest, Log2) {
+  EXPECT_EQ(APInt(15, 7).logBase2(), 2);
+  EXPECT_EQ(APInt(15, 7).ceilLogBase2(), 3);
+  EXPECT_EQ(APInt(15, 7).exactLogBase2(), -1);
+  EXPECT_EQ(APInt(15, 8).logBase2(), 3);
+  EXPECT_EQ(APInt(15, 8).ceilLogBase2(), 3);
+  EXPECT_EQ(APInt(15, 8).exactLogBase2(), 3);
+  EXPECT_EQ(APInt(15, 9).logBase2(), 3);
+  EXPECT_EQ(APInt(15, 9).ceilLogBase2(), 4);
+  EXPECT_EQ(APInt(15, 9).exactLogBase2(), -1);
+}
 
 #ifdef GTEST_HAS_DEATH_TEST
 TEST(APIntTest, StringDeath) {