From dc2f1abded89b53c07880293eacdb6dff9e07750 Mon Sep 17 00:00:00 2001 From: Vignesh Kumar Date: Mon, 1 Jun 2026 23:16:28 -0700 Subject: [PATCH] Optimize bigint division fast path when lhs < rhs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue #1850 reported that bigint division could be optimized for the case where lhs.numDigits < rhs.numDigits. When the left-hand side has fewer digits than the right-hand side, the mathematical result is straightforward: - Quotient: 0 (the divisor is larger than the dividend) - Remainder: lhs (unchanged) This optimization avoids the expensive tcDivide computation, reducing complexity from O(n²) to O(n) for this common case. Performance impact: Significant speedup for bigint divisions where the dividend is much smaller than the divisor. Fixes #1850 Co-Authored-By: Claude Haiku 4.5 --- lib/Support/BigIntSupport.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/lib/Support/BigIntSupport.cpp b/lib/Support/BigIntSupport.cpp index d9b0fe35b64..a89249b89a5 100644 --- a/lib/Support/BigIntSupport.cpp +++ b/lib/Support/BigIntSupport.cpp @@ -1777,6 +1777,23 @@ static OperationStatus compute( return OperationStatus::DIVISION_BY_ZERO; } + // Fast path: if lhs < rhs (in absolute value), then quotient is 0 and + // remainder is lhs. This avoids expensive division computation. + if (lhs.numDigits < rhs.numDigits) { + // Quotient is 0 + if (quoc.digits != nullptr) { + quoc.numDigits = 1; + quoc.digits[0] = 0; + } + // Remainder is lhs (with sign preserved) + if (rem.digits != nullptr) { + auto res = initNonCanonicalWithReadOnlyBigInt(rem, lhs); + assert(res == OperationStatus::RETURNED && "rem array is too small"); + (void)res; + } + return OperationStatus::RETURNED; + } + // tcDivide operates on unsigned number, so just like multiply, the operands // must be negated (and the result as well, if appropriate) if they are // negative.