[llvm] [LegalizeTypes] Expand UDIV/UREM by constant via chunk summation (PR #146238)

Simon Pilgrim via llvm-commits llvm-commits at lists.llvm.org
Sat Mar 14 05:12:22 PDT 2026


================
@@ -8233,6 +8231,74 @@ bool TargetLowering::expandDIVREMByConstant(SDNode *N,
                               DAG.getConstant(0, dl, HiLoVT));
       Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum, Carry);
     }
+  } else {
+    // If we cannot split in two halves, look for a smaller chunk width W
+    // such that (1 << W) % Divisor == 1.
+    const APInt &Divisor = CN->getAPIntValue();
+    unsigned BitWidth = VT.getScalarSizeInBits();
+    unsigned BestChunkWidth = 0;
+
+    // Determine the legal scalar integer type for chunk operations (e.g., i64).
+    EVT LegalVT = getTypeToTransformTo(*DAG.getContext(), VT);
+    unsigned LegalWidth = LegalVT.getScalarSizeInBits();
+    unsigned MaxChunk = std::min<unsigned>(LegalWidth, BitWidth);
+
+    // Precompute 2^MaxChunk mod Divisor
+    APInt Mod(Divisor.getBitWidth(), 1);
+    for (unsigned k = 0; k < MaxChunk; ++k)
+      Mod = Mod.shl(1).urem(Divisor);
+
+    // Since Divisor is odd, modular inverse of 2 is (Divisor + 1) / 2
+    APInt Inv2 = (Divisor + 1).lshr(1);
+
+    // Search for W where 2^W % Divisor == 1
+    for (unsigned i = MaxChunk; i > MaxChunk / 2; --i) {
----------------
RKSimon wrote:

(style)
```suggestion
    for (unsigned I = MaxChunk, E = MaxChunk / 2; I >E; --I) {
```

https://github.com/llvm/llvm-project/pull/146238


More information about the llvm-commits mailing list