[libc-commits] [libc] [llvm] [libc] Refactor `BigInt` (PR #86137)
via libc-commits
libc-commits at lists.llvm.org
Wed Mar 27 21:00:07 PDT 2024
================
@@ -559,57 +566,17 @@ struct BigInt {
// That is by truncating the fractionnal part
// https://stackoverflow.com/a/3602857
LIBC_INLINE constexpr cpp::optional<BigInt> div(const BigInt ÷r) {
- auto ÷nd = *this;
- if constexpr (SIGNED) {
- // Signed Multiword Division
- // 1. Negate the dividend it it is negative, and similarly for the
- // divisor.
- // 2. Convert the divident and divisor to unsigned representation.
- // 3. Use unsigned multiword division algorithm.
- // 4. Convert the quotient and remainder to signed representation.
- // 5. Negate the quotient if the dividend and divisor had opposite signs.
- // 6. Negate the remainder if the dividend was negative.
- const bool dividend_is_neg = dividend.is_neg();
- const bool divider_is_neg = divider.is_neg();
- unsigned_type udividend(dividend);
- unsigned_type udivider(divider);
- if (dividend_is_neg)
- udividend.negate();
- if (divider_is_neg)
- udivider.negate();
- auto maybe_remainder = udividend.div(udivider);
- if (!maybe_remainder)
- return cpp::nullopt;
- unsigned_type remainder = *maybe_remainder;
- if (dividend_is_neg != divider_is_neg)
- udividend.negate(); // this is the quotient
- dividend = signed_type(udividend);
- if (dividend_is_neg)
- remainder.negate();
- return signed_type(remainder);
- } else {
- BigInt remainder;
- if (divider.is_zero())
- return cpp::nullopt;
- if (divider == 1)
- return remainder;
- BigInt quotient;
- if (dividend >= divider) {
- BigInt subtractor = divider;
- int cur_bit = multiword::countl_zero(subtractor.val) -
- multiword::countl_zero(dividend.val);
- subtractor <<= cur_bit;
- for (; cur_bit >= 0 && dividend > 0; --cur_bit, subtractor >>= 1) {
- if (dividend < subtractor)
- continue;
- dividend -= subtractor;
- quotient.set_bit(cur_bit);
- }
- }
- remainder = dividend;
- dividend = quotient;
- return remainder;
- }
+ if (divider.is_zero())
+ return cpp::nullopt;
+ if (divider == 1)
----------------
lntue wrote:
Do you want to use `LIBC_UNLIKELY` to provide hints for these 2 cases?
https://github.com/llvm/llvm-project/pull/86137
More information about the libc-commits
mailing list