[libc-commits] [libc] [libc] `first_trailing_one(0)` should be `0`. (PR #130155)

Connector Switch via libc-commits libc-commits at lists.llvm.org
Thu Mar 6 09:57:57 PST 2025


https://github.com/c8ef created https://github.com/llvm/llvm-project/pull/130155

Fix this minor bug. See more context at #129892.

>From afe4ff0119db282997b7f72421a1055e652337c3 Mon Sep 17 00:00:00 2001
From: c8ef <c8ef at outlook.com>
Date: Thu, 6 Mar 2025 17:56:07 +0000
Subject: [PATCH] fix bug

---
 libc/src/__support/big_int.h                 | 5 +++--
 libc/src/__support/math_extras.h             | 5 +++--
 libc/test/src/__support/math_extras_test.cpp | 1 +
 3 files changed, 7 insertions(+), 4 deletions(-)

diff --git a/libc/src/__support/big_int.h b/libc/src/__support/big_int.h
index f44624a7eafce..b8d0a0487eeb8 100644
--- a/libc/src/__support/big_int.h
+++ b/libc/src/__support/big_int.h
@@ -1383,8 +1383,9 @@ first_trailing_zero(T value) {
 template <typename T>
 [[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t<is_big_int_v<T>, int>
 first_trailing_one(T value) {
-  return value == cpp::numeric_limits<T>::max() ? 0
-                                                : cpp::countr_zero(value) + 1;
+  return (value == 0 || value == cpp::numeric_limits<T>::max())
+             ? 0
+             : cpp::countr_zero(value) + 1;
 }
 
 } // namespace LIBC_NAMESPACE_DECL
diff --git a/libc/src/__support/math_extras.h b/libc/src/__support/math_extras.h
index 6f4a006aad270..c40fdb9cc97a1 100644
--- a/libc/src/__support/math_extras.h
+++ b/libc/src/__support/math_extras.h
@@ -146,8 +146,9 @@ first_trailing_zero(T value) {
 template <typename T>
 [[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t<cpp::is_unsigned_v<T>, int>
 first_trailing_one(T value) {
-  return value == cpp::numeric_limits<T>::max() ? 0
-                                                : cpp::countr_zero(value) + 1;
+  return (value == 0 || value == cpp::numeric_limits<T>::max())
+             ? 0
+             : cpp::countr_zero(value) + 1;
 }
 
 template <typename T>
diff --git a/libc/test/src/__support/math_extras_test.cpp b/libc/test/src/__support/math_extras_test.cpp
index 01b216081d034..d77bc5d2f80de 100644
--- a/libc/test/src/__support/math_extras_test.cpp
+++ b/libc/test/src/__support/math_extras_test.cpp
@@ -95,6 +95,7 @@ TYPED_TEST(LlvmLibcBitTest, FirstTrailingZero, UnsignedTypesNoBigInt) {
 }
 
 TYPED_TEST(LlvmLibcBitTest, FirstTrailingOne, UnsignedTypesNoBigInt) {
+  EXPECT_EQ(first_trailing_one<T>(static_cast<T>(0)), 0);
   EXPECT_EQ(first_trailing_one<T>(cpp::numeric_limits<T>::max()), 0);
   for (int i = 0U; i != cpp::numeric_limits<T>::digits; ++i) {
     auto lhs = T(T(1) << size_t(i));



More information about the libc-commits mailing list