[llvm] [ADT] implement countl_zero_constexpr and reuse it for countl_zero (PR #189111)

Max Graey via llvm-commits llvm-commits at lists.llvm.org
Fri Mar 27 13:55:55 PDT 2026


https://github.com/MaxGraey created https://github.com/llvm/llvm-project/pull/189111

Implement constant evaluated `countl_zero_constexpr` similar to [`countr_zero_constexpr`](https://github.com/llvm/llvm-project/blob/eb2ff7101373c2a2f03320ac11b13740b978a6fc/llvm/include/llvm/ADT/bit.h#L188) and use it for `countl_zero` instead bisection method.

>From 8459ed648e485798ac853616fc221099688dc168 Mon Sep 17 00:00:00 2001
From: MaxGraey <maxgraey at gmail.com>
Date: Fri, 27 Mar 2026 22:52:18 +0200
Subject: [PATCH] add countl_zero_constexpr and reuse it in countl_zero

---
 llvm/include/llvm/ADT/bit.h | 38 +++++++++++++++++++++++++++----------
 1 file changed, 28 insertions(+), 10 deletions(-)

diff --git a/llvm/include/llvm/ADT/bit.h b/llvm/include/llvm/ADT/bit.h
index 5971b75045b6b..14244efc7e230 100644
--- a/llvm/include/llvm/ADT/bit.h
+++ b/llvm/include/llvm/ADT/bit.h
@@ -227,6 +227,33 @@ template <typename T> [[nodiscard]] int countr_zero(T Val) {
   return countr_zero_constexpr(Val);
 }
 
+/// Count number of 0's from the most significant bit to the least
+///   stopping at the first 1.
+///
+/// A constexpr version of countl_zero.
+///
+/// Only unsigned integral types are allowed.
+///
+/// Returns std::numeric_limits<T>::digits on an input of 0.
+template <typename T> [[nodiscard]] constexpr int countl_zero_constexpr(T Val) {
+  static_assert(std::is_unsigned_v<T>,
+                "Only unsigned integral types are allowed.");
+
+  constexpr int Digits = std::numeric_limits<T>::digits;
+
+  if (!Val)
+    return Digits;
+
+  Val |= (Val >> 1);
+  Val |= (Val >> 2);
+  Val |= (Val >> 4);
+  if constexpr (Digits > 8)  Val |= (Val >> 8);
+  if constexpr (Digits > 16) Val |= (Val >> 16);
+  if constexpr (Digits > 32) Val |= (Val >> 32);
+
+  return Digits - llvm::popcount(Val);
+}
+
 /// Count number of 0's from the most significant bit to the least
 ///   stopping at the first 1.
 ///
@@ -258,16 +285,7 @@ template <typename T> [[nodiscard]] int countl_zero(T Val) {
 #endif
   }
 
-  // Fall back to the bisection method.
-  unsigned ZeroBits = 0;
-  for (T Shift = std::numeric_limits<T>::digits >> 1; Shift; Shift >>= 1) {
-    T Tmp = Val >> Shift;
-    if (Tmp)
-      Val = Tmp;
-    else
-      ZeroBits |= Shift;
-  }
-  return ZeroBits;
+  return countl_zero_constexpr(Val);
 }
 
 /// Count the number of ones from the most significant bit to the first



More information about the llvm-commits mailing list