popcount.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. //===----------------------------------------------------------------------===//
  2. //
  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
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #ifndef _LIBCPP___BIT_POPCOUNT_H
  9. #define _LIBCPP___BIT_POPCOUNT_H
  10. #include <__bit/rotate.h>
  11. #include <__concepts/arithmetic.h>
  12. #include <__config>
  13. #include <limits>
  14. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  15. # pragma GCC system_header
  16. #endif
  17. _LIBCPP_PUSH_MACROS
  18. #include <__undef_macros>
  19. _LIBCPP_BEGIN_NAMESPACE_STD
  20. inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
  21. int __libcpp_popcount(unsigned __x) _NOEXCEPT { return __builtin_popcount(__x); }
  22. inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
  23. int __libcpp_popcount(unsigned long __x) _NOEXCEPT { return __builtin_popcountl(__x); }
  24. inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR
  25. int __libcpp_popcount(unsigned long long __x) _NOEXCEPT { return __builtin_popcountll(__x); }
  26. #if _LIBCPP_STD_VER >= 20
  27. template <__libcpp_unsigned_integer _Tp>
  28. _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI constexpr int popcount(_Tp __t) noexcept {
  29. if (sizeof(_Tp) <= sizeof(unsigned int))
  30. return std::__libcpp_popcount(static_cast<unsigned int>(__t));
  31. else if (sizeof(_Tp) <= sizeof(unsigned long))
  32. return std::__libcpp_popcount(static_cast<unsigned long>(__t));
  33. else if (sizeof(_Tp) <= sizeof(unsigned long long))
  34. return std::__libcpp_popcount(static_cast<unsigned long long>(__t));
  35. else {
  36. int __ret = 0;
  37. while (__t != 0) {
  38. __ret += std::__libcpp_popcount(static_cast<unsigned long long>(__t));
  39. __t >>= numeric_limits<unsigned long long>::digits;
  40. }
  41. return __ret;
  42. }
  43. }
  44. #endif // _LIBCPP_STD_VER >= 20
  45. _LIBCPP_END_NAMESPACE_STD
  46. _LIBCPP_POP_MACROS
  47. #endif // _LIBCPP___BIT_POPCOUNT_H