[libcxx-commits] [libcxx] [libc++] Optimize std::has_single_bit (PR #133063)

via libcxx-commits libcxx-commits at lists.llvm.org
Wed Mar 26 03:00:22 PDT 2025


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-libcxx

Author: None (Alcaro)

<details>
<summary>Changes</summary>

Clang translates most implementations of has_single_bit to `(v ^ (v-1)) > v-1` - except the one definition libc++ actually uses.

Proof of correctness: https://godbolt.org/z/d61bxW4r1

(Could also be fixed by teaching Clang to optimize better, but making source match output feels clearer to me. And it improves unoptimized performance.)

---
Full diff: https://github.com/llvm/llvm-project/pull/133063.diff


1 Files Affected:

- (modified) libcxx/include/__bit/has_single_bit.h (+1-1) 


``````````diff
diff --git a/libcxx/include/__bit/has_single_bit.h b/libcxx/include/__bit/has_single_bit.h
index 52f5853a1bc8a..ac434092a148f 100644
--- a/libcxx/include/__bit/has_single_bit.h
+++ b/libcxx/include/__bit/has_single_bit.h
@@ -25,7 +25,7 @@ _LIBCPP_BEGIN_NAMESPACE_STD
 
 template <__libcpp_unsigned_integer _Tp>
 [[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr bool has_single_bit(_Tp __t) noexcept {
-  return __t != 0 && (((__t & (__t - 1)) == 0));
+  return (__t ^ (__t - 1)) > __t - 1;
 }
 
 _LIBCPP_END_NAMESPACE_STD

``````````

</details>


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


More information about the libcxx-commits mailing list