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 #define DEBUG_TYPE "instcombine"
16 #include "InstCombine.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/IR/IntrinsicInst.h"
19 #include "llvm/IR/PatternMatch.h"
21 using namespace PatternMatch;
24 /// simplifyValueKnownNonZero - The specific integer value is used in a context
25 /// where it is known to be non-zero. If this allows us to simplify the
26 /// computation, do so and return the new operand, otherwise return null.
27 static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC) {
28 // If V has multiple uses, then we would have to do more analysis to determine
29 // if this is safe. For example, the use could be in dynamically unreached
31 if (!V->hasOneUse()) return 0;
33 bool MadeChange = false;
35 // ((1 << A) >>u B) --> (1 << (A-B))
36 // Because V cannot be zero, we know that B is less than A.
37 Value *A = 0, *B = 0, *PowerOf2 = 0;
38 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(PowerOf2), m_Value(A))),
40 // The "1" can be any value known to be a power of 2.
41 isKnownToBeAPowerOfTwo(PowerOf2)) {
42 A = IC.Builder->CreateSub(A, B);
43 return IC.Builder->CreateShl(PowerOf2, A);
46 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
47 // inexact. Similarly for <<.
48 if (BinaryOperator *I = dyn_cast<BinaryOperator>(V))
49 if (I->isLogicalShift() && isKnownToBeAPowerOfTwo(I->getOperand(0))) {
50 // We know that this is an exact/nuw shift and that the input is a
51 // non-zero context as well.
52 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC)) {
57 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
62 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
63 I->setHasNoUnsignedWrap();
68 // TODO: Lots more we could do here:
69 // If V is a phi node, we can call this on each of its operands.
70 // "select cond, X, 0" can simplify to "X".
72 return MadeChange ? V : 0;
76 /// MultiplyOverflows - True if the multiply can not be expressed in an int
78 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
79 uint32_t W = C1->getBitWidth();
80 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
82 LHSExt = LHSExt.sext(W * 2);
83 RHSExt = RHSExt.sext(W * 2);
85 LHSExt = LHSExt.zext(W * 2);
86 RHSExt = RHSExt.zext(W * 2);
89 APInt MulExt = LHSExt * RHSExt;
92 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
94 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
95 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
96 return MulExt.slt(Min) || MulExt.sgt(Max);
99 /// \brief A helper routine of InstCombiner::visitMul().
101 /// If C is a vector of known powers of 2, then this function returns
102 /// a new vector obtained from C replacing each element with its logBase2.
103 /// Return a null pointer otherwise.
104 static Constant *getLogBase2Vector(ConstantDataVector *CV) {
106 SmallVector<Constant *, 4> Elts;
108 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
109 Constant *Elt = CV->getElementAsConstant(I);
110 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
112 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
115 return ConstantVector::get(Elts);
118 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
119 bool Changed = SimplifyAssociativeOrCommutative(I);
120 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
122 if (Value *V = SimplifyMulInst(Op0, Op1, DL))
123 return ReplaceInstUsesWith(I, V);
125 if (Value *V = SimplifyUsingDistributiveLaws(I))
126 return ReplaceInstUsesWith(I, V);
128 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X
129 return BinaryOperator::CreateNeg(Op0, I.getName());
131 // Also allow combining multiply instructions on vectors.
136 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
138 match(C1, m_APInt(IVal)))
139 // ((X << C1)*C2) == (X * (C2 << C1))
140 return BinaryOperator::CreateMul(NewOp, ConstantExpr::getShl(C1, C2));
142 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
143 Constant *NewCst = 0;
144 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
145 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
146 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
147 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
148 // Replace X*(2^C) with X << C, where C is a vector of known
149 // constant powers of 2.
150 NewCst = getLogBase2Vector(CV);
153 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
154 if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap();
155 if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap();
161 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
162 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
163 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
164 // The "* (2**n)" thus becomes a potential shifting opportunity.
166 const APInt & Val = CI->getValue();
167 const APInt &PosVal = Val.abs();
168 if (Val.isNegative() && PosVal.isPowerOf2()) {
169 Value *X = 0, *Y = 0;
170 if (Op0->hasOneUse()) {
173 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
174 Sub = Builder->CreateSub(X, Y, "suba");
175 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
176 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
179 BinaryOperator::CreateMul(Sub,
180 ConstantInt::get(Y->getType(), PosVal));
186 // Simplify mul instructions with a constant RHS.
187 if (isa<Constant>(Op1)) {
188 // Try to fold constant mul into select arguments.
189 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
190 if (Instruction *R = FoldOpIntoSelect(I, SI))
193 if (isa<PHINode>(Op0))
194 if (Instruction *NV = FoldOpIntoPhi(I))
197 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
201 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
202 Value *Add = Builder->CreateMul(X, Op1);
203 return BinaryOperator::CreateAdd(Add, Builder->CreateMul(C1, Op1));
208 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
209 if (Value *Op1v = dyn_castNegVal(Op1))
210 return BinaryOperator::CreateMul(Op0v, Op1v);
212 // (X / Y) * Y = X - (X % Y)
213 // (X / Y) * -Y = (X % Y) - X
216 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
218 (BO->getOpcode() != Instruction::UDiv &&
219 BO->getOpcode() != Instruction::SDiv)) {
221 BO = dyn_cast<BinaryOperator>(Op1);
223 Value *Neg = dyn_castNegVal(Op1C);
224 if (BO && BO->hasOneUse() &&
225 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
226 (BO->getOpcode() == Instruction::UDiv ||
227 BO->getOpcode() == Instruction::SDiv)) {
228 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
230 // If the division is exact, X % Y is zero, so we end up with X or -X.
231 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
232 if (SDiv->isExact()) {
234 return ReplaceInstUsesWith(I, Op0BO);
235 return BinaryOperator::CreateNeg(Op0BO);
239 if (BO->getOpcode() == Instruction::UDiv)
240 Rem = Builder->CreateURem(Op0BO, Op1BO);
242 Rem = Builder->CreateSRem(Op0BO, Op1BO);
246 return BinaryOperator::CreateSub(Op0BO, Rem);
247 return BinaryOperator::CreateSub(Rem, Op0BO);
251 /// i1 mul -> i1 and.
252 if (I.getType()->getScalarType()->isIntegerTy(1))
253 return BinaryOperator::CreateAnd(Op0, Op1);
255 // X*(1 << Y) --> X << Y
256 // (1 << Y)*X --> X << Y
259 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
260 return BinaryOperator::CreateShl(Op1, Y);
261 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
262 return BinaryOperator::CreateShl(Op0, Y);
265 // If one of the operands of the multiply is a cast from a boolean value, then
266 // we know the bool is either zero or one, so this is a 'masking' multiply.
267 // X * Y (where Y is 0 or 1) -> X & (0-Y)
268 if (!I.getType()->isVectorTy()) {
269 // -2 is "-1 << 1" so it is all bits set except the low one.
270 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
272 Value *BoolCast = 0, *OtherOp = 0;
273 if (MaskedValueIsZero(Op0, Negative2))
274 BoolCast = Op0, OtherOp = Op1;
275 else if (MaskedValueIsZero(Op1, Negative2))
276 BoolCast = Op1, OtherOp = Op0;
279 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
281 return BinaryOperator::CreateAnd(V, OtherOp);
285 return Changed ? &I : 0;
293 // And check for corresponding fast math flags
296 static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
298 if (!Op->hasOneUse())
301 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
304 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
308 Value *OpLog2Of = II->getArgOperand(0);
309 if (!OpLog2Of->hasOneUse())
312 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
315 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
318 if (match(I->getOperand(0), m_SpecificFP(0.5)))
319 Y = I->getOperand(1);
320 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
321 Y = I->getOperand(0);
324 static bool isFiniteNonZeroFp(Constant *C) {
325 if (C->getType()->isVectorTy()) {
326 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
328 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
329 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
335 return isa<ConstantFP>(C) &&
336 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
339 static bool isNormalFp(Constant *C) {
340 if (C->getType()->isVectorTy()) {
341 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
343 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
344 if (!CFP || !CFP->getValueAPF().isNormal())
350 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
353 /// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
354 /// true iff the given value is FMul or FDiv with one and only one operand
355 /// being a normal constant (i.e. not Zero/NaN/Infinity).
356 static bool isFMulOrFDivWithConstant(Value *V) {
357 Instruction *I = dyn_cast<Instruction>(V);
358 if (!I || (I->getOpcode() != Instruction::FMul &&
359 I->getOpcode() != Instruction::FDiv))
362 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
363 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
368 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
371 /// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
372 /// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
373 /// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
374 /// This function is to simplify "FMulOrDiv * C" and returns the
375 /// resulting expression. Note that this function could return NULL in
376 /// case the constants cannot be folded into a normal floating-point.
378 Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
379 Instruction *InsertBefore) {
380 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
382 Value *Opnd0 = FMulOrDiv->getOperand(0);
383 Value *Opnd1 = FMulOrDiv->getOperand(1);
385 Constant *C0 = dyn_cast<Constant>(Opnd0);
386 Constant *C1 = dyn_cast<Constant>(Opnd1);
388 BinaryOperator *R = 0;
390 // (X * C0) * C => X * (C0*C)
391 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
392 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
394 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
397 // (C0 / X) * C => (C0 * C) / X
398 if (FMulOrDiv->hasOneUse()) {
399 // It would otherwise introduce another div.
400 Constant *F = ConstantExpr::getFMul(C0, C);
402 R = BinaryOperator::CreateFDiv(F, Opnd1);
405 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
406 Constant *F = ConstantExpr::getFDiv(C, C1);
408 R = BinaryOperator::CreateFMul(Opnd0, F);
410 // (X / C1) * C => X / (C1/C)
411 Constant *F = ConstantExpr::getFDiv(C1, C);
413 R = BinaryOperator::CreateFDiv(Opnd0, F);
419 R->setHasUnsafeAlgebra(true);
420 InsertNewInstWith(R, *InsertBefore);
426 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
427 bool Changed = SimplifyAssociativeOrCommutative(I);
428 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
430 if (isa<Constant>(Op0))
433 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL))
434 return ReplaceInstUsesWith(I, V);
436 bool AllowReassociate = I.hasUnsafeAlgebra();
438 // Simplify mul instructions with a constant RHS.
439 if (isa<Constant>(Op1)) {
440 // Try to fold constant mul into select arguments.
441 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
442 if (Instruction *R = FoldOpIntoSelect(I, SI))
445 if (isa<PHINode>(Op0))
446 if (Instruction *NV = FoldOpIntoPhi(I))
449 // (fmul X, -1.0) --> (fsub -0.0, X)
450 if (match(Op1, m_SpecificFP(-1.0))) {
451 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
452 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
453 RI->copyFastMathFlags(&I);
457 Constant *C = cast<Constant>(Op1);
458 if (AllowReassociate && isFiniteNonZeroFp(C)) {
459 // Let MDC denote an expression in one of these forms:
460 // X * C, C/X, X/C, where C is a constant.
462 // Try to simplify "MDC * Constant"
463 if (isFMulOrFDivWithConstant(Op0))
464 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
465 return ReplaceInstUsesWith(I, V);
467 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
468 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
470 (FAddSub->getOpcode() == Instruction::FAdd ||
471 FAddSub->getOpcode() == Instruction::FSub)) {
472 Value *Opnd0 = FAddSub->getOperand(0);
473 Value *Opnd1 = FAddSub->getOperand(1);
474 Constant *C0 = dyn_cast<Constant>(Opnd0);
475 Constant *C1 = dyn_cast<Constant>(Opnd1);
479 std::swap(Opnd0, Opnd1);
483 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
484 Value *M1 = ConstantExpr::getFMul(C1, C);
485 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
486 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
489 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
492 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
493 ? BinaryOperator::CreateFAdd(M0, M1)
494 : BinaryOperator::CreateFSub(M0, M1);
495 RI->copyFastMathFlags(&I);
504 // Under unsafe algebra do:
505 // X * log2(0.5*Y) = X*log2(Y) - X
506 if (I.hasUnsafeAlgebra()) {
510 detectLog2OfHalf(Op0, OpY, Log2);
514 detectLog2OfHalf(Op1, OpY, Log2);
519 // if pattern detected emit alternate sequence
521 BuilderTy::FastMathFlagGuard Guard(*Builder);
522 Builder->SetFastMathFlags(Log2->getFastMathFlags());
523 Log2->setArgOperand(0, OpY);
524 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
525 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
527 return ReplaceInstUsesWith(I, FSub);
531 // Handle symmetric situation in a 2-iteration loop
534 for (int i = 0; i < 2; i++) {
535 bool IgnoreZeroSign = I.hasNoSignedZeros();
536 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
537 BuilderTy::FastMathFlagGuard Guard(*Builder);
538 Builder->SetFastMathFlags(I.getFastMathFlags());
540 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
541 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
545 Value *FMul = Builder->CreateFMul(N0, N1);
547 return ReplaceInstUsesWith(I, FMul);
550 if (Opnd0->hasOneUse()) {
551 // -X * Y => -(X*Y) (Promote negation as high as possible)
552 Value *T = Builder->CreateFMul(N0, Opnd1);
553 Value *Neg = Builder->CreateFNeg(T);
555 return ReplaceInstUsesWith(I, Neg);
559 // (X*Y) * X => (X*X) * Y where Y != X
560 // The purpose is two-fold:
561 // 1) to form a power expression (of X).
562 // 2) potentially shorten the critical path: After transformation, the
563 // latency of the instruction Y is amortized by the expression of X*X,
564 // and therefore Y is in a "less critical" position compared to what it
565 // was before the transformation.
567 if (AllowReassociate) {
568 Value *Opnd0_0, *Opnd0_1;
569 if (Opnd0->hasOneUse() &&
570 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
572 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
574 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
578 BuilderTy::FastMathFlagGuard Guard(*Builder);
579 Builder->SetFastMathFlags(I.getFastMathFlags());
580 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
582 Value *R = Builder->CreateFMul(T, Y);
584 return ReplaceInstUsesWith(I, R);
589 // B * (uitofp i1 C) -> select C, B, 0
590 if (I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) {
591 Value *LHS = Op0, *RHS = Op1;
593 if (!match(RHS, m_UIToFP(m_Value(C))))
596 if (match(RHS, m_UIToFP(m_Value(C))) &&
597 C->getType()->getScalarType()->isIntegerTy(1)) {
599 Value *Zero = ConstantFP::getNegativeZero(B->getType());
600 return SelectInst::Create(C, B, Zero);
604 // A * (1 - uitofp i1 C) -> select C, 0, A
605 if (I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) {
606 Value *LHS = Op0, *RHS = Op1;
608 if (!match(RHS, m_FSub(m_FPOne(), m_UIToFP(m_Value(C)))))
611 if (match(RHS, m_FSub(m_FPOne(), m_UIToFP(m_Value(C)))) &&
612 C->getType()->getScalarType()->isIntegerTy(1)) {
614 Value *Zero = ConstantFP::getNegativeZero(A->getType());
615 return SelectInst::Create(C, Zero, A);
619 if (!isa<Constant>(Op1))
620 std::swap(Opnd0, Opnd1);
625 return Changed ? &I : 0;
628 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
630 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
631 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
633 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
634 int NonNullOperand = -1;
635 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
636 if (ST->isNullValue())
638 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
639 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
640 if (ST->isNullValue())
643 if (NonNullOperand == -1)
646 Value *SelectCond = SI->getOperand(0);
648 // Change the div/rem to use 'Y' instead of the select.
649 I.setOperand(1, SI->getOperand(NonNullOperand));
651 // Okay, we know we replace the operand of the div/rem with 'Y' with no
652 // problem. However, the select, or the condition of the select may have
653 // multiple uses. Based on our knowledge that the operand must be non-zero,
654 // propagate the known value for the select into other uses of it, and
655 // propagate a known value of the condition into its other users.
657 // If the select and condition only have a single use, don't bother with this,
659 if (SI->use_empty() && SelectCond->hasOneUse())
662 // Scan the current block backward, looking for other uses of SI.
663 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
665 while (BBI != BBFront) {
667 // If we found a call to a function, we can't assume it will return, so
668 // information from below it cannot be propagated above it.
669 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
672 // Replace uses of the select or its condition with the known values.
673 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
676 *I = SI->getOperand(NonNullOperand);
678 } else if (*I == SelectCond) {
679 *I = Builder->getInt1(NonNullOperand == 1);
684 // If we past the instruction, quit looking for it.
687 if (&*BBI == SelectCond)
690 // If we ran out of things to eliminate, break out of the loop.
691 if (SelectCond == 0 && SI == 0)
699 /// This function implements the transforms common to both integer division
700 /// instructions (udiv and sdiv). It is called by the visitors to those integer
701 /// division instructions.
702 /// @brief Common integer divide transforms
703 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
704 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
706 // The RHS is known non-zero.
707 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
712 // Handle cases involving: [su]div X, (select Cond, Y, Z)
713 // This does not apply for fdiv.
714 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
717 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
718 // (X / C1) / C2 -> X / (C1*C2)
719 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
720 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
721 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
722 if (MultiplyOverflows(RHS, LHSRHS,
723 I.getOpcode()==Instruction::SDiv))
724 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
725 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
726 ConstantExpr::getMul(RHS, LHSRHS));
729 if (!RHS->isZero()) { // avoid X udiv 0
730 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
731 if (Instruction *R = FoldOpIntoSelect(I, SI))
733 if (isa<PHINode>(Op0))
734 if (Instruction *NV = FoldOpIntoPhi(I))
739 // See if we can fold away this div instruction.
740 if (SimplifyDemandedInstructionBits(I))
743 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
744 Value *X = 0, *Z = 0;
745 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
746 bool isSigned = I.getOpcode() == Instruction::SDiv;
747 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
748 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
749 return BinaryOperator::Create(I.getOpcode(), X, Op1);
755 /// dyn_castZExtVal - Checks if V is a zext or constant that can
756 /// be truncated to Ty without losing bits.
757 static Value *dyn_castZExtVal(Value *V, Type *Ty) {
758 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
759 if (Z->getSrcTy() == Ty)
760 return Z->getOperand(0);
761 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
762 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
763 return ConstantExpr::getTrunc(C, Ty);
769 const unsigned MaxDepth = 6;
770 typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
771 const BinaryOperator &I,
774 /// \brief Used to maintain state for visitUDivOperand().
775 struct UDivFoldAction {
776 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
777 ///< operand. This can be zero if this action
778 ///< joins two actions together.
780 Value *OperandToFold; ///< Which operand to fold.
782 Instruction *FoldResult; ///< The instruction returned when FoldAction is
785 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
786 ///< joins two actions together.
789 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
790 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(0) {}
791 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
792 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
796 // X udiv 2^C -> X >> C
797 static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
798 const BinaryOperator &I, InstCombiner &IC) {
799 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
800 BinaryOperator *LShr = BinaryOperator::CreateLShr(
801 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
802 if (I.isExact()) LShr->setIsExact();
806 // X udiv C, where C >= signbit
807 static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
808 const BinaryOperator &I, InstCombiner &IC) {
809 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
811 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
812 ConstantInt::get(I.getType(), 1));
815 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
816 static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
818 Instruction *ShiftLeft = cast<Instruction>(Op1);
819 if (isa<ZExtInst>(ShiftLeft))
820 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
823 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
824 Value *N = ShiftLeft->getOperand(1);
826 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
827 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
828 N = IC.Builder->CreateZExt(N, Z->getDestTy());
829 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
830 if (I.isExact()) LShr->setIsExact();
834 // \brief Recursively visits the possible right hand operands of a udiv
835 // instruction, seeing through select instructions, to determine if we can
836 // replace the udiv with something simpler. If we find that an operand is not
837 // able to simplify the udiv, we abort the entire transformation.
838 static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
839 SmallVectorImpl<UDivFoldAction> &Actions,
840 unsigned Depth = 0) {
841 // Check to see if this is an unsigned division with an exact power of 2,
842 // if so, convert to a right shift.
843 if (match(Op1, m_Power2())) {
844 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
845 return Actions.size();
848 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
849 // X udiv C, where C >= signbit
850 if (C->getValue().isNegative()) {
851 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
852 return Actions.size();
855 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
856 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
857 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
858 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
859 return Actions.size();
862 // The remaining tests are all recursive, so bail out if we hit the limit.
863 if (Depth++ == MaxDepth)
866 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
867 if (size_t LHSIdx = visitUDivOperand(Op0, SI->getOperand(1), I, Actions))
868 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions)) {
869 Actions.push_back(UDivFoldAction((FoldUDivOperandCb)0, Op1, LHSIdx-1));
870 return Actions.size();
876 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
877 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
879 if (Value *V = SimplifyUDivInst(Op0, Op1, DL))
880 return ReplaceInstUsesWith(I, V);
882 // Handle the integer div common cases
883 if (Instruction *Common = commonIDivTransforms(I))
886 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
887 if (Constant *C2 = dyn_cast<Constant>(Op1)) {
890 if (match(Op0, m_LShr(m_Value(X), m_Constant(C1))))
891 return BinaryOperator::CreateUDiv(X, ConstantExpr::getShl(C2, C1));
894 // (zext A) udiv (zext B) --> zext (A udiv B)
895 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
896 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
897 return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
901 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
902 SmallVector<UDivFoldAction, 6> UDivActions;
903 if (visitUDivOperand(Op0, Op1, I, UDivActions))
904 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
905 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
906 Value *ActionOp1 = UDivActions[i].OperandToFold;
909 Inst = Action(Op0, ActionOp1, I, *this);
911 // This action joins two actions together. The RHS of this action is
912 // simply the last action we processed, we saved the LHS action index in
913 // the joining action.
914 size_t SelectRHSIdx = i - 1;
915 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
916 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
917 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
918 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
919 SelectLHS, SelectRHS);
922 // If this is the last action to process, return it to the InstCombiner.
923 // Otherwise, we insert it before the UDiv and record it so that we may
924 // use it as part of a joining action (i.e., a SelectInst).
926 Inst->insertBefore(&I);
927 UDivActions[i].FoldResult = Inst;
935 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
936 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
938 if (Value *V = SimplifySDivInst(Op0, Op1, DL))
939 return ReplaceInstUsesWith(I, V);
941 // Handle the integer div common cases
942 if (Instruction *Common = commonIDivTransforms(I))
946 if (match(Op1, m_AllOnes()))
947 return BinaryOperator::CreateNeg(Op0);
949 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
950 // sdiv X, C --> ashr exact X, log2(C)
951 if (I.isExact() && RHS->getValue().isNonNegative() &&
952 RHS->getValue().isPowerOf2()) {
953 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
954 RHS->getValue().exactLogBase2());
955 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
959 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
960 // -X/C --> X/-C provided the negation doesn't overflow.
961 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
962 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
963 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
964 ConstantExpr::getNeg(RHS));
967 // If the sign bits of both operands are zero (i.e. we can prove they are
968 // unsigned inputs), turn this into a udiv.
969 if (I.getType()->isIntegerTy()) {
970 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
971 if (MaskedValueIsZero(Op0, Mask)) {
972 if (MaskedValueIsZero(Op1, Mask)) {
973 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
974 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
977 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
978 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
979 // Safe because the only negative value (1 << Y) can take on is
980 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
982 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
990 /// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
992 /// 1) 1/C is exact, or
993 /// 2) reciprocal is allowed.
994 /// If the conversion was successful, the simplified expression "X * 1/C" is
995 /// returned; otherwise, NULL is returned.
997 static Instruction *CvtFDivConstToReciprocal(Value *Dividend,
999 bool AllowReciprocal) {
1000 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
1003 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
1004 APFloat Reciprocal(FpVal.getSemantics());
1005 bool Cvt = FpVal.getExactInverse(&Reciprocal);
1007 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
1008 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1009 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1010 Cvt = !Reciprocal.isDenormal();
1017 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1018 return BinaryOperator::CreateFMul(Dividend, R);
1021 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1022 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1024 if (Value *V = SimplifyFDivInst(Op0, Op1, DL))
1025 return ReplaceInstUsesWith(I, V);
1027 if (isa<Constant>(Op0))
1028 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1029 if (Instruction *R = FoldOpIntoSelect(I, SI))
1032 bool AllowReassociate = I.hasUnsafeAlgebra();
1033 bool AllowReciprocal = I.hasAllowReciprocal();
1035 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1036 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1037 if (Instruction *R = FoldOpIntoSelect(I, SI))
1040 if (AllowReassociate) {
1042 Constant *C2 = Op1C;
1044 Instruction *Res = 0;
1046 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
1047 // (X*C1)/C2 => X * (C1/C2)
1049 Constant *C = ConstantExpr::getFDiv(C1, C2);
1051 Res = BinaryOperator::CreateFMul(X, C);
1052 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
1053 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1055 Constant *C = ConstantExpr::getFMul(C1, C2);
1056 if (isNormalFp(C)) {
1057 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
1059 Res = BinaryOperator::CreateFDiv(X, C);
1064 Res->setFastMathFlags(I.getFastMathFlags());
1070 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1071 T->copyFastMathFlags(&I);
1078 if (AllowReassociate && isa<Constant>(Op0)) {
1079 Constant *C1 = cast<Constant>(Op0), *C2;
1082 bool CreateDiv = true;
1084 // C1 / (X*C2) => (C1/C2) / X
1085 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
1086 Fold = ConstantExpr::getFDiv(C1, C2);
1087 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
1088 // C1 / (X/C2) => (C1*C2) / X
1089 Fold = ConstantExpr::getFMul(C1, C2);
1090 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
1091 // C1 / (C2/X) => (C1/C2) * X
1092 Fold = ConstantExpr::getFDiv(C1, C2);
1096 if (Fold && isNormalFp(Fold)) {
1097 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1098 : BinaryOperator::CreateFMul(X, Fold);
1099 R->setFastMathFlags(I.getFastMathFlags());
1105 if (AllowReassociate) {
1108 Instruction *SimpR = 0;
1110 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1111 // (X/Y) / Z => X / (Y*Z)
1113 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
1114 NewInst = Builder->CreateFMul(Y, Op1);
1115 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1116 FastMathFlags Flags = I.getFastMathFlags();
1117 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1118 RI->setFastMathFlags(Flags);
1120 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1122 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1123 // Z / (X/Y) => Z*Y / X
1125 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
1126 NewInst = Builder->CreateFMul(Op0, Y);
1127 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1128 FastMathFlags Flags = I.getFastMathFlags();
1129 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1130 RI->setFastMathFlags(Flags);
1132 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1137 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1138 T->setDebugLoc(I.getDebugLoc());
1139 SimpR->setFastMathFlags(I.getFastMathFlags());
1147 /// This function implements the transforms common to both integer remainder
1148 /// instructions (urem and srem). It is called by the visitors to those integer
1149 /// remainder instructions.
1150 /// @brief Common integer remainder transforms
1151 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1152 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1154 // The RHS is known non-zero.
1155 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
1160 // Handle cases involving: rem X, (select Cond, Y, Z)
1161 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1164 if (isa<Constant>(Op1)) {
1165 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1166 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1167 if (Instruction *R = FoldOpIntoSelect(I, SI))
1169 } else if (isa<PHINode>(Op0I)) {
1170 if (Instruction *NV = FoldOpIntoPhi(I))
1174 // See if we can fold away this rem instruction.
1175 if (SimplifyDemandedInstructionBits(I))
1183 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1184 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1186 if (Value *V = SimplifyURemInst(Op0, Op1, DL))
1187 return ReplaceInstUsesWith(I, V);
1189 if (Instruction *common = commonIRemTransforms(I))
1192 // (zext A) urem (zext B) --> zext (A urem B)
1193 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1194 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1195 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1198 // X urem Y -> X and Y-1, where Y is a power of 2,
1199 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true)) {
1200 Constant *N1 = Constant::getAllOnesValue(I.getType());
1201 Value *Add = Builder->CreateAdd(Op1, N1);
1202 return BinaryOperator::CreateAnd(Op0, Add);
1205 // 1 urem X -> zext(X != 1)
1206 if (match(Op0, m_One())) {
1207 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1208 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1209 return ReplaceInstUsesWith(I, Ext);
1215 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1216 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1218 if (Value *V = SimplifySRemInst(Op0, Op1, DL))
1219 return ReplaceInstUsesWith(I, V);
1221 // Handle the integer rem common cases
1222 if (Instruction *Common = commonIRemTransforms(I))
1225 if (Value *RHSNeg = dyn_castNegVal(Op1))
1226 if (!isa<Constant>(RHSNeg) ||
1227 (isa<ConstantInt>(RHSNeg) &&
1228 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
1230 Worklist.AddValue(I.getOperand(1));
1231 I.setOperand(1, RHSNeg);
1235 // If the sign bits of both operands are zero (i.e. we can prove they are
1236 // unsigned inputs), turn this into a urem.
1237 if (I.getType()->isIntegerTy()) {
1238 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1239 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
1240 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1241 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1245 // If it's a constant vector, flip any negative values positive.
1246 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1247 Constant *C = cast<Constant>(Op1);
1248 unsigned VWidth = C->getType()->getVectorNumElements();
1250 bool hasNegative = false;
1251 bool hasMissing = false;
1252 for (unsigned i = 0; i != VWidth; ++i) {
1253 Constant *Elt = C->getAggregateElement(i);
1259 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
1260 if (RHS->isNegative())
1264 if (hasNegative && !hasMissing) {
1265 SmallVector<Constant *, 16> Elts(VWidth);
1266 for (unsigned i = 0; i != VWidth; ++i) {
1267 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
1268 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
1269 if (RHS->isNegative())
1270 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
1274 Constant *NewRHSV = ConstantVector::get(Elts);
1275 if (NewRHSV != C) { // Don't loop on -MININT
1276 Worklist.AddValue(I.getOperand(1));
1277 I.setOperand(1, NewRHSV);
1286 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
1287 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1289 if (Value *V = SimplifyFRemInst(Op0, Op1, DL))
1290 return ReplaceInstUsesWith(I, V);
1292 // Handle cases involving: rem X, (select Cond, Y, Z)
1293 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))