Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 23 additions & 13 deletions llvm/include/llvm/ADT/bit.h
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,27 @@ template <typename T, typename = std::enable_if_t<std::is_unsigned_v<T>>>
/// Only unsigned integral types are allowed.
///
/// Returns std::numeric_limits<T>::digits on an input of 0.
template <typename T> [[nodiscard]] constexpr int countr_zero_constexpr(T Val) {
static_assert(std::is_unsigned_v<T>,
"Only unsigned integral types are allowed.");
if (!Val)
return std::numeric_limits<T>::digits;

// Use the bisection method.
unsigned ZeroBits = 0;
T Shift = std::numeric_limits<T>::digits >> 1;
T Mask = std::numeric_limits<T>::max() >> Shift;
while (Shift) {
if ((Val & Mask) == 0) {
Val >>= Shift;
ZeroBits |= Shift;
}
Shift >>= 1;
Mask >>= Shift;
}
return ZeroBits;
}

template <typename T> [[nodiscard]] int countr_zero(T Val) {
static_assert(std::is_unsigned_v<T>,
"Only unsigned integral types are allowed.");
Expand All @@ -179,19 +200,8 @@ template <typename T> [[nodiscard]] int countr_zero(T Val) {
#endif
}

// Fall back to the bisection method.
unsigned ZeroBits = 0;
T Shift = std::numeric_limits<T>::digits >> 1;
T Mask = std::numeric_limits<T>::max() >> Shift;
while (Shift) {
if ((Val & Mask) == 0) {
Val >>= Shift;
ZeroBits |= Shift;
}
Shift >>= 1;
Mask >>= Shift;
}
return ZeroBits;
// Fall back to the constexpr implementation.
return countr_zero_constexpr(Val);
}

/// Count number of 0's from the most significant bit to the least
Expand Down
20 changes: 20 additions & 0 deletions llvm/unittests/ADT/BitTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,26 @@ TEST(BitTest, CountlZero) {
}
}

TEST(BitTest, CountrZeroConstexpr) {
constexpr uint8_t Z8 = 0;
constexpr uint16_t Z16 = 0;
constexpr uint32_t Z32 = 0;
constexpr uint64_t Z64 = 0;
static_assert(llvm::countr_zero_constexpr(Z8) == 8, "");
static_assert(llvm::countr_zero_constexpr(Z16) == 16, "");
static_assert(llvm::countr_zero_constexpr(Z32) == 32, "");
static_assert(llvm::countr_zero_constexpr(Z64) == 64, "");

constexpr uint8_t NZ8 = 42;
constexpr uint16_t NZ16 = 42;
constexpr uint32_t NZ32 = 42;
constexpr uint64_t NZ64 = 42;
static_assert(llvm::countr_zero_constexpr(NZ8) == 1, "");
static_assert(llvm::countr_zero_constexpr(NZ16) == 1, "");
static_assert(llvm::countr_zero_constexpr(NZ32) == 1, "");
static_assert(llvm::countr_zero_constexpr(NZ64) == 1, "");
}

TEST(BitTest, CountrZero) {
uint8_t Z8 = 0;
uint16_t Z16 = 0;
Expand Down