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 nullptr;
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 = nullptr, *B = nullptr, *PowerOf2 = nullptr;
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 : nullptr;
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 True if C2 is a multiple of C1. Quotient contains C2/C1.
101 static bool IsMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
103 assert(C1.getBitWidth() == C2.getBitWidth() &&
104 "Inconsistent width of constants!");
106 APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
108 APInt::sdivrem(C1, C2, Quotient, Remainder);
110 APInt::udivrem(C1, C2, Quotient, Remainder);
112 return Remainder.isMinValue();
115 /// \brief A helper routine of InstCombiner::visitMul().
117 /// If C is a vector of known powers of 2, then this function returns
118 /// a new vector obtained from C replacing each element with its logBase2.
119 /// Return a null pointer otherwise.
120 static Constant *getLogBase2Vector(ConstantDataVector *CV) {
122 SmallVector<Constant *, 4> Elts;
124 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
125 Constant *Elt = CV->getElementAsConstant(I);
126 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
128 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
131 return ConstantVector::get(Elts);
134 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
135 bool Changed = SimplifyAssociativeOrCommutative(I);
136 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
138 if (Value *V = SimplifyVectorOp(I))
139 return ReplaceInstUsesWith(I, V);
141 if (Value *V = SimplifyMulInst(Op0, Op1, DL))
142 return ReplaceInstUsesWith(I, V);
144 if (Value *V = SimplifyUsingDistributiveLaws(I))
145 return ReplaceInstUsesWith(I, V);
147 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X
148 return BinaryOperator::CreateNeg(Op0, I.getName());
150 // Also allow combining multiply instructions on vectors.
155 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
157 match(C1, m_APInt(IVal)))
158 // ((X << C1)*C2) == (X * (C2 << C1))
159 return BinaryOperator::CreateMul(NewOp, ConstantExpr::getShl(C1, C2));
161 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
162 Constant *NewCst = nullptr;
163 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
164 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
165 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
166 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
167 // Replace X*(2^C) with X << C, where C is a vector of known
168 // constant powers of 2.
169 NewCst = getLogBase2Vector(CV);
172 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
173 if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap();
174 if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap();
180 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
181 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
182 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
183 // The "* (2**n)" thus becomes a potential shifting opportunity.
185 const APInt & Val = CI->getValue();
186 const APInt &PosVal = Val.abs();
187 if (Val.isNegative() && PosVal.isPowerOf2()) {
188 Value *X = nullptr, *Y = nullptr;
189 if (Op0->hasOneUse()) {
191 Value *Sub = nullptr;
192 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
193 Sub = Builder->CreateSub(X, Y, "suba");
194 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
195 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
198 BinaryOperator::CreateMul(Sub,
199 ConstantInt::get(Y->getType(), PosVal));
205 // Simplify mul instructions with a constant RHS.
206 if (isa<Constant>(Op1)) {
207 // Try to fold constant mul into select arguments.
208 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
209 if (Instruction *R = FoldOpIntoSelect(I, SI))
212 if (isa<PHINode>(Op0))
213 if (Instruction *NV = FoldOpIntoPhi(I))
216 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
220 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
221 Value *Mul = Builder->CreateMul(C1, Op1);
222 // Only go forward with the transform if C1*CI simplifies to a tidier
224 if (!match(Mul, m_Mul(m_Value(), m_Value())))
225 return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
230 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
231 if (Value *Op1v = dyn_castNegVal(Op1))
232 return BinaryOperator::CreateMul(Op0v, Op1v);
234 // (X / Y) * Y = X - (X % Y)
235 // (X / Y) * -Y = (X % Y) - X
238 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
240 (BO->getOpcode() != Instruction::UDiv &&
241 BO->getOpcode() != Instruction::SDiv)) {
243 BO = dyn_cast<BinaryOperator>(Op1);
245 Value *Neg = dyn_castNegVal(Op1C);
246 if (BO && BO->hasOneUse() &&
247 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
248 (BO->getOpcode() == Instruction::UDiv ||
249 BO->getOpcode() == Instruction::SDiv)) {
250 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
252 // If the division is exact, X % Y is zero, so we end up with X or -X.
253 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
254 if (SDiv->isExact()) {
256 return ReplaceInstUsesWith(I, Op0BO);
257 return BinaryOperator::CreateNeg(Op0BO);
261 if (BO->getOpcode() == Instruction::UDiv)
262 Rem = Builder->CreateURem(Op0BO, Op1BO);
264 Rem = Builder->CreateSRem(Op0BO, Op1BO);
268 return BinaryOperator::CreateSub(Op0BO, Rem);
269 return BinaryOperator::CreateSub(Rem, Op0BO);
273 /// i1 mul -> i1 and.
274 if (I.getType()->getScalarType()->isIntegerTy(1))
275 return BinaryOperator::CreateAnd(Op0, Op1);
277 // X*(1 << Y) --> X << Y
278 // (1 << Y)*X --> X << Y
281 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
282 return BinaryOperator::CreateShl(Op1, Y);
283 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
284 return BinaryOperator::CreateShl(Op0, Y);
287 // If one of the operands of the multiply is a cast from a boolean value, then
288 // we know the bool is either zero or one, so this is a 'masking' multiply.
289 // X * Y (where Y is 0 or 1) -> X & (0-Y)
290 if (!I.getType()->isVectorTy()) {
291 // -2 is "-1 << 1" so it is all bits set except the low one.
292 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
294 Value *BoolCast = nullptr, *OtherOp = nullptr;
295 if (MaskedValueIsZero(Op0, Negative2))
296 BoolCast = Op0, OtherOp = Op1;
297 else if (MaskedValueIsZero(Op1, Negative2))
298 BoolCast = Op1, OtherOp = Op0;
301 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
303 return BinaryOperator::CreateAnd(V, OtherOp);
307 return Changed ? &I : nullptr;
315 // And check for corresponding fast math flags
318 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))
459 return ReplaceInstUsesWith(I, V);
461 bool AllowReassociate = I.hasUnsafeAlgebra();
463 // Simplify mul instructions with a constant RHS.
464 if (isa<Constant>(Op1)) {
465 // Try to fold constant mul into select arguments.
466 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
467 if (Instruction *R = FoldOpIntoSelect(I, SI))
470 if (isa<PHINode>(Op0))
471 if (Instruction *NV = FoldOpIntoPhi(I))
474 // (fmul X, -1.0) --> (fsub -0.0, X)
475 if (match(Op1, m_SpecificFP(-1.0))) {
476 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
477 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
478 RI->copyFastMathFlags(&I);
482 Constant *C = cast<Constant>(Op1);
483 if (AllowReassociate && isFiniteNonZeroFp(C)) {
484 // Let MDC denote an expression in one of these forms:
485 // X * C, C/X, X/C, where C is a constant.
487 // Try to simplify "MDC * Constant"
488 if (isFMulOrFDivWithConstant(Op0))
489 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
490 return ReplaceInstUsesWith(I, V);
492 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
493 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
495 (FAddSub->getOpcode() == Instruction::FAdd ||
496 FAddSub->getOpcode() == Instruction::FSub)) {
497 Value *Opnd0 = FAddSub->getOperand(0);
498 Value *Opnd1 = FAddSub->getOperand(1);
499 Constant *C0 = dyn_cast<Constant>(Opnd0);
500 Constant *C1 = dyn_cast<Constant>(Opnd1);
504 std::swap(Opnd0, Opnd1);
508 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
509 Value *M1 = ConstantExpr::getFMul(C1, C);
510 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
511 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
514 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
517 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
518 ? BinaryOperator::CreateFAdd(M0, M1)
519 : BinaryOperator::CreateFSub(M0, M1);
520 RI->copyFastMathFlags(&I);
529 // Under unsafe algebra do:
530 // X * log2(0.5*Y) = X*log2(Y) - X
531 if (I.hasUnsafeAlgebra()) {
532 Value *OpX = nullptr;
533 Value *OpY = nullptr;
535 detectLog2OfHalf(Op0, OpY, Log2);
539 detectLog2OfHalf(Op1, OpY, Log2);
544 // if pattern detected emit alternate sequence
546 BuilderTy::FastMathFlagGuard Guard(*Builder);
547 Builder->SetFastMathFlags(Log2->getFastMathFlags());
548 Log2->setArgOperand(0, OpY);
549 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
550 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
552 return ReplaceInstUsesWith(I, FSub);
556 // Handle symmetric situation in a 2-iteration loop
559 for (int i = 0; i < 2; i++) {
560 bool IgnoreZeroSign = I.hasNoSignedZeros();
561 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
562 BuilderTy::FastMathFlagGuard Guard(*Builder);
563 Builder->SetFastMathFlags(I.getFastMathFlags());
565 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
566 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
570 Value *FMul = Builder->CreateFMul(N0, N1);
572 return ReplaceInstUsesWith(I, FMul);
575 if (Opnd0->hasOneUse()) {
576 // -X * Y => -(X*Y) (Promote negation as high as possible)
577 Value *T = Builder->CreateFMul(N0, Opnd1);
578 Value *Neg = Builder->CreateFNeg(T);
580 return ReplaceInstUsesWith(I, Neg);
584 // (X*Y) * X => (X*X) * Y where Y != X
585 // The purpose is two-fold:
586 // 1) to form a power expression (of X).
587 // 2) potentially shorten the critical path: After transformation, the
588 // latency of the instruction Y is amortized by the expression of X*X,
589 // and therefore Y is in a "less critical" position compared to what it
590 // was before the transformation.
592 if (AllowReassociate) {
593 Value *Opnd0_0, *Opnd0_1;
594 if (Opnd0->hasOneUse() &&
595 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
597 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
599 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
603 BuilderTy::FastMathFlagGuard Guard(*Builder);
604 Builder->SetFastMathFlags(I.getFastMathFlags());
605 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
607 Value *R = Builder->CreateFMul(T, Y);
609 return ReplaceInstUsesWith(I, R);
614 if (!isa<Constant>(Op1))
615 std::swap(Opnd0, Opnd1);
620 return Changed ? &I : nullptr;
623 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
625 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
626 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
628 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
629 int NonNullOperand = -1;
630 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
631 if (ST->isNullValue())
633 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
634 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
635 if (ST->isNullValue())
638 if (NonNullOperand == -1)
641 Value *SelectCond = SI->getOperand(0);
643 // Change the div/rem to use 'Y' instead of the select.
644 I.setOperand(1, SI->getOperand(NonNullOperand));
646 // Okay, we know we replace the operand of the div/rem with 'Y' with no
647 // problem. However, the select, or the condition of the select may have
648 // multiple uses. Based on our knowledge that the operand must be non-zero,
649 // propagate the known value for the select into other uses of it, and
650 // propagate a known value of the condition into its other users.
652 // If the select and condition only have a single use, don't bother with this,
654 if (SI->use_empty() && SelectCond->hasOneUse())
657 // Scan the current block backward, looking for other uses of SI.
658 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
660 while (BBI != BBFront) {
662 // If we found a call to a function, we can't assume it will return, so
663 // information from below it cannot be propagated above it.
664 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
667 // Replace uses of the select or its condition with the known values.
668 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
671 *I = SI->getOperand(NonNullOperand);
673 } else if (*I == SelectCond) {
674 *I = Builder->getInt1(NonNullOperand == 1);
679 // If we past the instruction, quit looking for it.
682 if (&*BBI == SelectCond)
683 SelectCond = nullptr;
685 // If we ran out of things to eliminate, break out of the loop.
686 if (!SelectCond && !SI)
694 /// This function implements the transforms common to both integer division
695 /// instructions (udiv and sdiv). It is called by the visitors to those integer
696 /// division instructions.
697 /// @brief Common integer divide transforms
698 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
699 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
701 // The RHS is known non-zero.
702 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
707 // Handle cases involving: [su]div X, (select Cond, Y, Z)
708 // This does not apply for fdiv.
709 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
712 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
713 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
714 // (X / C1) / C2 -> X / (C1*C2)
715 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
716 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
717 if (MultiplyOverflows(RHS, LHSRHS,
718 I.getOpcode() == Instruction::SDiv))
719 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
720 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
721 ConstantExpr::getMul(RHS, LHSRHS));
725 const APInt *C1, *C2;
726 if (match(RHS, m_APInt(C2))) {
727 bool IsSigned = I.getOpcode() == Instruction::SDiv;
728 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
729 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
730 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
732 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
733 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
734 BinaryOperator *BO = BinaryOperator::Create(
735 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
736 BO->setIsExact(I.isExact());
740 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
741 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
742 BinaryOperator *BO = BinaryOperator::Create(
743 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
744 BO->setHasNoUnsignedWrap(
746 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
747 BO->setHasNoSignedWrap(
748 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
753 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1)))) ||
754 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
755 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
756 APInt C1Shifted = APInt::getOneBitSet(
757 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
759 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
760 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
761 BinaryOperator *BO = BinaryOperator::Create(
762 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
763 BO->setIsExact(I.isExact());
767 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
768 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
769 BinaryOperator *BO = BinaryOperator::Create(
770 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
771 BO->setHasNoUnsignedWrap(
773 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
774 BO->setHasNoSignedWrap(
775 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
782 if (!RHS->isZero()) { // avoid X udiv 0
783 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
784 if (Instruction *R = FoldOpIntoSelect(I, SI))
786 if (isa<PHINode>(Op0))
787 if (Instruction *NV = FoldOpIntoPhi(I))
792 if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
793 if (One->isOne() && !I.getType()->isIntegerTy(1)) {
794 bool isSigned = I.getOpcode() == Instruction::SDiv;
796 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
797 // result is one, if Op1 is -1 then the result is minus one, otherwise
799 Value *Inc = Builder->CreateAdd(Op1, One);
800 Value *Cmp = Builder->CreateICmpULT(
801 Inc, ConstantInt::get(I.getType(), 3));
802 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
804 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
805 // result is one, otherwise it's zero.
806 return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
811 // See if we can fold away this div instruction.
812 if (SimplifyDemandedInstructionBits(I))
815 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
816 Value *X = nullptr, *Z = nullptr;
817 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
818 bool isSigned = I.getOpcode() == Instruction::SDiv;
819 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
820 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
821 return BinaryOperator::Create(I.getOpcode(), X, Op1);
827 /// dyn_castZExtVal - Checks if V is a zext or constant that can
828 /// be truncated to Ty without losing bits.
829 static Value *dyn_castZExtVal(Value *V, Type *Ty) {
830 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
831 if (Z->getSrcTy() == Ty)
832 return Z->getOperand(0);
833 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
834 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
835 return ConstantExpr::getTrunc(C, Ty);
841 const unsigned MaxDepth = 6;
842 typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
843 const BinaryOperator &I,
846 /// \brief Used to maintain state for visitUDivOperand().
847 struct UDivFoldAction {
848 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
849 ///< operand. This can be zero if this action
850 ///< joins two actions together.
852 Value *OperandToFold; ///< Which operand to fold.
854 Instruction *FoldResult; ///< The instruction returned when FoldAction is
857 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
858 ///< joins two actions together.
861 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
862 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
863 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
864 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
868 // X udiv 2^C -> X >> C
869 static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
870 const BinaryOperator &I, InstCombiner &IC) {
871 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
872 BinaryOperator *LShr = BinaryOperator::CreateLShr(
873 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
874 if (I.isExact()) LShr->setIsExact();
878 // X udiv C, where C >= signbit
879 static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
880 const BinaryOperator &I, InstCombiner &IC) {
881 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
883 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
884 ConstantInt::get(I.getType(), 1));
887 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
888 static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
890 Instruction *ShiftLeft = cast<Instruction>(Op1);
891 if (isa<ZExtInst>(ShiftLeft))
892 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
895 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
896 Value *N = ShiftLeft->getOperand(1);
898 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
899 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
900 N = IC.Builder->CreateZExt(N, Z->getDestTy());
901 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
902 if (I.isExact()) LShr->setIsExact();
906 // \brief Recursively visits the possible right hand operands of a udiv
907 // instruction, seeing through select instructions, to determine if we can
908 // replace the udiv with something simpler. If we find that an operand is not
909 // able to simplify the udiv, we abort the entire transformation.
910 static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
911 SmallVectorImpl<UDivFoldAction> &Actions,
912 unsigned Depth = 0) {
913 // Check to see if this is an unsigned division with an exact power of 2,
914 // if so, convert to a right shift.
915 if (match(Op1, m_Power2())) {
916 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
917 return Actions.size();
920 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
921 // X udiv C, where C >= signbit
922 if (C->getValue().isNegative()) {
923 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
924 return Actions.size();
927 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
928 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
929 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
930 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
931 return Actions.size();
934 // The remaining tests are all recursive, so bail out if we hit the limit.
935 if (Depth++ == MaxDepth)
938 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
940 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
941 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
942 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
943 return Actions.size();
949 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
950 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
952 if (Value *V = SimplifyVectorOp(I))
953 return ReplaceInstUsesWith(I, V);
955 if (Value *V = SimplifyUDivInst(Op0, Op1, DL))
956 return ReplaceInstUsesWith(I, V);
958 // Handle the integer div common cases
959 if (Instruction *Common = commonIDivTransforms(I))
962 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
963 if (Constant *C2 = dyn_cast<Constant>(Op1)) {
966 if (match(Op0, m_LShr(m_Value(X), m_Constant(C1))))
967 return BinaryOperator::CreateUDiv(X, ConstantExpr::getShl(C2, C1));
970 // (zext A) udiv (zext B) --> zext (A udiv B)
971 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
972 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
973 return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
977 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
978 SmallVector<UDivFoldAction, 6> UDivActions;
979 if (visitUDivOperand(Op0, Op1, I, UDivActions))
980 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
981 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
982 Value *ActionOp1 = UDivActions[i].OperandToFold;
985 Inst = Action(Op0, ActionOp1, I, *this);
987 // This action joins two actions together. The RHS of this action is
988 // simply the last action we processed, we saved the LHS action index in
989 // the joining action.
990 size_t SelectRHSIdx = i - 1;
991 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
992 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
993 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
994 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
995 SelectLHS, SelectRHS);
998 // If this is the last action to process, return it to the InstCombiner.
999 // Otherwise, we insert it before the UDiv and record it so that we may
1000 // use it as part of a joining action (i.e., a SelectInst).
1002 Inst->insertBefore(&I);
1003 UDivActions[i].FoldResult = Inst;
1011 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1012 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1014 if (Value *V = SimplifyVectorOp(I))
1015 return ReplaceInstUsesWith(I, V);
1017 if (Value *V = SimplifySDivInst(Op0, Op1, DL))
1018 return ReplaceInstUsesWith(I, V);
1020 // Handle the integer div common cases
1021 if (Instruction *Common = commonIDivTransforms(I))
1025 if (match(Op1, m_AllOnes()))
1026 return BinaryOperator::CreateNeg(Op0);
1028 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1029 // sdiv X, C --> ashr exact X, log2(C)
1030 if (I.isExact() && RHS->getValue().isNonNegative() &&
1031 RHS->getValue().isPowerOf2()) {
1032 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1033 RHS->getValue().exactLogBase2());
1034 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1038 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
1039 // X/INT_MIN -> X == INT_MIN
1040 if (RHS->isMinSignedValue())
1041 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1043 // -X/C --> X/-C provided the negation doesn't overflow.
1044 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
1045 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
1046 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
1047 ConstantExpr::getNeg(RHS));
1050 // If the sign bits of both operands are zero (i.e. we can prove they are
1051 // unsigned inputs), turn this into a udiv.
1052 if (I.getType()->isIntegerTy()) {
1053 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1054 if (MaskedValueIsZero(Op0, Mask)) {
1055 if (MaskedValueIsZero(Op1, Mask)) {
1056 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1057 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1060 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
1061 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1062 // Safe because the only negative value (1 << Y) can take on is
1063 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1064 // the sign bit set.
1065 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1073 /// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1075 /// 1) 1/C is exact, or
1076 /// 2) reciprocal is allowed.
1077 /// If the conversion was successful, the simplified expression "X * 1/C" is
1078 /// returned; otherwise, NULL is returned.
1080 static Instruction *CvtFDivConstToReciprocal(Value *Dividend,
1082 bool AllowReciprocal) {
1083 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
1086 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
1087 APFloat Reciprocal(FpVal.getSemantics());
1088 bool Cvt = FpVal.getExactInverse(&Reciprocal);
1090 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
1091 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1092 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1093 Cvt = !Reciprocal.isDenormal();
1100 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1101 return BinaryOperator::CreateFMul(Dividend, R);
1104 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1105 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1107 if (Value *V = SimplifyVectorOp(I))
1108 return ReplaceInstUsesWith(I, V);
1110 if (Value *V = SimplifyFDivInst(Op0, Op1, DL))
1111 return ReplaceInstUsesWith(I, V);
1113 if (isa<Constant>(Op0))
1114 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1115 if (Instruction *R = FoldOpIntoSelect(I, SI))
1118 bool AllowReassociate = I.hasUnsafeAlgebra();
1119 bool AllowReciprocal = I.hasAllowReciprocal();
1121 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1122 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1123 if (Instruction *R = FoldOpIntoSelect(I, SI))
1126 if (AllowReassociate) {
1127 Constant *C1 = nullptr;
1128 Constant *C2 = Op1C;
1130 Instruction *Res = nullptr;
1132 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
1133 // (X*C1)/C2 => X * (C1/C2)
1135 Constant *C = ConstantExpr::getFDiv(C1, C2);
1137 Res = BinaryOperator::CreateFMul(X, C);
1138 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
1139 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1141 Constant *C = ConstantExpr::getFMul(C1, C2);
1142 if (isNormalFp(C)) {
1143 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
1145 Res = BinaryOperator::CreateFDiv(X, C);
1150 Res->setFastMathFlags(I.getFastMathFlags());
1156 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1157 T->copyFastMathFlags(&I);
1164 if (AllowReassociate && isa<Constant>(Op0)) {
1165 Constant *C1 = cast<Constant>(Op0), *C2;
1166 Constant *Fold = nullptr;
1168 bool CreateDiv = true;
1170 // C1 / (X*C2) => (C1/C2) / X
1171 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
1172 Fold = ConstantExpr::getFDiv(C1, C2);
1173 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
1174 // C1 / (X/C2) => (C1*C2) / X
1175 Fold = ConstantExpr::getFMul(C1, C2);
1176 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
1177 // C1 / (C2/X) => (C1/C2) * X
1178 Fold = ConstantExpr::getFDiv(C1, C2);
1182 if (Fold && isNormalFp(Fold)) {
1183 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1184 : BinaryOperator::CreateFMul(X, Fold);
1185 R->setFastMathFlags(I.getFastMathFlags());
1191 if (AllowReassociate) {
1193 Value *NewInst = nullptr;
1194 Instruction *SimpR = nullptr;
1196 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1197 // (X/Y) / Z => X / (Y*Z)
1199 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
1200 NewInst = Builder->CreateFMul(Y, Op1);
1201 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1202 FastMathFlags Flags = I.getFastMathFlags();
1203 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1204 RI->setFastMathFlags(Flags);
1206 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1208 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1209 // Z / (X/Y) => Z*Y / X
1211 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
1212 NewInst = Builder->CreateFMul(Op0, Y);
1213 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1214 FastMathFlags Flags = I.getFastMathFlags();
1215 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1216 RI->setFastMathFlags(Flags);
1218 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1223 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1224 T->setDebugLoc(I.getDebugLoc());
1225 SimpR->setFastMathFlags(I.getFastMathFlags());
1233 /// This function implements the transforms common to both integer remainder
1234 /// instructions (urem and srem). It is called by the visitors to those integer
1235 /// remainder instructions.
1236 /// @brief Common integer remainder transforms
1237 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1238 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1240 // The RHS is known non-zero.
1241 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
1246 // Handle cases involving: rem X, (select Cond, Y, Z)
1247 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1250 if (isa<Constant>(Op1)) {
1251 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1252 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1253 if (Instruction *R = FoldOpIntoSelect(I, SI))
1255 } else if (isa<PHINode>(Op0I)) {
1256 if (Instruction *NV = FoldOpIntoPhi(I))
1260 // See if we can fold away this rem instruction.
1261 if (SimplifyDemandedInstructionBits(I))
1269 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1270 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1272 if (Value *V = SimplifyVectorOp(I))
1273 return ReplaceInstUsesWith(I, V);
1275 if (Value *V = SimplifyURemInst(Op0, Op1, DL))
1276 return ReplaceInstUsesWith(I, V);
1278 if (Instruction *common = commonIRemTransforms(I))
1281 // (zext A) urem (zext B) --> zext (A urem B)
1282 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1283 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1284 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1287 // X urem Y -> X and Y-1, where Y is a power of 2,
1288 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true)) {
1289 Constant *N1 = Constant::getAllOnesValue(I.getType());
1290 Value *Add = Builder->CreateAdd(Op1, N1);
1291 return BinaryOperator::CreateAnd(Op0, Add);
1294 // 1 urem X -> zext(X != 1)
1295 if (match(Op0, m_One())) {
1296 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1297 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1298 return ReplaceInstUsesWith(I, Ext);
1304 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1305 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1307 if (Value *V = SimplifyVectorOp(I))
1308 return ReplaceInstUsesWith(I, V);
1310 if (Value *V = SimplifySRemInst(Op0, Op1, DL))
1311 return ReplaceInstUsesWith(I, V);
1313 // Handle the integer rem common cases
1314 if (Instruction *Common = commonIRemTransforms(I))
1317 if (Value *RHSNeg = dyn_castNegVal(Op1))
1318 if (!isa<Constant>(RHSNeg) ||
1319 (isa<ConstantInt>(RHSNeg) &&
1320 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
1322 Worklist.AddValue(I.getOperand(1));
1323 I.setOperand(1, RHSNeg);
1327 // If the sign bits of both operands are zero (i.e. we can prove they are
1328 // unsigned inputs), turn this into a urem.
1329 if (I.getType()->isIntegerTy()) {
1330 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1331 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
1332 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1333 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1337 // If it's a constant vector, flip any negative values positive.
1338 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1339 Constant *C = cast<Constant>(Op1);
1340 unsigned VWidth = C->getType()->getVectorNumElements();
1342 bool hasNegative = false;
1343 bool hasMissing = false;
1344 for (unsigned i = 0; i != VWidth; ++i) {
1345 Constant *Elt = C->getAggregateElement(i);
1351 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
1352 if (RHS->isNegative())
1356 if (hasNegative && !hasMissing) {
1357 SmallVector<Constant *, 16> Elts(VWidth);
1358 for (unsigned i = 0; i != VWidth; ++i) {
1359 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
1360 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
1361 if (RHS->isNegative())
1362 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
1366 Constant *NewRHSV = ConstantVector::get(Elts);
1367 if (NewRHSV != C) { // Don't loop on -MININT
1368 Worklist.AddValue(I.getOperand(1));
1369 I.setOperand(1, NewRHSV);
1378 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
1379 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1381 if (Value *V = SimplifyVectorOp(I))
1382 return ReplaceInstUsesWith(I, V);
1384 if (Value *V = SimplifyFRemInst(Op0, Op1, DL))
1385 return ReplaceInstUsesWith(I, V);
1387 // Handle cases involving: rem X, (select Cond, Y, Z)
1388 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))