[libc-commits] [libc] [libc][stdbit] implement stdc_first_leading_one (C23) (PR #81502)

Nick Desaulniers via libc-commits libc-commits at lists.llvm.org
Wed Feb 14 09:13:09 PST 2024


================
@@ -268,6 +268,11 @@ SPECIALIZE_FLZ(first_leading_zero, unsigned long long, __builtin_clzll)
 
 #undef SPECIALIZE_FLZ
 
+template <typename T, typename = cpp::enable_if_t<cpp::is_unsigned_v<T>>>
+[[nodiscard]] LIBC_INLINE constexpr int first_leading_one(T value) {
+  return !value ? 0 : countl_zero<T>(static_cast<T>(value)) + 1;
----------------
nickdesaulniers wrote:

> would it be better to define first_leading_one as first_leading_zero(~value)?

Yes. acb2d5a140a2

> No need for the static_cast<T> here since the value is already of the right type.

In which case (using unary negation) the cast is necessary since the unary negation will result in implicit promotion for types smaller than `int`. We want to then truncate back to the correct size before calling `first_leading_zero`.

https://github.com/llvm/llvm-project/pull/81502


More information about the libc-commits mailing list