1 //===- InstCombineMulDivRem.cpp -------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the visit functions for mul, fmul, sdiv, udiv, fdiv,
13 //===----------------------------------------------------------------------===//
15 #include "InstCombineInternal.h"
16 #include "llvm/ADT/APFloat.h"
17 #include "llvm/ADT/APInt.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/IR/BasicBlock.h"
21 #include "llvm/IR/Constant.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/InstrTypes.h"
24 #include "llvm/IR/Instruction.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/IR/PatternMatch.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/IR/Value.h"
32 #include "llvm/Support/Casting.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/KnownBits.h"
35 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
42 using namespace PatternMatch;
44 #define DEBUG_TYPE "instcombine"
46 /// The specific integer value is used in a context where it is known to be
47 /// non-zero. If this allows us to simplify the computation, do so and return
48 /// the new operand, otherwise return null.
49 static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC,
51 // If V has multiple uses, then we would have to do more analysis to determine
52 // if this is safe. For example, the use could be in dynamically unreached
54 if (!V->hasOneUse()) return nullptr;
56 bool MadeChange = false;
58 // ((1 << A) >>u B) --> (1 << (A-B))
59 // Because V cannot be zero, we know that B is less than A.
60 Value *A = nullptr, *B = nullptr, *One = nullptr;
61 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) &&
62 match(One, m_One())) {
63 A = IC.Builder.CreateSub(A, B);
64 return IC.Builder.CreateShl(One, A);
67 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
68 // inexact. Similarly for <<.
69 BinaryOperator *I = dyn_cast<BinaryOperator>(V);
70 if (I && I->isLogicalShift() &&
71 IC.isKnownToBeAPowerOfTwo(I->getOperand(0), false, 0, &CxtI)) {
72 // We know that this is an exact/nuw shift and that the input is a
73 // non-zero context as well.
74 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
79 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
84 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
85 I->setHasNoUnsignedWrap();
90 // TODO: Lots more we could do here:
91 // If V is a phi node, we can call this on each of its operands.
92 // "select cond, X, 0" can simplify to "X".
94 return MadeChange ? V : nullptr;
97 /// True if the multiply can not be expressed in an int this size.
98 static bool MultiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
102 Product = C1.smul_ov(C2, Overflow);
104 Product = C1.umul_ov(C2, Overflow);
109 /// \brief True if C2 is a multiple of C1. Quotient contains C2/C1.
110 static bool IsMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
112 assert(C1.getBitWidth() == C2.getBitWidth() &&
113 "Inconsistent width of constants!");
115 // Bail if we will divide by zero.
119 // Bail if we would divide INT_MIN by -1.
120 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnesValue())
123 APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
125 APInt::sdivrem(C1, C2, Quotient, Remainder);
127 APInt::udivrem(C1, C2, Quotient, Remainder);
129 return Remainder.isMinValue();
132 /// \brief A helper routine of InstCombiner::visitMul().
134 /// If C is a vector of known powers of 2, then this function returns
135 /// a new vector obtained from C replacing each element with its logBase2.
136 /// Return a null pointer otherwise.
137 static Constant *getLogBase2Vector(ConstantDataVector *CV) {
139 SmallVector<Constant *, 4> Elts;
141 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
142 Constant *Elt = CV->getElementAsConstant(I);
143 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
145 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
148 return ConstantVector::get(Elts);
151 /// \brief Return true if we can prove that:
152 /// (mul LHS, RHS) === (mul nsw LHS, RHS)
153 bool InstCombiner::willNotOverflowSignedMul(const Value *LHS,
155 const Instruction &CxtI) const {
156 // Multiplying n * m significant bits yields a result of n + m significant
157 // bits. If the total number of significant bits does not exceed the
158 // result bit width (minus 1), there is no overflow.
159 // This means if we have enough leading sign bits in the operands
160 // we can guarantee that the result does not overflow.
161 // Ref: "Hacker's Delight" by Henry Warren
162 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
164 // Note that underestimating the number of sign bits gives a more
165 // conservative answer.
167 ComputeNumSignBits(LHS, 0, &CxtI) + ComputeNumSignBits(RHS, 0, &CxtI);
169 // First handle the easy case: if we have enough sign bits there's
170 // definitely no overflow.
171 if (SignBits > BitWidth + 1)
174 // There are two ambiguous cases where there can be no overflow:
175 // SignBits == BitWidth + 1 and
176 // SignBits == BitWidth
177 // The second case is difficult to check, therefore we only handle the
179 if (SignBits == BitWidth + 1) {
180 // It overflows only when both arguments are negative and the true
181 // product is exactly the minimum negative number.
182 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
183 // For simplicity we just check if at least one side is not negative.
184 KnownBits LHSKnown = computeKnownBits(LHS, /*Depth=*/0, &CxtI);
185 KnownBits RHSKnown = computeKnownBits(RHS, /*Depth=*/0, &CxtI);
186 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
192 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
193 bool Changed = SimplifyAssociativeOrCommutative(I);
194 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
196 if (Value *V = SimplifyVectorOp(I))
197 return replaceInstUsesWith(I, V);
199 if (Value *V = SimplifyMulInst(Op0, Op1, SQ.getWithInstruction(&I)))
200 return replaceInstUsesWith(I, V);
202 if (Value *V = SimplifyUsingDistributiveLaws(I))
203 return replaceInstUsesWith(I, V);
206 if (match(Op1, m_AllOnes())) {
207 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
208 if (I.hasNoSignedWrap())
209 BO->setHasNoSignedWrap();
213 // Also allow combining multiply instructions on vectors.
218 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
220 match(C1, m_APInt(IVal))) {
221 // ((X << C2)*C1) == (X * (C1 << C2))
222 Constant *Shl = ConstantExpr::getShl(C1, C2);
223 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
224 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
225 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
226 BO->setHasNoUnsignedWrap();
227 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
228 Shl->isNotMinSignedValue())
229 BO->setHasNoSignedWrap();
233 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
234 Constant *NewCst = nullptr;
235 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
236 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
237 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
238 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
239 // Replace X*(2^C) with X << C, where C is a vector of known
240 // constant powers of 2.
241 NewCst = getLogBase2Vector(CV);
244 unsigned Width = NewCst->getType()->getPrimitiveSizeInBits();
245 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
247 if (I.hasNoUnsignedWrap())
248 Shl->setHasNoUnsignedWrap();
249 if (I.hasNoSignedWrap()) {
251 if (match(NewCst, m_APInt(V)) && *V != Width - 1)
252 Shl->setHasNoSignedWrap();
260 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
261 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
262 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
263 // The "* (2**n)" thus becomes a potential shifting opportunity.
265 const APInt & Val = CI->getValue();
266 const APInt &PosVal = Val.abs();
267 if (Val.isNegative() && PosVal.isPowerOf2()) {
268 Value *X = nullptr, *Y = nullptr;
269 if (Op0->hasOneUse()) {
271 Value *Sub = nullptr;
272 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
273 Sub = Builder.CreateSub(X, Y, "suba");
274 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
275 Sub = Builder.CreateSub(Builder.CreateNeg(C1), Y, "subc");
278 BinaryOperator::CreateMul(Sub,
279 ConstantInt::get(Y->getType(), PosVal));
285 // Simplify mul instructions with a constant RHS.
286 if (isa<Constant>(Op1)) {
287 if (Instruction *FoldedMul = foldOpWithConstantIntoOperand(I))
290 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
294 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
295 Value *Mul = Builder.CreateMul(C1, Op1);
296 // Only go forward with the transform if C1*CI simplifies to a tidier
298 if (!match(Mul, m_Mul(m_Value(), m_Value())))
299 return BinaryOperator::CreateAdd(Builder.CreateMul(X, Op1), Mul);
304 if (Value *Op0v = dyn_castNegVal(Op0)) { // -X * -Y = X*Y
305 if (Value *Op1v = dyn_castNegVal(Op1)) {
306 BinaryOperator *BO = BinaryOperator::CreateMul(Op0v, Op1v);
307 if (I.hasNoSignedWrap() &&
308 match(Op0, m_NSWSub(m_Value(), m_Value())) &&
309 match(Op1, m_NSWSub(m_Value(), m_Value())))
310 BO->setHasNoSignedWrap();
315 // (X / Y) * Y = X - (X % Y)
316 // (X / Y) * -Y = (X % Y) - X
319 BinaryOperator *Div = dyn_cast<BinaryOperator>(Op0);
320 if (!Div || (Div->getOpcode() != Instruction::UDiv &&
321 Div->getOpcode() != Instruction::SDiv)) {
323 Div = dyn_cast<BinaryOperator>(Op1);
325 Value *Neg = dyn_castNegVal(Y);
326 if (Div && Div->hasOneUse() &&
327 (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) &&
328 (Div->getOpcode() == Instruction::UDiv ||
329 Div->getOpcode() == Instruction::SDiv)) {
330 Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1);
332 // If the division is exact, X % Y is zero, so we end up with X or -X.
333 if (Div->isExact()) {
335 return replaceInstUsesWith(I, X);
336 return BinaryOperator::CreateNeg(X);
339 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
341 Value *Rem = Builder.CreateBinOp(RemOpc, X, DivOp1);
343 return BinaryOperator::CreateSub(X, Rem);
344 return BinaryOperator::CreateSub(Rem, X);
348 /// i1 mul -> i1 and.
349 if (I.getType()->isIntOrIntVectorTy(1))
350 return BinaryOperator::CreateAnd(Op0, Op1);
352 // X*(1 << Y) --> X << Y
353 // (1 << Y)*X --> X << Y
356 BinaryOperator *BO = nullptr;
358 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
359 BO = BinaryOperator::CreateShl(Op1, Y);
360 ShlNSW = cast<ShlOperator>(Op0)->hasNoSignedWrap();
361 } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
362 BO = BinaryOperator::CreateShl(Op0, Y);
363 ShlNSW = cast<ShlOperator>(Op1)->hasNoSignedWrap();
366 if (I.hasNoUnsignedWrap())
367 BO->setHasNoUnsignedWrap();
368 if (I.hasNoSignedWrap() && ShlNSW)
369 BO->setHasNoSignedWrap();
374 // If one of the operands of the multiply is a cast from a boolean value, then
375 // we know the bool is either zero or one, so this is a 'masking' multiply.
376 // X * Y (where Y is 0 or 1) -> X & (0-Y)
377 if (!I.getType()->isVectorTy()) {
378 // -2 is "-1 << 1" so it is all bits set except the low one.
379 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
381 Value *BoolCast = nullptr, *OtherOp = nullptr;
382 if (MaskedValueIsZero(Op0, Negative2, 0, &I)) {
385 } else if (MaskedValueIsZero(Op1, Negative2, 0, &I)) {
391 Value *V = Builder.CreateSub(Constant::getNullValue(I.getType()),
393 return BinaryOperator::CreateAnd(V, OtherOp);
397 // Check for (mul (sext x), y), see if we can merge this into an
398 // integer mul followed by a sext.
399 if (SExtInst *Op0Conv = dyn_cast<SExtInst>(Op0)) {
400 // (mul (sext x), cst) --> (sext (mul x, cst'))
401 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
402 if (Op0Conv->hasOneUse()) {
404 ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
405 if (ConstantExpr::getSExt(CI, I.getType()) == Op1C &&
406 willNotOverflowSignedMul(Op0Conv->getOperand(0), CI, I)) {
407 // Insert the new, smaller mul.
409 Builder.CreateNSWMul(Op0Conv->getOperand(0), CI, "mulconv");
410 return new SExtInst(NewMul, I.getType());
415 // (mul (sext x), (sext y)) --> (sext (mul int x, y))
416 if (SExtInst *Op1Conv = dyn_cast<SExtInst>(Op1)) {
417 // Only do this if x/y have the same type, if at last one of them has a
418 // single use (so we don't increase the number of sexts), and if the
419 // integer mul will not overflow.
420 if (Op0Conv->getOperand(0)->getType() ==
421 Op1Conv->getOperand(0)->getType() &&
422 (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
423 willNotOverflowSignedMul(Op0Conv->getOperand(0),
424 Op1Conv->getOperand(0), I)) {
425 // Insert the new integer mul.
426 Value *NewMul = Builder.CreateNSWMul(
427 Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
428 return new SExtInst(NewMul, I.getType());
433 // Check for (mul (zext x), y), see if we can merge this into an
434 // integer mul followed by a zext.
435 if (auto *Op0Conv = dyn_cast<ZExtInst>(Op0)) {
436 // (mul (zext x), cst) --> (zext (mul x, cst'))
437 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
438 if (Op0Conv->hasOneUse()) {
440 ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
441 if (ConstantExpr::getZExt(CI, I.getType()) == Op1C &&
442 willNotOverflowUnsignedMul(Op0Conv->getOperand(0), CI, I)) {
443 // Insert the new, smaller mul.
445 Builder.CreateNUWMul(Op0Conv->getOperand(0), CI, "mulconv");
446 return new ZExtInst(NewMul, I.getType());
451 // (mul (zext x), (zext y)) --> (zext (mul int x, y))
452 if (auto *Op1Conv = dyn_cast<ZExtInst>(Op1)) {
453 // Only do this if x/y have the same type, if at last one of them has a
454 // single use (so we don't increase the number of zexts), and if the
455 // integer mul will not overflow.
456 if (Op0Conv->getOperand(0)->getType() ==
457 Op1Conv->getOperand(0)->getType() &&
458 (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
459 willNotOverflowUnsignedMul(Op0Conv->getOperand(0),
460 Op1Conv->getOperand(0), I)) {
461 // Insert the new integer mul.
462 Value *NewMul = Builder.CreateNUWMul(
463 Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
464 return new ZExtInst(NewMul, I.getType());
469 if (!I.hasNoSignedWrap() && willNotOverflowSignedMul(Op0, Op1, I)) {
471 I.setHasNoSignedWrap(true);
474 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedMul(Op0, Op1, I)) {
476 I.setHasNoUnsignedWrap(true);
479 return Changed ? &I : nullptr;
482 /// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
483 static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
484 if (!Op->hasOneUse())
487 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
490 if (II->getIntrinsicID() != Intrinsic::log2 || !II->isFast())
494 Value *OpLog2Of = II->getArgOperand(0);
495 if (!OpLog2Of->hasOneUse())
498 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
502 if (I->getOpcode() != Instruction::FMul || !I->isFast())
505 if (match(I->getOperand(0), m_SpecificFP(0.5)))
506 Y = I->getOperand(1);
507 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
508 Y = I->getOperand(0);
511 static bool isFiniteNonZeroFp(Constant *C) {
512 if (C->getType()->isVectorTy()) {
513 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
515 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
516 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
522 return isa<ConstantFP>(C) &&
523 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
526 static bool isNormalFp(Constant *C) {
527 if (C->getType()->isVectorTy()) {
528 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
530 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
531 if (!CFP || !CFP->getValueAPF().isNormal())
537 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
540 /// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
541 /// true iff the given value is FMul or FDiv with one and only one operand
542 /// being a normal constant (i.e. not Zero/NaN/Infinity).
543 static bool isFMulOrFDivWithConstant(Value *V) {
544 Instruction *I = dyn_cast<Instruction>(V);
545 if (!I || (I->getOpcode() != Instruction::FMul &&
546 I->getOpcode() != Instruction::FDiv))
549 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
550 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
555 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
558 /// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
559 /// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
560 /// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
561 /// This function is to simplify "FMulOrDiv * C" and returns the
562 /// resulting expression. Note that this function could return NULL in
563 /// case the constants cannot be folded into a normal floating-point.
564 Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
565 Instruction *InsertBefore) {
566 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
568 Value *Opnd0 = FMulOrDiv->getOperand(0);
569 Value *Opnd1 = FMulOrDiv->getOperand(1);
571 Constant *C0 = dyn_cast<Constant>(Opnd0);
572 Constant *C1 = dyn_cast<Constant>(Opnd1);
574 BinaryOperator *R = nullptr;
576 // (X * C0) * C => X * (C0*C)
577 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
578 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
580 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
583 // (C0 / X) * C => (C0 * C) / X
584 if (FMulOrDiv->hasOneUse()) {
585 // It would otherwise introduce another div.
586 Constant *F = ConstantExpr::getFMul(C0, C);
588 R = BinaryOperator::CreateFDiv(F, Opnd1);
591 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
592 Constant *F = ConstantExpr::getFDiv(C, C1);
594 R = BinaryOperator::CreateFMul(Opnd0, F);
596 // (X / C1) * C => X / (C1/C)
597 Constant *F = ConstantExpr::getFDiv(C1, C);
599 R = BinaryOperator::CreateFDiv(Opnd0, F);
606 InsertNewInstWith(R, *InsertBefore);
612 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
613 bool Changed = SimplifyAssociativeOrCommutative(I);
614 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
616 if (Value *V = SimplifyVectorOp(I))
617 return replaceInstUsesWith(I, V);
619 if (isa<Constant>(Op0))
622 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(),
623 SQ.getWithInstruction(&I)))
624 return replaceInstUsesWith(I, V);
626 bool AllowReassociate = I.isFast();
628 // Simplify mul instructions with a constant RHS.
629 if (isa<Constant>(Op1)) {
630 if (Instruction *FoldedMul = foldOpWithConstantIntoOperand(I))
633 // (fmul X, -1.0) --> (fsub -0.0, X)
634 if (match(Op1, m_SpecificFP(-1.0))) {
635 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
636 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
637 RI->copyFastMathFlags(&I);
641 Constant *C = cast<Constant>(Op1);
642 if (AllowReassociate && isFiniteNonZeroFp(C)) {
643 // Let MDC denote an expression in one of these forms:
644 // X * C, C/X, X/C, where C is a constant.
646 // Try to simplify "MDC * Constant"
647 if (isFMulOrFDivWithConstant(Op0))
648 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
649 return replaceInstUsesWith(I, V);
651 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
652 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
654 (FAddSub->getOpcode() == Instruction::FAdd ||
655 FAddSub->getOpcode() == Instruction::FSub)) {
656 Value *Opnd0 = FAddSub->getOperand(0);
657 Value *Opnd1 = FAddSub->getOperand(1);
658 Constant *C0 = dyn_cast<Constant>(Opnd0);
659 Constant *C1 = dyn_cast<Constant>(Opnd1);
663 std::swap(Opnd0, Opnd1);
667 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
668 Value *M1 = ConstantExpr::getFMul(C1, C);
669 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
670 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
673 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
676 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
677 ? BinaryOperator::CreateFAdd(M0, M1)
678 : BinaryOperator::CreateFSub(M0, M1);
679 RI->copyFastMathFlags(&I);
688 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
689 // sqrt(X) * sqrt(X) -> X
690 if (AllowReassociate && II->getIntrinsicID() == Intrinsic::sqrt)
691 return replaceInstUsesWith(I, II->getOperand(0));
693 // fabs(X) * fabs(X) -> X * X
694 if (II->getIntrinsicID() == Intrinsic::fabs) {
695 Instruction *FMulVal = BinaryOperator::CreateFMul(II->getOperand(0),
698 FMulVal->copyFastMathFlags(&I);
704 // Under unsafe algebra do:
705 // X * log2(0.5*Y) = X*log2(Y) - X
706 if (AllowReassociate) {
707 Value *OpX = nullptr;
708 Value *OpY = nullptr;
710 detectLog2OfHalf(Op0, OpY, Log2);
714 detectLog2OfHalf(Op1, OpY, Log2);
719 // if pattern detected emit alternate sequence
721 BuilderTy::FastMathFlagGuard Guard(Builder);
722 Builder.setFastMathFlags(Log2->getFastMathFlags());
723 Log2->setArgOperand(0, OpY);
724 Value *FMulVal = Builder.CreateFMul(OpX, Log2);
725 Value *FSub = Builder.CreateFSub(FMulVal, OpX);
727 return replaceInstUsesWith(I, FSub);
731 // sqrt(a) * sqrt(b) -> sqrt(a * b)
732 if (AllowReassociate &&
733 Op0->hasOneUse() && Op1->hasOneUse()) {
734 Value *Opnd0 = nullptr;
735 Value *Opnd1 = nullptr;
736 if (match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(Opnd0))) &&
737 match(Op1, m_Intrinsic<Intrinsic::sqrt>(m_Value(Opnd1)))) {
738 BuilderTy::FastMathFlagGuard Guard(Builder);
739 Builder.setFastMathFlags(I.getFastMathFlags());
740 Value *FMulVal = Builder.CreateFMul(Opnd0, Opnd1);
741 Value *Sqrt = Intrinsic::getDeclaration(I.getModule(),
742 Intrinsic::sqrt, I.getType());
743 Value *SqrtCall = Builder.CreateCall(Sqrt, FMulVal);
744 return replaceInstUsesWith(I, SqrtCall);
748 // Handle symmetric situation in a 2-iteration loop
751 for (int i = 0; i < 2; i++) {
752 bool IgnoreZeroSign = I.hasNoSignedZeros();
753 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
754 BuilderTy::FastMathFlagGuard Guard(Builder);
755 Builder.setFastMathFlags(I.getFastMathFlags());
757 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
758 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
762 Value *FMul = Builder.CreateFMul(N0, N1);
764 return replaceInstUsesWith(I, FMul);
767 if (Opnd0->hasOneUse()) {
768 // -X * Y => -(X*Y) (Promote negation as high as possible)
769 Value *T = Builder.CreateFMul(N0, Opnd1);
770 Value *Neg = Builder.CreateFNeg(T);
772 return replaceInstUsesWith(I, Neg);
776 // Handle specials cases for FMul with selects feeding the operation
777 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
778 return replaceInstUsesWith(I, V);
780 // (X*Y) * X => (X*X) * Y where Y != X
781 // The purpose is two-fold:
782 // 1) to form a power expression (of X).
783 // 2) potentially shorten the critical path: After transformation, the
784 // latency of the instruction Y is amortized by the expression of X*X,
785 // and therefore Y is in a "less critical" position compared to what it
786 // was before the transformation.
787 if (AllowReassociate) {
788 Value *Opnd0_0, *Opnd0_1;
789 if (Opnd0->hasOneUse() &&
790 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
792 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
794 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
798 BuilderTy::FastMathFlagGuard Guard(Builder);
799 Builder.setFastMathFlags(I.getFastMathFlags());
800 Value *T = Builder.CreateFMul(Opnd1, Opnd1);
801 Value *R = Builder.CreateFMul(T, Y);
803 return replaceInstUsesWith(I, R);
808 if (!isa<Constant>(Op1))
809 std::swap(Opnd0, Opnd1);
814 return Changed ? &I : nullptr;
817 /// Fold a divide or remainder with a select instruction divisor when one of the
818 /// select operands is zero. In that case, we can use the other select operand
819 /// because div/rem by zero is undefined.
820 bool InstCombiner::simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I) {
821 SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1));
826 if (match(SI->getTrueValue(), m_Zero()))
827 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
829 else if (match(SI->getFalseValue(), m_Zero()))
830 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
835 // Change the div/rem to use 'Y' instead of the select.
836 I.setOperand(1, SI->getOperand(NonNullOperand));
838 // Okay, we know we replace the operand of the div/rem with 'Y' with no
839 // problem. However, the select, or the condition of the select may have
840 // multiple uses. Based on our knowledge that the operand must be non-zero,
841 // propagate the known value for the select into other uses of it, and
842 // propagate a known value of the condition into its other users.
844 // If the select and condition only have a single use, don't bother with this,
846 Value *SelectCond = SI->getCondition();
847 if (SI->use_empty() && SelectCond->hasOneUse())
850 // Scan the current block backward, looking for other uses of SI.
851 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
852 Type *CondTy = SelectCond->getType();
853 while (BBI != BBFront) {
855 // If we found a call to a function, we can't assume it will return, so
856 // information from below it cannot be propagated above it.
857 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
860 // Replace uses of the select or its condition with the known values.
861 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
864 *I = SI->getOperand(NonNullOperand);
866 } else if (*I == SelectCond) {
867 *I = NonNullOperand == 1 ? ConstantInt::getTrue(CondTy)
868 : ConstantInt::getFalse(CondTy);
873 // If we past the instruction, quit looking for it.
876 if (&*BBI == SelectCond)
877 SelectCond = nullptr;
879 // If we ran out of things to eliminate, break out of the loop.
880 if (!SelectCond && !SI)
887 /// This function implements the transforms common to both integer division
888 /// instructions (udiv and sdiv). It is called by the visitors to those integer
889 /// division instructions.
890 /// @brief Common integer divide transforms
891 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
892 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
894 // The RHS is known non-zero.
895 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
900 // Handle cases involving: [su]div X, (select Cond, Y, Z)
901 // This does not apply for fdiv.
902 if (simplifyDivRemOfSelectWithZeroOp(I))
905 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
907 if (match(Op1, m_APInt(C2))) {
910 bool IsSigned = I.getOpcode() == Instruction::SDiv;
912 // (X / C1) / C2 -> X / (C1*C2)
913 if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
914 (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
915 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
916 if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
917 return BinaryOperator::Create(I.getOpcode(), X,
918 ConstantInt::get(I.getType(), Product));
921 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
922 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
923 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
925 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
926 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
927 BinaryOperator *BO = BinaryOperator::Create(
928 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
929 BO->setIsExact(I.isExact());
933 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
934 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
935 BinaryOperator *BO = BinaryOperator::Create(
936 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
937 BO->setHasNoUnsignedWrap(
939 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
940 BO->setHasNoSignedWrap(
941 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
946 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
947 *C1 != C1->getBitWidth() - 1) ||
948 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
949 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
950 APInt C1Shifted = APInt::getOneBitSet(
951 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
953 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
954 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
955 BinaryOperator *BO = BinaryOperator::Create(
956 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
957 BO->setIsExact(I.isExact());
961 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
962 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
963 BinaryOperator *BO = BinaryOperator::Create(
964 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
965 BO->setHasNoUnsignedWrap(
967 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
968 BO->setHasNoSignedWrap(
969 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
974 if (!C2->isNullValue()) // avoid X udiv 0
975 if (Instruction *FoldedDiv = foldOpWithConstantIntoOperand(I))
980 if (match(Op0, m_One())) {
981 assert(!I.getType()->isIntOrIntVectorTy(1) && "i1 divide not removed?");
982 if (I.getOpcode() == Instruction::SDiv) {
983 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
984 // result is one, if Op1 is -1 then the result is minus one, otherwise
986 Value *Inc = Builder.CreateAdd(Op1, Op0);
987 Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(I.getType(), 3));
988 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
990 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
991 // result is one, otherwise it's zero.
992 return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), I.getType());
996 // See if we can fold away this div instruction.
997 if (SimplifyDemandedInstructionBits(I))
1000 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
1001 Value *X = nullptr, *Z = nullptr;
1002 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
1003 bool isSigned = I.getOpcode() == Instruction::SDiv;
1004 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
1005 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
1006 return BinaryOperator::Create(I.getOpcode(), X, Op1);
1012 static const unsigned MaxDepth = 6;
1016 using FoldUDivOperandCb = Instruction *(*)(Value *Op0, Value *Op1,
1017 const BinaryOperator &I,
1020 /// \brief Used to maintain state for visitUDivOperand().
1021 struct UDivFoldAction {
1022 /// Informs visitUDiv() how to fold this operand. This can be zero if this
1023 /// action joins two actions together.
1024 FoldUDivOperandCb FoldAction;
1026 /// Which operand to fold.
1027 Value *OperandToFold;
1030 /// The instruction returned when FoldAction is invoked.
1031 Instruction *FoldResult;
1033 /// Stores the LHS action index if this action joins two actions together.
1034 size_t SelectLHSIdx;
1037 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
1038 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
1039 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
1040 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
1043 } // end anonymous namespace
1045 // X udiv 2^C -> X >> C
1046 static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
1047 const BinaryOperator &I, InstCombiner &IC) {
1048 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
1049 BinaryOperator *LShr = BinaryOperator::CreateLShr(
1050 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
1056 // X udiv C, where C >= signbit
1057 static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
1058 const BinaryOperator &I, InstCombiner &IC) {
1059 Value *ICI = IC.Builder.CreateICmpULT(Op0, cast<ConstantInt>(Op1));
1061 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
1062 ConstantInt::get(I.getType(), 1));
1065 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
1066 // X udiv (zext (C1 << N)), where C1 is "1<<C2" --> X >> (N+C2)
1067 static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
1070 if (!match(Op1, m_ZExt(m_Value(ShiftLeft))))
1075 if (!match(ShiftLeft, m_Shl(m_APInt(CI), m_Value(N))))
1076 llvm_unreachable("match should never fail here!");
1078 N = IC.Builder.CreateAdd(N, ConstantInt::get(N->getType(), CI->logBase2()));
1079 if (Op1 != ShiftLeft)
1080 N = IC.Builder.CreateZExt(N, Op1->getType());
1081 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
1087 // \brief Recursively visits the possible right hand operands of a udiv
1088 // instruction, seeing through select instructions, to determine if we can
1089 // replace the udiv with something simpler. If we find that an operand is not
1090 // able to simplify the udiv, we abort the entire transformation.
1091 static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
1092 SmallVectorImpl<UDivFoldAction> &Actions,
1093 unsigned Depth = 0) {
1094 // Check to see if this is an unsigned division with an exact power of 2,
1095 // if so, convert to a right shift.
1096 if (match(Op1, m_Power2())) {
1097 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
1098 return Actions.size();
1101 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
1102 // X udiv C, where C >= signbit
1103 if (C->getValue().isNegative()) {
1104 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
1105 return Actions.size();
1108 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
1109 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
1110 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
1111 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
1112 return Actions.size();
1115 // The remaining tests are all recursive, so bail out if we hit the limit.
1116 if (Depth++ == MaxDepth)
1119 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1121 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
1122 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
1123 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
1124 return Actions.size();
1130 /// If we have zero-extended operands of an unsigned div or rem, we may be able
1131 /// to narrow the operation (sink the zext below the math).
1132 static Instruction *narrowUDivURem(BinaryOperator &I,
1133 InstCombiner::BuilderTy &Builder) {
1134 Instruction::BinaryOps Opcode = I.getOpcode();
1135 Value *N = I.getOperand(0);
1136 Value *D = I.getOperand(1);
1137 Type *Ty = I.getType();
1139 if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) &&
1140 X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) {
1141 // udiv (zext X), (zext Y) --> zext (udiv X, Y)
1142 // urem (zext X), (zext Y) --> zext (urem X, Y)
1143 Value *NarrowOp = Builder.CreateBinOp(Opcode, X, Y);
1144 return new ZExtInst(NarrowOp, Ty);
1148 if ((match(N, m_OneUse(m_ZExt(m_Value(X)))) && match(D, m_Constant(C))) ||
1149 (match(D, m_OneUse(m_ZExt(m_Value(X)))) && match(N, m_Constant(C)))) {
1150 // If the constant is the same in the smaller type, use the narrow version.
1151 Constant *TruncC = ConstantExpr::getTrunc(C, X->getType());
1152 if (ConstantExpr::getZExt(TruncC, Ty) != C)
1155 // udiv (zext X), C --> zext (udiv X, C')
1156 // urem (zext X), C --> zext (urem X, C')
1157 // udiv C, (zext X) --> zext (udiv C', X)
1158 // urem C, (zext X) --> zext (urem C', X)
1159 Value *NarrowOp = isa<Constant>(D) ? Builder.CreateBinOp(Opcode, X, TruncC)
1160 : Builder.CreateBinOp(Opcode, TruncC, X);
1161 return new ZExtInst(NarrowOp, Ty);
1167 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
1168 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1170 if (Value *V = SimplifyVectorOp(I))
1171 return replaceInstUsesWith(I, V);
1173 if (Value *V = SimplifyUDivInst(Op0, Op1, SQ.getWithInstruction(&I)))
1174 return replaceInstUsesWith(I, V);
1176 // Handle the integer div common cases
1177 if (Instruction *Common = commonIDivTransforms(I))
1180 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
1183 const APInt *C1, *C2;
1184 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
1185 match(Op1, m_APInt(C2))) {
1187 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
1189 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1190 BinaryOperator *BO = BinaryOperator::CreateUDiv(
1191 X, ConstantInt::get(X->getType(), C2ShlC1));
1199 if (Instruction *NarrowDiv = narrowUDivURem(I, Builder))
1202 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1203 SmallVector<UDivFoldAction, 6> UDivActions;
1204 if (visitUDivOperand(Op0, Op1, I, UDivActions))
1205 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1206 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1207 Value *ActionOp1 = UDivActions[i].OperandToFold;
1210 Inst = Action(Op0, ActionOp1, I, *this);
1212 // This action joins two actions together. The RHS of this action is
1213 // simply the last action we processed, we saved the LHS action index in
1214 // the joining action.
1215 size_t SelectRHSIdx = i - 1;
1216 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1217 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1218 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1219 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1220 SelectLHS, SelectRHS);
1223 // If this is the last action to process, return it to the InstCombiner.
1224 // Otherwise, we insert it before the UDiv and record it so that we may
1225 // use it as part of a joining action (i.e., a SelectInst).
1227 Inst->insertBefore(&I);
1228 UDivActions[i].FoldResult = Inst;
1236 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1237 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1239 if (Value *V = SimplifyVectorOp(I))
1240 return replaceInstUsesWith(I, V);
1242 if (Value *V = SimplifySDivInst(Op0, Op1, SQ.getWithInstruction(&I)))
1243 return replaceInstUsesWith(I, V);
1245 // Handle the integer div common cases
1246 if (Instruction *Common = commonIDivTransforms(I))
1250 if (match(Op1, m_APInt(Op1C))) {
1252 if (Op1C->isAllOnesValue())
1253 return BinaryOperator::CreateNeg(Op0);
1255 // sdiv exact X, C --> ashr exact X, log2(C)
1256 if (I.isExact() && Op1C->isNonNegative() && Op1C->isPowerOf2()) {
1257 Value *ShAmt = ConstantInt::get(Op1->getType(), Op1C->exactLogBase2());
1258 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1261 // If the dividend is sign-extended and the constant divisor is small enough
1262 // to fit in the source type, shrink the division to the narrower type:
1263 // (sext X) sdiv C --> sext (X sdiv C)
1265 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1266 Op0Src->getType()->getScalarSizeInBits() >= Op1C->getMinSignedBits()) {
1268 // In the general case, we need to make sure that the dividend is not the
1269 // minimum signed value because dividing that by -1 is UB. But here, we
1270 // know that the -1 divisor case is already handled above.
1272 Constant *NarrowDivisor =
1273 ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType());
1274 Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor);
1275 return new SExtInst(NarrowOp, Op0->getType());
1279 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
1280 // X/INT_MIN -> X == INT_MIN
1281 if (RHS->isMinSignedValue())
1282 return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), I.getType());
1284 // -X/C --> X/-C provided the negation doesn't overflow.
1286 if (match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1287 auto *BO = BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(RHS));
1288 BO->setIsExact(I.isExact());
1293 // If the sign bits of both operands are zero (i.e. we can prove they are
1294 // unsigned inputs), turn this into a udiv.
1295 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
1296 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1297 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
1298 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1299 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1300 BO->setIsExact(I.isExact());
1304 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
1305 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1306 // Safe because the only negative value (1 << Y) can take on is
1307 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1308 // the sign bit set.
1309 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1310 BO->setIsExact(I.isExact());
1318 /// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1320 /// 1) 1/C is exact, or
1321 /// 2) reciprocal is allowed.
1322 /// If the conversion was successful, the simplified expression "X * 1/C" is
1323 /// returned; otherwise, nullptr is returned.
1324 static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
1325 bool AllowReciprocal) {
1326 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
1329 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
1330 APFloat Reciprocal(FpVal.getSemantics());
1331 bool Cvt = FpVal.getExactInverse(&Reciprocal);
1333 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
1334 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1335 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1336 Cvt = !Reciprocal.isDenormal();
1343 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1344 return BinaryOperator::CreateFMul(Dividend, R);
1347 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1348 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1350 if (Value *V = SimplifyVectorOp(I))
1351 return replaceInstUsesWith(I, V);
1353 if (Value *V = SimplifyFDivInst(Op0, Op1, I.getFastMathFlags(),
1354 SQ.getWithInstruction(&I)))
1355 return replaceInstUsesWith(I, V);
1357 if (isa<Constant>(Op0))
1358 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1359 if (Instruction *R = FoldOpIntoSelect(I, SI))
1362 bool AllowReassociate = I.isFast();
1363 bool AllowReciprocal = I.hasAllowReciprocal();
1365 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1366 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1367 if (Instruction *R = FoldOpIntoSelect(I, SI))
1370 if (AllowReassociate) {
1371 Constant *C1 = nullptr;
1372 Constant *C2 = Op1C;
1374 Instruction *Res = nullptr;
1376 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
1377 // (X*C1)/C2 => X * (C1/C2)
1379 Constant *C = ConstantExpr::getFDiv(C1, C2);
1381 Res = BinaryOperator::CreateFMul(X, C);
1382 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
1383 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1384 Constant *C = ConstantExpr::getFMul(C1, C2);
1385 if (isNormalFp(C)) {
1386 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
1388 Res = BinaryOperator::CreateFDiv(X, C);
1393 Res->setFastMathFlags(I.getFastMathFlags());
1399 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1400 T->copyFastMathFlags(&I);
1407 if (AllowReassociate && isa<Constant>(Op0)) {
1408 Constant *C1 = cast<Constant>(Op0), *C2;
1409 Constant *Fold = nullptr;
1411 bool CreateDiv = true;
1413 // C1 / (X*C2) => (C1/C2) / X
1414 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
1415 Fold = ConstantExpr::getFDiv(C1, C2);
1416 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
1417 // C1 / (X/C2) => (C1*C2) / X
1418 Fold = ConstantExpr::getFMul(C1, C2);
1419 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
1420 // C1 / (C2/X) => (C1/C2) * X
1421 Fold = ConstantExpr::getFDiv(C1, C2);
1425 if (Fold && isNormalFp(Fold)) {
1426 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1427 : BinaryOperator::CreateFMul(X, Fold);
1428 R->setFastMathFlags(I.getFastMathFlags());
1434 if (AllowReassociate) {
1436 Value *NewInst = nullptr;
1437 Instruction *SimpR = nullptr;
1439 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1440 // (X/Y) / Z => X / (Y*Z)
1441 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
1442 NewInst = Builder.CreateFMul(Y, Op1);
1443 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1444 FastMathFlags Flags = I.getFastMathFlags();
1445 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1446 RI->setFastMathFlags(Flags);
1448 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1450 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1451 // Z / (X/Y) => Z*Y / X
1452 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
1453 NewInst = Builder.CreateFMul(Op0, Y);
1454 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1455 FastMathFlags Flags = I.getFastMathFlags();
1456 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1457 RI->setFastMathFlags(Flags);
1459 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1464 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1465 T->setDebugLoc(I.getDebugLoc());
1466 SimpR->setFastMathFlags(I.getFastMathFlags());
1475 if (match(Op0, m_FNeg(m_Value(LHS))) && match(Op1, m_FNeg(m_Value(RHS)))) {
1476 I.setOperand(0, LHS);
1477 I.setOperand(1, RHS);
1484 /// This function implements the transforms common to both integer remainder
1485 /// instructions (urem and srem). It is called by the visitors to those integer
1486 /// remainder instructions.
1487 /// @brief Common integer remainder transforms
1488 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1489 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1491 // The RHS is known non-zero.
1492 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
1497 // Handle cases involving: rem X, (select Cond, Y, Z)
1498 if (simplifyDivRemOfSelectWithZeroOp(I))
1501 if (isa<Constant>(Op1)) {
1502 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1503 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1504 if (Instruction *R = FoldOpIntoSelect(I, SI))
1506 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
1507 const APInt *Op1Int;
1508 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
1509 (I.getOpcode() == Instruction::URem ||
1510 !Op1Int->isMinSignedValue())) {
1511 // foldOpIntoPhi will speculate instructions to the end of the PHI's
1512 // predecessor blocks, so do this only if we know the srem or urem
1514 if (Instruction *NV = foldOpIntoPhi(I, PN))
1519 // See if we can fold away this rem instruction.
1520 if (SimplifyDemandedInstructionBits(I))
1528 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1529 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1531 if (Value *V = SimplifyVectorOp(I))
1532 return replaceInstUsesWith(I, V);
1534 if (Value *V = SimplifyURemInst(Op0, Op1, SQ.getWithInstruction(&I)))
1535 return replaceInstUsesWith(I, V);
1537 if (Instruction *common = commonIRemTransforms(I))
1540 if (Instruction *NarrowRem = narrowUDivURem(I, Builder))
1543 // X urem Y -> X and Y-1, where Y is a power of 2,
1544 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
1545 Constant *N1 = Constant::getAllOnesValue(I.getType());
1546 Value *Add = Builder.CreateAdd(Op1, N1);
1547 return BinaryOperator::CreateAnd(Op0, Add);
1550 // 1 urem X -> zext(X != 1)
1551 if (match(Op0, m_One())) {
1552 Value *Cmp = Builder.CreateICmpNE(Op1, Op0);
1553 Value *Ext = Builder.CreateZExt(Cmp, I.getType());
1554 return replaceInstUsesWith(I, Ext);
1557 // X urem C -> X < C ? X : X - C, where C >= signbit.
1558 const APInt *DivisorC;
1559 if (match(Op1, m_APInt(DivisorC)) && DivisorC->isNegative()) {
1560 Value *Cmp = Builder.CreateICmpULT(Op0, Op1);
1561 Value *Sub = Builder.CreateSub(Op0, Op1);
1562 return SelectInst::Create(Cmp, Op0, Sub);
1568 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1569 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1571 if (Value *V = SimplifyVectorOp(I))
1572 return replaceInstUsesWith(I, V);
1574 if (Value *V = SimplifySRemInst(Op0, Op1, SQ.getWithInstruction(&I)))
1575 return replaceInstUsesWith(I, V);
1577 // Handle the integer rem common cases
1578 if (Instruction *Common = commonIRemTransforms(I))
1584 if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
1585 Worklist.AddValue(I.getOperand(1));
1586 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
1591 // If the sign bits of both operands are zero (i.e. we can prove they are
1592 // unsigned inputs), turn this into a urem.
1593 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
1594 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1595 MaskedValueIsZero(Op0, Mask, 0, &I)) {
1596 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1597 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1600 // If it's a constant vector, flip any negative values positive.
1601 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1602 Constant *C = cast<Constant>(Op1);
1603 unsigned VWidth = C->getType()->getVectorNumElements();
1605 bool hasNegative = false;
1606 bool hasMissing = false;
1607 for (unsigned i = 0; i != VWidth; ++i) {
1608 Constant *Elt = C->getAggregateElement(i);
1614 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
1615 if (RHS->isNegative())
1619 if (hasNegative && !hasMissing) {
1620 SmallVector<Constant *, 16> Elts(VWidth);
1621 for (unsigned i = 0; i != VWidth; ++i) {
1622 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
1623 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
1624 if (RHS->isNegative())
1625 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
1629 Constant *NewRHSV = ConstantVector::get(Elts);
1630 if (NewRHSV != C) { // Don't loop on -MININT
1631 Worklist.AddValue(I.getOperand(1));
1632 I.setOperand(1, NewRHSV);
1641 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
1642 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1644 if (Value *V = SimplifyVectorOp(I))
1645 return replaceInstUsesWith(I, V);
1647 if (Value *V = SimplifyFRemInst(Op0, Op1, I.getFastMathFlags(),
1648 SQ.getWithInstruction(&I)))
1649 return replaceInstUsesWith(I, V);