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,
30 // If V has multiple uses, then we would have to do more analysis to determine
31 // if this is safe. For example, the use could be in dynamically unreached
33 if (!V->hasOneUse()) return nullptr;
35 bool MadeChange = false;
37 // ((1 << A) >>u B) --> (1 << (A-B))
38 // Because V cannot be zero, we know that B is less than A.
39 Value *A = nullptr, *B = nullptr, *One = nullptr;
40 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) &&
41 match(One, m_One())) {
42 A = IC.Builder->CreateSub(A, B);
43 return IC.Builder->CreateShl(One, 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), false,
50 0, IC.getAssumptionTracker(),
52 IC.getDominatorTree())) {
53 // We know that this is an exact/nuw shift and that the input is a
54 // non-zero context as well.
55 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
60 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
65 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
66 I->setHasNoUnsignedWrap();
71 // TODO: Lots more we could do here:
72 // If V is a phi node, we can call this on each of its operands.
73 // "select cond, X, 0" can simplify to "X".
75 return MadeChange ? V : nullptr;
79 /// MultiplyOverflows - True if the multiply can not be expressed in an int
81 static bool MultiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
85 Product = C1.smul_ov(C2, Overflow);
87 Product = C1.umul_ov(C2, Overflow);
92 /// \brief True if C2 is a multiple of C1. Quotient contains C2/C1.
93 static bool IsMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
95 assert(C1.getBitWidth() == C2.getBitWidth() &&
96 "Inconsistent width of constants!");
98 APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
100 APInt::sdivrem(C1, C2, Quotient, Remainder);
102 APInt::udivrem(C1, C2, Quotient, Remainder);
104 return Remainder.isMinValue();
107 /// \brief A helper routine of InstCombiner::visitMul().
109 /// If C is a vector of known powers of 2, then this function returns
110 /// a new vector obtained from C replacing each element with its logBase2.
111 /// Return a null pointer otherwise.
112 static Constant *getLogBase2Vector(ConstantDataVector *CV) {
114 SmallVector<Constant *, 4> Elts;
116 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
117 Constant *Elt = CV->getElementAsConstant(I);
118 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
120 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
123 return ConstantVector::get(Elts);
126 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
127 bool Changed = SimplifyAssociativeOrCommutative(I);
128 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
130 if (Value *V = SimplifyVectorOp(I))
131 return ReplaceInstUsesWith(I, V);
133 if (Value *V = SimplifyMulInst(Op0, Op1, DL, TLI, DT, AT))
134 return ReplaceInstUsesWith(I, V);
136 if (Value *V = SimplifyUsingDistributiveLaws(I))
137 return ReplaceInstUsesWith(I, V);
140 if (match(Op1, m_AllOnes())) {
141 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
142 if (I.hasNoSignedWrap())
143 BO->setHasNoSignedWrap();
147 // Also allow combining multiply instructions on vectors.
152 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
154 match(C1, m_APInt(IVal))) {
155 // ((X << C2)*C1) == (X * (C1 << C2))
156 Constant *Shl = ConstantExpr::getShl(C1, C2);
157 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
158 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
159 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
160 BO->setHasNoUnsignedWrap();
161 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
162 Shl->isNotMinSignedValue())
163 BO->setHasNoSignedWrap();
167 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
168 Constant *NewCst = nullptr;
169 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
170 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
171 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
172 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
173 // Replace X*(2^C) with X << C, where C is a vector of known
174 // constant powers of 2.
175 NewCst = getLogBase2Vector(CV);
178 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
180 if (I.hasNoUnsignedWrap())
181 Shl->setHasNoUnsignedWrap();
188 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
189 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
190 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
191 // The "* (2**n)" thus becomes a potential shifting opportunity.
193 const APInt & Val = CI->getValue();
194 const APInt &PosVal = Val.abs();
195 if (Val.isNegative() && PosVal.isPowerOf2()) {
196 Value *X = nullptr, *Y = nullptr;
197 if (Op0->hasOneUse()) {
199 Value *Sub = nullptr;
200 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
201 Sub = Builder->CreateSub(X, Y, "suba");
202 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
203 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
206 BinaryOperator::CreateMul(Sub,
207 ConstantInt::get(Y->getType(), PosVal));
213 // Simplify mul instructions with a constant RHS.
214 if (isa<Constant>(Op1)) {
215 // Try to fold constant mul into select arguments.
216 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
217 if (Instruction *R = FoldOpIntoSelect(I, SI))
220 if (isa<PHINode>(Op0))
221 if (Instruction *NV = FoldOpIntoPhi(I))
224 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
228 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
229 Value *Mul = Builder->CreateMul(C1, Op1);
230 // Only go forward with the transform if C1*CI simplifies to a tidier
232 if (!match(Mul, m_Mul(m_Value(), m_Value())))
233 return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
238 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
239 if (Value *Op1v = dyn_castNegVal(Op1))
240 return BinaryOperator::CreateMul(Op0v, Op1v);
242 // (X / Y) * Y = X - (X % Y)
243 // (X / Y) * -Y = (X % Y) - X
246 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
248 (BO->getOpcode() != Instruction::UDiv &&
249 BO->getOpcode() != Instruction::SDiv)) {
251 BO = dyn_cast<BinaryOperator>(Op1);
253 Value *Neg = dyn_castNegVal(Op1C);
254 if (BO && BO->hasOneUse() &&
255 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
256 (BO->getOpcode() == Instruction::UDiv ||
257 BO->getOpcode() == Instruction::SDiv)) {
258 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
260 // If the division is exact, X % Y is zero, so we end up with X or -X.
261 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
262 if (SDiv->isExact()) {
264 return ReplaceInstUsesWith(I, Op0BO);
265 return BinaryOperator::CreateNeg(Op0BO);
269 if (BO->getOpcode() == Instruction::UDiv)
270 Rem = Builder->CreateURem(Op0BO, Op1BO);
272 Rem = Builder->CreateSRem(Op0BO, Op1BO);
276 return BinaryOperator::CreateSub(Op0BO, Rem);
277 return BinaryOperator::CreateSub(Rem, Op0BO);
281 /// i1 mul -> i1 and.
282 if (I.getType()->getScalarType()->isIntegerTy(1))
283 return BinaryOperator::CreateAnd(Op0, Op1);
285 // X*(1 << Y) --> X << Y
286 // (1 << Y)*X --> X << Y
289 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
290 return BinaryOperator::CreateShl(Op1, Y);
291 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
292 return BinaryOperator::CreateShl(Op0, Y);
295 // If one of the operands of the multiply is a cast from a boolean value, then
296 // we know the bool is either zero or one, so this is a 'masking' multiply.
297 // X * Y (where Y is 0 or 1) -> X & (0-Y)
298 if (!I.getType()->isVectorTy()) {
299 // -2 is "-1 << 1" so it is all bits set except the low one.
300 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
302 Value *BoolCast = nullptr, *OtherOp = nullptr;
303 if (MaskedValueIsZero(Op0, Negative2, 0, &I))
304 BoolCast = Op0, OtherOp = Op1;
305 else if (MaskedValueIsZero(Op1, Negative2, 0, &I))
306 BoolCast = Op1, OtherOp = Op0;
309 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
311 return BinaryOperator::CreateAnd(V, OtherOp);
315 return Changed ? &I : nullptr;
318 /// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
319 static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
320 if (!Op->hasOneUse())
323 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
326 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
330 Value *OpLog2Of = II->getArgOperand(0);
331 if (!OpLog2Of->hasOneUse())
334 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
337 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
340 if (match(I->getOperand(0), m_SpecificFP(0.5)))
341 Y = I->getOperand(1);
342 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
343 Y = I->getOperand(0);
346 static bool isFiniteNonZeroFp(Constant *C) {
347 if (C->getType()->isVectorTy()) {
348 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
350 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
351 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
357 return isa<ConstantFP>(C) &&
358 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
361 static bool isNormalFp(Constant *C) {
362 if (C->getType()->isVectorTy()) {
363 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
365 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
366 if (!CFP || !CFP->getValueAPF().isNormal())
372 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
375 /// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
376 /// true iff the given value is FMul or FDiv with one and only one operand
377 /// being a normal constant (i.e. not Zero/NaN/Infinity).
378 static bool isFMulOrFDivWithConstant(Value *V) {
379 Instruction *I = dyn_cast<Instruction>(V);
380 if (!I || (I->getOpcode() != Instruction::FMul &&
381 I->getOpcode() != Instruction::FDiv))
384 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
385 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
390 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
393 /// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
394 /// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
395 /// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
396 /// This function is to simplify "FMulOrDiv * C" and returns the
397 /// resulting expression. Note that this function could return NULL in
398 /// case the constants cannot be folded into a normal floating-point.
400 Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
401 Instruction *InsertBefore) {
402 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
404 Value *Opnd0 = FMulOrDiv->getOperand(0);
405 Value *Opnd1 = FMulOrDiv->getOperand(1);
407 Constant *C0 = dyn_cast<Constant>(Opnd0);
408 Constant *C1 = dyn_cast<Constant>(Opnd1);
410 BinaryOperator *R = nullptr;
412 // (X * C0) * C => X * (C0*C)
413 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
414 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
416 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
419 // (C0 / X) * C => (C0 * C) / X
420 if (FMulOrDiv->hasOneUse()) {
421 // It would otherwise introduce another div.
422 Constant *F = ConstantExpr::getFMul(C0, C);
424 R = BinaryOperator::CreateFDiv(F, Opnd1);
427 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
428 Constant *F = ConstantExpr::getFDiv(C, C1);
430 R = BinaryOperator::CreateFMul(Opnd0, F);
432 // (X / C1) * C => X / (C1/C)
433 Constant *F = ConstantExpr::getFDiv(C1, C);
435 R = BinaryOperator::CreateFDiv(Opnd0, F);
441 R->setHasUnsafeAlgebra(true);
442 InsertNewInstWith(R, *InsertBefore);
448 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
449 bool Changed = SimplifyAssociativeOrCommutative(I);
450 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
452 if (Value *V = SimplifyVectorOp(I))
453 return ReplaceInstUsesWith(I, V);
455 if (isa<Constant>(Op0))
458 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL, TLI,
460 return ReplaceInstUsesWith(I, V);
462 bool AllowReassociate = I.hasUnsafeAlgebra();
464 // Simplify mul instructions with a constant RHS.
465 if (isa<Constant>(Op1)) {
466 // Try to fold constant mul into select arguments.
467 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
468 if (Instruction *R = FoldOpIntoSelect(I, SI))
471 if (isa<PHINode>(Op0))
472 if (Instruction *NV = FoldOpIntoPhi(I))
475 // (fmul X, -1.0) --> (fsub -0.0, X)
476 if (match(Op1, m_SpecificFP(-1.0))) {
477 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
478 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
479 RI->copyFastMathFlags(&I);
483 Constant *C = cast<Constant>(Op1);
484 if (AllowReassociate && isFiniteNonZeroFp(C)) {
485 // Let MDC denote an expression in one of these forms:
486 // X * C, C/X, X/C, where C is a constant.
488 // Try to simplify "MDC * Constant"
489 if (isFMulOrFDivWithConstant(Op0))
490 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
491 return ReplaceInstUsesWith(I, V);
493 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
494 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
496 (FAddSub->getOpcode() == Instruction::FAdd ||
497 FAddSub->getOpcode() == Instruction::FSub)) {
498 Value *Opnd0 = FAddSub->getOperand(0);
499 Value *Opnd1 = FAddSub->getOperand(1);
500 Constant *C0 = dyn_cast<Constant>(Opnd0);
501 Constant *C1 = dyn_cast<Constant>(Opnd1);
505 std::swap(Opnd0, Opnd1);
509 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
510 Value *M1 = ConstantExpr::getFMul(C1, C);
511 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
512 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
515 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
518 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
519 ? BinaryOperator::CreateFAdd(M0, M1)
520 : BinaryOperator::CreateFSub(M0, M1);
521 RI->copyFastMathFlags(&I);
529 // sqrt(X) * sqrt(X) -> X
530 if (AllowReassociate && (Op0 == Op1))
531 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0))
532 if (II->getIntrinsicID() == Intrinsic::sqrt)
533 return ReplaceInstUsesWith(I, II->getOperand(0));
535 // Under unsafe algebra do:
536 // X * log2(0.5*Y) = X*log2(Y) - X
537 if (AllowReassociate) {
538 Value *OpX = nullptr;
539 Value *OpY = nullptr;
541 detectLog2OfHalf(Op0, OpY, Log2);
545 detectLog2OfHalf(Op1, OpY, Log2);
550 // if pattern detected emit alternate sequence
552 BuilderTy::FastMathFlagGuard Guard(*Builder);
553 Builder->SetFastMathFlags(Log2->getFastMathFlags());
554 Log2->setArgOperand(0, OpY);
555 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
556 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
558 return ReplaceInstUsesWith(I, FSub);
562 // Handle symmetric situation in a 2-iteration loop
565 for (int i = 0; i < 2; i++) {
566 bool IgnoreZeroSign = I.hasNoSignedZeros();
567 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
568 BuilderTy::FastMathFlagGuard Guard(*Builder);
569 Builder->SetFastMathFlags(I.getFastMathFlags());
571 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
572 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
576 Value *FMul = Builder->CreateFMul(N0, N1);
578 return ReplaceInstUsesWith(I, FMul);
581 if (Opnd0->hasOneUse()) {
582 // -X * Y => -(X*Y) (Promote negation as high as possible)
583 Value *T = Builder->CreateFMul(N0, Opnd1);
584 Value *Neg = Builder->CreateFNeg(T);
586 return ReplaceInstUsesWith(I, Neg);
590 // (X*Y) * X => (X*X) * Y where Y != X
591 // The purpose is two-fold:
592 // 1) to form a power expression (of X).
593 // 2) potentially shorten the critical path: After transformation, the
594 // latency of the instruction Y is amortized by the expression of X*X,
595 // and therefore Y is in a "less critical" position compared to what it
596 // was before the transformation.
598 if (AllowReassociate) {
599 Value *Opnd0_0, *Opnd0_1;
600 if (Opnd0->hasOneUse() &&
601 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
603 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
605 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
609 BuilderTy::FastMathFlagGuard Guard(*Builder);
610 Builder->SetFastMathFlags(I.getFastMathFlags());
611 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
613 Value *R = Builder->CreateFMul(T, Y);
615 return ReplaceInstUsesWith(I, R);
620 if (!isa<Constant>(Op1))
621 std::swap(Opnd0, Opnd1);
626 return Changed ? &I : nullptr;
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)
689 SelectCond = nullptr;
691 // If we ran out of things to eliminate, break out of the loop.
692 if (!SelectCond && !SI)
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, &I)) {
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 (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
720 if (match(Op1, m_APInt(C2))) {
723 bool IsSigned = I.getOpcode() == Instruction::SDiv;
725 // (X / C1) / C2 -> X / (C1*C2)
726 if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
727 (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
728 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
729 if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
730 return BinaryOperator::Create(I.getOpcode(), X,
731 ConstantInt::get(I.getType(), Product));
734 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
735 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
736 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
738 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
739 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
740 BinaryOperator *BO = BinaryOperator::Create(
741 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
742 BO->setIsExact(I.isExact());
746 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
747 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
748 BinaryOperator *BO = BinaryOperator::Create(
749 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
750 BO->setHasNoUnsignedWrap(
752 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
753 BO->setHasNoSignedWrap(
754 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
759 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
760 *C1 != C1->getBitWidth() - 1) ||
761 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
762 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
763 APInt C1Shifted = APInt::getOneBitSet(
764 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
766 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
767 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
768 BinaryOperator *BO = BinaryOperator::Create(
769 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
770 BO->setIsExact(I.isExact());
774 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
775 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
776 BinaryOperator *BO = BinaryOperator::Create(
777 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
778 BO->setHasNoUnsignedWrap(
780 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
781 BO->setHasNoSignedWrap(
782 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
787 if (*C2 != 0) { // avoid X udiv 0
788 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
789 if (Instruction *R = FoldOpIntoSelect(I, SI))
791 if (isa<PHINode>(Op0))
792 if (Instruction *NV = FoldOpIntoPhi(I))
798 if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
799 if (One->isOne() && !I.getType()->isIntegerTy(1)) {
800 bool isSigned = I.getOpcode() == Instruction::SDiv;
802 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
803 // result is one, if Op1 is -1 then the result is minus one, otherwise
805 Value *Inc = Builder->CreateAdd(Op1, One);
806 Value *Cmp = Builder->CreateICmpULT(
807 Inc, ConstantInt::get(I.getType(), 3));
808 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
810 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
811 // result is one, otherwise it's zero.
812 return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
817 // See if we can fold away this div instruction.
818 if (SimplifyDemandedInstructionBits(I))
821 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
822 Value *X = nullptr, *Z = nullptr;
823 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
824 bool isSigned = I.getOpcode() == Instruction::SDiv;
825 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
826 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
827 return BinaryOperator::Create(I.getOpcode(), X, Op1);
833 /// dyn_castZExtVal - Checks if V is a zext or constant that can
834 /// be truncated to Ty without losing bits.
835 static Value *dyn_castZExtVal(Value *V, Type *Ty) {
836 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
837 if (Z->getSrcTy() == Ty)
838 return Z->getOperand(0);
839 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
840 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
841 return ConstantExpr::getTrunc(C, Ty);
847 const unsigned MaxDepth = 6;
848 typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
849 const BinaryOperator &I,
852 /// \brief Used to maintain state for visitUDivOperand().
853 struct UDivFoldAction {
854 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
855 ///< operand. This can be zero if this action
856 ///< joins two actions together.
858 Value *OperandToFold; ///< Which operand to fold.
860 Instruction *FoldResult; ///< The instruction returned when FoldAction is
863 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
864 ///< joins two actions together.
867 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
868 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
869 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
870 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
874 // X udiv 2^C -> X >> C
875 static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
876 const BinaryOperator &I, InstCombiner &IC) {
877 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
878 BinaryOperator *LShr = BinaryOperator::CreateLShr(
879 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
885 // X udiv C, where C >= signbit
886 static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
887 const BinaryOperator &I, InstCombiner &IC) {
888 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
890 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
891 ConstantInt::get(I.getType(), 1));
894 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
895 static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
897 Instruction *ShiftLeft = cast<Instruction>(Op1);
898 if (isa<ZExtInst>(ShiftLeft))
899 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
902 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
903 Value *N = ShiftLeft->getOperand(1);
905 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
906 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
907 N = IC.Builder->CreateZExt(N, Z->getDestTy());
908 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
914 // \brief Recursively visits the possible right hand operands of a udiv
915 // instruction, seeing through select instructions, to determine if we can
916 // replace the udiv with something simpler. If we find that an operand is not
917 // able to simplify the udiv, we abort the entire transformation.
918 static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
919 SmallVectorImpl<UDivFoldAction> &Actions,
920 unsigned Depth = 0) {
921 // Check to see if this is an unsigned division with an exact power of 2,
922 // if so, convert to a right shift.
923 if (match(Op1, m_Power2())) {
924 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
925 return Actions.size();
928 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
929 // X udiv C, where C >= signbit
930 if (C->getValue().isNegative()) {
931 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
932 return Actions.size();
935 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
936 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
937 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
938 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
939 return Actions.size();
942 // The remaining tests are all recursive, so bail out if we hit the limit.
943 if (Depth++ == MaxDepth)
946 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
948 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
949 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
950 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
951 return Actions.size();
957 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
958 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
960 if (Value *V = SimplifyVectorOp(I))
961 return ReplaceInstUsesWith(I, V);
963 if (Value *V = SimplifyUDivInst(Op0, Op1, DL, TLI, DT, AT))
964 return ReplaceInstUsesWith(I, V);
966 // Handle the integer div common cases
967 if (Instruction *Common = commonIDivTransforms(I))
970 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
973 const APInt *C1, *C2;
974 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
975 match(Op1, m_APInt(C2))) {
977 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
979 return BinaryOperator::CreateUDiv(
980 X, ConstantInt::get(X->getType(), C2ShlC1));
984 // (zext A) udiv (zext B) --> zext (A udiv B)
985 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
986 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
988 Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", I.isExact()),
991 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
992 SmallVector<UDivFoldAction, 6> UDivActions;
993 if (visitUDivOperand(Op0, Op1, I, UDivActions))
994 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
995 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
996 Value *ActionOp1 = UDivActions[i].OperandToFold;
999 Inst = Action(Op0, ActionOp1, I, *this);
1001 // This action joins two actions together. The RHS of this action is
1002 // simply the last action we processed, we saved the LHS action index in
1003 // the joining action.
1004 size_t SelectRHSIdx = i - 1;
1005 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1006 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1007 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1008 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1009 SelectLHS, SelectRHS);
1012 // If this is the last action to process, return it to the InstCombiner.
1013 // Otherwise, we insert it before the UDiv and record it so that we may
1014 // use it as part of a joining action (i.e., a SelectInst).
1016 Inst->insertBefore(&I);
1017 UDivActions[i].FoldResult = Inst;
1025 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1026 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1028 if (Value *V = SimplifyVectorOp(I))
1029 return ReplaceInstUsesWith(I, V);
1031 if (Value *V = SimplifySDivInst(Op0, Op1, DL, TLI, DT, AT))
1032 return ReplaceInstUsesWith(I, V);
1034 // Handle the integer div common cases
1035 if (Instruction *Common = commonIDivTransforms(I))
1039 if (match(Op1, m_AllOnes()))
1040 return BinaryOperator::CreateNeg(Op0);
1042 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1043 // sdiv X, C --> ashr exact X, log2(C)
1044 if (I.isExact() && RHS->getValue().isNonNegative() &&
1045 RHS->getValue().isPowerOf2()) {
1046 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1047 RHS->getValue().exactLogBase2());
1048 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1052 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
1053 // X/INT_MIN -> X == INT_MIN
1054 if (RHS->isMinSignedValue())
1055 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1057 // -X/C --> X/-C provided the negation doesn't overflow.
1058 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
1059 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
1060 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
1061 ConstantExpr::getNeg(RHS));
1064 // If the sign bits of both operands are zero (i.e. we can prove they are
1065 // unsigned inputs), turn this into a udiv.
1066 if (I.getType()->isIntegerTy()) {
1067 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1068 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1069 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
1070 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1071 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1074 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
1075 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1076 // Safe because the only negative value (1 << Y) can take on is
1077 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1078 // the sign bit set.
1079 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1087 /// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1089 /// 1) 1/C is exact, or
1090 /// 2) reciprocal is allowed.
1091 /// If the conversion was successful, the simplified expression "X * 1/C" is
1092 /// returned; otherwise, NULL is returned.
1094 static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
1095 bool AllowReciprocal) {
1096 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
1099 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
1100 APFloat Reciprocal(FpVal.getSemantics());
1101 bool Cvt = FpVal.getExactInverse(&Reciprocal);
1103 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
1104 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1105 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1106 Cvt = !Reciprocal.isDenormal();
1113 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1114 return BinaryOperator::CreateFMul(Dividend, R);
1117 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1118 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1120 if (Value *V = SimplifyVectorOp(I))
1121 return ReplaceInstUsesWith(I, V);
1123 if (Value *V = SimplifyFDivInst(Op0, Op1, DL, TLI, DT, AT))
1124 return ReplaceInstUsesWith(I, V);
1126 if (isa<Constant>(Op0))
1127 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1128 if (Instruction *R = FoldOpIntoSelect(I, SI))
1131 bool AllowReassociate = I.hasUnsafeAlgebra();
1132 bool AllowReciprocal = I.hasAllowReciprocal();
1134 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1135 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1136 if (Instruction *R = FoldOpIntoSelect(I, SI))
1139 if (AllowReassociate) {
1140 Constant *C1 = nullptr;
1141 Constant *C2 = Op1C;
1143 Instruction *Res = nullptr;
1145 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
1146 // (X*C1)/C2 => X * (C1/C2)
1148 Constant *C = ConstantExpr::getFDiv(C1, C2);
1150 Res = BinaryOperator::CreateFMul(X, C);
1151 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
1152 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1154 Constant *C = ConstantExpr::getFMul(C1, C2);
1155 if (isNormalFp(C)) {
1156 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
1158 Res = BinaryOperator::CreateFDiv(X, C);
1163 Res->setFastMathFlags(I.getFastMathFlags());
1169 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1170 T->copyFastMathFlags(&I);
1177 if (AllowReassociate && isa<Constant>(Op0)) {
1178 Constant *C1 = cast<Constant>(Op0), *C2;
1179 Constant *Fold = nullptr;
1181 bool CreateDiv = true;
1183 // C1 / (X*C2) => (C1/C2) / X
1184 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
1185 Fold = ConstantExpr::getFDiv(C1, C2);
1186 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
1187 // C1 / (X/C2) => (C1*C2) / X
1188 Fold = ConstantExpr::getFMul(C1, C2);
1189 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
1190 // C1 / (C2/X) => (C1/C2) * X
1191 Fold = ConstantExpr::getFDiv(C1, C2);
1195 if (Fold && isNormalFp(Fold)) {
1196 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1197 : BinaryOperator::CreateFMul(X, Fold);
1198 R->setFastMathFlags(I.getFastMathFlags());
1204 if (AllowReassociate) {
1206 Value *NewInst = nullptr;
1207 Instruction *SimpR = nullptr;
1209 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1210 // (X/Y) / Z => X / (Y*Z)
1212 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
1213 NewInst = Builder->CreateFMul(Y, Op1);
1214 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1215 FastMathFlags Flags = I.getFastMathFlags();
1216 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1217 RI->setFastMathFlags(Flags);
1219 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1221 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1222 // Z / (X/Y) => Z*Y / X
1224 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
1225 NewInst = Builder->CreateFMul(Op0, Y);
1226 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1227 FastMathFlags Flags = I.getFastMathFlags();
1228 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1229 RI->setFastMathFlags(Flags);
1231 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1236 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1237 T->setDebugLoc(I.getDebugLoc());
1238 SimpR->setFastMathFlags(I.getFastMathFlags());
1246 /// This function implements the transforms common to both integer remainder
1247 /// instructions (urem and srem). It is called by the visitors to those integer
1248 /// remainder instructions.
1249 /// @brief Common integer remainder transforms
1250 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1251 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1253 // The RHS is known non-zero.
1254 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
1259 // Handle cases involving: rem X, (select Cond, Y, Z)
1260 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1263 if (isa<Constant>(Op1)) {
1264 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1265 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1266 if (Instruction *R = FoldOpIntoSelect(I, SI))
1268 } else if (isa<PHINode>(Op0I)) {
1269 if (Instruction *NV = FoldOpIntoPhi(I))
1273 // See if we can fold away this rem instruction.
1274 if (SimplifyDemandedInstructionBits(I))
1282 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1283 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1285 if (Value *V = SimplifyVectorOp(I))
1286 return ReplaceInstUsesWith(I, V);
1288 if (Value *V = SimplifyURemInst(Op0, Op1, DL, TLI, DT, AT))
1289 return ReplaceInstUsesWith(I, V);
1291 if (Instruction *common = commonIRemTransforms(I))
1294 // (zext A) urem (zext B) --> zext (A urem B)
1295 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1296 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1297 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1300 // X urem Y -> X and Y-1, where Y is a power of 2,
1301 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, AT, &I, DT)) {
1302 Constant *N1 = Constant::getAllOnesValue(I.getType());
1303 Value *Add = Builder->CreateAdd(Op1, N1);
1304 return BinaryOperator::CreateAnd(Op0, Add);
1307 // 1 urem X -> zext(X != 1)
1308 if (match(Op0, m_One())) {
1309 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1310 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1311 return ReplaceInstUsesWith(I, Ext);
1317 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1318 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1320 if (Value *V = SimplifyVectorOp(I))
1321 return ReplaceInstUsesWith(I, V);
1323 if (Value *V = SimplifySRemInst(Op0, Op1, DL, TLI, DT, AT))
1324 return ReplaceInstUsesWith(I, V);
1326 // Handle the integer rem common cases
1327 if (Instruction *Common = commonIRemTransforms(I))
1333 if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
1334 Worklist.AddValue(I.getOperand(1));
1335 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
1340 // If the sign bits of both operands are zero (i.e. we can prove they are
1341 // unsigned inputs), turn this into a urem.
1342 if (I.getType()->isIntegerTy()) {
1343 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1344 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1345 MaskedValueIsZero(Op0, Mask, 0, &I)) {
1346 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1347 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1351 // If it's a constant vector, flip any negative values positive.
1352 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1353 Constant *C = cast<Constant>(Op1);
1354 unsigned VWidth = C->getType()->getVectorNumElements();
1356 bool hasNegative = false;
1357 bool hasMissing = false;
1358 for (unsigned i = 0; i != VWidth; ++i) {
1359 Constant *Elt = C->getAggregateElement(i);
1365 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
1366 if (RHS->isNegative())
1370 if (hasNegative && !hasMissing) {
1371 SmallVector<Constant *, 16> Elts(VWidth);
1372 for (unsigned i = 0; i != VWidth; ++i) {
1373 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
1374 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
1375 if (RHS->isNegative())
1376 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
1380 Constant *NewRHSV = ConstantVector::get(Elts);
1381 if (NewRHSV != C) { // Don't loop on -MININT
1382 Worklist.AddValue(I.getOperand(1));
1383 I.setOperand(1, NewRHSV);
1392 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
1393 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1395 if (Value *V = SimplifyVectorOp(I))
1396 return ReplaceInstUsesWith(I, V);
1398 if (Value *V = SimplifyFRemInst(Op0, Op1, DL, TLI, DT, AT))
1399 return ReplaceInstUsesWith(I, V);
1401 // Handle cases involving: rem X, (select Cond, Y, Z)
1402 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))