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