[llvm] [ADT] Define countr_zero in terms of popcount (NFC) (PR #158519)

Kazu Hirata via llvm-commits llvm-commits at lists.llvm.org
Sun Sep 14 20:30:25 PDT 2025


================
@@ -148,6 +148,35 @@ template <typename T, typename = std::enable_if_t<std::is_unsigned_v<T>>>
   return (Value != 0) && ((Value & (Value - 1)) == 0);
 }
 
+/// Count the number of set bits in a value.
+/// Ex. popcount(0xF000F000) = 8
+/// Returns 0 if the word is zero.
+template <typename T, typename = std::enable_if_t<std::is_unsigned_v<T>>>
+[[nodiscard]] inline int popcount(T Value) noexcept {
+  if constexpr (sizeof(T) <= 4) {
+#if defined(__GNUC__)
+    return (int)__builtin_popcount(Value);
+#else
+    uint32_t v = Value;
+    v = v - ((v >> 1) & 0x55555555);
+    v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
+    return int(((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24);
+#endif
+  } else if constexpr (sizeof(T) <= 8) {
+#if defined(__GNUC__)
+    return (int)__builtin_popcountll(Value);
+#else
+    uint64_t v = Value;
+    v = v - ((v >> 1) & 0x5555555555555555ULL);
+    v = (v & 0x3333333333333333ULL) + ((v >> 2) & 0x3333333333333333ULL);
+    v = (v + (v >> 4)) & 0x0F0F0F0F0F0F0F0FULL;
+    return int((uint64_t)(v * 0x0101010101010101ULL) >> 56);
+#endif
+  } else {
+    static_assert(sizeof(T) == 0, "T must be 8 bytes or less");
+  }
----------------
kazutakahirata wrote:

Done.

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


More information about the llvm-commits mailing list