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