1//===-- A class to manipulate wide integers. --------------------*- 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#ifndef LLVM_LIBC_SRC___SUPPORT_BIG_INT_H
10#define LLVM_LIBC_SRC___SUPPORT_BIG_INT_H
11
12#include "hdr/stdint_proxy.h"
13#include "src/__support/CPP/array.h"
14#include "src/__support/CPP/bit.h" // countl_zero
15#include "src/__support/CPP/limits.h"
16#include "src/__support/CPP/optional.h"
17#include "src/__support/CPP/type_traits.h"
18#include "src/__support/macros/attributes.h" // LIBC_INLINE
19#include "src/__support/macros/config.h"
20#include "src/__support/macros/optimization.h" // LIBC_UNLIKELY
21#include "src/__support/macros/properties/compiler.h" // LIBC_COMPILER_IS_CLANG
22#include "src/__support/macros/properties/types.h" // LIBC_TYPES_HAS_INT128, LIBC_TYPES_HAS_INT64
23#include "src/__support/math_extras.h" // add_with_carry, sub_with_borrow
24#include "src/__support/number_pair.h"
25
26#include <stddef.h> // For size_t
27
28namespace LIBC_NAMESPACE_DECL {
29
30namespace multiword {
31
32// A type trait mapping unsigned integers to their half-width unsigned
33// counterparts.
34template <typename T> struct half_width;
35template <> struct half_width<uint16_t> : cpp::type_identity<uint8_t> {};
36template <> struct half_width<uint32_t> : cpp::type_identity<uint16_t> {};
37#ifdef LIBC_TYPES_HAS_INT64
38template <> struct half_width<uint64_t> : cpp::type_identity<uint32_t> {};
39#ifdef LIBC_TYPES_HAS_INT128
40template <> struct half_width<__uint128_t> : cpp::type_identity<uint64_t> {};
41#endif // LIBC_TYPES_HAS_INT128
42#endif // LIBC_TYPES_HAS_INT64
43template <typename T> using half_width_t = typename half_width<T>::type;
44
45// An array of two elements that can be used in multiword operations.
46template <typename T> struct DoubleWide final : cpp::array<T, 2> {
47 using UP = cpp::array<T, 2>;
48 using UP::UP;
49 LIBC_INLINE constexpr DoubleWide(T lo, T hi) : UP({lo, hi}) {}
50};
51
52// Converts an unsigned value into a DoubleWide<half_width_t<T>>.
53template <typename T> LIBC_INLINE constexpr auto split(T value) {
54 static_assert(cpp::is_unsigned_v<T>);
55 using half_type = half_width_t<T>;
56 return DoubleWide<half_type>(
57 half_type(value),
58 half_type(value >> cpp::numeric_limits<half_type>::digits));
59}
60
61// The low part of a DoubleWide value.
62template <typename T> LIBC_INLINE constexpr T lo(const DoubleWide<T> &value) {
63 return value[0];
64}
65// The high part of a DoubleWide value.
66template <typename T> LIBC_INLINE constexpr T hi(const DoubleWide<T> &value) {
67 return value[1];
68}
69// The low part of an unsigned value.
70template <typename T> LIBC_INLINE constexpr half_width_t<T> lo(T value) {
71 return lo(split(value));
72}
73// The high part of an unsigned value.
74template <typename T> LIBC_INLINE constexpr half_width_t<T> hi(T value) {
75 return hi(split(value));
76}
77
78// Returns 'a' times 'b' in a DoubleWide<word>. Cannot overflow by construction.
79template <typename word>
80LIBC_INLINE constexpr DoubleWide<word> mul2(word a, word b) {
81 if constexpr (cpp::is_same_v<word, uint8_t>) {
82 return split<uint16_t>(value: uint16_t(a) * uint16_t(b));
83 } else if constexpr (cpp::is_same_v<word, uint16_t>) {
84 return split<uint32_t>(value: uint32_t(a) * uint32_t(b));
85 }
86#ifdef LIBC_TYPES_HAS_INT64
87 else if constexpr (cpp::is_same_v<word, uint32_t>) {
88 return split<uint64_t>(value: uint64_t(a) * uint64_t(b));
89 }
90#endif
91#ifdef LIBC_TYPES_HAS_INT128
92 else if constexpr (cpp::is_same_v<word, uint64_t>) {
93 return split<__uint128_t>(value: __uint128_t(a) * __uint128_t(b));
94 }
95#endif
96 else {
97 using half_word = half_width_t<word>;
98 constexpr auto shiftl = [](word value) -> word {
99 return value << cpp::numeric_limits<half_word>::digits;
100 };
101 constexpr auto shiftr = [](word value) -> word {
102 return value >> cpp::numeric_limits<half_word>::digits;
103 };
104 // Here we do a one digit multiplication where 'a' and 'b' are of type
105 // word. We split 'a' and 'b' into half words and perform the classic long
106 // multiplication with 'a' and 'b' being two-digit numbers.
107
108 // a a_hi a_lo
109 // x b => x b_hi b_lo
110 // ---- -----------
111 // c result
112 // We convert 'lo' and 'hi' from 'half_word' to 'word' so multiplication
113 // doesn't overflow.
114 word a_lo = lo(a);
115 word b_lo = lo(b);
116 word a_hi = hi(a);
117 word b_hi = hi(b);
118 word step1 = b_lo * a_lo; // no overflow;
119 word step2 = b_lo * a_hi; // no overflow;
120 word step3 = b_hi * a_lo; // no overflow;
121 word step4 = b_hi * a_hi; // no overflow;
122 word lo_digit = step1;
123 word hi_digit = step4;
124 word no_carry = 0;
125 word carry = 0;
126 [[maybe_unused]] word _ = 0; // unused carry variable.
127 lo_digit = LIBC_NAMESPACE::add_with_carry<word>(lo_digit, shiftl(step2),
128 no_carry, carry);
129 hi_digit =
130 LIBC_NAMESPACE::add_with_carry<word>(hi_digit, shiftr(step2), carry, _);
131 lo_digit = LIBC_NAMESPACE::add_with_carry<word>(lo_digit, shiftl(step3),
132 no_carry, carry);
133 hi_digit =
134 LIBC_NAMESPACE::add_with_carry<word>(hi_digit, shiftr(step3), carry, _);
135 return DoubleWide<word>(lo_digit, hi_digit);
136 }
137}
138
139// In-place 'dst op= rhs' with operation with carry propagation. Returns carry.
140template <typename Function, typename word, size_t N, size_t M>
141LIBC_INLINE constexpr word inplace_binop(Function op_with_carry,
142 cpp::array<word, N> &dst,
143 const cpp::array<word, M> &rhs) {
144 static_assert(N >= M);
145 word carry_out = 0;
146 for (size_t i = 0; i < N; ++i) {
147 const bool has_rhs_value = i < M;
148 const word rhs_value = has_rhs_value ? rhs[i] : 0;
149 const word carry_in = carry_out;
150 dst[i] = op_with_carry(dst[i], rhs_value, carry_in, carry_out);
151 // stop early when rhs is over and no carry is to be propagated.
152 if (!has_rhs_value && carry_out == 0)
153 break;
154 }
155 return carry_out;
156}
157
158// In-place addition. Returns carry.
159template <typename word, size_t N, size_t M>
160LIBC_INLINE constexpr word add_with_carry(cpp::array<word, N> &dst,
161 const cpp::array<word, M> &rhs) {
162 return inplace_binop(LIBC_NAMESPACE::add_with_carry<word>, dst, rhs);
163}
164
165// In-place subtraction. Returns borrow.
166template <typename word, size_t N, size_t M>
167LIBC_INLINE constexpr word sub_with_borrow(cpp::array<word, N> &dst,
168 const cpp::array<word, M> &rhs) {
169 return inplace_binop(LIBC_NAMESPACE::sub_with_borrow<word>, dst, rhs);
170}
171
172// In-place multiply-add. Returns carry.
173// i.e., 'dst += b * c'
174template <typename word, size_t N>
175LIBC_INLINE constexpr word mul_add_with_carry(cpp::array<word, N> &dst, word b,
176 word c) {
177 return add_with_carry(dst, mul2(b, c));
178}
179
180// An array of two elements serving as an accumulator during multiword
181// computations.
182template <typename T> struct Accumulator final : cpp::array<T, 2> {
183 using UP = cpp::array<T, 2>;
184 LIBC_INLINE constexpr Accumulator() : UP({0, 0}) {}
185 LIBC_INLINE constexpr T advance(T carry_in) {
186 auto result = UP::front();
187 UP::front() = UP::back();
188 UP::back() = carry_in;
189 return result;
190 }
191 LIBC_INLINE constexpr T sum() const { return UP::front(); }
192 LIBC_INLINE constexpr T carry() const { return UP::back(); }
193};
194
195// In-place multiplication by a single word. Returns carry.
196template <typename word, size_t N>
197LIBC_INLINE constexpr word scalar_multiply_with_carry(cpp::array<word, N> &dst,
198 word x) {
199 Accumulator<word> acc;
200 for (auto &val : dst) {
201 const word carry = mul_add_with_carry(acc, val, x);
202 val = acc.advance(carry);
203 }
204 return acc.carry();
205}
206
207// Multiplication of 'lhs' by 'rhs' into 'dst'. Returns carry.
208// This function is safe to use for signed numbers.
209// https://stackoverflow.com/a/20793834
210// https://pages.cs.wisc.edu/%7Emarkhill/cs354/Fall2008/beyond354/int.mult.html
211template <typename word, size_t O, size_t M, size_t N>
212LIBC_INLINE constexpr word multiply_with_carry(cpp::array<word, O> &dst,
213 const cpp::array<word, M> &lhs,
214 const cpp::array<word, N> &rhs) {
215 static_assert(O >= M + N);
216 Accumulator<word> acc;
217 for (size_t i = 0; i < O; ++i) {
218 const size_t lower_idx = i < N ? 0 : i - N + 1;
219 const size_t upper_idx = i < M ? i : M - 1;
220 word carry = 0;
221 for (size_t j = lower_idx; j <= upper_idx; ++j)
222 carry += mul_add_with_carry(acc, lhs[j], rhs[i - j]);
223 dst[i] = acc.advance(carry);
224 }
225 return acc.carry();
226}
227
228template <typename word, size_t N>
229LIBC_INLINE constexpr void quick_mul_hi(cpp::array<word, N> &dst,
230 const cpp::array<word, N> &lhs,
231 const cpp::array<word, N> &rhs) {
232 Accumulator<word> acc;
233 word carry = 0;
234 // First round of accumulation for those at N - 1 in the full product.
235 for (size_t i = 0; i < N; ++i)
236 carry += mul_add_with_carry(acc, lhs[i], rhs[N - 1 - i]);
237 for (size_t i = N; i < 2 * N - 1; ++i) {
238 acc.advance(carry);
239 carry = 0;
240 for (size_t j = i - N + 1; j < N; ++j)
241 carry += mul_add_with_carry(acc, lhs[j], rhs[i - j]);
242 dst[i - N] = acc.sum();
243 }
244 dst.back() = acc.carry();
245}
246
247template <typename word, size_t N>
248LIBC_INLINE constexpr bool is_negative(const cpp::array<word, N> &array) {
249 constexpr size_t WORD_BITS = cpp::numeric_limits<word>::digits;
250 return (array.back() >> (WORD_BITS - 1)) != 0;
251}
252// An enum for the shift function below.
253enum Direction { LEFT, RIGHT };
254
255// A bitwise shift on an array of elements.
256// 'offset' must be less than TOTAL_BITS (i.e., sizeof(word) * CHAR_BIT * N)
257// otherwise the behavior is undefined.
258template <Direction direction, bool is_signed, typename word, size_t N>
259LIBC_INLINE constexpr cpp::array<word, N> shift(cpp::array<word, N> array,
260 size_t offset) {
261 static_assert(direction == LEFT || direction == RIGHT);
262 constexpr size_t WORD_BITS = cpp::numeric_limits<word>::digits;
263#if LIBC_HAS_BUILTIN_BIT_CAST
264#ifdef LIBC_TYPES_HAS_INT128
265 constexpr size_t TOTAL_BITS = N * WORD_BITS;
266 if constexpr (TOTAL_BITS == 128 &&
267 __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) {
268 using type = cpp::conditional_t<is_signed, __int128_t, __uint128_t>;
269 auto tmp = cpp::bit_cast<type>(array);
270 if constexpr (direction == LEFT)
271 tmp <<= offset;
272 else
273 tmp >>= offset;
274 return cpp::bit_cast<cpp::array<word, N>>(tmp);
275 }
276#endif
277#endif // LIBC_HAS_BUILTIN_BIT_CAST
278
279 if (LIBC_UNLIKELY(offset == 0))
280 return array;
281 const bool is_neg = is_signed && is_negative(array);
282 constexpr auto at = [](size_t index) -> int {
283 // reverse iteration when direction == LEFT.
284 if constexpr (direction == LEFT)
285 return int(N) - int(index) - 1;
286 return int(index);
287 };
288 const auto safe_get_at = [&](size_t index) -> word {
289 // return appropriate value when accessing out of bound elements.
290 const int i = at(index);
291 if (i < 0)
292 return 0;
293 if (i >= int(N))
294 return is_neg ? cpp::numeric_limits<word>::max() : 0;
295 return array[static_cast<unsigned>(i)];
296 };
297 const size_t index_offset = offset / WORD_BITS;
298 const size_t bit_offset = offset % WORD_BITS;
299#ifdef LIBC_COMPILER_IS_CLANG
300 __builtin_assume(index_offset < N);
301#endif
302 cpp::array<word, N> out = {};
303 for (size_t index = 0; index < N; ++index) {
304 const word part1 = safe_get_at(index + index_offset);
305 const word part2 = safe_get_at(index + index_offset + 1);
306 word &dst = out[static_cast<unsigned>(at(index))];
307 if (bit_offset == 0)
308 dst = part1; // no crosstalk between parts.
309 else if constexpr (direction == LEFT)
310 dst = static_cast<word>((part1 << bit_offset) |
311 (part2 >> (WORD_BITS - bit_offset)));
312 else
313 dst = static_cast<word>((part1 >> bit_offset) |
314 (part2 << (WORD_BITS - bit_offset)));
315 }
316 return out;
317}
318
319#define DECLARE_COUNTBIT(NAME, INDEX_EXPR) \
320 template <typename word, size_t N> \
321 LIBC_INLINE constexpr int NAME(const cpp::array<word, N> &val) { \
322 int bit_count = 0; \
323 for (size_t i = 0; i < N; ++i) { \
324 const int word_count = cpp::NAME<word>(val[INDEX_EXPR]); \
325 bit_count += word_count; \
326 if (word_count != cpp::numeric_limits<word>::digits) \
327 break; \
328 } \
329 return bit_count; \
330 }
331
332DECLARE_COUNTBIT(countr_zero, i) // iterating forward
333DECLARE_COUNTBIT(countr_one, i) // iterating forward
334DECLARE_COUNTBIT(countl_zero, N - i - 1) // iterating backward
335DECLARE_COUNTBIT(countl_one, N - i - 1) // iterating backward
336
337} // namespace multiword
338
339template <size_t Bits, bool Signed, typename WordType = uint64_t>
340struct BigInt {
341private:
342 static_assert(cpp::is_integral_v<WordType> && cpp::is_unsigned_v<WordType>,
343 "WordType must be unsigned integer.");
344
345 struct Division {
346 BigInt quotient{};
347 BigInt remainder{};
348 };
349
350public:
351 using word_type = WordType;
352 using unsigned_type = BigInt<Bits, false, word_type>;
353 using signed_type = BigInt<Bits, true, word_type>;
354
355 LIBC_INLINE_VAR static constexpr bool SIGNED = Signed;
356 LIBC_INLINE_VAR static constexpr size_t BITS = Bits;
357 LIBC_INLINE_VAR
358 static constexpr size_t WORD_SIZE = sizeof(WordType) * CHAR_BIT;
359
360 static_assert(Bits > 0 && Bits % WORD_SIZE == 0,
361 "Number of bits in BigInt should be a multiple of WORD_SIZE.");
362
363 LIBC_INLINE_VAR static constexpr size_t WORD_COUNT = Bits / WORD_SIZE;
364
365 cpp::array<WordType, WORD_COUNT> val;
366
367 LIBC_INLINE constexpr BigInt() = default;
368
369 LIBC_INLINE constexpr BigInt(const BigInt &other) = default;
370
371 template <size_t OtherBits, bool OtherSigned, typename OtherWordType>
372 LIBC_INLINE constexpr BigInt(
373 const BigInt<OtherBits, OtherSigned, OtherWordType> &other)
374 : val{} {
375 using BigIntOther = BigInt<OtherBits, OtherSigned, OtherWordType>;
376 [[maybe_unused]] const bool should_sign_extend = Signed && other.is_neg();
377
378 static_assert(!(Bits == OtherBits && WORD_SIZE != BigIntOther::WORD_SIZE) &&
379 "This is currently untested for casting between bigints with "
380 "the same bit width but different word sizes.");
381
382 if constexpr (BigIntOther::WORD_SIZE < WORD_SIZE) {
383 // OtherWordType is smaller
384 constexpr size_t WORD_SIZE_RATIO = WORD_SIZE / BigIntOther::WORD_SIZE;
385 static_assert(
386 (WORD_SIZE % BigIntOther::WORD_SIZE) == 0 &&
387 "Word types must be multiples of each other for correct conversion.");
388 if constexpr (OtherBits >= Bits) { // truncate
389 // for each big word
390 for (size_t i = 0; i < WORD_COUNT; ++i) {
391 WordType cur_word = 0;
392 // combine WORD_SIZE_RATIO small words into a big word
393 for (size_t j = 0; j < WORD_SIZE_RATIO; ++j)
394 cur_word |= static_cast<WordType>(other[(i * WORD_SIZE_RATIO) + j])
395 << (BigIntOther::WORD_SIZE * j);
396
397 val[i] = cur_word;
398 }
399 } else { // zero or sign extend
400 size_t i = 0;
401 WordType cur_word = 0;
402 // for each small word
403 for (; i < BigIntOther::WORD_COUNT; ++i) {
404 // combine WORD_SIZE_RATIO small words into a big word
405 cur_word |= static_cast<WordType>(other[i])
406 << (BigIntOther::WORD_SIZE * (i % WORD_SIZE_RATIO));
407 // if we've completed a big word, copy it into place and reset
408 if ((i % WORD_SIZE_RATIO) == WORD_SIZE_RATIO - 1) {
409 val[i / WORD_SIZE_RATIO] = cur_word;
410 cur_word = 0;
411 }
412 }
413 // Pretend there are extra words of the correct sign extension as needed
414
415 const WordType extension_bits =
416 should_sign_extend ? cpp::numeric_limits<WordType>::max()
417 : cpp::numeric_limits<WordType>::min();
418 if ((i % WORD_SIZE_RATIO) != 0) {
419 cur_word |= static_cast<WordType>(extension_bits)
420 << (BigIntOther::WORD_SIZE * (i % WORD_SIZE_RATIO));
421 }
422 // Copy the last word into place.
423 val[(i / WORD_SIZE_RATIO)] = cur_word;
424 extend(index: (i / WORD_SIZE_RATIO) + 1, is_neg: should_sign_extend);
425 }
426 } else if constexpr (BigIntOther::WORD_SIZE == WORD_SIZE) {
427 if constexpr (OtherBits >= Bits) { // truncate
428 for (size_t i = 0; i < WORD_COUNT; ++i)
429 val[i] = other[i];
430 } else { // zero or sign extend
431 size_t i = 0;
432 for (; i < BigIntOther::WORD_COUNT; ++i)
433 val[i] = other[i];
434 extend(index: i, is_neg: should_sign_extend);
435 }
436 } else {
437 // OtherWordType is bigger.
438 constexpr size_t WORD_SIZE_RATIO = BigIntOther::WORD_SIZE / WORD_SIZE;
439 static_assert(
440 (BigIntOther::WORD_SIZE % WORD_SIZE) == 0 &&
441 "Word types must be multiples of each other for correct conversion.");
442 if constexpr (OtherBits >= Bits) { // truncate
443 // for each small word
444 for (size_t i = 0; i < WORD_COUNT; ++i) {
445 // split each big word into WORD_SIZE_RATIO small words
446 val[i] = static_cast<WordType>(other[i / WORD_SIZE_RATIO] >>
447 ((i % WORD_SIZE_RATIO) * WORD_SIZE));
448 }
449 } else { // zero or sign extend
450 size_t i = 0;
451 // for each big word
452 for (; i < BigIntOther::WORD_COUNT; ++i) {
453 // split each big word into WORD_SIZE_RATIO small words
454 for (size_t j = 0; j < WORD_SIZE_RATIO; ++j)
455 val[(i * WORD_SIZE_RATIO) + j] =
456 static_cast<WordType>(other[i] >> (j * WORD_SIZE));
457 }
458 extend(index: i * WORD_SIZE_RATIO, is_neg: should_sign_extend);
459 }
460 }
461 }
462
463 // Construct a BigInt from a C array.
464 template <size_t N>
465 LIBC_INLINE constexpr BigInt(const WordType (&nums)[N]) : val{} {
466 static_assert(N == WORD_COUNT);
467 for (size_t i = 0; i < WORD_COUNT; ++i)
468 val[i] = nums[i];
469 }
470
471 LIBC_INLINE constexpr explicit BigInt(
472 const cpp::array<WordType, WORD_COUNT> &words)
473 : val{} {
474 val = words;
475 }
476
477 // Initialize the first word to |v| and the rest to 0.
478 template <typename T, typename = cpp::enable_if_t<cpp::is_integral_v<T>>>
479 LIBC_INLINE constexpr BigInt(T v) : val{} {
480 constexpr size_t T_SIZE = sizeof(T) * CHAR_BIT;
481 const bool is_neg = v < 0;
482 for (size_t i = 0; i < WORD_COUNT; ++i) {
483 if (v == 0) {
484 extend(index: i, is_neg);
485 return;
486 }
487 val[i] = static_cast<WordType>(v);
488 if constexpr (T_SIZE > WORD_SIZE)
489 v >>= WORD_SIZE;
490 else
491 v = 0;
492 }
493 }
494 LIBC_INLINE constexpr BigInt &operator=(const BigInt &other) = default;
495
496 // constants
497 LIBC_INLINE static constexpr BigInt zero() { return BigInt(); }
498 LIBC_INLINE static constexpr BigInt one() { return BigInt(1); }
499 LIBC_INLINE static constexpr BigInt all_ones() { return ~zero(); }
500 LIBC_INLINE static constexpr BigInt min() {
501 BigInt out{};
502 if constexpr (SIGNED)
503 out.set_msb();
504 return out;
505 }
506 LIBC_INLINE static constexpr BigInt max() {
507 BigInt out = all_ones();
508 if constexpr (SIGNED)
509 out.clear_msb();
510 return out;
511 }
512
513 // TODO: Reuse the Sign type.
514 LIBC_INLINE constexpr bool is_neg() const { return SIGNED && get_msb(); }
515
516 template <size_t OtherBits, bool OtherSigned, typename OtherWordType>
517 LIBC_INLINE constexpr explicit
518 operator BigInt<OtherBits, OtherSigned, OtherWordType>() const {
519 return BigInt<OtherBits, OtherSigned, OtherWordType>(this);
520 }
521
522 template <typename T> LIBC_INLINE constexpr explicit operator T() const {
523 return to<T>();
524 }
525
526 template <typename T>
527 LIBC_INLINE constexpr cpp::enable_if_t<
528 cpp::is_integral_v<T> && !cpp::is_same_v<T, bool>, T>
529 to() const {
530 constexpr size_t T_SIZE = sizeof(T) * CHAR_BIT;
531 T lo = static_cast<T>(val[0]);
532 if constexpr (T_SIZE <= WORD_SIZE)
533 return lo;
534 constexpr size_t MAX_COUNT =
535 T_SIZE > Bits ? WORD_COUNT : T_SIZE / WORD_SIZE;
536 for (size_t i = 1; i < MAX_COUNT; ++i)
537 lo += static_cast<T>(static_cast<T>(val[i]) << (WORD_SIZE * i));
538 if constexpr (Signed && (T_SIZE > Bits)) {
539 // Extend sign for negative numbers.
540 constexpr T MASK = (~T(0) << Bits);
541 if (is_neg())
542 lo |= MASK;
543 }
544 return lo;
545 }
546
547 LIBC_INLINE constexpr explicit operator bool() const { return !is_zero(); }
548
549 LIBC_INLINE constexpr bool is_zero() const {
550 for (auto part : val)
551 if (part != 0)
552 return false;
553 return true;
554 }
555
556 // Add 'rhs' to this number and store the result in this number.
557 // Returns the carry value produced by the addition operation.
558 LIBC_INLINE constexpr WordType add_overflow(const BigInt &rhs) {
559 return multiword::add_with_carry(val, rhs.val);
560 }
561
562 LIBC_INLINE constexpr BigInt operator+(const BigInt &other) const {
563 BigInt result = *this;
564 result.add_overflow(rhs: other);
565 return result;
566 }
567
568 // This will only apply when initializing a variable from constant values, so
569 // it will always use the constexpr version of add_with_carry.
570 LIBC_INLINE constexpr BigInt operator+(BigInt &&other) const {
571 // We use addition commutativity to reuse 'other' and prevent allocation.
572 other.add_overflow(rhs: *this); // Returned carry value is ignored.
573 return other;
574 }
575
576 LIBC_INLINE constexpr BigInt &operator+=(const BigInt &other) {
577 add_overflow(rhs: other); // Returned carry value is ignored.
578 return *this;
579 }
580
581 // Subtract 'rhs' to this number and store the result in this number.
582 // Returns the carry value produced by the subtraction operation.
583 LIBC_INLINE constexpr WordType sub_overflow(const BigInt &rhs) {
584 return multiword::sub_with_borrow(val, rhs.val);
585 }
586
587 LIBC_INLINE constexpr BigInt operator-(const BigInt &other) const {
588 BigInt result = *this;
589 result.sub_overflow(rhs: other); // Returned carry value is ignored.
590 return result;
591 }
592
593 LIBC_INLINE constexpr BigInt operator-(BigInt &&other) const {
594 BigInt result = *this;
595 result.sub_overflow(rhs: other); // Returned carry value is ignored.
596 return result;
597 }
598
599 LIBC_INLINE constexpr BigInt &operator-=(const BigInt &other) {
600 // TODO(lntue): Set overflow flag / errno when carry is true.
601 sub_overflow(rhs: other); // Returned carry value is ignored.
602 return *this;
603 }
604
605 // Multiply this number with x and store the result in this number.
606 LIBC_INLINE constexpr WordType mul(WordType x) {
607 return multiword::scalar_multiply_with_carry(val, x);
608 }
609
610 // Return the full product.
611 template <size_t OtherBits>
612 LIBC_INLINE constexpr auto
613 ful_mul(const BigInt<OtherBits, Signed, WordType> &other) const {
614 BigInt<Bits + OtherBits, Signed, WordType> result{};
615 multiword::multiply_with_carry(result.val, val, other.val);
616 return result;
617 }
618
619 LIBC_INLINE constexpr BigInt operator*(const BigInt &other) const {
620 // Perform full mul and truncate.
621 return BigInt(ful_mul(other));
622 }
623
624 // Fast hi part of the full product. The normal product `operator*` returns
625 // `Bits` least significant bits of the full product, while this function will
626 // approximate `Bits` most significant bits of the full product with errors
627 // bounded by:
628 // 0 <= (a.full_mul(b) >> Bits) - a.quick_mul_hi(b)) <= WORD_COUNT - 1.
629 //
630 // An example usage of this is to quickly (but less accurately) compute the
631 // product of (normalized) mantissas of floating point numbers:
632 // (mant_1, mant_2) -> quick_mul_hi -> normalize leading bit
633 // is much more efficient than:
634 // (mant_1, mant_2) -> ful_mul -> normalize leading bit
635 // -> convert back to same Bits width by shifting/rounding,
636 // especially for higher precisions.
637 //
638 // Performance summary:
639 // Number of 64-bit x 64-bit -> 128-bit multiplications performed.
640 // Bits WORD_COUNT ful_mul quick_mul_hi Error bound
641 // 128 2 4 3 1
642 // 196 3 9 6 2
643 // 256 4 16 10 3
644 // 512 8 64 36 7
645 LIBC_INLINE constexpr BigInt quick_mul_hi(const BigInt &other) const {
646 BigInt result{};
647 multiword::quick_mul_hi(result.val, val, other.val);
648 return result;
649 }
650
651 // BigInt(x).pow_n(n) computes x ^ n.
652 // Note 0 ^ 0 == 1.
653 LIBC_INLINE constexpr void pow_n(uint64_t power) {
654 static_assert(!Signed);
655 BigInt result = one();
656 BigInt cur_power = *this;
657 while (power > 0) {
658 if ((power % 2) > 0)
659 result *= cur_power;
660 power >>= 1;
661 cur_power *= cur_power;
662 }
663 *this = result;
664 }
665
666 // Performs inplace signed / unsigned division. Returns remainder if not
667 // dividing by zero.
668 // For signed numbers it behaves like C++ signed integer division.
669 // That is by truncating the fractionnal part
670 // https://stackoverflow.com/a/3602857
671 LIBC_INLINE constexpr cpp::optional<BigInt> div(const BigInt &divider) {
672 if (LIBC_UNLIKELY(divider.is_zero()))
673 return cpp::nullopt;
674 if (LIBC_UNLIKELY(divider == BigInt::one()))
675 return BigInt::zero();
676 Division result;
677 if constexpr (SIGNED)
678 result = divide_signed(dividend: *this, divider);
679 else
680 result = divide_unsigned(dividend: *this, divider);
681 *this = result.quotient;
682 return result.remainder;
683 }
684
685 // Efficiently perform BigInt / (x * 2^e), where x is a half-word-size
686 // unsigned integer, and return the remainder. The main idea is as follow:
687 // Let q = y / (x * 2^e) be the quotient, and
688 // r = y % (x * 2^e) be the remainder.
689 // First, notice that:
690 // r % (2^e) = y % (2^e),
691 // so we just need to focus on all the bits of y that is >= 2^e.
692 // To speed up the shift-and-add steps, we only use x as the divisor, and
693 // performing 32-bit shiftings instead of bit-by-bit shiftings.
694 // Since the remainder of each division step < x < 2^(WORD_SIZE / 2), the
695 // computation of each step is now properly contained within WordType.
696 // And finally we perform some extra alignment steps for the remaining bits.
697 LIBC_INLINE constexpr cpp::optional<BigInt>
698 div_uint_half_times_pow_2(multiword::half_width_t<WordType> x, size_t e) {
699 BigInt remainder{};
700 if (x == 0)
701 return cpp::nullopt;
702 if (e >= Bits) {
703 remainder = *this;
704 *this = BigInt<Bits, false, WordType>();
705 return remainder;
706 }
707 BigInt quotient{};
708 WordType x_word = static_cast<WordType>(x);
709 constexpr size_t LOG2_WORD_SIZE =
710 static_cast<size_t>(cpp::bit_width(value: WORD_SIZE) - 1);
711 constexpr size_t HALF_WORD_SIZE = WORD_SIZE >> 1;
712 constexpr WordType HALF_MASK = ((WordType(1) << HALF_WORD_SIZE) - 1);
713 // lower = smallest multiple of WORD_SIZE that is >= e.
714 size_t lower = ((e >> LOG2_WORD_SIZE) + ((e & (WORD_SIZE - 1)) != 0))
715 << LOG2_WORD_SIZE;
716 // lower_pos is the index of the closest WORD_SIZE-bit chunk >= 2^e.
717 size_t lower_pos = lower / WORD_SIZE;
718 // Keep track of current remainder mod x * 2^(32*i)
719 WordType rem = 0;
720 // pos is the index of the current 64-bit chunk that we are processing.
721 size_t pos = WORD_COUNT;
722
723 // TODO: look into if constexpr(Bits > 256) skip leading zeroes.
724
725 for (size_t q_pos = WORD_COUNT - lower_pos; q_pos > 0; --q_pos) {
726 // q_pos is 1 + the index of the current WORD_SIZE-bit chunk of the
727 // quotient being processed. Performing the division / modulus with
728 // divisor:
729 // x * 2^(WORD_SIZE*q_pos - WORD_SIZE/2),
730 // i.e. using the upper (WORD_SIZE/2)-bit of the current WORD_SIZE-bit
731 // chunk.
732 rem <<= HALF_WORD_SIZE;
733 rem += val[--pos] >> HALF_WORD_SIZE;
734 WordType q_tmp = rem / x_word;
735 rem %= x_word;
736
737 // Performing the division / modulus with divisor:
738 // x * 2^(WORD_SIZE*(q_pos - 1)),
739 // i.e. using the lower (WORD_SIZE/2)-bit of the current WORD_SIZE-bit
740 // chunk.
741 rem <<= HALF_WORD_SIZE;
742 rem += val[pos] & HALF_MASK;
743 quotient.val[q_pos - 1] = (q_tmp << HALF_WORD_SIZE) + rem / x_word;
744 rem %= x_word;
745 }
746
747 // So far, what we have is:
748 // quotient = y / (x * 2^lower), and
749 // rem = (y % (x * 2^lower)) / 2^lower.
750 // If (lower > e), we will need to perform an extra adjustment of the
751 // quotient and remainder, namely:
752 // y / (x * 2^e) = [ y / (x * 2^lower) ] * 2^(lower - e) +
753 // + (rem * 2^(lower - e)) / x
754 // (y % (x * 2^e)) / 2^e = (rem * 2^(lower - e)) % x
755 size_t last_shift = lower - e;
756
757 if (last_shift > 0) {
758 // quotient * 2^(lower - e)
759 quotient <<= last_shift;
760 WordType q_tmp = 0;
761 WordType d = val[--pos];
762 if (last_shift >= HALF_WORD_SIZE) {
763 // The shifting (rem * 2^(lower - e)) might overflow WordTyoe, so we
764 // perform a HALF_WORD_SIZE-bit shift first.
765 rem <<= HALF_WORD_SIZE;
766 rem += d >> HALF_WORD_SIZE;
767 d &= HALF_MASK;
768 q_tmp = rem / x_word;
769 rem %= x_word;
770 last_shift -= HALF_WORD_SIZE;
771 } else {
772 // Only use the upper HALF_WORD_SIZE-bit of the current WORD_SIZE-bit
773 // chunk.
774 d >>= HALF_WORD_SIZE;
775 }
776
777 if (last_shift > 0) {
778 rem <<= HALF_WORD_SIZE;
779 rem += d;
780 q_tmp <<= last_shift;
781 x_word <<= HALF_WORD_SIZE - last_shift;
782 q_tmp += rem / x_word;
783 rem %= x_word;
784 }
785
786 quotient.val[0] += q_tmp;
787
788 if (lower - e <= HALF_WORD_SIZE) {
789 // The remainder rem * 2^(lower - e) might overflow to the higher
790 // WORD_SIZE-bit chunk.
791 if (pos < WORD_COUNT - 1) {
792 remainder[pos + 1] = rem >> HALF_WORD_SIZE;
793 }
794 remainder[pos] = (rem << HALF_WORD_SIZE) + (val[pos] & HALF_MASK);
795 } else {
796 remainder[pos] = rem;
797 }
798
799 } else {
800 remainder[pos] = rem;
801 }
802
803 // Set the remaining lower bits of the remainder.
804 for (; pos > 0; --pos) {
805 remainder[pos - 1] = val[pos - 1];
806 }
807
808 *this = quotient;
809 return remainder;
810 }
811
812 LIBC_INLINE constexpr BigInt operator/(const BigInt &other) const {
813 BigInt result(*this);
814 result.div(divider: other);
815 return result;
816 }
817
818 LIBC_INLINE constexpr BigInt &operator/=(const BigInt &other) {
819 div(divider: other);
820 return *this;
821 }
822
823 LIBC_INLINE constexpr BigInt operator%(const BigInt &other) const {
824 BigInt result(*this);
825 return *result.div(divider: other);
826 }
827
828 LIBC_INLINE constexpr BigInt operator%=(const BigInt &other) {
829 *this = *this % other;
830 return *this;
831 }
832
833 LIBC_INLINE constexpr BigInt &operator*=(const BigInt &other) {
834 *this = *this * other;
835 return *this;
836 }
837
838 LIBC_INLINE constexpr BigInt &operator<<=(size_t s) {
839 val = multiword::shift<multiword::LEFT, SIGNED>(val, s);
840 return *this;
841 }
842
843 LIBC_INLINE constexpr BigInt operator<<(size_t s) const {
844 return BigInt(multiword::shift<multiword::LEFT, SIGNED>(val, s));
845 }
846
847 LIBC_INLINE constexpr BigInt &operator>>=(size_t s) {
848 val = multiword::shift<multiword::RIGHT, SIGNED>(val, s);
849 return *this;
850 }
851
852 LIBC_INLINE constexpr BigInt operator>>(size_t s) const {
853 return BigInt(multiword::shift<multiword::RIGHT, SIGNED>(val, s));
854 }
855
856#define DEFINE_BINOP(OP) \
857 LIBC_INLINE friend constexpr BigInt operator OP(const BigInt &lhs, \
858 const BigInt &rhs) { \
859 BigInt result{}; \
860 for (size_t i = 0; i < WORD_COUNT; ++i) \
861 result[i] = lhs[i] OP rhs[i]; \
862 return result; \
863 } \
864 LIBC_INLINE friend constexpr BigInt operator OP## = \
865 (BigInt & lhs, const BigInt &rhs) { \
866 for (size_t i = 0; i < WORD_COUNT; ++i) \
867 lhs[i] OP## = rhs[i]; \
868 return lhs; \
869 }
870
871 DEFINE_BINOP(&) // & and &=
872 DEFINE_BINOP(|) // | and |=
873 DEFINE_BINOP(^) // ^ and ^=
874#undef DEFINE_BINOP
875
876 LIBC_INLINE constexpr BigInt operator~() const {
877 BigInt result{};
878 for (size_t i = 0; i < WORD_COUNT; ++i)
879 result[i] = static_cast<WordType>(~val[i]);
880 return result;
881 }
882
883 LIBC_INLINE constexpr BigInt operator-() const {
884 BigInt result(*this);
885 result.negate();
886 return result;
887 }
888
889 LIBC_INLINE friend constexpr bool operator==(const BigInt &lhs,
890 const BigInt &rhs) {
891 for (size_t i = 0; i < WORD_COUNT; ++i)
892 if (lhs.val[i] != rhs.val[i])
893 return false;
894 return true;
895 }
896
897 LIBC_INLINE friend constexpr bool operator!=(const BigInt &lhs,
898 const BigInt &rhs) {
899 return !(lhs == rhs);
900 }
901
902 LIBC_INLINE friend constexpr bool operator>(const BigInt &lhs,
903 const BigInt &rhs) {
904 return cmp(lhs, rhs) > 0;
905 }
906 LIBC_INLINE friend constexpr bool operator>=(const BigInt &lhs,
907 const BigInt &rhs) {
908 return cmp(lhs, rhs) >= 0;
909 }
910 LIBC_INLINE friend constexpr bool operator<(const BigInt &lhs,
911 const BigInt &rhs) {
912 return cmp(lhs, rhs) < 0;
913 }
914 LIBC_INLINE friend constexpr bool operator<=(const BigInt &lhs,
915 const BigInt &rhs) {
916 return cmp(lhs, rhs) <= 0;
917 }
918
919 LIBC_INLINE constexpr BigInt &operator++() {
920 increment();
921 return *this;
922 }
923
924 LIBC_INLINE constexpr BigInt operator++(int) {
925 BigInt oldval(*this);
926 increment();
927 return oldval;
928 }
929
930 LIBC_INLINE constexpr BigInt &operator--() {
931 decrement();
932 return *this;
933 }
934
935 LIBC_INLINE constexpr BigInt operator--(int) {
936 BigInt oldval(*this);
937 decrement();
938 return oldval;
939 }
940
941 // Return the i-th word of the number.
942 LIBC_INLINE constexpr const WordType &operator[](size_t i) const {
943 return val[i];
944 }
945
946 // Return the i-th word of the number.
947 LIBC_INLINE constexpr WordType &operator[](size_t i) { return val[i]; }
948
949 // Return the i-th bit of the number.
950 LIBC_INLINE constexpr bool get_bit(size_t i) const {
951 const size_t word_index = i / WORD_SIZE;
952 return 1 & (val[word_index] >> (i % WORD_SIZE));
953 }
954
955 // Set the i-th bit of the number.
956 LIBC_INLINE constexpr void set_bit(size_t i) {
957 const size_t word_index = i / WORD_SIZE;
958 val[word_index] |= WordType(1) << (i % WORD_SIZE);
959 }
960
961private:
962 LIBC_INLINE friend constexpr int cmp(const BigInt &lhs, const BigInt &rhs) {
963 constexpr auto compare = [](WordType a, WordType b) {
964 return a == b ? 0 : a > b ? 1 : -1;
965 };
966 if constexpr (Signed) {
967 const bool lhs_is_neg = lhs.is_neg();
968 const bool rhs_is_neg = rhs.is_neg();
969 if (lhs_is_neg != rhs_is_neg)
970 return rhs_is_neg ? 1 : -1;
971 }
972 for (size_t i = WORD_COUNT; i-- > 0;)
973 if (auto cmp = compare(lhs[i], rhs[i]); cmp != 0)
974 return cmp;
975 return 0;
976 }
977
978 LIBC_INLINE constexpr void bitwise_not() {
979 for (auto &part : val)
980 part = static_cast<WordType>(~part);
981 }
982
983 LIBC_INLINE constexpr void negate() {
984 bitwise_not();
985 increment();
986 }
987
988 LIBC_INLINE constexpr void increment() {
989 multiword::add_with_carry(val, cpp::array<WordType, 1>{1});
990 }
991
992 LIBC_INLINE constexpr void decrement() {
993 multiword::sub_with_borrow(val, cpp::array<WordType, 1>{1});
994 }
995
996 LIBC_INLINE constexpr void extend(size_t index, bool is_neg) {
997 const WordType value = is_neg ? cpp::numeric_limits<WordType>::max()
998 : cpp::numeric_limits<WordType>::min();
999 for (size_t i = index; i < WORD_COUNT; ++i)
1000 val[i] = value;
1001 }
1002
1003 LIBC_INLINE constexpr bool get_msb() const {
1004 return val.back() >> (WORD_SIZE - 1);
1005 }
1006
1007 LIBC_INLINE constexpr void set_msb() {
1008 val.back() |= mask_leading_ones<WordType, 1>();
1009 }
1010
1011 LIBC_INLINE constexpr void clear_msb() {
1012 val.back() &= mask_trailing_ones<WordType, WORD_SIZE - 1>();
1013 }
1014 LIBC_INLINE constexpr static Division divide_unsigned(const BigInt &dividend,
1015 const BigInt &divider) {
1016 BigInt remainder = dividend;
1017 BigInt quotient{};
1018 if (remainder >= divider) {
1019 BigInt subtractor = divider;
1020 int cur_bit = multiword::countl_zero(subtractor.val) -
1021 multiword::countl_zero(remainder.val);
1022 subtractor <<= static_cast<size_t>(cur_bit);
1023 for (; cur_bit >= 0 && remainder > 0; --cur_bit, subtractor >>= 1) {
1024 if (remainder < subtractor)
1025 continue;
1026 remainder -= subtractor;
1027 quotient.set_bit(static_cast<size_t>(cur_bit));
1028 }
1029 }
1030 return Division{quotient, remainder};
1031 }
1032
1033 LIBC_INLINE constexpr static Division divide_signed(const BigInt &dividend,
1034 const BigInt &divider) {
1035 // Special case because it is not possible to negate the min value of a
1036 // signed integer.
1037 if (dividend == min() && divider == min())
1038 return Division{one(), zero()};
1039 // 1. Convert the dividend and divisor to unsigned representation.
1040 unsigned_type udividend(dividend);
1041 unsigned_type udivider(divider);
1042 // 2. Negate the dividend if it's negative, and similarly for the divisor.
1043 const bool dividend_is_neg = dividend.is_neg();
1044 const bool divider_is_neg = divider.is_neg();
1045 if (dividend_is_neg)
1046 udividend.negate();
1047 if (divider_is_neg)
1048 udivider.negate();
1049 // 3. Use unsigned multiword division algorithm.
1050 const auto unsigned_result = divide_unsigned(dividend: udividend, divider: udivider);
1051 // 4. Convert the quotient and remainder to signed representation.
1052 Division result;
1053 result.quotient = signed_type(unsigned_result.quotient);
1054 result.remainder = signed_type(unsigned_result.remainder);
1055 // 5. Negate the quotient if the dividend and divisor had opposite signs.
1056 if (dividend_is_neg != divider_is_neg)
1057 result.quotient.negate();
1058 // 6. Negate the remainder if the dividend was negative.
1059 if (dividend_is_neg)
1060 result.remainder.negate();
1061 return result;
1062 }
1063
1064 friend signed_type;
1065 friend unsigned_type;
1066};
1067
1068namespace internal {
1069// We default BigInt's WordType to 'uint64_t' or 'uint32_t' depending on type
1070// availability.
1071template <size_t Bits>
1072struct WordTypeSelector : cpp::type_identity<
1073#ifdef LIBC_TYPES_HAS_INT64
1074 uint64_t
1075#else
1076 uint32_t
1077#endif // LIBC_TYPES_HAS_INT64
1078 > {
1079};
1080// Except if we request 16 or 32 bits explicitly.
1081template <> struct WordTypeSelector<16> : cpp::type_identity<uint16_t> {};
1082template <> struct WordTypeSelector<32> : cpp::type_identity<uint32_t> {};
1083template <> struct WordTypeSelector<96> : cpp::type_identity<uint32_t> {};
1084
1085template <size_t Bits>
1086using WordTypeSelectorT = typename WordTypeSelector<Bits>::type;
1087} // namespace internal
1088
1089template <size_t Bits>
1090using UInt = BigInt<Bits, false, internal::WordTypeSelectorT<Bits>>;
1091
1092template <size_t Bits>
1093using Int = BigInt<Bits, true, internal::WordTypeSelectorT<Bits>>;
1094
1095// Provides limits of BigInt.
1096template <size_t Bits, bool Signed, typename T>
1097struct cpp::numeric_limits<BigInt<Bits, Signed, T>> {
1098 LIBC_INLINE static constexpr BigInt<Bits, Signed, T> max() {
1099 return BigInt<Bits, Signed, T>::max();
1100 }
1101 LIBC_INLINE static constexpr BigInt<Bits, Signed, T> min() {
1102 return BigInt<Bits, Signed, T>::min();
1103 }
1104 // Meant to match std::numeric_limits interface.
1105 // NOLINTNEXTLINE(readability-identifier-naming)
1106 LIBC_INLINE_VAR static constexpr int digits = Bits - Signed;
1107};
1108
1109// type traits to determine whether a T is a BigInt.
1110template <typename T> struct is_big_int : cpp::false_type {};
1111
1112template <size_t Bits, bool Signed, typename T>
1113struct is_big_int<BigInt<Bits, Signed, T>> : cpp::true_type {};
1114
1115template <class T>
1116LIBC_INLINE_VAR constexpr bool is_big_int_v = is_big_int<T>::value;
1117
1118// extensions of type traits to include BigInt
1119
1120// is_integral_or_big_int
1121template <typename T>
1122struct is_integral_or_big_int
1123 : cpp::bool_constant<(cpp::is_integral_v<T> || is_big_int_v<T>)> {};
1124
1125template <typename T>
1126LIBC_INLINE_VAR constexpr bool is_integral_or_big_int_v =
1127 is_integral_or_big_int<T>::value;
1128
1129// make_big_int_unsigned
1130template <typename T> struct make_big_int_unsigned;
1131
1132template <size_t Bits, bool Signed, typename T>
1133struct make_big_int_unsigned<BigInt<Bits, Signed, T>>
1134 : cpp::type_identity<BigInt<Bits, false, T>> {};
1135
1136template <typename T>
1137using make_big_int_unsigned_t = typename make_big_int_unsigned<T>::type;
1138
1139// make_big_int_signed
1140template <typename T> struct make_big_int_signed;
1141
1142template <size_t Bits, bool Signed, typename T>
1143struct make_big_int_signed<BigInt<Bits, Signed, T>>
1144 : cpp::type_identity<BigInt<Bits, true, T>> {};
1145
1146template <typename T>
1147using make_big_int_signed_t = typename make_big_int_signed<T>::type;
1148
1149// make_integral_or_big_int_unsigned
1150template <typename T, class = void> struct make_integral_or_big_int_unsigned;
1151
1152template <typename T>
1153struct make_integral_or_big_int_unsigned<
1154 T, cpp::enable_if_t<cpp::is_integral_v<T>>> : cpp::make_unsigned<T> {};
1155
1156template <typename T>
1157struct make_integral_or_big_int_unsigned<T, cpp::enable_if_t<is_big_int_v<T>>>
1158 : make_big_int_unsigned<T> {};
1159
1160template <typename T>
1161using make_integral_or_big_int_unsigned_t =
1162 typename make_integral_or_big_int_unsigned<T>::type;
1163
1164// make_integral_or_big_int_signed
1165template <typename T, class = void> struct make_integral_or_big_int_signed;
1166
1167template <typename T>
1168struct make_integral_or_big_int_signed<T,
1169 cpp::enable_if_t<cpp::is_integral_v<T>>>
1170 : cpp::make_signed<T> {};
1171
1172template <typename T>
1173struct make_integral_or_big_int_signed<T, cpp::enable_if_t<is_big_int_v<T>>>
1174 : make_big_int_signed<T> {};
1175
1176template <typename T>
1177using make_integral_or_big_int_signed_t =
1178 typename make_integral_or_big_int_signed<T>::type;
1179
1180// is_unsigned_integral_or_big_int
1181template <typename T>
1182struct is_unsigned_integral_or_big_int
1183 : cpp::bool_constant<
1184 cpp::is_same_v<T, make_integral_or_big_int_unsigned_t<T>>> {};
1185
1186template <typename T>
1187// Meant to look like <type_traits> helper variable templates.
1188// NOLINTNEXTLINE(readability-identifier-naming)
1189LIBC_INLINE_VAR constexpr bool is_unsigned_integral_or_big_int_v =
1190 is_unsigned_integral_or_big_int<T>::value;
1191
1192namespace cpp {
1193
1194// Specialization of cpp::popcount ('bit.h') for BigInt.
1195template <typename T>
1196[[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t<is_big_int_v<T>, int>
1197popcount(T value) {
1198 int bits = 0;
1199 for (auto word : value.val)
1200 if (word)
1201 bits += popcount(word);
1202 return bits;
1203}
1204
1205// Specialization of cpp::has_single_bit ('bit.h') for BigInt.
1206template <typename T>
1207[[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t<is_big_int_v<T>, bool>
1208has_single_bit(T value) {
1209 int bits = 0;
1210 for (auto word : value.val) {
1211 if (word == 0)
1212 continue;
1213 bits += popcount(word);
1214 if (bits > 1)
1215 return false;
1216 }
1217 return bits == 1;
1218}
1219
1220// Specialization of cpp::countr_zero ('bit.h') for BigInt.
1221template <typename T>
1222[[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t<is_big_int_v<T>, int>
1223countr_zero(const T &value) {
1224 return multiword::countr_zero(value.val);
1225}
1226
1227// Specialization of cpp::countl_zero ('bit.h') for BigInt.
1228template <typename T>
1229[[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t<is_big_int_v<T>, int>
1230countl_zero(const T &value) {
1231 return multiword::countl_zero(value.val);
1232}
1233
1234// Specialization of cpp::countl_one ('bit.h') for BigInt.
1235template <typename T>
1236[[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t<is_big_int_v<T>, int>
1237countl_one(T value) {
1238 return multiword::countl_one(value.val);
1239}
1240
1241// Specialization of cpp::countr_one ('bit.h') for BigInt.
1242template <typename T>
1243[[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t<is_big_int_v<T>, int>
1244countr_one(T value) {
1245 return multiword::countr_one(value.val);
1246}
1247
1248// Specialization of cpp::bit_width ('bit.h') for BigInt.
1249template <typename T>
1250[[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t<is_big_int_v<T>, int>
1251bit_width(T value) {
1252 return cpp::numeric_limits<T>::digits - cpp::countl_zero(value);
1253}
1254
1255// Forward-declare rotr so that rotl can use it.
1256template <typename T>
1257[[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t<is_big_int_v<T>, T>
1258rotr(T value, int rotate);
1259
1260// Specialization of cpp::rotl ('bit.h') for BigInt.
1261template <typename T>
1262[[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t<is_big_int_v<T>, T>
1263rotl(T value, int rotate) {
1264 constexpr int N = cpp::numeric_limits<T>::digits;
1265 rotate = rotate % N;
1266 if (!rotate)
1267 return value;
1268 if (rotate < 0)
1269 return cpp::rotr<T>(value, -rotate);
1270 return (value << static_cast<size_t>(rotate)) |
1271 (value >> (N - static_cast<size_t>(rotate)));
1272}
1273
1274// Specialization of cpp::rotr ('bit.h') for BigInt.
1275template <typename T>
1276[[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t<is_big_int_v<T>, T>
1277rotr(T value, int rotate) {
1278 constexpr int N = cpp::numeric_limits<T>::digits;
1279 rotate = rotate % N;
1280 if (!rotate)
1281 return value;
1282 if (rotate < 0)
1283 return cpp::rotl<T>(value, -rotate);
1284 return (value >> static_cast<size_t>(rotate)) |
1285 (value << (N - static_cast<size_t>(rotate)));
1286}
1287
1288} // namespace cpp
1289
1290// Specialization of mask_trailing_ones ('math_extras.h') for BigInt.
1291template <typename T, size_t count>
1292LIBC_INLINE constexpr cpp::enable_if_t<is_big_int_v<T>, T>
1293mask_trailing_ones() {
1294 static_assert(!T::SIGNED && count <= T::BITS);
1295 if (count == T::BITS)
1296 return T::all_ones();
1297 constexpr size_t QUOTIENT = count / T::WORD_SIZE;
1298 constexpr size_t REMAINDER = count % T::WORD_SIZE;
1299 T out{};
1300 for (size_t i = 0; i <= QUOTIENT; ++i)
1301 out[i] = i < QUOTIENT
1302 ? cpp::numeric_limits<typename T::word_type>::max()
1303 : mask_trailing_ones<typename T::word_type, REMAINDER>();
1304 return out;
1305}
1306
1307// Specialization of mask_leading_ones ('math_extras.h') for BigInt.
1308template <typename T, size_t count>
1309LIBC_INLINE constexpr cpp::enable_if_t<is_big_int_v<T>, T> mask_leading_ones() {
1310 static_assert(!T::SIGNED && count <= T::BITS);
1311 if (count == T::BITS)
1312 return T::all_ones();
1313 constexpr size_t QUOTIENT = (T::BITS - count - 1U) / T::WORD_SIZE;
1314 constexpr size_t REMAINDER = count % T::WORD_SIZE;
1315 T out{};
1316 for (size_t i = QUOTIENT; i < T::WORD_COUNT; ++i)
1317 out[i] = i > QUOTIENT
1318 ? cpp::numeric_limits<typename T::word_type>::max()
1319 : mask_leading_ones<typename T::word_type, REMAINDER>();
1320 return out;
1321}
1322
1323// Specialization of mask_trailing_zeros ('math_extras.h') for BigInt.
1324template <typename T, size_t count>
1325LIBC_INLINE constexpr cpp::enable_if_t<is_big_int_v<T>, T>
1326mask_trailing_zeros() {
1327 return mask_leading_ones<T, T::BITS - count>();
1328}
1329
1330// Specialization of mask_leading_zeros ('math_extras.h') for BigInt.
1331template <typename T, size_t count>
1332LIBC_INLINE constexpr cpp::enable_if_t<is_big_int_v<T>, T>
1333mask_leading_zeros() {
1334 return mask_trailing_ones<T, T::BITS - count>();
1335}
1336
1337// Specialization of count_zeros ('math_extras.h') for BigInt.
1338template <typename T>
1339[[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t<is_big_int_v<T>, int>
1340count_zeros(T value) {
1341 return cpp::popcount(~value);
1342}
1343
1344// Specialization of first_leading_zero ('math_extras.h') for BigInt.
1345template <typename T>
1346[[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t<is_big_int_v<T>, int>
1347first_leading_zero(T value) {
1348 return value == cpp::numeric_limits<T>::max() ? 0
1349 : cpp::countl_one(value) + 1;
1350}
1351
1352// Specialization of first_leading_one ('math_extras.h') for BigInt.
1353template <typename T>
1354[[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t<is_big_int_v<T>, int>
1355first_leading_one(T value) {
1356 return first_leading_zero(~value);
1357}
1358
1359// Specialization of first_trailing_zero ('math_extras.h') for BigInt.
1360template <typename T>
1361[[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t<is_big_int_v<T>, int>
1362first_trailing_zero(T value) {
1363 return value == cpp::numeric_limits<T>::max() ? 0
1364 : cpp::countr_zero(~value) + 1;
1365}
1366
1367// Specialization of first_trailing_one ('math_extras.h') for BigInt.
1368template <typename T>
1369[[nodiscard]] LIBC_INLINE constexpr cpp::enable_if_t<is_big_int_v<T>, int>
1370first_trailing_one(T value) {
1371 return value == 0 ? 0 : cpp::countr_zero(value) + 1;
1372}
1373
1374static_assert(LIBC_NAMESPACE::cpp::is_trivially_constructible<
1375 LIBC_NAMESPACE::BigInt<128, false>>::value);
1376static_assert(LIBC_NAMESPACE::cpp::is_trivially_copyable<
1377 LIBC_NAMESPACE::BigInt<128, false>>::value);
1378
1379} // namespace LIBC_NAMESPACE_DECL
1380
1381#endif // LLVM_LIBC_SRC___SUPPORT_BIG_INT_H
1382