[libcxx-commits] [libcxx] [libc++] Use _BitInt and __builtin_popcountg in bitset::count() (PR #160679)
Nikolas Klauser via libcxx-commits
libcxx-commits at lists.llvm.org
Thu Sep 25 05:40:28 PDT 2025
================
@@ -867,7 +867,14 @@ bitset<_Size>::to_string(char __zero, char __one) const {
template <size_t _Size>
inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX23 size_t bitset<_Size>::count() const _NOEXCEPT {
- return static_cast<size_t>(std::count(__base::__make_iter(0), __base::__make_iter(_Size), true));
+#ifdef _LIBCPP_COMPILER_CLANG_BASED
+ if constexpr (_Size <= __base::__bits_per_word) {
+ return __builtin_popcountg(static_cast<unsigned _BitInt(_Size)>(__base::__first_));
+ } else
+#endif
+ {
+ return static_cast<size_t>(std::count(__base::__make_iter(0), __base::__make_iter(_Size), true));
----------------
philnik777 wrote:
We could detect that, but it would be both significantly more complex and wouldn't allow us to emit bit-precise `popcount`s (unless we emit a branch for every bit length). Since the branch here is relatively trivial I don't think it's worth the complexity and potential missed optimizations due to imperfect inlining - especially for the extremely common case of `_Size <= 64`.
https://github.com/llvm/llvm-project/pull/160679
More information about the libcxx-commits
mailing list