[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 06:33:01 PDT 2025


https://github.com/philnik777 updated https://github.com/llvm/llvm-project/pull/160679

>From c5c359b2eb441dee61ff16e5c47271b86835b4cd Mon Sep 17 00:00:00 2001
From: Nikolas Klauser <nikolasklauser at berlin.de>
Date: Thu, 25 Sep 2025 11:51:32 +0200
Subject: [PATCH] [libc++] Use _BitInt and __builtin_popcountg in
 bitset::count()

---
 libcxx/include/bitset | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)

diff --git a/libcxx/include/bitset b/libcxx/include/bitset
index e2b46154ae730..3453c2fcde71e 100644
--- a/libcxx/include/bitset
+++ b/libcxx/include/bitset
@@ -867,7 +867,16 @@ 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));
+#  if defined(_LIBCPP_COMPILER_CLANG_BASED) && !defined(_LIBCPP_CXX03_LANG)
+  if constexpr (_Size == 0) {
+    return 0;
+  } else 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));
+  }
 }
 
 template <size_t _Size>



More information about the libcxx-commits mailing list