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 "InstCombine.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/IR/IntrinsicInst.h"
18 #include "llvm/IR/PatternMatch.h"
20 using namespace PatternMatch;
22 #define DEBUG_TYPE "instcombine"
25 /// simplifyValueKnownNonZero - The specific integer value is used in a context
26 /// where it is known to be non-zero. If this allows us to simplify the
27 /// computation, do so and return the new operand, otherwise return null.
28 static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC) {
29 // If V has multiple uses, then we would have to do more analysis to determine
30 // if this is safe. For example, the use could be in dynamically unreached
32 if (!V->hasOneUse()) return 0;
34 bool MadeChange = false;
36 // ((1 << A) >>u B) --> (1 << (A-B))
37 // Because V cannot be zero, we know that B is less than A.
38 Value *A = 0, *B = 0, *PowerOf2 = 0;
39 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(PowerOf2), m_Value(A))),
41 // The "1" can be any value known to be a power of 2.
42 isKnownToBeAPowerOfTwo(PowerOf2)) {
43 A = IC.Builder->CreateSub(A, B);
44 return IC.Builder->CreateShl(PowerOf2, A);
47 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
48 // inexact. Similarly for <<.
49 if (BinaryOperator *I = dyn_cast<BinaryOperator>(V))
50 if (I->isLogicalShift() && isKnownToBeAPowerOfTwo(I->getOperand(0))) {
51 // We know that this is an exact/nuw shift and that the input is a
52 // non-zero context as well.
53 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC)) {
58 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
63 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
64 I->setHasNoUnsignedWrap();
69 // TODO: Lots more we could do here:
70 // If V is a phi node, we can call this on each of its operands.
71 // "select cond, X, 0" can simplify to "X".
73 return MadeChange ? V : 0;
77 /// MultiplyOverflows - True if the multiply can not be expressed in an int
79 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
80 uint32_t W = C1->getBitWidth();
81 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
83 LHSExt = LHSExt.sext(W * 2);
84 RHSExt = RHSExt.sext(W * 2);
86 LHSExt = LHSExt.zext(W * 2);
87 RHSExt = RHSExt.zext(W * 2);
90 APInt MulExt = LHSExt * RHSExt;
93 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
95 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
96 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
97 return MulExt.slt(Min) || MulExt.sgt(Max);
100 /// \brief A helper routine of InstCombiner::visitMul().
102 /// If C is a vector of known powers of 2, then this function returns
103 /// a new vector obtained from C replacing each element with its logBase2.
104 /// Return a null pointer otherwise.
105 static Constant *getLogBase2Vector(ConstantDataVector *CV) {
107 SmallVector<Constant *, 4> Elts;
109 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
110 Constant *Elt = CV->getElementAsConstant(I);
111 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
113 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
116 return ConstantVector::get(Elts);
119 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
120 bool Changed = SimplifyAssociativeOrCommutative(I);
121 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
123 if (Value *V = SimplifyMulInst(Op0, Op1, DL))
124 return ReplaceInstUsesWith(I, V);
126 if (Value *V = SimplifyUsingDistributiveLaws(I))
127 return ReplaceInstUsesWith(I, V);
129 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X
130 return BinaryOperator::CreateNeg(Op0, I.getName());
132 // Also allow combining multiply instructions on vectors.
137 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
139 match(C1, m_APInt(IVal)))
140 // ((X << C1)*C2) == (X * (C2 << C1))
141 return BinaryOperator::CreateMul(NewOp, ConstantExpr::getShl(C1, C2));
143 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
144 Constant *NewCst = 0;
145 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
146 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
147 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
148 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
149 // Replace X*(2^C) with X << C, where C is a vector of known
150 // constant powers of 2.
151 NewCst = getLogBase2Vector(CV);
154 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
155 if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap();
156 if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap();
162 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
163 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
164 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
165 // The "* (2**n)" thus becomes a potential shifting opportunity.
167 const APInt & Val = CI->getValue();
168 const APInt &PosVal = Val.abs();
169 if (Val.isNegative() && PosVal.isPowerOf2()) {
170 Value *X = 0, *Y = 0;
171 if (Op0->hasOneUse()) {
174 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
175 Sub = Builder->CreateSub(X, Y, "suba");
176 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
177 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
180 BinaryOperator::CreateMul(Sub,
181 ConstantInt::get(Y->getType(), PosVal));
187 // Simplify mul instructions with a constant RHS.
188 if (isa<Constant>(Op1)) {
189 // Try to fold constant mul into select arguments.
190 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
191 if (Instruction *R = FoldOpIntoSelect(I, SI))
194 if (isa<PHINode>(Op0))
195 if (Instruction *NV = FoldOpIntoPhi(I))
198 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
202 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
203 Value *Add = Builder->CreateMul(X, Op1);
204 return BinaryOperator::CreateAdd(Add, Builder->CreateMul(C1, Op1));
209 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
210 if (Value *Op1v = dyn_castNegVal(Op1))
211 return BinaryOperator::CreateMul(Op0v, Op1v);
213 // (X / Y) * Y = X - (X % Y)
214 // (X / Y) * -Y = (X % Y) - X
217 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
219 (BO->getOpcode() != Instruction::UDiv &&
220 BO->getOpcode() != Instruction::SDiv)) {
222 BO = dyn_cast<BinaryOperator>(Op1);
224 Value *Neg = dyn_castNegVal(Op1C);
225 if (BO && BO->hasOneUse() &&
226 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
227 (BO->getOpcode() == Instruction::UDiv ||
228 BO->getOpcode() == Instruction::SDiv)) {
229 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
231 // If the division is exact, X % Y is zero, so we end up with X or -X.
232 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
233 if (SDiv->isExact()) {
235 return ReplaceInstUsesWith(I, Op0BO);
236 return BinaryOperator::CreateNeg(Op0BO);
240 if (BO->getOpcode() == Instruction::UDiv)
241 Rem = Builder->CreateURem(Op0BO, Op1BO);
243 Rem = Builder->CreateSRem(Op0BO, Op1BO);
247 return BinaryOperator::CreateSub(Op0BO, Rem);
248 return BinaryOperator::CreateSub(Rem, Op0BO);
252 /// i1 mul -> i1 and.
253 if (I.getType()->getScalarType()->isIntegerTy(1))
254 return BinaryOperator::CreateAnd(Op0, Op1);
256 // X*(1 << Y) --> X << Y
257 // (1 << Y)*X --> X << Y
260 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
261 return BinaryOperator::CreateShl(Op1, Y);
262 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
263 return BinaryOperator::CreateShl(Op0, Y);
266 // If one of the operands of the multiply is a cast from a boolean value, then
267 // we know the bool is either zero or one, so this is a 'masking' multiply.
268 // X * Y (where Y is 0 or 1) -> X & (0-Y)
269 if (!I.getType()->isVectorTy()) {
270 // -2 is "-1 << 1" so it is all bits set except the low one.
271 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
273 Value *BoolCast = 0, *OtherOp = 0;
274 if (MaskedValueIsZero(Op0, Negative2))
275 BoolCast = Op0, OtherOp = Op1;
276 else if (MaskedValueIsZero(Op1, Negative2))
277 BoolCast = Op1, OtherOp = Op0;
280 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
282 return BinaryOperator::CreateAnd(V, OtherOp);
286 return Changed ? &I : 0;
294 // And check for corresponding fast math flags
297 static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
299 if (!Op->hasOneUse())
302 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
305 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
309 Value *OpLog2Of = II->getArgOperand(0);
310 if (!OpLog2Of->hasOneUse())
313 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
316 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
319 if (match(I->getOperand(0), m_SpecificFP(0.5)))
320 Y = I->getOperand(1);
321 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
322 Y = I->getOperand(0);
325 static bool isFiniteNonZeroFp(Constant *C) {
326 if (C->getType()->isVectorTy()) {
327 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
329 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
330 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
336 return isa<ConstantFP>(C) &&
337 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
340 static bool isNormalFp(Constant *C) {
341 if (C->getType()->isVectorTy()) {
342 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
344 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
345 if (!CFP || !CFP->getValueAPF().isNormal())
351 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
354 /// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
355 /// true iff the given value is FMul or FDiv with one and only one operand
356 /// being a normal constant (i.e. not Zero/NaN/Infinity).
357 static bool isFMulOrFDivWithConstant(Value *V) {
358 Instruction *I = dyn_cast<Instruction>(V);
359 if (!I || (I->getOpcode() != Instruction::FMul &&
360 I->getOpcode() != Instruction::FDiv))
363 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
364 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
369 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
372 /// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
373 /// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
374 /// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
375 /// This function is to simplify "FMulOrDiv * C" and returns the
376 /// resulting expression. Note that this function could return NULL in
377 /// case the constants cannot be folded into a normal floating-point.
379 Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
380 Instruction *InsertBefore) {
381 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
383 Value *Opnd0 = FMulOrDiv->getOperand(0);
384 Value *Opnd1 = FMulOrDiv->getOperand(1);
386 Constant *C0 = dyn_cast<Constant>(Opnd0);
387 Constant *C1 = dyn_cast<Constant>(Opnd1);
389 BinaryOperator *R = 0;
391 // (X * C0) * C => X * (C0*C)
392 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
393 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
395 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
398 // (C0 / X) * C => (C0 * C) / X
399 if (FMulOrDiv->hasOneUse()) {
400 // It would otherwise introduce another div.
401 Constant *F = ConstantExpr::getFMul(C0, C);
403 R = BinaryOperator::CreateFDiv(F, Opnd1);
406 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
407 Constant *F = ConstantExpr::getFDiv(C, C1);
409 R = BinaryOperator::CreateFMul(Opnd0, F);
411 // (X / C1) * C => X / (C1/C)
412 Constant *F = ConstantExpr::getFDiv(C1, C);
414 R = BinaryOperator::CreateFDiv(Opnd0, F);
420 R->setHasUnsafeAlgebra(true);
421 InsertNewInstWith(R, *InsertBefore);
427 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
428 bool Changed = SimplifyAssociativeOrCommutative(I);
429 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
431 if (isa<Constant>(Op0))
434 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL))
435 return ReplaceInstUsesWith(I, V);
437 bool AllowReassociate = I.hasUnsafeAlgebra();
439 // Simplify mul instructions with a constant RHS.
440 if (isa<Constant>(Op1)) {
441 // Try to fold constant mul into select arguments.
442 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
443 if (Instruction *R = FoldOpIntoSelect(I, SI))
446 if (isa<PHINode>(Op0))
447 if (Instruction *NV = FoldOpIntoPhi(I))
450 // (fmul X, -1.0) --> (fsub -0.0, X)
451 if (match(Op1, m_SpecificFP(-1.0))) {
452 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
453 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
454 RI->copyFastMathFlags(&I);
458 Constant *C = cast<Constant>(Op1);
459 if (AllowReassociate && isFiniteNonZeroFp(C)) {
460 // Let MDC denote an expression in one of these forms:
461 // X * C, C/X, X/C, where C is a constant.
463 // Try to simplify "MDC * Constant"
464 if (isFMulOrFDivWithConstant(Op0))
465 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
466 return ReplaceInstUsesWith(I, V);
468 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
469 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
471 (FAddSub->getOpcode() == Instruction::FAdd ||
472 FAddSub->getOpcode() == Instruction::FSub)) {
473 Value *Opnd0 = FAddSub->getOperand(0);
474 Value *Opnd1 = FAddSub->getOperand(1);
475 Constant *C0 = dyn_cast<Constant>(Opnd0);
476 Constant *C1 = dyn_cast<Constant>(Opnd1);
480 std::swap(Opnd0, Opnd1);
484 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
485 Value *M1 = ConstantExpr::getFMul(C1, C);
486 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
487 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
490 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
493 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
494 ? BinaryOperator::CreateFAdd(M0, M1)
495 : BinaryOperator::CreateFSub(M0, M1);
496 RI->copyFastMathFlags(&I);
505 // Under unsafe algebra do:
506 // X * log2(0.5*Y) = X*log2(Y) - X
507 if (I.hasUnsafeAlgebra()) {
511 detectLog2OfHalf(Op0, OpY, Log2);
515 detectLog2OfHalf(Op1, OpY, Log2);
520 // if pattern detected emit alternate sequence
522 BuilderTy::FastMathFlagGuard Guard(*Builder);
523 Builder->SetFastMathFlags(Log2->getFastMathFlags());
524 Log2->setArgOperand(0, OpY);
525 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
526 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
528 return ReplaceInstUsesWith(I, FSub);
532 // Handle symmetric situation in a 2-iteration loop
535 for (int i = 0; i < 2; i++) {
536 bool IgnoreZeroSign = I.hasNoSignedZeros();
537 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
538 BuilderTy::FastMathFlagGuard Guard(*Builder);
539 Builder->SetFastMathFlags(I.getFastMathFlags());
541 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
542 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
546 Value *FMul = Builder->CreateFMul(N0, N1);
548 return ReplaceInstUsesWith(I, FMul);
551 if (Opnd0->hasOneUse()) {
552 // -X * Y => -(X*Y) (Promote negation as high as possible)
553 Value *T = Builder->CreateFMul(N0, Opnd1);
554 Value *Neg = Builder->CreateFNeg(T);
556 return ReplaceInstUsesWith(I, Neg);
560 // (X*Y) * X => (X*X) * Y where Y != X
561 // The purpose is two-fold:
562 // 1) to form a power expression (of X).
563 // 2) potentially shorten the critical path: After transformation, the
564 // latency of the instruction Y is amortized by the expression of X*X,
565 // and therefore Y is in a "less critical" position compared to what it
566 // was before the transformation.
568 if (AllowReassociate) {
569 Value *Opnd0_0, *Opnd0_1;
570 if (Opnd0->hasOneUse() &&
571 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
573 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
575 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
579 BuilderTy::FastMathFlagGuard Guard(*Builder);
580 Builder->SetFastMathFlags(I.getFastMathFlags());
581 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
583 Value *R = Builder->CreateFMul(T, Y);
585 return ReplaceInstUsesWith(I, R);
590 // B * (uitofp i1 C) -> select C, B, 0
591 if (I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) {
592 Value *LHS = Op0, *RHS = Op1;
594 if (!match(RHS, m_UIToFP(m_Value(C))))
597 if (match(RHS, m_UIToFP(m_Value(C))) &&
598 C->getType()->getScalarType()->isIntegerTy(1)) {
600 Value *Zero = ConstantFP::getNegativeZero(B->getType());
601 return SelectInst::Create(C, B, Zero);
605 // A * (1 - uitofp i1 C) -> select C, 0, A
606 if (I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) {
607 Value *LHS = Op0, *RHS = Op1;
609 if (!match(RHS, m_FSub(m_FPOne(), m_UIToFP(m_Value(C)))))
612 if (match(RHS, m_FSub(m_FPOne(), m_UIToFP(m_Value(C)))) &&
613 C->getType()->getScalarType()->isIntegerTy(1)) {
615 Value *Zero = ConstantFP::getNegativeZero(A->getType());
616 return SelectInst::Create(C, Zero, A);
620 if (!isa<Constant>(Op1))
621 std::swap(Opnd0, Opnd1);
626 return Changed ? &I : 0;
629 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
631 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
632 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
634 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
635 int NonNullOperand = -1;
636 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
637 if (ST->isNullValue())
639 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
640 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
641 if (ST->isNullValue())
644 if (NonNullOperand == -1)
647 Value *SelectCond = SI->getOperand(0);
649 // Change the div/rem to use 'Y' instead of the select.
650 I.setOperand(1, SI->getOperand(NonNullOperand));
652 // Okay, we know we replace the operand of the div/rem with 'Y' with no
653 // problem. However, the select, or the condition of the select may have
654 // multiple uses. Based on our knowledge that the operand must be non-zero,
655 // propagate the known value for the select into other uses of it, and
656 // propagate a known value of the condition into its other users.
658 // If the select and condition only have a single use, don't bother with this,
660 if (SI->use_empty() && SelectCond->hasOneUse())
663 // Scan the current block backward, looking for other uses of SI.
664 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
666 while (BBI != BBFront) {
668 // If we found a call to a function, we can't assume it will return, so
669 // information from below it cannot be propagated above it.
670 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
673 // Replace uses of the select or its condition with the known values.
674 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
677 *I = SI->getOperand(NonNullOperand);
679 } else if (*I == SelectCond) {
680 *I = Builder->getInt1(NonNullOperand == 1);
685 // If we past the instruction, quit looking for it.
688 if (&*BBI == SelectCond)
691 // If we ran out of things to eliminate, break out of the loop.
692 if (SelectCond == 0 && SI == 0)
700 /// This function implements the transforms common to both integer division
701 /// instructions (udiv and sdiv). It is called by the visitors to those integer
702 /// division instructions.
703 /// @brief Common integer divide transforms
704 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
705 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
707 // The RHS is known non-zero.
708 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
713 // Handle cases involving: [su]div X, (select Cond, Y, Z)
714 // This does not apply for fdiv.
715 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
718 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
719 // (X / C1) / C2 -> X / (C1*C2)
720 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
721 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
722 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
723 if (MultiplyOverflows(RHS, LHSRHS,
724 I.getOpcode()==Instruction::SDiv))
725 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
726 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
727 ConstantExpr::getMul(RHS, LHSRHS));
730 if (!RHS->isZero()) { // avoid X udiv 0
731 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
732 if (Instruction *R = FoldOpIntoSelect(I, SI))
734 if (isa<PHINode>(Op0))
735 if (Instruction *NV = FoldOpIntoPhi(I))
740 // See if we can fold away this div instruction.
741 if (SimplifyDemandedInstructionBits(I))
744 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
745 Value *X = 0, *Z = 0;
746 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
747 bool isSigned = I.getOpcode() == Instruction::SDiv;
748 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
749 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
750 return BinaryOperator::Create(I.getOpcode(), X, Op1);
756 /// dyn_castZExtVal - Checks if V is a zext or constant that can
757 /// be truncated to Ty without losing bits.
758 static Value *dyn_castZExtVal(Value *V, Type *Ty) {
759 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
760 if (Z->getSrcTy() == Ty)
761 return Z->getOperand(0);
762 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
763 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
764 return ConstantExpr::getTrunc(C, Ty);
770 const unsigned MaxDepth = 6;
771 typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
772 const BinaryOperator &I,
775 /// \brief Used to maintain state for visitUDivOperand().
776 struct UDivFoldAction {
777 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
778 ///< operand. This can be zero if this action
779 ///< joins two actions together.
781 Value *OperandToFold; ///< Which operand to fold.
783 Instruction *FoldResult; ///< The instruction returned when FoldAction is
786 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
787 ///< joins two actions together.
790 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
791 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(0) {}
792 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
793 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
797 // X udiv 2^C -> X >> C
798 static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
799 const BinaryOperator &I, InstCombiner &IC) {
800 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
801 BinaryOperator *LShr = BinaryOperator::CreateLShr(
802 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
803 if (I.isExact()) LShr->setIsExact();
807 // X udiv C, where C >= signbit
808 static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
809 const BinaryOperator &I, InstCombiner &IC) {
810 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
812 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
813 ConstantInt::get(I.getType(), 1));
816 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
817 static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
819 Instruction *ShiftLeft = cast<Instruction>(Op1);
820 if (isa<ZExtInst>(ShiftLeft))
821 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
824 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
825 Value *N = ShiftLeft->getOperand(1);
827 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
828 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
829 N = IC.Builder->CreateZExt(N, Z->getDestTy());
830 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
831 if (I.isExact()) LShr->setIsExact();
835 // \brief Recursively visits the possible right hand operands of a udiv
836 // instruction, seeing through select instructions, to determine if we can
837 // replace the udiv with something simpler. If we find that an operand is not
838 // able to simplify the udiv, we abort the entire transformation.
839 static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
840 SmallVectorImpl<UDivFoldAction> &Actions,
841 unsigned Depth = 0) {
842 // Check to see if this is an unsigned division with an exact power of 2,
843 // if so, convert to a right shift.
844 if (match(Op1, m_Power2())) {
845 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
846 return Actions.size();
849 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
850 // X udiv C, where C >= signbit
851 if (C->getValue().isNegative()) {
852 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
853 return Actions.size();
856 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
857 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
858 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
859 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
860 return Actions.size();
863 // The remaining tests are all recursive, so bail out if we hit the limit.
864 if (Depth++ == MaxDepth)
867 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
868 if (size_t LHSIdx = visitUDivOperand(Op0, SI->getOperand(1), I, Actions))
869 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions)) {
870 Actions.push_back(UDivFoldAction((FoldUDivOperandCb)0, Op1, LHSIdx-1));
871 return Actions.size();
877 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
878 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
880 if (Value *V = SimplifyUDivInst(Op0, Op1, DL))
881 return ReplaceInstUsesWith(I, V);
883 // Handle the integer div common cases
884 if (Instruction *Common = commonIDivTransforms(I))
887 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
888 if (Constant *C2 = dyn_cast<Constant>(Op1)) {
891 if (match(Op0, m_LShr(m_Value(X), m_Constant(C1))))
892 return BinaryOperator::CreateUDiv(X, ConstantExpr::getShl(C2, C1));
895 // (zext A) udiv (zext B) --> zext (A udiv B)
896 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
897 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
898 return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
902 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
903 SmallVector<UDivFoldAction, 6> UDivActions;
904 if (visitUDivOperand(Op0, Op1, I, UDivActions))
905 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
906 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
907 Value *ActionOp1 = UDivActions[i].OperandToFold;
910 Inst = Action(Op0, ActionOp1, I, *this);
912 // This action joins two actions together. The RHS of this action is
913 // simply the last action we processed, we saved the LHS action index in
914 // the joining action.
915 size_t SelectRHSIdx = i - 1;
916 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
917 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
918 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
919 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
920 SelectLHS, SelectRHS);
923 // If this is the last action to process, return it to the InstCombiner.
924 // Otherwise, we insert it before the UDiv and record it so that we may
925 // use it as part of a joining action (i.e., a SelectInst).
927 Inst->insertBefore(&I);
928 UDivActions[i].FoldResult = Inst;
936 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
937 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
939 if (Value *V = SimplifySDivInst(Op0, Op1, DL))
940 return ReplaceInstUsesWith(I, V);
942 // Handle the integer div common cases
943 if (Instruction *Common = commonIDivTransforms(I))
947 if (match(Op1, m_AllOnes()))
948 return BinaryOperator::CreateNeg(Op0);
950 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
951 // sdiv X, C --> ashr exact X, log2(C)
952 if (I.isExact() && RHS->getValue().isNonNegative() &&
953 RHS->getValue().isPowerOf2()) {
954 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
955 RHS->getValue().exactLogBase2());
956 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
960 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
961 // -X/C --> X/-C provided the negation doesn't overflow.
962 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
963 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
964 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
965 ConstantExpr::getNeg(RHS));
968 // If the sign bits of both operands are zero (i.e. we can prove they are
969 // unsigned inputs), turn this into a udiv.
970 if (I.getType()->isIntegerTy()) {
971 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
972 if (MaskedValueIsZero(Op0, Mask)) {
973 if (MaskedValueIsZero(Op1, Mask)) {
974 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
975 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
978 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
979 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
980 // Safe because the only negative value (1 << Y) can take on is
981 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
983 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
991 /// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
993 /// 1) 1/C is exact, or
994 /// 2) reciprocal is allowed.
995 /// If the conversion was successful, the simplified expression "X * 1/C" is
996 /// returned; otherwise, NULL is returned.
998 static Instruction *CvtFDivConstToReciprocal(Value *Dividend,
1000 bool AllowReciprocal) {
1001 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
1004 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
1005 APFloat Reciprocal(FpVal.getSemantics());
1006 bool Cvt = FpVal.getExactInverse(&Reciprocal);
1008 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
1009 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1010 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1011 Cvt = !Reciprocal.isDenormal();
1018 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1019 return BinaryOperator::CreateFMul(Dividend, R);
1022 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1023 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1025 if (Value *V = SimplifyFDivInst(Op0, Op1, DL))
1026 return ReplaceInstUsesWith(I, V);
1028 if (isa<Constant>(Op0))
1029 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1030 if (Instruction *R = FoldOpIntoSelect(I, SI))
1033 bool AllowReassociate = I.hasUnsafeAlgebra();
1034 bool AllowReciprocal = I.hasAllowReciprocal();
1036 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1037 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1038 if (Instruction *R = FoldOpIntoSelect(I, SI))
1041 if (AllowReassociate) {
1043 Constant *C2 = Op1C;
1045 Instruction *Res = 0;
1047 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
1048 // (X*C1)/C2 => X * (C1/C2)
1050 Constant *C = ConstantExpr::getFDiv(C1, C2);
1052 Res = BinaryOperator::CreateFMul(X, C);
1053 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
1054 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1056 Constant *C = ConstantExpr::getFMul(C1, C2);
1057 if (isNormalFp(C)) {
1058 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
1060 Res = BinaryOperator::CreateFDiv(X, C);
1065 Res->setFastMathFlags(I.getFastMathFlags());
1071 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1072 T->copyFastMathFlags(&I);
1079 if (AllowReassociate && isa<Constant>(Op0)) {
1080 Constant *C1 = cast<Constant>(Op0), *C2;
1083 bool CreateDiv = true;
1085 // C1 / (X*C2) => (C1/C2) / X
1086 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
1087 Fold = ConstantExpr::getFDiv(C1, C2);
1088 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
1089 // C1 / (X/C2) => (C1*C2) / X
1090 Fold = ConstantExpr::getFMul(C1, C2);
1091 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
1092 // C1 / (C2/X) => (C1/C2) * X
1093 Fold = ConstantExpr::getFDiv(C1, C2);
1097 if (Fold && isNormalFp(Fold)) {
1098 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1099 : BinaryOperator::CreateFMul(X, Fold);
1100 R->setFastMathFlags(I.getFastMathFlags());
1106 if (AllowReassociate) {
1109 Instruction *SimpR = 0;
1111 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1112 // (X/Y) / Z => X / (Y*Z)
1114 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
1115 NewInst = Builder->CreateFMul(Y, Op1);
1116 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1117 FastMathFlags Flags = I.getFastMathFlags();
1118 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1119 RI->setFastMathFlags(Flags);
1121 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1123 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1124 // Z / (X/Y) => Z*Y / X
1126 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
1127 NewInst = Builder->CreateFMul(Op0, Y);
1128 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1129 FastMathFlags Flags = I.getFastMathFlags();
1130 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1131 RI->setFastMathFlags(Flags);
1133 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1138 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1139 T->setDebugLoc(I.getDebugLoc());
1140 SimpR->setFastMathFlags(I.getFastMathFlags());
1148 /// This function implements the transforms common to both integer remainder
1149 /// instructions (urem and srem). It is called by the visitors to those integer
1150 /// remainder instructions.
1151 /// @brief Common integer remainder transforms
1152 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1153 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1155 // The RHS is known non-zero.
1156 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
1161 // Handle cases involving: rem X, (select Cond, Y, Z)
1162 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1165 if (isa<Constant>(Op1)) {
1166 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1167 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1168 if (Instruction *R = FoldOpIntoSelect(I, SI))
1170 } else if (isa<PHINode>(Op0I)) {
1171 if (Instruction *NV = FoldOpIntoPhi(I))
1175 // See if we can fold away this rem instruction.
1176 if (SimplifyDemandedInstructionBits(I))
1184 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1185 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1187 if (Value *V = SimplifyURemInst(Op0, Op1, DL))
1188 return ReplaceInstUsesWith(I, V);
1190 if (Instruction *common = commonIRemTransforms(I))
1193 // (zext A) urem (zext B) --> zext (A urem B)
1194 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1195 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1196 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1199 // X urem Y -> X and Y-1, where Y is a power of 2,
1200 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true)) {
1201 Constant *N1 = Constant::getAllOnesValue(I.getType());
1202 Value *Add = Builder->CreateAdd(Op1, N1);
1203 return BinaryOperator::CreateAnd(Op0, Add);
1206 // 1 urem X -> zext(X != 1)
1207 if (match(Op0, m_One())) {
1208 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1209 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1210 return ReplaceInstUsesWith(I, Ext);
1216 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1217 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1219 if (Value *V = SimplifySRemInst(Op0, Op1, DL))
1220 return ReplaceInstUsesWith(I, V);
1222 // Handle the integer rem common cases
1223 if (Instruction *Common = commonIRemTransforms(I))
1226 if (Value *RHSNeg = dyn_castNegVal(Op1))
1227 if (!isa<Constant>(RHSNeg) ||
1228 (isa<ConstantInt>(RHSNeg) &&
1229 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
1231 Worklist.AddValue(I.getOperand(1));
1232 I.setOperand(1, RHSNeg);
1236 // If the sign bits of both operands are zero (i.e. we can prove they are
1237 // unsigned inputs), turn this into a urem.
1238 if (I.getType()->isIntegerTy()) {
1239 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1240 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
1241 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1242 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1246 // If it's a constant vector, flip any negative values positive.
1247 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1248 Constant *C = cast<Constant>(Op1);
1249 unsigned VWidth = C->getType()->getVectorNumElements();
1251 bool hasNegative = false;
1252 bool hasMissing = false;
1253 for (unsigned i = 0; i != VWidth; ++i) {
1254 Constant *Elt = C->getAggregateElement(i);
1260 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
1261 if (RHS->isNegative())
1265 if (hasNegative && !hasMissing) {
1266 SmallVector<Constant *, 16> Elts(VWidth);
1267 for (unsigned i = 0; i != VWidth; ++i) {
1268 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
1269 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
1270 if (RHS->isNegative())
1271 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
1275 Constant *NewRHSV = ConstantVector::get(Elts);
1276 if (NewRHSV != C) { // Don't loop on -MININT
1277 Worklist.AddValue(I.getOperand(1));
1278 I.setOperand(1, NewRHSV);
1287 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
1288 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1290 if (Value *V = SimplifyFRemInst(Op0, Op1, DL))
1291 return ReplaceInstUsesWith(I, V);
1293 // Handle cases involving: rem X, (select Cond, Y, Z)
1294 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))