Skip to content

Commit

Permalink
[libc][__support][bit] simplify FLZ (llvm#81678)
Browse files Browse the repository at this point in the history
`countl_zero(~x)` *is* `countl_one(x)`
  • Loading branch information
nickdesaulniers authored Feb 14, 2024
1 parent 4efbf52 commit 0f6f5bf
Showing 1 changed file with 1 addition and 20 deletions.
21 changes: 1 addition & 20 deletions libc/src/__support/CPP/bit.h
Original file line number Diff line number Diff line change
Expand Up @@ -226,30 +226,11 @@ LIBC_INLINE constexpr To bit_or_static_cast(const From &from) {
}
}

#define SPECIALIZE_FLZ(NAME, TYPE, BUILTIN) \
template <> [[nodiscard]] LIBC_INLINE constexpr int NAME<TYPE>(TYPE value) { \
static_assert(cpp::is_unsigned_v<TYPE>); \
return value == cpp::numeric_limits<TYPE>::max() \
? 0 \
: BUILTIN(static_cast<TYPE>(~value)) + 1; \
}

template <typename T, typename = cpp::enable_if_t<cpp::is_unsigned_v<T>>>
[[nodiscard]] LIBC_INLINE constexpr int first_leading_zero(T value) {
return value == cpp::numeric_limits<T>::max()
? 0
: countl_zero(static_cast<T>(~value)) + 1;
return value == cpp::numeric_limits<T>::max() ? 0 : countl_one(value) + 1;
}

#if LIBC_HAS_BUILTIN(__builtin_clzs)
SPECIALIZE_FLZ(first_leading_zero, unsigned short, __builtin_clzs)
#endif
SPECIALIZE_FLZ(first_leading_zero, unsigned int, __builtin_clz)
SPECIALIZE_FLZ(first_leading_zero, unsigned long, __builtin_clzl)
SPECIALIZE_FLZ(first_leading_zero, unsigned long long, __builtin_clzll)

#undef SPECIALIZE_FLZ

} // namespace LIBC_NAMESPACE::cpp

#endif // LLVM_LIBC_SRC___SUPPORT_CPP_BIT_H

0 comments on commit 0f6f5bf

Please sign in to comment.