LLVM 22.0.0git
bit.h
Go to the documentation of this file.
1//===-- llvm/ADT/bit.h - C++20 <bit> ----------------------------*- C++ -*-===//
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/// \file
10/// This file implements the C++20 <bit> header.
11///
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ADT_BIT_H
15#define LLVM_ADT_BIT_H
16
18#include <cstddef> // for std::size_t
19#include <cstdint>
20#include <limits>
21#include <type_traits>
22
23#if !__has_builtin(__builtin_bit_cast)
24#include <cstring>
25#endif
26
27#if defined(_MSC_VER) && !defined(_DEBUG)
28#include <cstdlib> // for _byteswap_{ushort,ulong,uint64}
29#endif
30
31#if defined(__linux__) || defined(__GNU__) || defined(__HAIKU__) || \
32 defined(__Fuchsia__) || defined(__EMSCRIPTEN__) || defined(__NetBSD__) || \
33 defined(__OpenBSD__) || defined(__DragonFly__) || defined(__managarm__)
34#include <endian.h>
35#elif defined(_AIX)
36#include <sys/machine.h>
37#elif defined(__sun)
38/* Solaris provides _BIG_ENDIAN/_LITTLE_ENDIAN selector in sys/types.h */
39#include <sys/types.h>
40#define BIG_ENDIAN 4321
41#define LITTLE_ENDIAN 1234
42#if defined(_BIG_ENDIAN)
43#define BYTE_ORDER BIG_ENDIAN
44#else
45#define BYTE_ORDER LITTLE_ENDIAN
46#endif
47#elif defined(__MVS__)
48#define BIG_ENDIAN 4321
49#define LITTLE_ENDIAN 1234
50#define BYTE_ORDER BIG_ENDIAN
51#else
52#if !defined(BYTE_ORDER) && !defined(_WIN32)
53#include <machine/endian.h>
54#endif
55#endif
56
57#ifdef _MSC_VER
58// Declare these intrinsics manually rather including intrin.h. It's very
59// expensive, and bit.h is popular via MathExtras.h.
60// #include <intrin.h>
61extern "C" {
62unsigned char _BitScanForward(unsigned long *_Index, unsigned long _Mask);
63unsigned char _BitScanForward64(unsigned long *_Index, unsigned __int64 _Mask);
64unsigned char _BitScanReverse(unsigned long *_Index, unsigned long _Mask);
65unsigned char _BitScanReverse64(unsigned long *_Index, unsigned __int64 _Mask);
66}
67#endif
68
69namespace llvm {
70
71enum class endianness {
72 big,
73 little,
74#if defined(BYTE_ORDER) && defined(BIG_ENDIAN) && BYTE_ORDER == BIG_ENDIAN
75 native = big
76#else
78#endif
79};
80
81// This implementation of bit_cast is different from the C++20 one in two ways:
82// - It isn't constexpr because that requires compiler support.
83// - It requires trivially-constructible To, to avoid UB in the implementation.
84template <
85 typename To, typename From,
86 typename = std::enable_if_t<sizeof(To) == sizeof(From)>,
87 typename = std::enable_if_t<std::is_trivially_constructible<To>::value>,
88 typename = std::enable_if_t<std::is_trivially_copyable<To>::value>,
89 typename = std::enable_if_t<std::is_trivially_copyable<From>::value>>
90[[nodiscard]] inline To bit_cast(const From &from) noexcept {
91#if __has_builtin(__builtin_bit_cast)
92 return __builtin_bit_cast(To, from);
93#else
94 To to;
95 std::memcpy(&to, &from, sizeof(To));
96 return to;
97#endif
98}
99
100/// Reverses the bytes in the given integer value V.
101template <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>
102[[nodiscard]] constexpr T byteswap(T V) noexcept {
103 if constexpr (sizeof(T) == 1) {
104 return V;
105 } else if constexpr (sizeof(T) == 2) {
106 uint16_t UV = V;
107#if defined(_MSC_VER) && !defined(_DEBUG)
108 // The DLL version of the runtime lacks these functions (bug!?), but in a
109 // release build they're replaced with BSWAP instructions anyway.
110 return _byteswap_ushort(UV);
111#else
112 uint16_t Hi = UV << 8;
113 uint16_t Lo = UV >> 8;
114 return Hi | Lo;
115#endif
116 } else if constexpr (sizeof(T) == 4) {
117 uint32_t UV = V;
118#if __has_builtin(__builtin_bswap32)
119 return __builtin_bswap32(UV);
120#elif defined(_MSC_VER) && !defined(_DEBUG)
121 return _byteswap_ulong(UV);
122#else
123 uint32_t Byte0 = UV & 0x000000FF;
124 uint32_t Byte1 = UV & 0x0000FF00;
125 uint32_t Byte2 = UV & 0x00FF0000;
126 uint32_t Byte3 = UV & 0xFF000000;
127 return (Byte0 << 24) | (Byte1 << 8) | (Byte2 >> 8) | (Byte3 >> 24);
128#endif
129 } else if constexpr (sizeof(T) == 8) {
130 uint64_t UV = V;
131#if __has_builtin(__builtin_bswap64)
132 return __builtin_bswap64(UV);
133#elif defined(_MSC_VER) && !defined(_DEBUG)
134 return _byteswap_uint64(UV);
135#else
136 uint64_t Hi = llvm::byteswap<uint32_t>(UV);
137 uint32_t Lo = llvm::byteswap<uint32_t>(UV >> 32);
138 return (Hi << 32) | Lo;
139#endif
140 } else {
141 static_assert(!sizeof(T *), "Don't know how to handle the given type.");
142 return 0;
143 }
144}
145
146template <typename T, typename = std::enable_if_t<std::is_unsigned_v<T>>>
147[[nodiscard]] constexpr inline bool has_single_bit(T Value) noexcept {
148 return (Value != 0) && ((Value & (Value - 1)) == 0);
149}
150
151/// Count number of 0's from the least significant bit to the most
152/// stopping at the first 1.
153///
154/// Only unsigned integral types are allowed.
155///
156/// Returns std::numeric_limits<T>::digits on an input of 0.
157template <typename T> [[nodiscard]] int countr_zero(T Val) {
158 static_assert(std::is_unsigned_v<T>,
159 "Only unsigned integral types are allowed.");
160 if (!Val)
161 return std::numeric_limits<T>::digits;
162
163 // Use the intrinsic if available.
164 if constexpr (sizeof(T) == 4) {
165#if __has_builtin(__builtin_ctz) || defined(__GNUC__)
166 return __builtin_ctz(Val);
167#elif defined(_MSC_VER)
168 unsigned long Index;
169 _BitScanForward(&Index, Val);
170 return Index;
171#endif
172 } else if constexpr (sizeof(T) == 8) {
173#if __has_builtin(__builtin_ctzll) || defined(__GNUC__)
174 return __builtin_ctzll(Val);
175#elif defined(_MSC_VER) && defined(_M_X64)
176 unsigned long Index;
177 _BitScanForward64(&Index, Val);
178 return Index;
179#endif
180 }
181
182 // Fall back to the bisection method.
183 unsigned ZeroBits = 0;
184 T Shift = std::numeric_limits<T>::digits >> 1;
185 T Mask = std::numeric_limits<T>::max() >> Shift;
186 while (Shift) {
187 if ((Val & Mask) == 0) {
188 Val >>= Shift;
189 ZeroBits |= Shift;
190 }
191 Shift >>= 1;
192 Mask >>= Shift;
193 }
194 return ZeroBits;
195}
196
197/// Count number of 0's from the most significant bit to the least
198/// stopping at the first 1.
199///
200/// Only unsigned integral types are allowed.
201///
202/// Returns std::numeric_limits<T>::digits on an input of 0.
203template <typename T> [[nodiscard]] int countl_zero(T Val) {
204 static_assert(std::is_unsigned_v<T>,
205 "Only unsigned integral types are allowed.");
206 if (!Val)
207 return std::numeric_limits<T>::digits;
208
209 // Use the intrinsic if available.
210 if constexpr (sizeof(T) == 4) {
211#if __has_builtin(__builtin_clz) || defined(__GNUC__)
212 return __builtin_clz(Val);
213#elif defined(_MSC_VER)
214 unsigned long Index;
215 _BitScanReverse(&Index, Val);
216 return Index ^ 31;
217#endif
218 } else if constexpr (sizeof(T) == 8) {
219#if __has_builtin(__builtin_clzll) || defined(__GNUC__)
220 return __builtin_clzll(Val);
221#elif defined(_MSC_VER) && defined(_M_X64)
222 unsigned long Index;
223 _BitScanReverse64(&Index, Val);
224 return Index ^ 63;
225#endif
226 }
227
228 // Fall back to the bisection method.
229 unsigned ZeroBits = 0;
230 for (T Shift = std::numeric_limits<T>::digits >> 1; Shift; Shift >>= 1) {
231 T Tmp = Val >> Shift;
232 if (Tmp)
233 Val = Tmp;
234 else
235 ZeroBits |= Shift;
236 }
237 return ZeroBits;
238}
239
240/// Count the number of ones from the most significant bit to the first
241/// zero bit.
242///
243/// Ex. countl_one(0xFF0FFF00) == 8.
244/// Only unsigned integral types are allowed.
245///
246/// Returns std::numeric_limits<T>::digits on an input of all ones.
247template <typename T> [[nodiscard]] int countl_one(T Value) {
248 static_assert(std::is_unsigned_v<T>,
249 "Only unsigned integral types are allowed.");
250 return llvm::countl_zero<T>(~Value);
251}
252
253/// Count the number of ones from the least significant bit to the first
254/// zero bit.
255///
256/// Ex. countr_one(0x00FF00FF) == 8.
257/// Only unsigned integral types are allowed.
258///
259/// Returns std::numeric_limits<T>::digits on an input of all ones.
260template <typename T> [[nodiscard]] int countr_one(T Value) {
261 static_assert(std::is_unsigned_v<T>,
262 "Only unsigned integral types are allowed.");
263 return llvm::countr_zero<T>(~Value);
264}
265
266/// Returns the number of bits needed to represent Value if Value is nonzero.
267/// Returns 0 otherwise.
268///
269/// Ex. bit_width(5) == 3.
270template <typename T> [[nodiscard]] int bit_width(T Value) {
271 static_assert(std::is_unsigned_v<T>,
272 "Only unsigned integral types are allowed.");
273 return std::numeric_limits<T>::digits - llvm::countl_zero(Value);
274}
275
276/// Returns the largest integral power of two no greater than Value if Value is
277/// nonzero. Returns 0 otherwise.
278///
279/// Ex. bit_floor(5) == 4.
280template <typename T> [[nodiscard]] T bit_floor(T Value) {
281 static_assert(std::is_unsigned_v<T>,
282 "Only unsigned integral types are allowed.");
283 if (!Value)
284 return 0;
285 return T(1) << (llvm::bit_width(Value) - 1);
286}
287
288/// Returns the smallest integral power of two no smaller than Value if Value is
289/// nonzero. Returns 1 otherwise.
290///
291/// Ex. bit_ceil(5) == 8.
292///
293/// The return value is undefined if the input is larger than the largest power
294/// of two representable in T.
295template <typename T> [[nodiscard]] T bit_ceil(T Value) {
296 static_assert(std::is_unsigned_v<T>,
297 "Only unsigned integral types are allowed.");
298 if (Value < 2)
299 return 1;
300 return T(1) << llvm::bit_width<T>(Value - 1u);
301}
302
303/// Count the number of set bits in a value.
304/// Ex. popcount(0xF000F000) = 8
305/// Returns 0 if the word is zero.
306template <typename T, typename = std::enable_if_t<std::is_unsigned_v<T>>>
307[[nodiscard]] inline int popcount(T Value) noexcept {
308 if constexpr (sizeof(T) <= 4) {
309#if defined(__GNUC__)
310 return (int)__builtin_popcount(Value);
311#else
312 uint32_t v = Value;
313 v = v - ((v >> 1) & 0x55555555);
314 v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
315 return int(((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24);
316#endif
317 } else if constexpr (sizeof(T) <= 8) {
318#if defined(__GNUC__)
319 return (int)__builtin_popcountll(Value);
320#else
321 uint64_t v = Value;
322 v = v - ((v >> 1) & 0x5555555555555555ULL);
323 v = (v & 0x3333333333333333ULL) + ((v >> 2) & 0x3333333333333333ULL);
324 v = (v + (v >> 4)) & 0x0F0F0F0F0F0F0F0FULL;
325 return int((uint64_t)(v * 0x0101010101010101ULL) >> 56);
326#endif
327 } else {
328 static_assert(sizeof(T) == 0, "T must be 8 bytes or less");
329 }
330}
331
332// Forward-declare rotr so that rotl can use it.
333template <typename T, typename = std::enable_if_t<std::is_unsigned_v<T>>>
334[[nodiscard]] constexpr T rotr(T V, int R);
335
336template <typename T, typename = std::enable_if_t<std::is_unsigned_v<T>>>
337[[nodiscard]] constexpr T rotl(T V, int R) {
338 unsigned N = std::numeric_limits<T>::digits;
339
340 R = R % N;
341 if (!R)
342 return V;
343
344 if (R < 0)
345 return llvm::rotr(V, -R);
346
347 return (V << R) | (V >> (N - R));
348}
349
350template <typename T, typename> [[nodiscard]] constexpr T rotr(T V, int R) {
351 unsigned N = std::numeric_limits<T>::digits;
352
353 R = R % N;
354 if (!R)
355 return V;
356
357 if (R < 0)
358 return llvm::rotl(V, -R);
359
360 return (V >> R) | (V << (N - R));
361}
362
363} // namespace llvm
364
365#endif
BlockVerifier::State From
uint32_t Index
#define T
LLVM Value Representation.
Definition: Value.h:75
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
constexpr T rotr(T V, int R)
Definition: bit.h:350
int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition: bit.h:307
int countr_one(T Value)
Count the number of ones from the least significant bit to the first zero bit.
Definition: bit.h:260
constexpr T byteswap(T V) noexcept
Reverses the bytes in the given integer value V.
Definition: bit.h:102
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition: bit.h:270
T bit_ceil(T Value)
Returns the smallest integral power of two no smaller than Value if Value is nonzero.
Definition: bit.h:295
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition: bit.h:157
constexpr bool has_single_bit(T Value) noexcept
Definition: bit.h:147
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition: bit.h:203
int countl_one(T Value)
Count the number of ones from the most significant bit to the first zero bit.
Definition: bit.h:247
To bit_cast(const From &from) noexcept
Definition: bit.h:90
endianness
Definition: bit.h:71
T bit_floor(T Value)
Returns the largest integral power of two no greater than Value if Value is nonzero.
Definition: bit.h:280
constexpr T rotl(T V, int R)
Definition: bit.h:337
#define N