LLVM 23.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 {
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 __has_builtin(__builtin_bswap16)
108 return __builtin_bswap16(UV);
109#elif defined(_MSC_VER) && !defined(_DEBUG)
110 // The DLL version of the runtime lacks these functions (bug!?), but in a
111 // release build they're replaced with BSWAP instructions anyway.
112 return _byteswap_ushort(UV);
113#else
114 uint16_t Hi = UV << 8;
115 uint16_t Lo = UV >> 8;
116 return Hi | Lo;
117#endif
118 } else if constexpr (sizeof(T) == 4) {
119 uint32_t UV = V;
120#if __has_builtin(__builtin_bswap32)
121 return __builtin_bswap32(UV);
122#elif defined(_MSC_VER) && !defined(_DEBUG)
123 return _byteswap_ulong(UV);
124#else
125 uint32_t Byte0 = UV & 0x000000FF;
126 uint32_t Byte1 = UV & 0x0000FF00;
127 uint32_t Byte2 = UV & 0x00FF0000;
128 uint32_t Byte3 = UV & 0xFF000000;
129 return (Byte0 << 24) | (Byte1 << 8) | (Byte2 >> 8) | (Byte3 >> 24);
130#endif
131 } else if constexpr (sizeof(T) == 8) {
132 uint64_t UV = V;
133#if __has_builtin(__builtin_bswap64)
134 return __builtin_bswap64(UV);
135#elif defined(_MSC_VER) && !defined(_DEBUG)
136 return _byteswap_uint64(UV);
137#else
140 return (Hi << 32) | Lo;
141#endif
142 } else {
143 static_assert(!sizeof(T *), "Don't know how to handle the given type.");
144 return 0;
145 }
146}
147
148template <typename T, typename = std::enable_if_t<std::is_unsigned_v<T>>>
149[[nodiscard]] constexpr inline bool has_single_bit(T Value) noexcept {
150 return (Value != 0) && ((Value & (Value - 1)) == 0);
151}
152
153/// Count the number of set bits in a value.
154/// Ex. popcount(0xF000F000) = 8
155/// Returns 0 if Value is zero.
156template <typename T> [[nodiscard]] constexpr int popcount(T Value) noexcept {
157 static_assert(std::is_unsigned_v<T>, "T must be an unsigned integer type");
158 static_assert(sizeof(T) <= 8, "T must be 8 bytes or less");
159
160 if constexpr (sizeof(T) <= 4) {
161#if defined(__GNUC__)
162 return (int)__builtin_popcount(Value);
163#else
164 uint32_t V = Value;
165 V = V - ((V >> 1) & 0x55555555);
166 V = (V & 0x33333333) + ((V >> 2) & 0x33333333);
167 return int(((V + (V >> 4) & 0xF0F0F0F) * 0x1010101) >> 24);
168#endif
169 } else {
170#if defined(__GNUC__)
171 return (int)__builtin_popcountll(Value);
172#else
173 uint64_t V = Value;
174 V = V - ((V >> 1) & 0x5555555555555555ULL);
175 V = (V & 0x3333333333333333ULL) + ((V >> 2) & 0x3333333333333333ULL);
176 V = (V + (V >> 4)) & 0x0F0F0F0F0F0F0F0FULL;
177 return int((uint64_t)(V * 0x0101010101010101ULL) >> 56);
178#endif
179 }
180}
181
182/// Count number of 0's from the least significant bit to the most
183/// stopping at the first 1.
184///
185/// A constexpr version of countr_zero.
186///
187/// Only unsigned integral types are allowed.
188///
189/// Returns std::numeric_limits<T>::digits on an input of 0.
190template <typename T> [[nodiscard]] constexpr int countr_zero_constexpr(T Val) {
191 static_assert(std::is_unsigned_v<T>,
192 "Only unsigned integral types are allowed.");
193 // "(Val & -Val) - 1" generates a mask with all bits set up to (but not
194 // including) the least significant set bit of Val.
195 return llvm::popcount(static_cast<std::make_unsigned_t<T>>((Val & -Val) - 1));
196}
197
198/// Count number of 0's from the least significant bit to the most
199/// stopping at the first 1.
200///
201/// Only unsigned integral types are allowed.
202///
203/// Returns std::numeric_limits<T>::digits on an input of 0.
204template <typename T> [[nodiscard]] int countr_zero(T Val) {
205 static_assert(std::is_unsigned_v<T>,
206 "Only unsigned integral types are allowed.");
207 if (!Val)
208 return std::numeric_limits<T>::digits;
209
210 // Use the intrinsic if available.
211 if constexpr (sizeof(T) <= 4) {
212#if __has_builtin(__builtin_ctz) || defined(__GNUC__)
213 return __builtin_ctz(Val);
214#elif defined(_MSC_VER)
215 unsigned long Index;
216 _BitScanForward(&Index, Val);
217 return Index;
218#endif
219 } else if constexpr (sizeof(T) == 8) {
220#if __has_builtin(__builtin_ctzll) || defined(__GNUC__)
221 return __builtin_ctzll(Val);
222#elif defined(_MSC_VER) && defined(_M_X64)
223 unsigned long Index;
224 _BitScanForward64(&Index, Val);
225 return Index;
226#endif
227 }
228
229 return countr_zero_constexpr(Val);
230}
231
232/// Count number of 0's from the most significant bit to the least
233/// stopping at the first 1.
234///
235/// A constexpr version of countl_zero.
236///
237/// Only unsigned integral types are allowed.
238///
239/// Returns std::numeric_limits<T>::digits on an input of 0.
240template <typename T> [[nodiscard]] constexpr int countl_zero_constexpr(T Val) {
241 static_assert(std::is_unsigned_v<T>,
242 "Only unsigned integral types are allowed.");
243 if (!Val)
244 return std::numeric_limits<T>::digits;
245
246 unsigned ZeroBits = 0;
247 for (T Shift = std::numeric_limits<T>::digits >> 1; Shift; Shift >>= 1) {
248 T Tmp = Val >> Shift;
249 if (Tmp)
250 Val = Tmp;
251 else
252 ZeroBits |= Shift;
253 }
254 return ZeroBits;
255}
256
257/// Count number of 0's from the most significant bit to the least
258/// stopping at the first 1.
259///
260/// Only unsigned integral types are allowed.
261///
262/// Returns std::numeric_limits<T>::digits on an input of 0.
263template <typename T> [[nodiscard]] int countl_zero(T Val) {
264 static_assert(std::is_unsigned_v<T>,
265 "Only unsigned integral types are allowed.");
266
267 constexpr int BitWidth = std::numeric_limits<T>::digits;
268
269 if (!Val)
270 return BitWidth;
271
272 // Use the intrinsic if available.
273 if constexpr (sizeof(T) <= 4) {
274#if __has_builtin(__builtin_clz) || defined(__GNUC__)
275 constexpr int Padding = std::numeric_limits<uint32_t>::digits - BitWidth;
276 return __builtin_clz(Val) - Padding;
277#elif defined(_MSC_VER)
278 unsigned long Index;
279 _BitScanReverse(&Index, Val);
280 return static_cast<int>((BitWidth - 1) - Index);
281#endif
282 } else if constexpr (sizeof(T) == 8) {
283#if __has_builtin(__builtin_clzll) || defined(__GNUC__)
284 return __builtin_clzll(Val);
285#elif defined(_MSC_VER) && defined(_M_X64)
286 unsigned long Index;
287 _BitScanReverse64(&Index, Val);
288 return Index ^ 63;
289#endif
290 }
291
292 return countl_zero_constexpr(Val);
293}
294
295/// Count the number of ones from the most significant bit to the first
296/// zero bit.
297///
298/// Ex. countl_one(0xFF0FFF00) == 8.
299/// Only unsigned integral types are allowed.
300///
301/// Returns std::numeric_limits<T>::digits on an input of all ones.
302template <typename T> [[nodiscard]] int countl_one(T Value) {
303 static_assert(std::is_unsigned_v<T>,
304 "Only unsigned integral types are allowed.");
306}
307
308/// Count the number of ones from the least significant bit to the first
309/// zero bit.
310///
311/// Ex. countr_one(0x00FF00FF) == 8.
312/// Only unsigned integral types are allowed.
313///
314/// Returns std::numeric_limits<T>::digits on an input of all ones.
315template <typename T> [[nodiscard]] int countr_one(T Value) {
316 static_assert(std::is_unsigned_v<T>,
317 "Only unsigned integral types are allowed.");
319}
320
321/// Returns the number of bits needed to represent Value if Value is nonzero.
322/// Returns 0 otherwise.
323///
324/// Ex. bit_width(5) == 3.
325template <typename T> [[nodiscard]] int bit_width(T Value) {
326 static_assert(std::is_unsigned_v<T>,
327 "Only unsigned integral types are allowed.");
328 return std::numeric_limits<T>::digits - llvm::countl_zero(Value);
329}
330
331/// Returns the number of bits needed to represent Value if Value is nonzero.
332/// Returns 0 otherwise.
333///
334/// A constexpr version of bit_width.
335///
336/// Ex. bit_width_constexpr(5) == 3.
337template <typename T> [[nodiscard]] constexpr int bit_width_constexpr(T Value) {
338 static_assert(std::is_unsigned_v<T>,
339 "Only unsigned integral types are allowed.");
340 return std::numeric_limits<T>::digits - llvm::countl_zero_constexpr(Value);
341}
342
343/// Returns the largest integral power of two no greater than Value if Value is
344/// nonzero. Returns 0 otherwise.
345///
346/// Ex. bit_floor(5) == 4.
347template <typename T> [[nodiscard]] T bit_floor(T Value) {
348 static_assert(std::is_unsigned_v<T>,
349 "Only unsigned integral types are allowed.");
350 if (!Value)
351 return 0;
352 return T(1) << (llvm::bit_width(Value) - 1);
353}
354
355/// Returns the smallest integral power of two no smaller than Value if Value is
356/// nonzero. Returns 1 otherwise.
357///
358/// Ex. bit_ceil(5) == 8.
359///
360/// The return value is undefined if the input is larger than the largest power
361/// of two representable in T.
362template <typename T> [[nodiscard]] T bit_ceil(T Value) {
363 static_assert(std::is_unsigned_v<T>,
364 "Only unsigned integral types are allowed.");
365 if (Value < 2)
366 return 1;
367 return T(1) << llvm::bit_width<T>(Value - 1u);
368}
369
370/// Returns the smallest integral power of two no smaller than Value if Value is
371/// nonzero. Returns 1 otherwise.
372///
373/// Ex. bit_ceil(5) == 8.
374///
375/// The return value is undefined if the input is larger than the largest power
376/// of two representable in T.
377template <typename T> [[nodiscard]] constexpr T bit_ceil_constexpr(T Value) {
378 static_assert(std::is_unsigned_v<T>,
379 "Only unsigned integral types are allowed.");
380 if (Value < 2)
381 return 1;
382 return T(1) << llvm::bit_width_constexpr<T>(Value - 1u);
383}
384
385template <typename T, typename = std::enable_if_t<std::is_unsigned_v<T>>>
386[[nodiscard]] constexpr T rotl(T V, int R) {
387 constexpr unsigned N = std::numeric_limits<T>::digits;
388
389 static_assert(has_single_bit(N), "& (N - 1) is only valid for powers of two");
390 R = R & (N - 1);
391
392 if (R == 0)
393 return V;
394
395 return (V << R) | (V >> (N - R));
396}
397
398template <typename T, typename = std::enable_if_t<std::is_unsigned_v<T>>>
399[[nodiscard]] constexpr T rotr(T V, int R) {
400 constexpr unsigned N = std::numeric_limits<T>::digits;
401
402 static_assert(has_single_bit(N), "& (N - 1) is only valid for powers of two");
403 R = R & (N - 1);
404
405 if (R == 0)
406 return V;
407
408 return (V >> R) | (V << (N - R));
409}
410
411} // namespace llvm
412
413#endif
#define T
LLVM Value Representation.
Definition Value.h:75
This is an optimization pass for GlobalISel generic memory operations.
constexpr T rotr(T V, int R)
Definition bit.h:399
constexpr T bit_ceil_constexpr(T Value)
Returns the smallest integral power of two no smaller than Value if Value is nonzero.
Definition bit.h:377
int countr_one(T Value)
Count the number of ones from the least significant bit to the first zero bit.
Definition bit.h:315
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:325
T bit_ceil(T Value)
Returns the smallest integral power of two no smaller than Value if Value is nonzero.
Definition bit.h:362
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
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:204
constexpr bool has_single_bit(T Value) noexcept
Definition bit.h:149
constexpr int countl_zero_constexpr(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:240
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:263
int countl_one(T Value)
Count the number of ones from the most significant bit to the first zero bit.
Definition bit.h:302
To bit_cast(const From &from) noexcept
Definition bit.h:90
constexpr unsigned BitWidth
constexpr int countr_zero_constexpr(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:190
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:347
constexpr int bit_width_constexpr(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition bit.h:337
constexpr T rotl(T V, int R)
Definition bit.h:386
#define N