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