1 //===----------------------------------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // TODO: __builtin_popcountg is available since Clang 19 and GCC 14. When support for older versions is dropped, we can
10 // refactor this code to exclusively use __builtin_popcountg.
12 #ifndef _LIBCPP___BIT_POPCOUNT_H
13 #define _LIBCPP___BIT_POPCOUNT_H
15 #include <__bit/rotate.h>
16 #include <__concepts/arithmetic.h>
20 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
21 # pragma GCC system_header
25 #include <__undef_macros>
27 _LIBCPP_BEGIN_NAMESPACE_STD
29 inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR
int __libcpp_popcount(unsigned __x
) _NOEXCEPT
{
30 return __builtin_popcount(__x
);
33 inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR
int __libcpp_popcount(unsigned long __x
) _NOEXCEPT
{
34 return __builtin_popcountl(__x
);
37 inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR
int __libcpp_popcount(unsigned long long __x
) _NOEXCEPT
{
38 return __builtin_popcountll(__x
);
41 #if _LIBCPP_STD_VER >= 20
43 template <__libcpp_unsigned_integer _Tp
>
44 [[nodiscard
]] _LIBCPP_HIDE_FROM_ABI
constexpr int popcount(_Tp __t
) noexcept
{
45 # if __has_builtin(__builtin_popcountg)
46 return __builtin_popcountg(__t
);
47 # else // __has_builtin(__builtin_popcountg)
48 if (sizeof(_Tp
) <= sizeof(unsigned int))
49 return std::__libcpp_popcount(static_cast<unsigned int>(__t
));
50 else if (sizeof(_Tp
) <= sizeof(unsigned long))
51 return std::__libcpp_popcount(static_cast<unsigned long>(__t
));
52 else if (sizeof(_Tp
) <= sizeof(unsigned long long))
53 return std::__libcpp_popcount(static_cast<unsigned long long>(__t
));
57 __ret
+= std::__libcpp_popcount(static_cast<unsigned long long>(__t
));
58 __t
>>= numeric_limits
<unsigned long long>::digits
;
62 # endif // __has_builtin(__builtin_popcountg)
65 #endif // _LIBCPP_STD_VER >= 20
67 _LIBCPP_END_NAMESPACE_STD
71 #endif // _LIBCPP___BIT_POPCOUNT_H