[llvm] [TargetLowering] Refactor expandDIVREMByConstant to share more code. NFC (PR #187582)

Craig Topper via llvm-commits llvm-commits at lists.llvm.org
Sat Mar 21 09:38:25 PDT 2026


https://github.com/topperc updated https://github.com/llvm/llvm-project/pull/187582

>From 23652b9f6faee0668e02e796c5445a0e83c0e707 Mon Sep 17 00:00:00 2001
From: Craig Topper <craig.topper at sifive.com>
Date: Thu, 19 Mar 2026 09:08:46 -0700
Subject: [PATCH 1/5] Replace LegalVT with HiLoVT.

---
 .../CodeGen/SelectionDAG/TargetLowering.cpp   | 37 +++++++------------
 1 file changed, 13 insertions(+), 24 deletions(-)

diff --git a/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp b/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
index 9e4f3789a01e2..860319b974588 100644
--- a/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
+++ b/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
@@ -8243,23 +8243,18 @@ bool TargetLowering::expandDIVREMByConstant(SDNode *N,
     unsigned BitWidth = VT.getScalarSizeInBits();
     unsigned BestChunkWidth = 0;
 
-    // Determine the legal scalar integer type for chunk operations.
-    EVT LegalVT = getTypeToTransformTo(*DAG.getContext(), VT);
-    unsigned LegalWidth = LegalVT.getScalarSizeInBits();
-    unsigned MaxChunk = std::min<unsigned>(LegalWidth, BitWidth);
-
     // Search for I where 2^I % Divisor == 1
-    for (unsigned I = MaxChunk, E = MaxChunk / 2; I > E; --I) {
+    for (unsigned I = HBitWidth - 1, E = HBitWidth / 2; I > E; --I) {
       APInt Mod = APInt::getOneBitSet(Divisor.getBitWidth(), I).urem(Divisor);
 
       if (Mod.isOne()) {
-        // Ensure (NumChunks * MaxChunkValue) doesn't overflow LegalVT
+        // Ensure (NumChunks * MaxChunkValue) doesn't overflow HiLoVT
         unsigned NumChunks = divideCeil(BitWidth, I);
 
-        // Ensure the sum won't overflow the hardware register (LegalWidth).
+        // Ensure the sum won't overflow the hardware register (HBitWidth).
         // Summing N chunks adds ceil(log2(N)) extra carry bits to the width.
         // Safety check: Base Chunk Width (I) + Carry Bits <= Register Width.
-        if (I + llvm::bit_width(NumChunks - 1) <= LegalWidth) {
+        if (I + llvm::bit_width(NumChunks - 1) <= HBitWidth) {
           BestChunkWidth = I;
           break;
         }
@@ -8274,9 +8269,9 @@ bool TargetLowering::expandDIVREMByConstant(SDNode *N,
     if (TrailingZeros) {
       // Save the shifted off bits if we need the remainder.
       if (Opcode != ISD::UDIV) {
-        APInt Mask = APInt::getLowBitsSet(BitWidth, TrailingZeros);
+        APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros);
         PartialRem =
-            DAG.getNode(ISD::AND, dl, VT, In, DAG.getConstant(Mask, dl, VT));
+            DAG.getNode(ISD::AND, dl, HiLoVT, LL, DAG.getConstant(Mask, dl, HiLoVT));
       }
       EVT ShiftVT = getShiftAmountTy(VT, DAG.getDataLayout());
       In = DAG.getNode(ISD::SRL, dl, VT, In,
@@ -8287,28 +8282,23 @@ bool TargetLowering::expandDIVREMByConstant(SDNode *N,
       std::tie(LL, LH) = DAG.SplitScalar(In, dl, HiLoVT, HiLoVT);
     }
 
-    SDValue TotalSum = DAG.getConstant(0, dl, LegalVT);
+    Sum = DAG.getConstant(0, dl, HiLoVT);
     SDValue Mask = DAG.getConstant(
-        APInt::getLowBitsSet(LegalWidth, BestChunkWidth), dl, LegalVT);
+        APInt::getLowBitsSet(HBitWidth, BestChunkWidth), dl, HiLoVT);
 
     for (unsigned I = 0; I < BitWidth; I += BestChunkWidth) {
       SDValue Shift = DAG.getShiftAmountConstant(I, VT, dl);
       SDValue Chunk = DAG.getNode(ISD::SRL, dl, VT, In, Shift);
-      // Truncate to LegalVT
-      SDValue TruncChunk = DAG.getNode(ISD::TRUNCATE, dl, LegalVT, Chunk);
+      // Truncate to HiLoVT
+      SDValue TruncChunk = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Chunk);
       // For the last chunk, we might not need a mask if it's smaller than
       // BestChunkWidth, but applying it is always safe.
       SDValue MaskedChunk =
-          DAG.getNode(ISD::AND, dl, LegalVT, TruncChunk, Mask);
-      TotalSum = DAG.getNode(ISD::ADD, dl, LegalVT, TotalSum, MaskedChunk);
+          DAG.getNode(ISD::AND, dl, HiLoVT, TruncChunk, Mask);
+      Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum, MaskedChunk);
     }
-    Sum = DAG.getNode(ISD::ZERO_EXTEND, dl, HiLoVT, TotalSum);
   }
 
-  // If we didn't find a sum, we can't do the expansion.
-  if (!Sum)
-    return false;
-
   // Perform a HiLoVT urem on the Sum using truncated divisor.
   SDValue RemL =
       DAG.getNode(ISD::UREM, dl, HiLoVT, Sum,
@@ -8343,8 +8333,7 @@ bool TargetLowering::expandDIVREMByConstant(SDNode *N,
       RemL = DAG.getNode(ISD::SHL, dl, HiLoVT, RemL,
                          DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl));
 
-      SDValue PartialRemLo = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, PartialRem);
-      RemL = DAG.getNode(ISD::ADD, dl, HiLoVT, RemL, PartialRemLo);
+      RemL = DAG.getNode(ISD::ADD, dl, HiLoVT, RemL, PartialRem);
     }
     Result.push_back(RemL);
     Result.push_back(DAG.getConstant(0, dl, HiLoVT));

>From 813254e5d83196a1fdc1d252626ca41e76b4654c Mon Sep 17 00:00:00 2001
From: Craig Topper <craig.topper at sifive.com>
Date: Thu, 19 Mar 2026 10:23:06 -0700
Subject: [PATCH 2/5] [TargetLowering] Use legally typed shifts to split chunks
 in expandDIVREMByConstant.

This replaces LegalVT with HiLoVT and LegalWidth with HBitWidth as
there the same for all current uses.

Then we rewrite the shifts to operate on LL and LH.

There's a slight regression on RISC-V due to different node numbering
leading to different DAG combine order. I have other refactoring
I'd like to explore then I may try to fix that.
---
 .../CodeGen/SelectionDAG/TargetLowering.cpp   | 51 ++++++++++++++-----
 llvm/test/CodeGen/RISCV/urem-lkk.ll           | 24 +++++----
 2 files changed, 50 insertions(+), 25 deletions(-)

diff --git a/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp b/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
index 860319b974588..220419de9782b 100644
--- a/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
+++ b/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
@@ -8264,8 +8264,10 @@ bool TargetLowering::expandDIVREMByConstant(SDNode *N,
     if (!BestChunkWidth)
       return false;
 
-    SDValue In =
-        LL ? DAG.getNode(ISD::BUILD_PAIR, dl, VT, LL, LH) : N->getOperand(0);
+    assert(!LL == !LH && "Expected both input halves or no input halves!");
+    if (!LL)
+      std::tie(LL, LH) = DAG.SplitScalar(N->getOperand(0), dl, HiLoVT, HiLoVT);
+
     if (TrailingZeros) {
       // Save the shifted off bits if we need the remainder.
       if (Opcode != ISD::UDIV) {
@@ -8273,13 +8275,20 @@ bool TargetLowering::expandDIVREMByConstant(SDNode *N,
         PartialRem =
             DAG.getNode(ISD::AND, dl, HiLoVT, LL, DAG.getConstant(Mask, dl, HiLoVT));
       }
-      EVT ShiftVT = getShiftAmountTy(VT, DAG.getDataLayout());
-      In = DAG.getNode(ISD::SRL, dl, VT, In,
-                       DAG.getShiftAmountConstant(TrailingZeros, ShiftVT, dl));
 
-      std::tie(LL, LH) = DAG.SplitScalar(In, dl, HiLoVT, HiLoVT);
-    } else if (!LL) {
-      std::tie(LL, LH) = DAG.SplitScalar(In, dl, HiLoVT, HiLoVT);
+      if (isOperationLegal(ISD::FSHR, HiLoVT))
+        LL = DAG.getNode(ISD::FSHR, dl, HiLoVT, LH, LL,
+                         DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl));
+      else
+        LL = DAG.getNode(
+            ISD::OR, dl, HiLoVT,
+            DAG.getNode(ISD::SRL, dl, HiLoVT, LL,
+                        DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl)),
+            DAG.getNode(ISD::SHL, dl, HiLoVT, LH,
+                        DAG.getShiftAmountConstant(HBitWidth - TrailingZeros,
+                                                   HiLoVT, dl)));
+      LH = DAG.getNode(ISD::SRL, dl, HiLoVT, LH,
+                       DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl));
     }
 
     Sum = DAG.getConstant(0, dl, HiLoVT);
@@ -8287,14 +8296,28 @@ bool TargetLowering::expandDIVREMByConstant(SDNode *N,
         APInt::getLowBitsSet(HBitWidth, BestChunkWidth), dl, HiLoVT);
 
     for (unsigned I = 0; I < BitWidth; I += BestChunkWidth) {
-      SDValue Shift = DAG.getShiftAmountConstant(I, VT, dl);
-      SDValue Chunk = DAG.getNode(ISD::SRL, dl, VT, In, Shift);
-      // Truncate to HiLoVT
-      SDValue TruncChunk = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Chunk);
+      SDValue Chunk;
+      if (I == 0) {
+        Chunk = LL;
+      } else if (I >= HBitWidth) {
+        Chunk =
+            DAG.getNode(ISD::SRL, dl, HiLoVT, LH,
+                        DAG.getShiftAmountConstant(I - HBitWidth, HiLoVT, dl));
+      } else if (isOperationLegal(ISD::FSHR, HiLoVT)) {
+        Chunk = DAG.getNode(ISD::FSHR, dl, HiLoVT, LH, LL,
+                            DAG.getShiftAmountConstant(I, HiLoVT, dl));
+      } else {
+        Chunk = DAG.getNode(
+            ISD::OR, dl, HiLoVT,
+            DAG.getNode(ISD::SRL, dl, HiLoVT, LL,
+                        DAG.getShiftAmountConstant(I, HiLoVT, dl)),
+            DAG.getNode(ISD::SHL, dl, HiLoVT, LH,
+                        DAG.getShiftAmountConstant(HBitWidth - I, HiLoVT, dl)));
+      }
+
       // For the last chunk, we might not need a mask if it's smaller than
       // BestChunkWidth, but applying it is always safe.
-      SDValue MaskedChunk =
-          DAG.getNode(ISD::AND, dl, HiLoVT, TruncChunk, Mask);
+      SDValue MaskedChunk = DAG.getNode(ISD::AND, dl, HiLoVT, Chunk, Mask);
       Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum, MaskedChunk);
     }
   }
diff --git a/llvm/test/CodeGen/RISCV/urem-lkk.ll b/llvm/test/CodeGen/RISCV/urem-lkk.ll
index 00fe1a5eb1118..52ef3a6e72ff1 100644
--- a/llvm/test/CodeGen/RISCV/urem-lkk.ll
+++ b/llvm/test/CodeGen/RISCV/urem-lkk.ll
@@ -231,21 +231,23 @@ define i64 @dont_fold_urem_i64(i64 %x) nounwind {
 ; RV32IM:       # %bb.0:
 ; RV32IM-NEXT:    slli a2, a1, 31
 ; RV32IM-NEXT:    srli a3, a0, 1
-; RV32IM-NEXT:    andi a4, a1, 2046
+; RV32IM-NEXT:    lui a4, 512
+; RV32IM-NEXT:    srli a5, a1, 1
 ; RV32IM-NEXT:    srli a1, a1, 11
 ; RV32IM-NEXT:    or a2, a3, a2
-; RV32IM-NEXT:    slli a4, a4, 10
+; RV32IM-NEXT:    slli a5, a5, 11
 ; RV32IM-NEXT:    srli a3, a2, 21
-; RV32IM-NEXT:    or a3, a3, a4
-; RV32IM-NEXT:    lui a4, 21400
-; RV32IM-NEXT:    slli a2, a2, 11
-; RV32IM-NEXT:    srli a2, a2, 11
-; RV32IM-NEXT:    add a2, a2, a3
-; RV32IM-NEXT:    li a3, 49
-; RV32IM-NEXT:    addi a4, a4, -2006
+; RV32IM-NEXT:    or a3, a3, a5
+; RV32IM-NEXT:    lui a5, 21400
+; RV32IM-NEXT:    addi a4, a4, -1
+; RV32IM-NEXT:    and a2, a2, a4
 ; RV32IM-NEXT:    add a1, a2, a1
-; RV32IM-NEXT:    mulhu a2, a1, a4
-; RV32IM-NEXT:    mul a2, a2, a3
+; RV32IM-NEXT:    li a2, 49
+; RV32IM-NEXT:    addi a5, a5, -2006
+; RV32IM-NEXT:    and a3, a3, a4
+; RV32IM-NEXT:    add a1, a1, a3
+; RV32IM-NEXT:    mulhu a3, a1, a5
+; RV32IM-NEXT:    mul a2, a3, a2
 ; RV32IM-NEXT:    sub a1, a1, a2
 ; RV32IM-NEXT:    slli a1, a1, 1
 ; RV32IM-NEXT:    andi a0, a0, 1

>From 779385f6c44c7c07f66d70a42d1ca60d4d219008 Mon Sep 17 00:00:00 2001
From: Craig Topper <craig.topper at sifive.com>
Date: Thu, 19 Mar 2026 12:43:48 -0700
Subject: [PATCH 3/5] fixup! clang-format

---
 llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp b/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
index 220419de9782b..a6d501b578e9e 100644
--- a/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
+++ b/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
@@ -8272,8 +8272,8 @@ bool TargetLowering::expandDIVREMByConstant(SDNode *N,
       // Save the shifted off bits if we need the remainder.
       if (Opcode != ISD::UDIV) {
         APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros);
-        PartialRem =
-            DAG.getNode(ISD::AND, dl, HiLoVT, LL, DAG.getConstant(Mask, dl, HiLoVT));
+        PartialRem = DAG.getNode(ISD::AND, dl, HiLoVT, LL,
+                                 DAG.getConstant(Mask, dl, HiLoVT));
       }
 
       if (isOperationLegal(ISD::FSHR, HiLoVT))

>From a8ce667f5593d0b3fa6d1b4b11e6a0e04776f3a4 Mon Sep 17 00:00:00 2001
From: Craig Topper <craig.topper at sifive.com>
Date: Thu, 19 Mar 2026 13:19:42 -0700
Subject: [PATCH 4/5] [TargetLowering] Refactor expandDIVREMByConstant to share
 more code. NFC

Make the (1 << HBitWidth) % Divisor == 1 path special case within
the recently added chunk summing algorithm. This allows us to
share the trailing zero shifting code.

While there make some comment improvements and avoid creating
unnecessary nodes.
---
 .../CodeGen/SelectionDAG/TargetLowering.cpp   | 161 ++++++++----------
 1 file changed, 71 insertions(+), 90 deletions(-)

diff --git a/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp b/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
index a6d501b578e9e..1cb99d0daa31c 100644
--- a/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
+++ b/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
@@ -8115,8 +8115,15 @@ bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
 // If (1 << (BitWidth / 2)) % Constant == 1, then the remainder
 // can be computed
 // as:
-//   Sum += __builtin_uadd_overflow(Lo, High, &Sum);
-//   Remainder = Sum % Constant
+//   Sum = __builtin_uadd_overflow(Lo, High, &Sum);
+//   Remainder = Sum % Constant;
+//
+// If (1 << (BitWidth / 2)) % Constant != 1, we can search for a smaller value
+// W such that W != (BitWidth / 2) and (1 << W) % Constant != 1. We can break
+// High:Low into 3 chunks of W bits and compute remainder as
+//   Sum = Chunk0 + Chunk1 + Chunk2;
+//   Remainder = Sum % Constant;
+//
 // This is based on "Remainder by Summing Digits" from Hacker's Delight.
 //
 // For division, we can compute the remainder using the algorithm described
@@ -8180,42 +8187,65 @@ bool TargetLowering::expandDIVREMByConstant(SDNode *N,
     Divisor.lshrInPlace(TrailingZeros);
   }
 
+  // Look for the largest chunk width W such that (1 << W) % Divisor == 1.
+  unsigned BestChunkWidth = 0;
+  for (unsigned I = HBitWidth, E = HBitWidth / 2; I > E; --I) {
+    APInt Mod = APInt::getOneBitSet(Divisor.getBitWidth(), I).urem(Divisor);
+
+    if (!Mod.isOne())
+      continue;
+
+    // If best chunk is HBitWidth, we can use it and handle the carry out.
+    // Otherwise, ensure the sum won't overflow HiLoVT (HBitWidth).
+    // Summing N chunks adds ceil(log2(N)) extra carry bits to the width.
+    // Safety check: Base Chunk Width (I) + Carry Bits <= Register Width.
+    unsigned NumChunks = divideCeil(BitWidth, I);
+    if (I == HBitWidth || I + llvm::bit_width(NumChunks - 1) <= HBitWidth) {
+      BestChunkWidth = I;
+      break;
+    }
+  }
+
+  // If we didn't find a chunk size, exit.
+  if (!BestChunkWidth)
+    return false;
+
   SDLoc dl(N);
-  SDValue Sum;
-  SDValue PartialRem;
 
-  // If (1 << HBitWidth) % divisor == 1, we can add the two halves together and
-  // then add in the carry.
-  if (HalfMaxPlus1.urem(Divisor).isOne()) {
-    assert(!LL == !LH && "Expected both input halves or no input halves!");
-    if (!LL)
-      std::tie(LL, LH) = DAG.SplitScalar(N->getOperand(0), dl, HiLoVT, HiLoVT);
+  assert(!LL == !LH && "Expected both input halves or no input halves!");
+  if (!LL)
+    std::tie(LL, LH) = DAG.SplitScalar(N->getOperand(0), dl, HiLoVT, HiLoVT);
 
-    // Shift the input by the number of TrailingZeros in the divisor. The
-    // shifted out bits will be added to the remainder later.
-    if (TrailingZeros) {
-      // Save the shifted off bits if we need the remainder.
-      if (Opcode != ISD::UDIV) {
-        APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros);
-        PartialRem = DAG.getNode(ISD::AND, dl, HiLoVT, LL,
-                                 DAG.getConstant(Mask, dl, HiLoVT));
-      }
+  // Shift the input by the number of TrailingZeros in the divisor. The
+  // shifted out bits will be added to the remainder later.
+  SDValue PartialRem;
+  if (TrailingZeros) {
+    // Save the shifted off bits if we need the remainder.
+    if (Opcode != ISD::UDIV) {
+      APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros);
+      PartialRem = DAG.getNode(ISD::AND, dl, HiLoVT, LL,
+                               DAG.getConstant(Mask, dl, HiLoVT));
+    }
 
-      if (isOperationLegal(ISD::FSHR, HiLoVT))
-        LL = DAG.getNode(ISD::FSHR, dl, HiLoVT, LH, LL,
-                         DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl));
-      else
-        LL = DAG.getNode(
-            ISD::OR, dl, HiLoVT,
-            DAG.getNode(ISD::SRL, dl, HiLoVT, LL,
-                        DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl)),
-            DAG.getNode(ISD::SHL, dl, HiLoVT, LH,
-                        DAG.getShiftAmountConstant(HBitWidth - TrailingZeros,
-                                                   HiLoVT, dl)));
-      LH = DAG.getNode(ISD::SRL, dl, HiLoVT, LH,
+    if (isOperationLegal(ISD::FSHR, HiLoVT))
+      LL = DAG.getNode(ISD::FSHR, dl, HiLoVT, LH, LL,
                        DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl));
-    }
+    else
+      LL = DAG.getNode(
+          ISD::OR, dl, HiLoVT,
+          DAG.getNode(ISD::SRL, dl, HiLoVT, LL,
+                      DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl)),
+          DAG.getNode(ISD::SHL, dl, HiLoVT, LH,
+                      DAG.getShiftAmountConstant(HBitWidth - TrailingZeros,
+                                                 HiLoVT, dl)));
+    LH = DAG.getNode(ISD::SRL, dl, HiLoVT, LH,
+                     DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl));
+  }
 
+  SDValue Sum;
+  // If BestChunkWidth is HBitWidth add low and high half. If there is a carry
+  // out, add that to the final sum.
+  if (BestChunkWidth == HBitWidth) {
     // Use uaddo_carry if we can, otherwise use a compare to detect overflow.
     EVT SetCCType =
         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), HiLoVT);
@@ -8238,60 +8268,8 @@ bool TargetLowering::expandDIVREMByConstant(SDNode *N,
       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.
-    unsigned BitWidth = VT.getScalarSizeInBits();
-    unsigned BestChunkWidth = 0;
-
-    // Search for I where 2^I % Divisor == 1
-    for (unsigned I = HBitWidth - 1, E = HBitWidth / 2; I > E; --I) {
-      APInt Mod = APInt::getOneBitSet(Divisor.getBitWidth(), I).urem(Divisor);
-
-      if (Mod.isOne()) {
-        // Ensure (NumChunks * MaxChunkValue) doesn't overflow HiLoVT
-        unsigned NumChunks = divideCeil(BitWidth, I);
-
-        // Ensure the sum won't overflow the hardware register (HBitWidth).
-        // Summing N chunks adds ceil(log2(N)) extra carry bits to the width.
-        // Safety check: Base Chunk Width (I) + Carry Bits <= Register Width.
-        if (I + llvm::bit_width(NumChunks - 1) <= HBitWidth) {
-          BestChunkWidth = I;
-          break;
-        }
-      }
-    }
-
-    if (!BestChunkWidth)
-      return false;
-
-    assert(!LL == !LH && "Expected both input halves or no input halves!");
-    if (!LL)
-      std::tie(LL, LH) = DAG.SplitScalar(N->getOperand(0), dl, HiLoVT, HiLoVT);
-
-    if (TrailingZeros) {
-      // Save the shifted off bits if we need the remainder.
-      if (Opcode != ISD::UDIV) {
-        APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros);
-        PartialRem = DAG.getNode(ISD::AND, dl, HiLoVT, LL,
-                                 DAG.getConstant(Mask, dl, HiLoVT));
-      }
-
-      if (isOperationLegal(ISD::FSHR, HiLoVT))
-        LL = DAG.getNode(ISD::FSHR, dl, HiLoVT, LH, LL,
-                         DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl));
-      else
-        LL = DAG.getNode(
-            ISD::OR, dl, HiLoVT,
-            DAG.getNode(ISD::SRL, dl, HiLoVT, LL,
-                        DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl)),
-            DAG.getNode(ISD::SHL, dl, HiLoVT, LH,
-                        DAG.getShiftAmountConstant(HBitWidth - TrailingZeros,
-                                                   HiLoVT, dl)));
-      LH = DAG.getNode(ISD::SRL, dl, HiLoVT, LH,
-                       DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl));
-    }
-
-    Sum = DAG.getConstant(0, dl, HiLoVT);
+    // Otherwise split into multple chunks and add them together. We chose
+    // BestChunkWidth so that the sum will not overflow.
     SDValue Mask = DAG.getConstant(
         APInt::getLowBitsSet(HBitWidth, BestChunkWidth), dl, HiLoVT);
 
@@ -8317,8 +8295,11 @@ bool TargetLowering::expandDIVREMByConstant(SDNode *N,
 
       // For the last chunk, we might not need a mask if it's smaller than
       // BestChunkWidth, but applying it is always safe.
-      SDValue MaskedChunk = DAG.getNode(ISD::AND, dl, HiLoVT, Chunk, Mask);
-      Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum, MaskedChunk);
+      Chunk = DAG.getNode(ISD::AND, dl, HiLoVT, Chunk, Mask);
+      if (!Sum)
+        Sum = Chunk;
+      else
+        Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum, Chunk);
     }
   }
 
@@ -8351,7 +8332,7 @@ bool TargetLowering::expandDIVREMByConstant(SDNode *N,
 
   if (Opcode != ISD::UDIV) {
     // If we shifted the input, shift the remainder left and add the bits we
-    // shifted off the input.
+    // shifted off the input. This add does not overflow.
     if (TrailingZeros) {
       RemL = DAG.getNode(ISD::SHL, dl, HiLoVT, RemL,
                          DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl));
@@ -8359,7 +8340,7 @@ bool TargetLowering::expandDIVREMByConstant(SDNode *N,
       RemL = DAG.getNode(ISD::ADD, dl, HiLoVT, RemL, PartialRem);
     }
     Result.push_back(RemL);
-    Result.push_back(DAG.getConstant(0, dl, HiLoVT));
+    Result.push_back(RemH);
   }
 
   return true;

>From 8650b627629030e530bcbee27850b1d4ec778796 Mon Sep 17 00:00:00 2001
From: Craig Topper <craig.topper at sifive.com>
Date: Sat, 21 Mar 2026 09:38:02 -0700
Subject: [PATCH 5/5] fixup! Address review comments

---
 llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)

diff --git a/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp b/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
index 0724e9f61590c..7d7138c45b1dc 100644
--- a/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
+++ b/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp
@@ -8122,7 +8122,7 @@ bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
 //   Remainder = Sum % Constant;
 //
 // If (1 << (BitWidth / 2)) % Constant != 1, we can search for a smaller value
-// W such that W != (BitWidth / 2) and (1 << W) % Constant != 1. We can break
+// W such that W != (BitWidth / 2) and (1 << W) % Constant == 1. We can break
 // High:Low into 3 chunks of W bits and compute remainder as
 //   Sum = Chunk0 + Chunk1 + Chunk2;
 //   Remainder = Sum % Constant;
@@ -8219,6 +8219,8 @@ bool TargetLowering::expandDIVREMByConstant(SDNode *N,
   if (!LL)
     std::tie(LL, LH) = DAG.SplitScalar(N->getOperand(0), dl, HiLoVT, HiLoVT);
 
+  bool HasFSHR = isOperationLegal(ISD::FSHR, HiLoVT);
+
   // Shift the input by the number of TrailingZeros in the divisor. The
   // shifted out bits will be added to the remainder later.
   SDValue PartialRem;
@@ -8230,7 +8232,7 @@ bool TargetLowering::expandDIVREMByConstant(SDNode *N,
                                DAG.getConstant(Mask, dl, HiLoVT));
     }
 
-    if (isOperationLegal(ISD::FSHR, HiLoVT))
+    if (HasFSHR)
       LL = DAG.getNode(ISD::FSHR, dl, HiLoVT, LH, LL,
                        DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl));
     else
@@ -8284,7 +8286,7 @@ bool TargetLowering::expandDIVREMByConstant(SDNode *N,
         Chunk =
             DAG.getNode(ISD::SRL, dl, HiLoVT, LH,
                         DAG.getShiftAmountConstant(I - HBitWidth, HiLoVT, dl));
-      } else if (isOperationLegal(ISD::FSHR, HiLoVT)) {
+      } else if (HasFSHR) {
         Chunk = DAG.getNode(ISD::FSHR, dl, HiLoVT, LH, LL,
                             DAG.getShiftAmountConstant(I, HiLoVT, dl));
       } else {



More information about the llvm-commits mailing list