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