Path: blob/main/contrib/llvm-project/libcxx/include/__cxx03/__bit/countr.h
213799 views
//===----------------------------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78// TODO: __builtin_ctzg is available since Clang 19 and GCC 14. When support for older versions is dropped, we can9// refactor this code to exclusively use __builtin_ctzg.1011#ifndef _LIBCPP___CXX03___BIT_COUNTR_H12#define _LIBCPP___CXX03___BIT_COUNTR_H1314#include <__cxx03/__bit/rotate.h>15#include <__cxx03/__config>16#include <__cxx03/limits>1718#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)19# pragma GCC system_header20#endif2122_LIBCPP_PUSH_MACROS23#include <__cxx03/__undef_macros>2425_LIBCPP_BEGIN_NAMESPACE_STD2627_LIBCPP_NODISCARD inline _LIBCPP_HIDE_FROM_ABI int __libcpp_ctz(unsigned __x) _NOEXCEPT { return __builtin_ctz(__x); }2829_LIBCPP_NODISCARD inline _LIBCPP_HIDE_FROM_ABI int __libcpp_ctz(unsigned long __x) _NOEXCEPT {30return __builtin_ctzl(__x);31}3233_LIBCPP_NODISCARD inline _LIBCPP_HIDE_FROM_ABI int __libcpp_ctz(unsigned long long __x) _NOEXCEPT {34return __builtin_ctzll(__x);35}3637template <class _Tp>38_LIBCPP_NODISCARD _LIBCPP_HIDE_FROM_ABI int __countr_zero(_Tp __t) _NOEXCEPT {39#if __has_builtin(__builtin_ctzg)40return __builtin_ctzg(__t, numeric_limits<_Tp>::digits);41#else // __has_builtin(__builtin_ctzg)42if (__t == 0)43return numeric_limits<_Tp>::digits;44if (sizeof(_Tp) <= sizeof(unsigned int))45return std::__libcpp_ctz(static_cast<unsigned int>(__t));46else if (sizeof(_Tp) <= sizeof(unsigned long))47return std::__libcpp_ctz(static_cast<unsigned long>(__t));48else if (sizeof(_Tp) <= sizeof(unsigned long long))49return std::__libcpp_ctz(static_cast<unsigned long long>(__t));50else {51int __ret = 0;52const unsigned int __ulldigits = numeric_limits<unsigned long long>::digits;53while (static_cast<unsigned long long>(__t) == 0uLL) {54__ret += __ulldigits;55__t >>= __ulldigits;56}57return __ret + std::__libcpp_ctz(static_cast<unsigned long long>(__t));58}59#endif // __has_builtin(__builtin_ctzg)60}6162_LIBCPP_END_NAMESPACE_STD6364_LIBCPP_POP_MACROS6566#endif // _LIBCPP___CXX03___BIT_COUNTR_H676869