LLVM 20.0.0git
MathExtras.h
Go to the documentation of this file.
1//===-- llvm/Support/MathExtras.h - Useful math functions -------*- 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// This file contains some functions that are useful for math stuff.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_SUPPORT_MATHEXTRAS_H
14#define LLVM_SUPPORT_MATHEXTRAS_H
15
16#include "llvm/ADT/bit.h"
18#include <cassert>
19#include <climits>
20#include <cstdint>
21#include <cstring>
22#include <limits>
23#include <type_traits>
24
25namespace llvm {
26/// Some template parameter helpers to optimize for bitwidth, for functions that
27/// take multiple arguments.
28
29// We can't verify signedness, since callers rely on implicit coercions to
30// signed/unsigned.
31template <typename T, typename U>
33 std::enable_if_t<std::is_integral_v<T> && std::is_integral_v<U>>;
34
35// Use std::common_type_t to widen only up to the widest argument.
36template <typename T, typename U, typename = enableif_int<T, U>>
38 std::common_type_t<std::make_unsigned_t<T>, std::make_unsigned_t<U>>;
39template <typename T, typename U, typename = enableif_int<T, U>>
41 std::common_type_t<std::make_signed_t<T>, std::make_signed_t<U>>;
42
43/// Mathematical constants.
44namespace numbers {
45// TODO: Track C++20 std::numbers.
46// TODO: Favor using the hexadecimal FP constants (requires C++17).
47// clang-format off
48constexpr double e = 2.7182818284590452354, // (0x1.5bf0a8b145769P+1) https://oeis.org/A001113
49 egamma = .57721566490153286061, // (0x1.2788cfc6fb619P-1) https://oeis.org/A001620
50 ln2 = .69314718055994530942, // (0x1.62e42fefa39efP-1) https://oeis.org/A002162
51 ln10 = 2.3025850929940456840, // (0x1.26bb1bbb55516P+1) https://oeis.org/A002392
52 log2e = 1.4426950408889634074, // (0x1.71547652b82feP+0)
53 log10e = .43429448190325182765, // (0x1.bcb7b1526e50eP-2)
54 pi = 3.1415926535897932385, // (0x1.921fb54442d18P+1) https://oeis.org/A000796
55 inv_pi = .31830988618379067154, // (0x1.45f306dc9c883P-2) https://oeis.org/A049541
56 sqrtpi = 1.7724538509055160273, // (0x1.c5bf891b4ef6bP+0) https://oeis.org/A002161
57 inv_sqrtpi = .56418958354775628695, // (0x1.20dd750429b6dP-1) https://oeis.org/A087197
58 sqrt2 = 1.4142135623730950488, // (0x1.6a09e667f3bcdP+0) https://oeis.org/A00219
59 inv_sqrt2 = .70710678118654752440, // (0x1.6a09e667f3bcdP-1)
60 sqrt3 = 1.7320508075688772935, // (0x1.bb67ae8584caaP+0) https://oeis.org/A002194
61 inv_sqrt3 = .57735026918962576451, // (0x1.279a74590331cP-1)
62 phi = 1.6180339887498948482; // (0x1.9e3779b97f4a8P+0) https://oeis.org/A001622
63constexpr float ef = 2.71828183F, // (0x1.5bf0a8P+1) https://oeis.org/A001113
64 egammaf = .577215665F, // (0x1.2788d0P-1) https://oeis.org/A001620
65 ln2f = .693147181F, // (0x1.62e430P-1) https://oeis.org/A002162
66 ln10f = 2.30258509F, // (0x1.26bb1cP+1) https://oeis.org/A002392
67 log2ef = 1.44269504F, // (0x1.715476P+0)
68 log10ef = .434294482F, // (0x1.bcb7b2P-2)
69 pif = 3.14159265F, // (0x1.921fb6P+1) https://oeis.org/A000796
70 inv_pif = .318309886F, // (0x1.45f306P-2) https://oeis.org/A049541
71 sqrtpif = 1.77245385F, // (0x1.c5bf8aP+0) https://oeis.org/A002161
72 inv_sqrtpif = .564189584F, // (0x1.20dd76P-1) https://oeis.org/A087197
73 sqrt2f = 1.41421356F, // (0x1.6a09e6P+0) https://oeis.org/A002193
74 inv_sqrt2f = .707106781F, // (0x1.6a09e6P-1)
75 sqrt3f = 1.73205081F, // (0x1.bb67aeP+0) https://oeis.org/A002194
76 inv_sqrt3f = .577350269F, // (0x1.279a74P-1)
77 phif = 1.61803399F; // (0x1.9e377aP+0) https://oeis.org/A001622
78// clang-format on
79} // namespace numbers
80
81/// Create a bitmask with the N right-most bits set to 1, and all other
82/// bits set to 0. Only unsigned types are allowed.
83template <typename T> T maskTrailingOnes(unsigned N) {
84 static_assert(std::is_unsigned_v<T>, "Invalid type!");
85 const unsigned Bits = CHAR_BIT * sizeof(T);
86 assert(N <= Bits && "Invalid bit index");
87 if (N == 0)
88 return 0;
89 return T(-1) >> (Bits - N);
90}
91
92/// Create a bitmask with the N left-most bits set to 1, and all other
93/// bits set to 0. Only unsigned types are allowed.
94template <typename T> T maskLeadingOnes(unsigned N) {
95 return ~maskTrailingOnes<T>(CHAR_BIT * sizeof(T) - N);
96}
97
98/// Create a bitmask with the N right-most bits set to 0, and all other
99/// bits set to 1. Only unsigned types are allowed.
100template <typename T> T maskTrailingZeros(unsigned N) {
101 return maskLeadingOnes<T>(CHAR_BIT * sizeof(T) - N);
102}
103
104/// Create a bitmask with the N left-most bits set to 0, and all other
105/// bits set to 1. Only unsigned types are allowed.
106template <typename T> T maskLeadingZeros(unsigned N) {
107 return maskTrailingOnes<T>(CHAR_BIT * sizeof(T) - N);
108}
109
110/// Macro compressed bit reversal table for 256 bits.
111///
112/// http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable
113static const unsigned char BitReverseTable256[256] = {
114#define R2(n) n, n + 2 * 64, n + 1 * 64, n + 3 * 64
115#define R4(n) R2(n), R2(n + 2 * 16), R2(n + 1 * 16), R2(n + 3 * 16)
116#define R6(n) R4(n), R4(n + 2 * 4), R4(n + 1 * 4), R4(n + 3 * 4)
117 R6(0), R6(2), R6(1), R6(3)
118#undef R2
119#undef R4
120#undef R6
121};
122
123/// Reverse the bits in \p Val.
124template <typename T> T reverseBits(T Val) {
125#if __has_builtin(__builtin_bitreverse8)
126 if constexpr (std::is_same_v<T, uint8_t>)
127 return __builtin_bitreverse8(Val);
128#endif
129#if __has_builtin(__builtin_bitreverse16)
130 if constexpr (std::is_same_v<T, uint16_t>)
131 return __builtin_bitreverse16(Val);
132#endif
133#if __has_builtin(__builtin_bitreverse32)
134 if constexpr (std::is_same_v<T, uint32_t>)
135 return __builtin_bitreverse32(Val);
136#endif
137#if __has_builtin(__builtin_bitreverse64)
138 if constexpr (std::is_same_v<T, uint64_t>)
139 return __builtin_bitreverse64(Val);
140#endif
141
142 unsigned char in[sizeof(Val)];
143 unsigned char out[sizeof(Val)];
144 std::memcpy(in, &Val, sizeof(Val));
145 for (unsigned i = 0; i < sizeof(Val); ++i)
146 out[(sizeof(Val) - i) - 1] = BitReverseTable256[in[i]];
147 std::memcpy(&Val, out, sizeof(Val));
148 return Val;
149}
150
151// NOTE: The following support functions use the _32/_64 extensions instead of
152// type overloading so that signed and unsigned integers can be used without
153// ambiguity.
154
155/// Return the high 32 bits of a 64 bit value.
157 return static_cast<uint32_t>(Value >> 32);
158}
159
160/// Return the low 32 bits of a 64 bit value.
162 return static_cast<uint32_t>(Value);
163}
164
165/// Make a 64-bit integer from a high / low pair of 32-bit integers.
167 return ((uint64_t)High << 32) | (uint64_t)Low;
168}
169
170/// Checks if an integer fits into the given bit width.
171template <unsigned N> constexpr bool isInt(int64_t x) {
172 if constexpr (N == 0)
173 return 0 == x;
174 if constexpr (N == 8)
175 return static_cast<int8_t>(x) == x;
176 if constexpr (N == 16)
177 return static_cast<int16_t>(x) == x;
178 if constexpr (N == 32)
179 return static_cast<int32_t>(x) == x;
180 if constexpr (N < 64)
181 return -(INT64_C(1) << (N - 1)) <= x && x < (INT64_C(1) << (N - 1));
182 (void)x; // MSVC v19.25 warns that x is unused.
183 return true;
184}
185
186/// Checks if a signed integer is an N bit number shifted left by S.
187template <unsigned N, unsigned S>
188constexpr bool isShiftedInt(int64_t x) {
189 static_assert(S < 64, "isShiftedInt<N, S> with S >= 64 is too much.");
190 static_assert(N + S <= 64, "isShiftedInt<N, S> with N + S > 64 is too wide.");
191 return isInt<N + S>(x) && (x % (UINT64_C(1) << S) == 0);
192}
193
194/// Checks if an unsigned integer fits into the given bit width.
195template <unsigned N> constexpr bool isUInt(uint64_t x) {
196 if constexpr (N == 0)
197 return 0 == x;
198 if constexpr (N == 8)
199 return static_cast<uint8_t>(x) == x;
200 if constexpr (N == 16)
201 return static_cast<uint16_t>(x) == x;
202 if constexpr (N == 32)
203 return static_cast<uint32_t>(x) == x;
204 if constexpr (N < 64)
205 return x < (UINT64_C(1) << (N));
206 (void)x; // MSVC v19.25 warns that x is unused.
207 return true;
208}
209
210/// Checks if a unsigned integer is an N bit number shifted left by S.
211template <unsigned N, unsigned S>
212constexpr bool isShiftedUInt(uint64_t x) {
213 static_assert(S < 64, "isShiftedUInt<N, S> with S >= 64 is too much.");
214 static_assert(N + S <= 64,
215 "isShiftedUInt<N, S> with N + S > 64 is too wide.");
216 // S must be strictly less than 64. So 1 << S is not undefined behavior.
217 return isUInt<N + S>(x) && (x % (UINT64_C(1) << S) == 0);
218}
219
220/// Gets the maximum value for a N-bit unsigned integer.
222 assert(N <= 64 && "integer width out of range");
223
224 // uint64_t(1) << 64 is undefined behavior, so we can't do
225 // (uint64_t(1) << N) - 1
226 // without checking first that N != 64. But this works and doesn't have a
227 // branch for N != 0.
228 // Unfortunately, shifting a uint64_t right by 64 bit is undefined
229 // behavior, so the condition on N == 0 is necessary. Fortunately, most
230 // optimizers do not emit branches for this check.
231 if (N == 0)
232 return 0;
233 return UINT64_MAX >> (64 - N);
234}
235
236/// Gets the minimum value for a N-bit signed integer.
237inline int64_t minIntN(int64_t N) {
238 assert(N <= 64 && "integer width out of range");
239
240 if (N == 0)
241 return 0;
242 return UINT64_C(1) + ~(UINT64_C(1) << (N - 1));
243}
244
245/// Gets the maximum value for a N-bit signed integer.
246inline int64_t maxIntN(int64_t N) {
247 assert(N <= 64 && "integer width out of range");
248
249 // This relies on two's complement wraparound when N == 64, so we convert to
250 // int64_t only at the very end to avoid UB.
251 if (N == 0)
252 return 0;
253 return (UINT64_C(1) << (N - 1)) - 1;
254}
255
256/// Checks if an unsigned integer fits into the given (dynamic) bit width.
257inline bool isUIntN(unsigned N, uint64_t x) {
258 return N >= 64 || x <= maxUIntN(N);
259}
260
261/// Checks if an signed integer fits into the given (dynamic) bit width.
262inline bool isIntN(unsigned N, int64_t x) {
263 return N >= 64 || (minIntN(N) <= x && x <= maxIntN(N));
264}
265
266/// Return true if the argument is a non-empty sequence of ones starting at the
267/// least significant bit with the remainder zero (32 bit version).
268/// Ex. isMask_32(0x0000FFFFU) == true.
269constexpr bool isMask_32(uint32_t Value) {
270 return Value && ((Value + 1) & Value) == 0;
271}
272
273/// Return true if the argument is a non-empty sequence of ones starting at the
274/// least significant bit with the remainder zero (64 bit version).
275constexpr bool isMask_64(uint64_t Value) {
276 return Value && ((Value + 1) & Value) == 0;
277}
278
279/// Return true if the argument contains a non-empty sequence of ones with the
280/// remainder zero (32 bit version.) Ex. isShiftedMask_32(0x0000FF00U) == true.
282 return Value && isMask_32((Value - 1) | Value);
283}
284
285/// Return true if the argument contains a non-empty sequence of ones with the
286/// remainder zero (64 bit version.)
288 return Value && isMask_64((Value - 1) | Value);
289}
290
291/// Return true if the argument is a power of two > 0.
292/// Ex. isPowerOf2_32(0x00100000U) == true (32 bit edition.)
293constexpr bool isPowerOf2_32(uint32_t Value) {
295}
296
297/// Return true if the argument is a power of two > 0 (64 bit edition.)
298constexpr bool isPowerOf2_64(uint64_t Value) {
300}
301
302/// Return true if the argument contains a non-empty sequence of ones with the
303/// remainder zero (32 bit version.) Ex. isShiftedMask_32(0x0000FF00U) == true.
304/// If true, \p MaskIdx will specify the index of the lowest set bit and \p
305/// MaskLen is updated to specify the length of the mask, else neither are
306/// updated.
307inline bool isShiftedMask_32(uint32_t Value, unsigned &MaskIdx,
308 unsigned &MaskLen) {
310 return false;
311 MaskIdx = llvm::countr_zero(Value);
312 MaskLen = llvm::popcount(Value);
313 return true;
314}
315
316/// Return true if the argument contains a non-empty sequence of ones with the
317/// remainder zero (64 bit version.) If true, \p MaskIdx will specify the index
318/// of the lowest set bit and \p MaskLen is updated to specify the length of the
319/// mask, else neither are updated.
320inline bool isShiftedMask_64(uint64_t Value, unsigned &MaskIdx,
321 unsigned &MaskLen) {
323 return false;
324 MaskIdx = llvm::countr_zero(Value);
325 MaskLen = llvm::popcount(Value);
326 return true;
327}
328
329/// Compile time Log2.
330/// Valid only for positive powers of two.
331template <size_t kValue> constexpr size_t CTLog2() {
332 static_assert(kValue > 0 && llvm::isPowerOf2_64(kValue),
333 "Value is not a valid power of 2");
334 return 1 + CTLog2<kValue / 2>();
335}
336
337template <> constexpr size_t CTLog2<1>() { return 0; }
338
339/// Return the floor log base 2 of the specified value, -1 if the value is zero.
340/// (32 bit edition.)
341/// Ex. Log2_32(32) == 5, Log2_32(1) == 0, Log2_32(0) == -1, Log2_32(6) == 2
342inline unsigned Log2_32(uint32_t Value) {
343 return 31 - llvm::countl_zero(Value);
344}
345
346/// Return the floor log base 2 of the specified value, -1 if the value is zero.
347/// (64 bit edition.)
348inline unsigned Log2_64(uint64_t Value) {
349 return 63 - llvm::countl_zero(Value);
350}
351
352/// Return the ceil log base 2 of the specified value, 32 if the value is zero.
353/// (32 bit edition).
354/// Ex. Log2_32_Ceil(32) == 5, Log2_32_Ceil(1) == 0, Log2_32_Ceil(6) == 3
355inline unsigned Log2_32_Ceil(uint32_t Value) {
356 return 32 - llvm::countl_zero(Value - 1);
357}
358
359/// Return the ceil log base 2 of the specified value, 64 if the value is zero.
360/// (64 bit edition.)
361inline unsigned Log2_64_Ceil(uint64_t Value) {
362 return 64 - llvm::countl_zero(Value - 1);
363}
364
365/// A and B are either alignments or offsets. Return the minimum alignment that
366/// may be assumed after adding the two together.
367template <typename U, typename V, typename T = common_uint<U, V>>
368constexpr T MinAlign(U A, V B) {
369 // The largest power of 2 that divides both A and B.
370 //
371 // Replace "-Value" by "1+~Value" in the following commented code to avoid
372 // MSVC warning C4146
373 // return (A | B) & -(A | B);
374 return (A | B) & (1 + ~(A | B));
375}
376
377/// Fallback when arguments aren't integral.
379 return (A | B) & (1 + ~(A | B));
380}
381
382/// Returns the next power of two (in 64-bits) that is strictly greater than A.
383/// Returns zero on overflow.
385 A |= (A >> 1);
386 A |= (A >> 2);
387 A |= (A >> 4);
388 A |= (A >> 8);
389 A |= (A >> 16);
390 A |= (A >> 32);
391 return A + 1;
392}
393
394/// Returns the power of two which is greater than or equal to the given value.
395/// Essentially, it is a ceil operation across the domain of powers of two.
397 if (!A || A > UINT64_MAX / 2)
398 return 0;
399 return UINT64_C(1) << Log2_64_Ceil(A);
400}
401
402/// Returns the integer ceil(Numerator / Denominator). Unsigned version.
403/// Guaranteed to never overflow.
404template <typename U, typename V, typename T = common_uint<U, V>>
405constexpr T divideCeil(U Numerator, V Denominator) {
406 assert(Denominator && "Division by zero");
407 T Bias = (Numerator != 0);
408 return (Numerator - Bias) / Denominator + Bias;
409}
410
411/// Fallback when arguments aren't integral.
412constexpr uint64_t divideCeil(uint64_t Numerator, uint64_t Denominator) {
413 assert(Denominator && "Division by zero");
414 uint64_t Bias = (Numerator != 0);
415 return (Numerator - Bias) / Denominator + Bias;
416}
417
418// Check whether divideCeilSigned or divideFloorSigned would overflow. This
419// happens only when Numerator = INT_MIN and Denominator = -1.
420template <typename U, typename V>
421constexpr bool divideSignedWouldOverflow(U Numerator, V Denominator) {
422 return Numerator == std::numeric_limits<U>::min() && Denominator == -1;
423}
424
425/// Returns the integer ceil(Numerator / Denominator). Signed version.
426/// Overflow is explicitly forbidden with an assert.
427template <typename U, typename V, typename T = common_sint<U, V>>
428constexpr T divideCeilSigned(U Numerator, V Denominator) {
429 assert(Denominator && "Division by zero");
430 assert(!divideSignedWouldOverflow(Numerator, Denominator) &&
431 "Divide would overflow");
432 if (!Numerator)
433 return 0;
434 // C's integer division rounds towards 0.
435 T Bias = Denominator >= 0 ? 1 : -1;
436 bool SameSign = (Numerator >= 0) == (Denominator >= 0);
437 return SameSign ? (Numerator - Bias) / Denominator + 1
438 : Numerator / Denominator;
439}
440
441/// Returns the integer floor(Numerator / Denominator). Signed version.
442/// Overflow is explicitly forbidden with an assert.
443template <typename U, typename V, typename T = common_sint<U, V>>
444constexpr T divideFloorSigned(U Numerator, V Denominator) {
445 assert(Denominator && "Division by zero");
446 assert(!divideSignedWouldOverflow(Numerator, Denominator) &&
447 "Divide would overflow");
448 if (!Numerator)
449 return 0;
450 // C's integer division rounds towards 0.
451 T Bias = Denominator >= 0 ? -1 : 1;
452 bool SameSign = (Numerator >= 0) == (Denominator >= 0);
453 return SameSign ? Numerator / Denominator
454 : (Numerator - Bias) / Denominator - 1;
455}
456
457/// Returns the remainder of the Euclidean division of LHS by RHS. Result is
458/// always non-negative.
459template <typename U, typename V, typename T = common_sint<U, V>>
460constexpr T mod(U Numerator, V Denominator) {
461 assert(Denominator >= 1 && "Mod by non-positive number");
462 T Mod = Numerator % Denominator;
463 return Mod < 0 ? Mod + Denominator : Mod;
464}
465
466/// Returns (Numerator / Denominator) rounded by round-half-up. Guaranteed to
467/// never overflow.
468template <typename U, typename V, typename T = common_uint<U, V>>
469constexpr T divideNearest(U Numerator, V Denominator) {
470 assert(Denominator && "Division by zero");
471 T Mod = Numerator % Denominator;
472 return (Numerator / Denominator) +
473 (Mod > (static_cast<T>(Denominator) - 1) / 2);
474}
475
476/// Returns the next integer (mod 2**nbits) that is greater than or equal to
477/// \p Value and is a multiple of \p Align. \p Align must be non-zero.
478///
479/// Examples:
480/// \code
481/// alignTo(5, 8) = 8
482/// alignTo(17, 8) = 24
483/// alignTo(~0LL, 8) = 0
484/// alignTo(321, 255) = 510
485/// \endcode
486///
487/// Will overflow only if result is not representable in T.
488template <typename U, typename V, typename T = common_uint<U, V>>
489constexpr T alignTo(U Value, V Align) {
490 assert(Align != 0u && "Align can't be 0.");
491 T CeilDiv = divideCeil(Value, Align);
492 return CeilDiv * Align;
493}
494
495/// Fallback when arguments aren't integral.
497 assert(Align != 0u && "Align can't be 0.");
498 uint64_t CeilDiv = divideCeil(Value, Align);
499 return CeilDiv * Align;
500}
501
502/// Will overflow only if result is not representable in T.
503template <typename U, typename V, typename T = common_uint<U, V>>
504constexpr T alignToPowerOf2(U Value, V Align) {
505 assert(Align != 0 && (Align & (Align - 1)) == 0 &&
506 "Align must be a power of 2");
507 T NegAlign = static_cast<T>(0) - Align;
508 return (Value + (Align - 1)) & NegAlign;
509}
510
511/// Fallback when arguments aren't integral.
513 assert(Align != 0 && (Align & (Align - 1)) == 0 &&
514 "Align must be a power of 2");
515 uint64_t NegAlign = 0 - Align;
516 return (Value + (Align - 1)) & NegAlign;
517}
518
519/// If non-zero \p Skew is specified, the return value will be a minimal integer
520/// that is greater than or equal to \p Size and equal to \p A * N + \p Skew for
521/// some integer N. If \p Skew is larger than \p A, its value is adjusted to '\p
522/// Skew mod \p A'. \p Align must be non-zero.
523///
524/// Examples:
525/// \code
526/// alignTo(5, 8, 7) = 7
527/// alignTo(17, 8, 1) = 17
528/// alignTo(~0LL, 8, 3) = 3
529/// alignTo(321, 255, 42) = 552
530/// \endcode
531///
532/// May overflow.
533template <typename U, typename V, typename W,
534 typename T = common_uint<common_uint<U, V>, W>>
535constexpr T alignTo(U Value, V Align, W Skew) {
536 assert(Align != 0u && "Align can't be 0.");
537 Skew %= Align;
538 return alignTo(Value - Skew, Align) + Skew;
539}
540
541/// Returns the next integer (mod 2**nbits) that is greater than or equal to
542/// \p Value and is a multiple of \c Align. \c Align must be non-zero.
543///
544/// Will overflow only if result is not representable in T.
545template <auto Align, typename V, typename T = common_uint<decltype(Align), V>>
546constexpr T alignTo(V Value) {
547 static_assert(Align != 0u, "Align must be non-zero");
548 T CeilDiv = divideCeil(Value, Align);
549 return CeilDiv * Align;
550}
551
552/// Returns the largest unsigned integer less than or equal to \p Value and is
553/// \p Skew mod \p Align. \p Align must be non-zero. Guaranteed to never
554/// overflow.
555template <typename U, typename V, typename W = uint8_t,
556 typename T = common_uint<common_uint<U, V>, W>>
557constexpr T alignDown(U Value, V Align, W Skew = 0) {
558 assert(Align != 0u && "Align can't be 0.");
559 Skew %= Align;
560 return (Value - Skew) / Align * Align + Skew;
561}
562
563/// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
564/// Requires B <= 32.
565template <unsigned B> constexpr int32_t SignExtend32(uint32_t X) {
566 static_assert(B <= 32, "Bit width out of range.");
567 if constexpr (B == 0)
568 return 0;
569 return int32_t(X << (32 - B)) >> (32 - B);
570}
571
572/// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
573/// Requires B <= 32.
574inline int32_t SignExtend32(uint32_t X, unsigned B) {
575 assert(B <= 32 && "Bit width out of range.");
576 if (B == 0)
577 return 0;
578 return int32_t(X << (32 - B)) >> (32 - B);
579}
580
581/// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
582/// Requires B <= 64.
583template <unsigned B> constexpr int64_t SignExtend64(uint64_t x) {
584 static_assert(B <= 64, "Bit width out of range.");
585 if constexpr (B == 0)
586 return 0;
587 return int64_t(x << (64 - B)) >> (64 - B);
588}
589
590/// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
591/// Requires B <= 64.
592inline int64_t SignExtend64(uint64_t X, unsigned B) {
593 assert(B <= 64 && "Bit width out of range.");
594 if (B == 0)
595 return 0;
596 return int64_t(X << (64 - B)) >> (64 - B);
597}
598
599/// Subtract two unsigned integers, X and Y, of type T and return the absolute
600/// value of the result.
601template <typename U, typename V, typename T = common_uint<U, V>>
602constexpr T AbsoluteDifference(U X, V Y) {
603 return X > Y ? (X - Y) : (Y - X);
604}
605
606/// Add two unsigned integers, X and Y, of type T. Clamp the result to the
607/// maximum representable value of T on overflow. ResultOverflowed indicates if
608/// the result is larger than the maximum representable value of type T.
609template <typename T>
610std::enable_if_t<std::is_unsigned_v<T>, T>
611SaturatingAdd(T X, T Y, bool *ResultOverflowed = nullptr) {
612 bool Dummy;
613 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
614 // Hacker's Delight, p. 29
615 T Z = X + Y;
616 Overflowed = (Z < X || Z < Y);
617 if (Overflowed)
618 return std::numeric_limits<T>::max();
619 else
620 return Z;
621}
622
623/// Add multiple unsigned integers of type T. Clamp the result to the
624/// maximum representable value of T on overflow.
625template <class T, class... Ts>
626std::enable_if_t<std::is_unsigned_v<T>, T> SaturatingAdd(T X, T Y, T Z,
627 Ts... Args) {
628 bool Overflowed = false;
629 T XY = SaturatingAdd(X, Y, &Overflowed);
630 if (Overflowed)
631 return SaturatingAdd(std::numeric_limits<T>::max(), T(1), Args...);
632 return SaturatingAdd(XY, Z, Args...);
633}
634
635/// Multiply two unsigned integers, X and Y, of type T. Clamp the result to the
636/// maximum representable value of T on overflow. ResultOverflowed indicates if
637/// the result is larger than the maximum representable value of type T.
638template <typename T>
639std::enable_if_t<std::is_unsigned_v<T>, T>
640SaturatingMultiply(T X, T Y, bool *ResultOverflowed = nullptr) {
641 bool Dummy;
642 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
643
644 // Hacker's Delight, p. 30 has a different algorithm, but we don't use that
645 // because it fails for uint16_t (where multiplication can have undefined
646 // behavior due to promotion to int), and requires a division in addition
647 // to the multiplication.
648
649 Overflowed = false;
650
651 // Log2(Z) would be either Log2Z or Log2Z + 1.
652 // Special case: if X or Y is 0, Log2_64 gives -1, and Log2Z
653 // will necessarily be less than Log2Max as desired.
654 int Log2Z = Log2_64(X) + Log2_64(Y);
655 const T Max = std::numeric_limits<T>::max();
656 int Log2Max = Log2_64(Max);
657 if (Log2Z < Log2Max) {
658 return X * Y;
659 }
660 if (Log2Z > Log2Max) {
661 Overflowed = true;
662 return Max;
663 }
664
665 // We're going to use the top bit, and maybe overflow one
666 // bit past it. Multiply all but the bottom bit then add
667 // that on at the end.
668 T Z = (X >> 1) * Y;
669 if (Z & ~(Max >> 1)) {
670 Overflowed = true;
671 return Max;
672 }
673 Z <<= 1;
674 if (X & 1)
675 return SaturatingAdd(Z, Y, ResultOverflowed);
676
677 return Z;
678}
679
680/// Multiply two unsigned integers, X and Y, and add the unsigned integer, A to
681/// the product. Clamp the result to the maximum representable value of T on
682/// overflow. ResultOverflowed indicates if the result is larger than the
683/// maximum representable value of type T.
684template <typename T>
685std::enable_if_t<std::is_unsigned_v<T>, T>
686SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed = nullptr) {
687 bool Dummy;
688 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
689
690 T Product = SaturatingMultiply(X, Y, &Overflowed);
691 if (Overflowed)
692 return Product;
693
694 return SaturatingAdd(A, Product, &Overflowed);
695}
696
697/// Use this rather than HUGE_VALF; the latter causes warnings on MSVC.
698extern const float huge_valf;
699
700/// Add two signed integers, computing the two's complement truncated result,
701/// returning true if overflow occurred.
702template <typename T>
703std::enable_if_t<std::is_signed_v<T>, T> AddOverflow(T X, T Y, T &Result) {
704#if __has_builtin(__builtin_add_overflow)
705 return __builtin_add_overflow(X, Y, &Result);
706#else
707 // Perform the unsigned addition.
708 using U = std::make_unsigned_t<T>;
709 const U UX = static_cast<U>(X);
710 const U UY = static_cast<U>(Y);
711 const U UResult = UX + UY;
712
713 // Convert to signed.
714 Result = static_cast<T>(UResult);
715
716 // Adding two positive numbers should result in a positive number.
717 if (X > 0 && Y > 0)
718 return Result <= 0;
719 // Adding two negatives should result in a negative number.
720 if (X < 0 && Y < 0)
721 return Result >= 0;
722 return false;
723#endif
724}
725
726/// Subtract two signed integers, computing the two's complement truncated
727/// result, returning true if an overflow ocurred.
728template <typename T>
729std::enable_if_t<std::is_signed_v<T>, T> SubOverflow(T X, T Y, T &Result) {
730#if __has_builtin(__builtin_sub_overflow)
731 return __builtin_sub_overflow(X, Y, &Result);
732#else
733 // Perform the unsigned addition.
734 using U = std::make_unsigned_t<T>;
735 const U UX = static_cast<U>(X);
736 const U UY = static_cast<U>(Y);
737 const U UResult = UX - UY;
738
739 // Convert to signed.
740 Result = static_cast<T>(UResult);
741
742 // Subtracting a positive number from a negative results in a negative number.
743 if (X <= 0 && Y > 0)
744 return Result >= 0;
745 // Subtracting a negative number from a positive results in a positive number.
746 if (X >= 0 && Y < 0)
747 return Result <= 0;
748 return false;
749#endif
750}
751
752/// Multiply two signed integers, computing the two's complement truncated
753/// result, returning true if an overflow ocurred.
754template <typename T>
755std::enable_if_t<std::is_signed_v<T>, T> MulOverflow(T X, T Y, T &Result) {
756#if __has_builtin(__builtin_mul_overflow)
757 return __builtin_mul_overflow(X, Y, &Result);
758#else
759 // Perform the unsigned multiplication on absolute values.
760 using U = std::make_unsigned_t<T>;
761 const U UX = X < 0 ? (0 - static_cast<U>(X)) : static_cast<U>(X);
762 const U UY = Y < 0 ? (0 - static_cast<U>(Y)) : static_cast<U>(Y);
763 const U UResult = UX * UY;
764
765 // Convert to signed.
766 const bool IsNegative = (X < 0) ^ (Y < 0);
767 Result = IsNegative ? (0 - UResult) : UResult;
768
769 // If any of the args was 0, result is 0 and no overflow occurs.
770 if (UX == 0 || UY == 0)
771 return false;
772
773 // UX and UY are in [1, 2^n], where n is the number of digits.
774 // Check how the max allowed absolute value (2^n for negative, 2^(n-1) for
775 // positive) divided by an argument compares to the other.
776 if (IsNegative)
777 return UX > (static_cast<U>(std::numeric_limits<T>::max()) + U(1)) / UY;
778 else
779 return UX > (static_cast<U>(std::numeric_limits<T>::max())) / UY;
780#endif
781}
782
783/// Type to force float point values onto the stack, so that x86 doesn't add
784/// hidden precision, avoiding rounding differences on various platforms.
785#if defined(__i386__) || defined(_M_IX86)
786using stack_float_t = volatile float;
787#else
788using stack_float_t = float;
789#endif
790
791} // namespace llvm
792
793#endif
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
#define R6(n)
#define T
uint64_t High
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file implements the C++20 <bit> header.
LLVM Value Representation.
Definition: Value.h:74
#define UINT64_MAX
Definition: DataTypes.h:77
constexpr float inv_sqrtpif
Definition: MathExtras.h:72
constexpr double sqrt2
Definition: MathExtras.h:58
constexpr double inv_sqrt2
Definition: MathExtras.h:59
constexpr double inv_pi
Definition: MathExtras.h:55
constexpr double sqrtpi
Definition: MathExtras.h:56
constexpr float pif
Definition: MathExtras.h:69
constexpr float sqrtpif
Definition: MathExtras.h:71
constexpr float log10ef
Definition: MathExtras.h:68
constexpr float ln10f
Definition: MathExtras.h:66
constexpr double ln2
Definition: MathExtras.h:50
constexpr double inv_sqrt3
Definition: MathExtras.h:61
constexpr double egamma
Definition: MathExtras.h:49
constexpr float phif
Definition: MathExtras.h:77
constexpr float sqrt3f
Definition: MathExtras.h:75
constexpr double ln10
Definition: MathExtras.h:51
constexpr double inv_sqrtpi
Definition: MathExtras.h:57
constexpr float log2ef
Definition: MathExtras.h:67
constexpr double e
Definition: MathExtras.h:48
constexpr double phi
Definition: MathExtras.h:62
constexpr float sqrt2f
Definition: MathExtras.h:73
constexpr double sqrt3
Definition: MathExtras.h:60
constexpr float inv_pif
Definition: MathExtras.h:70
constexpr float inv_sqrt2f
Definition: MathExtras.h:74
constexpr double log10e
Definition: MathExtras.h:53
constexpr double log2e
Definition: MathExtras.h:52
constexpr float egammaf
Definition: MathExtras.h:64
constexpr double pi
Definition: MathExtras.h:54
constexpr float ln2f
Definition: MathExtras.h:65
constexpr float ef
Definition: MathExtras.h:63
constexpr float inv_sqrt3f
Definition: MathExtras.h:76
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
std::common_type_t< std::make_unsigned_t< T >, std::make_unsigned_t< U > > common_uint
Definition: MathExtras.h:38
float stack_float_t
Type to force float point values onto the stack, so that x86 doesn't add hidden precision,...
Definition: MathExtras.h:788
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition: MathExtras.h:355
std::enable_if_t< std::is_signed_v< T >, T > MulOverflow(T X, T Y, T &Result)
Multiply two signed integers, computing the two's complement truncated result, returning true if an o...
Definition: MathExtras.h:755
int64_t maxIntN(int64_t N)
Gets the maximum value for a N-bit signed integer.
Definition: MathExtras.h:246
constexpr bool divideSignedWouldOverflow(U Numerator, V Denominator)
Definition: MathExtras.h:421
LLVM_ATTRIBUTE_ALWAYS_INLINE DynamicAPInt mod(const DynamicAPInt &LHS, const DynamicAPInt &RHS)
is always non-negative.
Definition: DynamicAPInt.h:382
int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition: bit.h:385
constexpr size_t CTLog2()
Compile time Log2.
Definition: MathExtras.h:331
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition: MathExtras.h:171
bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition: MathExtras.h:257
constexpr size_t CTLog2< 1 >()
Definition: MathExtras.h:337
unsigned Log2_64_Ceil(uint64_t Value)
Return the ceil log base 2 of the specified value, 64 if the value is zero.
Definition: MathExtras.h:361
constexpr bool isMask_32(uint32_t Value)
Return true if the argument is a non-empty sequence of ones starting at the least significant bit wit...
Definition: MathExtras.h:269
constexpr T divideFloorSigned(U Numerator, V Denominator)
Returns the integer floor(Numerator / Denominator).
Definition: MathExtras.h:444
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition: MathExtras.h:557
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition: MathExtras.h:298
constexpr bool isShiftedMask_32(uint32_t Value)
Return true if the argument contains a non-empty sequence of ones with the remainder zero (32 bit ver...
Definition: MathExtras.h:281
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition: MathExtras.h:348
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition: MathExtras.h:396
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:215
constexpr bool isShiftedMask_64(uint64_t Value)
Return true if the argument contains a non-empty sequence of ones with the remainder zero (64 bit ver...
Definition: MathExtras.h:287
constexpr T MinAlign(U A, V B)
A and B are either alignments or offsets.
Definition: MathExtras.h:368
constexpr T divideNearest(U Numerator, V Denominator)
Returns (Numerator / Denominator) rounded by round-half-up.
Definition: MathExtras.h:469
constexpr bool has_single_bit(T Value) noexcept
Definition: bit.h:146
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition: MathExtras.h:342
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:281
T maskLeadingZeros(unsigned N)
Create a bitmask with the N left-most bits set to 0, and all other bits set to 1.
Definition: MathExtras.h:106
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:293
T maskTrailingOnes(unsigned N)
Create a bitmask with the N right-most bits set to 1, and all other bits set to 0.
Definition: MathExtras.h:83
T maskTrailingZeros(unsigned N)
Create a bitmask with the N right-most bits set to 0, and all other bits set to 1.
Definition: MathExtras.h:100
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
Definition: MathExtras.h:156
std::common_type_t< std::make_signed_t< T >, std::make_signed_t< U > > common_sint
Definition: MathExtras.h:41
constexpr T alignToPowerOf2(U Value, V Align)
Will overflow only if result is not representable in T.
Definition: MathExtras.h:504
constexpr bool isMask_64(uint64_t Value)
Return true if the argument is a non-empty sequence of ones starting at the least significant bit wit...
Definition: MathExtras.h:275
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, and add the unsigned integer, A to the product.
Definition: MathExtras.h:686
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition: MathExtras.h:195
constexpr T divideCeilSigned(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition: MathExtras.h:428
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
Definition: MathExtras.h:161
@ Mod
The access may modify the value stored in memory.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition: MathExtras.h:405
const float huge_valf
Use this rather than HUGE_VALF; the latter causes warnings on MSVC.
Definition: MathExtras.cpp:28
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingMultiply(T X, T Y, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, of type T.
Definition: MathExtras.h:640
bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition: MathExtras.h:262
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
constexpr T AbsoluteDifference(U X, V Y)
Subtract two unsigned integers, X and Y, of type T and return the absolute value of the result.
Definition: MathExtras.h:602
int64_t minIntN(int64_t N)
Gets the minimum value for a N-bit signed integer.
Definition: MathExtras.h:237
constexpr bool isShiftedInt(int64_t x)
Checks if a signed integer is an N bit number shifted left by S.
Definition: MathExtras.h:188
constexpr int32_t SignExtend32(uint32_t X)
Sign-extend the number in the bottom B bits of X to a 32-bit integer.
Definition: MathExtras.h:565
T maskLeadingOnes(unsigned N)
Create a bitmask with the N left-most bits set to 1, and all other bits set to 0.
Definition: MathExtras.h:94
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition: MathExtras.h:583
std::enable_if_t< std::is_signed_v< T >, T > AddOverflow(T X, T Y, T &Result)
Add two signed integers, computing the two's complement truncated result, returning true if overflow ...
Definition: MathExtras.h:703
std::enable_if_t< std::is_signed_v< T >, T > SubOverflow(T X, T Y, T &Result)
Subtract two signed integers, computing the two's complement truncated result, returning true if an o...
Definition: MathExtras.h:729
static const unsigned char BitReverseTable256[256]
Macro compressed bit reversal table for 256 bits.
Definition: MathExtras.h:113
T reverseBits(T Val)
Reverse the bits in Val.
Definition: MathExtras.h:124
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingAdd(T X, T Y, bool *ResultOverflowed=nullptr)
Add two unsigned integers, X and Y, of type T.
Definition: MathExtras.h:611
std::enable_if_t< std::is_integral_v< T > &&std::is_integral_v< U > > enableif_int
Some template parameter helpers to optimize for bitwidth, for functions that take multiple arguments.
Definition: MathExtras.h:33
constexpr bool isShiftedUInt(uint64_t x)
Checks if a unsigned integer is an N bit number shifted left by S.
Definition: MathExtras.h:212
constexpr uint64_t Make_64(uint32_t High, uint32_t Low)
Make a 64-bit integer from a high / low pair of 32-bit integers.
Definition: MathExtras.h:166
uint64_t maxUIntN(uint64_t N)
Gets the maximum value for a N-bit unsigned integer.
Definition: MathExtras.h:221
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition: MathExtras.h:384
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39