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 #ifndef _LIBCPP___BIT_POPCOUNT_H
10 #define _LIBCPP___BIT_POPCOUNT_H
12 #include <__bit/rotate.h>
13 #include <__concepts/arithmetic.h>
17 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
18 # pragma GCC system_header
22 #include <__undef_macros>
24 _LIBCPP_BEGIN_NAMESPACE_STD
26 inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
27 int __libcpp_popcount(unsigned __x
) _NOEXCEPT
{ return __builtin_popcount(__x
); }
29 inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
30 int __libcpp_popcount(unsigned long __x
) _NOEXCEPT
{ return __builtin_popcountl(__x
); }
32 inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
33 int __libcpp_popcount(unsigned long long __x
) _NOEXCEPT
{ return __builtin_popcountll(__x
); }
35 #if _LIBCPP_STD_VER >= 20
37 template <__libcpp_unsigned_integer _Tp
>
38 _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI
constexpr int popcount(_Tp __t
) noexcept
{
39 if (sizeof(_Tp
) <= sizeof(unsigned int))
40 return std::__libcpp_popcount(static_cast<unsigned int>(__t
));
41 else if (sizeof(_Tp
) <= sizeof(unsigned long))
42 return std::__libcpp_popcount(static_cast<unsigned long>(__t
));
43 else if (sizeof(_Tp
) <= sizeof(unsigned long long))
44 return std::__libcpp_popcount(static_cast<unsigned long long>(__t
));
48 __ret
+= std::__libcpp_popcount(static_cast<unsigned long long>(__t
));
49 __t
>>= numeric_limits
<unsigned long long>::digits
;
55 #endif // _LIBCPP_STD_VER >= 20
57 _LIBCPP_END_NAMESPACE_STD
61 #endif // _LIBCPP___BIT_POPCOUNT_H