Skip to content

Commit 132d2c9

Browse files
Alcaroaadeshps-mcw
authored andcommitted
[libc++] Optimize std::has_single_bit (llvm#133063)
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.)
1 parent 296a95a commit 132d2c9

File tree

1 file changed

+1
-1
lines changed

1 file changed

+1
-1
lines changed

libcxx/include/__bit/has_single_bit.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ _LIBCPP_BEGIN_NAMESPACE_STD
2525

2626
template <__unsigned_integer _Tp>
2727
[[nodiscard]] _LIBCPP_HIDE_FROM_ABI constexpr bool has_single_bit(_Tp __t) noexcept {
28-
return __t != 0 && ((__t & (__t - 1)) == 0);
28+
return __builtin_popcountg(__t) == 1;
2929
}
3030

3131
_LIBCPP_END_NAMESPACE_STD

0 commit comments

Comments
 (0)