Skip to content

Commit 55f0a1b

Browse files
committed
[RISCV] Optimize multiplication with constant
1. Break MUL with specific constant to a SLLI and an ADD/SUB on riscv32 with the M extension. 2. Break MUL with specific constant to two SLLI and an ADD/SUB, if the constant needs a pair of LUI/ADDI to construct. Reviewed by: craig.topper Differential Revision: https://reviews.llvm.org/D93619
1 parent 467cbd2 commit 55f0a1b

File tree

2 files changed

+227
-211
lines changed

2 files changed

+227
-211
lines changed

llvm/lib/Target/RISCV/RISCVISelLowering.cpp

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3899,16 +3899,28 @@ bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
38993899
SDValue C) const {
39003900
// Check integral scalar types.
39013901
if (VT.isScalarInteger()) {
3902-
// Do not perform the transformation on riscv32 with the M extension.
3903-
if (!Subtarget.is64Bit() && Subtarget.hasStdExtM())
3902+
// Omit the optimization if the sub target has the M extension and the data
3903+
// size exceeds XLen.
3904+
if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
39043905
return false;
39053906
if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
3906-
if (ConstNode->getAPIntValue().getBitWidth() > 8 * sizeof(int64_t))
3907+
// Break the MUL to a SLLI and an ADD/SUB.
3908+
const APInt &Imm = ConstNode->getAPIntValue();
3909+
if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
3910+
(1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
3911+
return true;
3912+
// Omit the following optimization if the sub target has the M extension
3913+
// and the data size >= XLen.
3914+
if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
39073915
return false;
3908-
int64_t Imm = ConstNode->getSExtValue();
3909-
if (isPowerOf2_64(Imm + 1) || isPowerOf2_64(Imm - 1) ||
3910-
isPowerOf2_64(1 - Imm) || isPowerOf2_64(-1 - Imm))
3916+
// Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
3917+
// a pair of LUI/ADDI.
3918+
if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
3919+
APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
3920+
if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
3921+
(1 - ImmS).isPowerOf2())
39113922
return true;
3923+
}
39123924
}
39133925
}
39143926

0 commit comments

Comments
 (0)