[llvm] [orc-rt] Simplify bit.h countl_zero and bit_width (PR #225547)

Lang Hames via llvm-commits llvm-commits at lists.llvm.org
Tue Sep 22 15:55:10 PDT 2026


https://github.com/lhames created https://github.com/llvm/llvm-project/pull/225547

The old countl_zero algorithm wasn't recognized / optimized by clang on arm64 or x86-64. Switch to a simpler loop that clang recognizes and rewrite bit_width in terms of countl_zero. NFCI.

>From 5549a9374e4af4951be6a416173bd37f2e398d20 Mon Sep 17 00:00:00 2001
From: Lang Hames <lhames at gmail.com>
Date: Wed, 23 Sep 2026 08:48:15 +1000
Subject: [PATCH] [orc-rt] Simplify bit.h countl_zero and bit_width

The old countl_zero algorithm wasn't recognized / optimized by clang on
arm64 or x86-64. Switch to a simpler loop that clang recognizes and
rewrite bit_width in terms of countl_zero. NFCI.
---
 orc-rt/include/orc-rt/support/bit.h | 29 +++++++++--------------------
 1 file changed, 9 insertions(+), 20 deletions(-)

diff --git a/orc-rt/include/orc-rt/support/bit.h b/orc-rt/include/orc-rt/support/bit.h
index ee3218e7684bc..ba00ba60bd98b 100644
--- a/orc-rt/include/orc-rt/support/bit.h
+++ b/orc-rt/include/orc-rt/support/bit.h
@@ -110,19 +110,15 @@ template <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>
 
 /// Calculates the number of leading zeros.
 template <typename T, typename _ = std::enable_if_t<std::is_unsigned_v<T>>>
-[[nodiscard]] constexpr int countl_zero(T Val) noexcept {
-  if (!Val)
-    return std::numeric_limits<T>::digits;
-
-  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;
+[[nodiscard]] constexpr int countl_zero(T Value) noexcept {
+  size_t LeadingZeros = std::numeric_limits<T>::digits;
+
+  while (Value) {
+    --LeadingZeros;
+    Value >>= 1;
   }
-  return ZeroBits;
+
+  return LeadingZeros;
 }
 
 /// Returns the number of bits needed to represent Value if Value is nonzero.
@@ -131,14 +127,7 @@ template <typename T, typename _ = std::enable_if_t<std::is_unsigned_v<T>>>
 /// Ex. bit_width(5) == 3.
 template <typename T, typename _ = std::enable_if_t<std::is_unsigned_v<T>>>
 [[nodiscard]] constexpr int bit_width(T Value) noexcept {
-  int Width = 0;
-
-  while (Value != 0) {
-    Value >>= 1;
-    ++Width;
-  }
-
-  return Width;
+  return std::numeric_limits<T>::digits - countl_zero(Value);
 }
 
 template <typename T, typename = std::enable_if_t<std::is_unsigned_v<T>>>



More information about the llvm-commits mailing list