[llvm] ad3e0e4 - [APInt] Add APInt::isOneBitSet helper.
Simon Pilgrim via llvm-commits
llvm-commits at lists.llvm.org
Tue Jan 3 08:12:14 PST 2023
Author: Simon Pilgrim
Date: 2023-01-03T16:10:29Z
New Revision: ad3e0e4b419461bbc56a79a33167e93141ba5859
URL: https://github.com/llvm/llvm-project/commit/ad3e0e4b419461bbc56a79a33167e93141ba5859
DIFF: https://github.com/llvm/llvm-project/commit/ad3e0e4b419461bbc56a79a33167e93141ba5859.diff
LOG: [APInt] Add APInt::isOneBitSet helper.
Equivalent tester for the APInt::getOneBitSet builder.
This should allow us to remove a number of cases where we're doing "Val == (1 << BitNo)" style code patterns.
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 ab8bf3eb1fe1..4b0886835824 100644
--- a/llvm/include/llvm/ADT/APInt.h
+++ b/llvm/include/llvm/ADT/APInt.h
@@ -343,6 +343,13 @@ class [[nodiscard]] APInt {
/// \returns true if this APInt is non-positive.
bool isNonPositive() const { return !isStrictlyPositive(); }
+ /// Determine if this APInt Value only has the specified bit set.
+ ///
+ /// \returns true if this APInt only has the specified bit set.
+ bool isOneBitSet(unsigned BitNo) const {
+ return (*this)[BitNo] && countPopulation() == 1;
+ }
+
/// Determine if all bits are set. This is true for zero-width values.
bool isAllOnes() const {
if (BitWidth == 0)
diff --git a/llvm/unittests/ADT/APIntTest.cpp b/llvm/unittests/ADT/APIntTest.cpp
index e7632c088a9c..0377e05c11cd 100644
--- a/llvm/unittests/ADT/APIntTest.cpp
+++ b/llvm/unittests/ADT/APIntTest.cpp
@@ -1793,6 +1793,16 @@ TEST(APIntTest, isShiftedMask) {
}
}
+TEST(APIntTest, isOneBitSet) {
+ EXPECT_FALSE(APInt(5, 0x00).isOneBitSet(0));
+ EXPECT_FALSE(APInt(5, 0x02).isOneBitSet(0));
+ EXPECT_FALSE(APInt(5, 0x03).isOneBitSet(0));
+ EXPECT_TRUE(APInt(5, 0x02).isOneBitSet(1));
+ EXPECT_TRUE(APInt(32, (unsigned)(0xffu << 31)).isOneBitSet(31));
+
+ EXPECT_TRUE(APInt::getOneBitSet(255, 13).isOneBitSet(13));
+}
+
TEST(APIntTest, isPowerOf2) {
EXPECT_FALSE(APInt(5, 0x00).isPowerOf2());
EXPECT_FALSE(APInt(32, 0x11).isPowerOf2());
More information about the llvm-commits
mailing list