[libc-commits] [libc] [libc][__support][bit] simplify FLZ (PR #81678)

Nick Desaulniers via libc-commits libc-commits at lists.llvm.org
Wed Feb 14 08:52:21 PST 2024


https://github.com/nickdesaulniers updated https://github.com/llvm/llvm-project/pull/81678

>From 1333e699f4d32d0da642471816afb13c7f5ef95d Mon Sep 17 00:00:00 2001
From: Nick Desaulniers <ndesaulniers at google.com>
Date: Tue, 13 Feb 2024 14:17:24 -0800
Subject: [PATCH] [libc][__support][bit] simplify FLZ

`countl_zero(~x)` *is* `countl_one(x)`
---
 libc/src/__support/CPP/bit.h | 21 +--------------------
 1 file changed, 1 insertion(+), 20 deletions(-)

diff --git a/libc/src/__support/CPP/bit.h b/libc/src/__support/CPP/bit.h
index a8bf75a9a2efac..4115d67c7705c0 100644
--- a/libc/src/__support/CPP/bit.h
+++ b/libc/src/__support/CPP/bit.h
@@ -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



More information about the libc-commits mailing list