[llvm] [GlobalISel] Handle div-by-pow2 (PR #83155)

Thorsten Schütt via llvm-commits llvm-commits at lists.llvm.org
Tue Feb 27 11:05:59 PST 2024


================
@@ -5286,6 +5286,62 @@ MachineInstr *CombinerHelper::buildSDivUsingMul(MachineInstr &MI) {
   return MIB.buildMul(Ty, Res, Factor);
 }
 
+bool CombinerHelper::matchSDivByPow2(MachineInstr &MI) {
+  assert(MI.getOpcode() == TargetOpcode::G_SDIV && "Expected SDIV");
+  auto &SDiv = cast<GenericMachineInstr>(MI);
+  Register RHS = SDiv.getReg(2);
+  auto MatchPow2 = [&](const Constant *C) {
+    if (auto *CI = dyn_cast<ConstantInt>(C))
+      return CI->getValue().isPowerOf2() || CI->getValue().isNegatedPowerOf2();
+    return false;
+  };
+  return matchUnaryPredicate(MRI, RHS, MatchPow2, /* AllowUndefs */ false);
+}
+
+void CombinerHelper::applySDivByPow2(MachineInstr &MI) {
+  assert(MI.getOpcode() == TargetOpcode::G_SDIV && "Expected SDIV");
+  auto &SDiv = cast<GenericMachineInstr>(MI);
+  Register Dst = SDiv.getReg(0);
+  Register LHS = SDiv.getReg(1);
+  Register RHS = SDiv.getReg(2);
+  LLT Ty = MRI.getType(Dst);
+  LLT ShiftAmtTy = getTargetLowering().getPreferredShiftAmountTy(Ty);
+  LLT CVT = LLT::scalar(1);
+
+  Builder.setInstrAndDebugLoc(MI);
+
+  unsigned Bitwidth = Ty.getScalarSizeInBits();
+  auto Bits = Builder.buildConstant(ShiftAmtTy, Bitwidth);
+  auto C1 = Builder.buildCTTZ(Ty, RHS);
+  C1 = Builder.buildZExtOrTrunc(ShiftAmtTy, C1);
+  auto Inexact = Builder.buildSub(ShiftAmtTy, Bits, C1);
+  // TODO: Need to check whether Inexact is constant
+  auto Sign = Builder.buildAShr(
+      Ty, LHS, Builder.buildConstant(ShiftAmtTy, Bitwidth - 1));
+  // Add (LHS < 0) ? abs2 - 1 : 0;
+  auto Srl = Builder.buildShl(Ty, Sign, Inexact);
+  auto Add = Builder.buildAdd(Ty, LHS, Srl);
+  auto Sra = Builder.buildAShr(Ty, Add, C1);
+  // Special case: (sdiv X, 1) -> X
+  // Special Case: (sdiv X, -1) -> 0-X
+  auto One = Builder.buildConstant(Ty, 1);
+  auto AllOnes = Builder.buildConstant(Ty, APInt::getAllOnes(Bitwidth));
+  auto IsOne = Builder.buildICmp(CmpInst::Predicate::ICMP_EQ, CVT, RHS, One);
----------------
tschuett wrote:

You could use the `BuildFn` pattern to merge the two functions, pass the constant to the apply fn, or retrieve the constant in the apply fn:
```
std::optional<ValueAndVReg> MaybeRHS =
      getIConstantVRegValWithLookThrough(RHS, MRI);
  if (!MaybeRHS)
    return false;
```

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


More information about the llvm-commits mailing list