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, *PowerOf2 = nullptr;
40 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(PowerOf2), m_Value(A))),
42 // The "1" can be any value known to be a power of 2.
43 isKnownToBeAPowerOfTwo(PowerOf2, false, 0, IC.getAssumptionTracker(),
44 CxtI, IC.getDominatorTree())) {
45 A = IC.Builder->CreateSub(A, B);
46 return IC.Builder->CreateShl(PowerOf2, A);
49 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
50 // inexact. Similarly for <<.
51 if (BinaryOperator *I = dyn_cast<BinaryOperator>(V))
52 if (I->isLogicalShift() && isKnownToBeAPowerOfTwo(I->getOperand(0), false,
53 0, IC.getAssumptionTracker(),
55 IC.getDominatorTree())) {
56 // We know that this is an exact/nuw shift and that the input is a
57 // non-zero context as well.
58 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
63 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
68 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
69 I->setHasNoUnsignedWrap();
74 // TODO: Lots more we could do here:
75 // If V is a phi node, we can call this on each of its operands.
76 // "select cond, X, 0" can simplify to "X".
78 return MadeChange ? V : nullptr;
82 /// MultiplyOverflows - True if the multiply can not be expressed in an int
84 static bool MultiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
88 Product = C1.smul_ov(C2, Overflow);
90 Product = C1.umul_ov(C2, Overflow);
95 /// \brief True if C2 is a multiple of C1. Quotient contains C2/C1.
96 static bool IsMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
98 assert(C1.getBitWidth() == C2.getBitWidth() &&
99 "Inconsistent width of constants!");
101 APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
103 APInt::sdivrem(C1, C2, Quotient, Remainder);
105 APInt::udivrem(C1, C2, Quotient, Remainder);
107 return Remainder.isMinValue();
110 /// \brief A helper routine of InstCombiner::visitMul().
112 /// If C is a vector of known powers of 2, then this function returns
113 /// a new vector obtained from C replacing each element with its logBase2.
114 /// Return a null pointer otherwise.
115 static Constant *getLogBase2Vector(ConstantDataVector *CV) {
117 SmallVector<Constant *, 4> Elts;
119 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
120 Constant *Elt = CV->getElementAsConstant(I);
121 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
123 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
126 return ConstantVector::get(Elts);
129 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
130 bool Changed = SimplifyAssociativeOrCommutative(I);
131 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
133 if (Value *V = SimplifyVectorOp(I))
134 return ReplaceInstUsesWith(I, V);
136 if (Value *V = SimplifyMulInst(Op0, Op1, DL, TLI, DT, AT))
137 return ReplaceInstUsesWith(I, V);
139 if (Value *V = SimplifyUsingDistributiveLaws(I))
140 return ReplaceInstUsesWith(I, V);
142 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X
143 return BinaryOperator::CreateNeg(Op0, I.getName());
145 // Also allow combining multiply instructions on vectors.
150 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
152 match(C1, m_APInt(IVal)))
153 // ((X << C1)*C2) == (X * (C2 << C1))
154 return BinaryOperator::CreateMul(NewOp, ConstantExpr::getShl(C1, C2));
156 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
157 Constant *NewCst = nullptr;
158 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
159 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
160 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
161 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
162 // Replace X*(2^C) with X << C, where C is a vector of known
163 // constant powers of 2.
164 NewCst = getLogBase2Vector(CV);
167 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
169 if (I.hasNoUnsignedWrap())
170 Shl->setHasNoUnsignedWrap();
177 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
178 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
179 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
180 // The "* (2**n)" thus becomes a potential shifting opportunity.
182 const APInt & Val = CI->getValue();
183 const APInt &PosVal = Val.abs();
184 if (Val.isNegative() && PosVal.isPowerOf2()) {
185 Value *X = nullptr, *Y = nullptr;
186 if (Op0->hasOneUse()) {
188 Value *Sub = nullptr;
189 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
190 Sub = Builder->CreateSub(X, Y, "suba");
191 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
192 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
195 BinaryOperator::CreateMul(Sub,
196 ConstantInt::get(Y->getType(), PosVal));
202 // Simplify mul instructions with a constant RHS.
203 if (isa<Constant>(Op1)) {
204 // Try to fold constant mul into select arguments.
205 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
206 if (Instruction *R = FoldOpIntoSelect(I, SI))
209 if (isa<PHINode>(Op0))
210 if (Instruction *NV = FoldOpIntoPhi(I))
213 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
217 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
218 Value *Mul = Builder->CreateMul(C1, Op1);
219 // Only go forward with the transform if C1*CI simplifies to a tidier
221 if (!match(Mul, m_Mul(m_Value(), m_Value())))
222 return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
227 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
228 if (Value *Op1v = dyn_castNegVal(Op1))
229 return BinaryOperator::CreateMul(Op0v, Op1v);
231 // (X / Y) * Y = X - (X % Y)
232 // (X / Y) * -Y = (X % Y) - X
235 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
237 (BO->getOpcode() != Instruction::UDiv &&
238 BO->getOpcode() != Instruction::SDiv)) {
240 BO = dyn_cast<BinaryOperator>(Op1);
242 Value *Neg = dyn_castNegVal(Op1C);
243 if (BO && BO->hasOneUse() &&
244 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
245 (BO->getOpcode() == Instruction::UDiv ||
246 BO->getOpcode() == Instruction::SDiv)) {
247 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
249 // If the division is exact, X % Y is zero, so we end up with X or -X.
250 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
251 if (SDiv->isExact()) {
253 return ReplaceInstUsesWith(I, Op0BO);
254 return BinaryOperator::CreateNeg(Op0BO);
258 if (BO->getOpcode() == Instruction::UDiv)
259 Rem = Builder->CreateURem(Op0BO, Op1BO);
261 Rem = Builder->CreateSRem(Op0BO, Op1BO);
265 return BinaryOperator::CreateSub(Op0BO, Rem);
266 return BinaryOperator::CreateSub(Rem, Op0BO);
270 /// i1 mul -> i1 and.
271 if (I.getType()->getScalarType()->isIntegerTy(1))
272 return BinaryOperator::CreateAnd(Op0, Op1);
274 // X*(1 << Y) --> X << Y
275 // (1 << Y)*X --> X << Y
278 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
279 return BinaryOperator::CreateShl(Op1, Y);
280 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
281 return BinaryOperator::CreateShl(Op0, Y);
284 // If one of the operands of the multiply is a cast from a boolean value, then
285 // we know the bool is either zero or one, so this is a 'masking' multiply.
286 // X * Y (where Y is 0 or 1) -> X & (0-Y)
287 if (!I.getType()->isVectorTy()) {
288 // -2 is "-1 << 1" so it is all bits set except the low one.
289 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
291 Value *BoolCast = nullptr, *OtherOp = nullptr;
292 if (MaskedValueIsZero(Op0, Negative2, 0, &I))
293 BoolCast = Op0, OtherOp = Op1;
294 else if (MaskedValueIsZero(Op1, Negative2, 0, &I))
295 BoolCast = Op1, OtherOp = Op0;
298 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
300 return BinaryOperator::CreateAnd(V, OtherOp);
304 return Changed ? &I : nullptr;
307 /// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
308 static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
309 if (!Op->hasOneUse())
312 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
315 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
319 Value *OpLog2Of = II->getArgOperand(0);
320 if (!OpLog2Of->hasOneUse())
323 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
326 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
329 if (match(I->getOperand(0), m_SpecificFP(0.5)))
330 Y = I->getOperand(1);
331 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
332 Y = I->getOperand(0);
335 static bool isFiniteNonZeroFp(Constant *C) {
336 if (C->getType()->isVectorTy()) {
337 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
339 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
340 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
346 return isa<ConstantFP>(C) &&
347 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
350 static bool isNormalFp(Constant *C) {
351 if (C->getType()->isVectorTy()) {
352 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
354 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
355 if (!CFP || !CFP->getValueAPF().isNormal())
361 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
364 /// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
365 /// true iff the given value is FMul or FDiv with one and only one operand
366 /// being a normal constant (i.e. not Zero/NaN/Infinity).
367 static bool isFMulOrFDivWithConstant(Value *V) {
368 Instruction *I = dyn_cast<Instruction>(V);
369 if (!I || (I->getOpcode() != Instruction::FMul &&
370 I->getOpcode() != Instruction::FDiv))
373 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
374 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
379 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
382 /// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
383 /// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
384 /// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
385 /// This function is to simplify "FMulOrDiv * C" and returns the
386 /// resulting expression. Note that this function could return NULL in
387 /// case the constants cannot be folded into a normal floating-point.
389 Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
390 Instruction *InsertBefore) {
391 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
393 Value *Opnd0 = FMulOrDiv->getOperand(0);
394 Value *Opnd1 = FMulOrDiv->getOperand(1);
396 Constant *C0 = dyn_cast<Constant>(Opnd0);
397 Constant *C1 = dyn_cast<Constant>(Opnd1);
399 BinaryOperator *R = nullptr;
401 // (X * C0) * C => X * (C0*C)
402 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
403 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
405 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
408 // (C0 / X) * C => (C0 * C) / X
409 if (FMulOrDiv->hasOneUse()) {
410 // It would otherwise introduce another div.
411 Constant *F = ConstantExpr::getFMul(C0, C);
413 R = BinaryOperator::CreateFDiv(F, Opnd1);
416 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
417 Constant *F = ConstantExpr::getFDiv(C, C1);
419 R = BinaryOperator::CreateFMul(Opnd0, F);
421 // (X / C1) * C => X / (C1/C)
422 Constant *F = ConstantExpr::getFDiv(C1, C);
424 R = BinaryOperator::CreateFDiv(Opnd0, F);
430 R->setHasUnsafeAlgebra(true);
431 InsertNewInstWith(R, *InsertBefore);
437 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
438 bool Changed = SimplifyAssociativeOrCommutative(I);
439 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
441 if (Value *V = SimplifyVectorOp(I))
442 return ReplaceInstUsesWith(I, V);
444 if (isa<Constant>(Op0))
447 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL, TLI,
449 return ReplaceInstUsesWith(I, V);
451 bool AllowReassociate = I.hasUnsafeAlgebra();
453 // Simplify mul instructions with a constant RHS.
454 if (isa<Constant>(Op1)) {
455 // Try to fold constant mul into select arguments.
456 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
457 if (Instruction *R = FoldOpIntoSelect(I, SI))
460 if (isa<PHINode>(Op0))
461 if (Instruction *NV = FoldOpIntoPhi(I))
464 // (fmul X, -1.0) --> (fsub -0.0, X)
465 if (match(Op1, m_SpecificFP(-1.0))) {
466 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
467 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
468 RI->copyFastMathFlags(&I);
472 Constant *C = cast<Constant>(Op1);
473 if (AllowReassociate && isFiniteNonZeroFp(C)) {
474 // Let MDC denote an expression in one of these forms:
475 // X * C, C/X, X/C, where C is a constant.
477 // Try to simplify "MDC * Constant"
478 if (isFMulOrFDivWithConstant(Op0))
479 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
480 return ReplaceInstUsesWith(I, V);
482 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
483 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
485 (FAddSub->getOpcode() == Instruction::FAdd ||
486 FAddSub->getOpcode() == Instruction::FSub)) {
487 Value *Opnd0 = FAddSub->getOperand(0);
488 Value *Opnd1 = FAddSub->getOperand(1);
489 Constant *C0 = dyn_cast<Constant>(Opnd0);
490 Constant *C1 = dyn_cast<Constant>(Opnd1);
494 std::swap(Opnd0, Opnd1);
498 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
499 Value *M1 = ConstantExpr::getFMul(C1, C);
500 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
501 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
504 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
507 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
508 ? BinaryOperator::CreateFAdd(M0, M1)
509 : BinaryOperator::CreateFSub(M0, M1);
510 RI->copyFastMathFlags(&I);
518 // sqrt(X) * sqrt(X) -> X
519 if (AllowReassociate && (Op0 == Op1))
520 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0))
521 if (II->getIntrinsicID() == Intrinsic::sqrt)
522 return ReplaceInstUsesWith(I, II->getOperand(0));
524 // Under unsafe algebra do:
525 // X * log2(0.5*Y) = X*log2(Y) - X
526 if (AllowReassociate) {
527 Value *OpX = nullptr;
528 Value *OpY = nullptr;
530 detectLog2OfHalf(Op0, OpY, Log2);
534 detectLog2OfHalf(Op1, OpY, Log2);
539 // if pattern detected emit alternate sequence
541 BuilderTy::FastMathFlagGuard Guard(*Builder);
542 Builder->SetFastMathFlags(Log2->getFastMathFlags());
543 Log2->setArgOperand(0, OpY);
544 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
545 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
547 return ReplaceInstUsesWith(I, FSub);
551 // Handle symmetric situation in a 2-iteration loop
554 for (int i = 0; i < 2; i++) {
555 bool IgnoreZeroSign = I.hasNoSignedZeros();
556 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
557 BuilderTy::FastMathFlagGuard Guard(*Builder);
558 Builder->SetFastMathFlags(I.getFastMathFlags());
560 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
561 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
565 Value *FMul = Builder->CreateFMul(N0, N1);
567 return ReplaceInstUsesWith(I, FMul);
570 if (Opnd0->hasOneUse()) {
571 // -X * Y => -(X*Y) (Promote negation as high as possible)
572 Value *T = Builder->CreateFMul(N0, Opnd1);
573 Value *Neg = Builder->CreateFNeg(T);
575 return ReplaceInstUsesWith(I, Neg);
579 // (X*Y) * X => (X*X) * Y where Y != X
580 // The purpose is two-fold:
581 // 1) to form a power expression (of X).
582 // 2) potentially shorten the critical path: After transformation, the
583 // latency of the instruction Y is amortized by the expression of X*X,
584 // and therefore Y is in a "less critical" position compared to what it
585 // was before the transformation.
587 if (AllowReassociate) {
588 Value *Opnd0_0, *Opnd0_1;
589 if (Opnd0->hasOneUse() &&
590 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
592 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
594 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
598 BuilderTy::FastMathFlagGuard Guard(*Builder);
599 Builder->SetFastMathFlags(I.getFastMathFlags());
600 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
602 Value *R = Builder->CreateFMul(T, Y);
604 return ReplaceInstUsesWith(I, R);
609 if (!isa<Constant>(Op1))
610 std::swap(Opnd0, Opnd1);
615 return Changed ? &I : nullptr;
618 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
620 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
621 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
623 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
624 int NonNullOperand = -1;
625 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
626 if (ST->isNullValue())
628 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
629 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
630 if (ST->isNullValue())
633 if (NonNullOperand == -1)
636 Value *SelectCond = SI->getOperand(0);
638 // Change the div/rem to use 'Y' instead of the select.
639 I.setOperand(1, SI->getOperand(NonNullOperand));
641 // Okay, we know we replace the operand of the div/rem with 'Y' with no
642 // problem. However, the select, or the condition of the select may have
643 // multiple uses. Based on our knowledge that the operand must be non-zero,
644 // propagate the known value for the select into other uses of it, and
645 // propagate a known value of the condition into its other users.
647 // If the select and condition only have a single use, don't bother with this,
649 if (SI->use_empty() && SelectCond->hasOneUse())
652 // Scan the current block backward, looking for other uses of SI.
653 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
655 while (BBI != BBFront) {
657 // If we found a call to a function, we can't assume it will return, so
658 // information from below it cannot be propagated above it.
659 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
662 // Replace uses of the select or its condition with the known values.
663 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
666 *I = SI->getOperand(NonNullOperand);
668 } else if (*I == SelectCond) {
669 *I = Builder->getInt1(NonNullOperand == 1);
674 // If we past the instruction, quit looking for it.
677 if (&*BBI == SelectCond)
678 SelectCond = nullptr;
680 // If we ran out of things to eliminate, break out of the loop.
681 if (!SelectCond && !SI)
689 /// This function implements the transforms common to both integer division
690 /// instructions (udiv and sdiv). It is called by the visitors to those integer
691 /// division instructions.
692 /// @brief Common integer divide transforms
693 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
694 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
696 // The RHS is known non-zero.
697 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
702 // Handle cases involving: [su]div X, (select Cond, Y, Z)
703 // This does not apply for fdiv.
704 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
707 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
709 if (match(Op1, m_APInt(C2))) {
712 bool IsSigned = I.getOpcode() == Instruction::SDiv;
714 // (X / C1) / C2 -> X / (C1*C2)
715 if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
716 (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
717 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
718 if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
719 return BinaryOperator::Create(I.getOpcode(), X,
720 ConstantInt::get(I.getType(), Product));
723 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
724 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
725 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
727 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
728 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
729 BinaryOperator *BO = BinaryOperator::Create(
730 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
731 BO->setIsExact(I.isExact());
735 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
736 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
737 BinaryOperator *BO = BinaryOperator::Create(
738 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
739 BO->setHasNoUnsignedWrap(
741 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
742 BO->setHasNoSignedWrap(
743 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
748 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
749 *C1 != C1->getBitWidth() - 1) ||
750 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
751 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
752 APInt C1Shifted = APInt::getOneBitSet(
753 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
755 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
756 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
757 BinaryOperator *BO = BinaryOperator::Create(
758 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
759 BO->setIsExact(I.isExact());
763 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
764 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
765 BinaryOperator *BO = BinaryOperator::Create(
766 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
767 BO->setHasNoUnsignedWrap(
769 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
770 BO->setHasNoSignedWrap(
771 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
776 if (*C2 != 0) { // avoid X udiv 0
777 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
778 if (Instruction *R = FoldOpIntoSelect(I, SI))
780 if (isa<PHINode>(Op0))
781 if (Instruction *NV = FoldOpIntoPhi(I))
787 if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
788 if (One->isOne() && !I.getType()->isIntegerTy(1)) {
789 bool isSigned = I.getOpcode() == Instruction::SDiv;
791 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
792 // result is one, if Op1 is -1 then the result is minus one, otherwise
794 Value *Inc = Builder->CreateAdd(Op1, One);
795 Value *Cmp = Builder->CreateICmpULT(
796 Inc, ConstantInt::get(I.getType(), 3));
797 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
799 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
800 // result is one, otherwise it's zero.
801 return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
806 // See if we can fold away this div instruction.
807 if (SimplifyDemandedInstructionBits(I))
810 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
811 Value *X = nullptr, *Z = nullptr;
812 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
813 bool isSigned = I.getOpcode() == Instruction::SDiv;
814 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
815 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
816 return BinaryOperator::Create(I.getOpcode(), X, Op1);
822 /// dyn_castZExtVal - Checks if V is a zext or constant that can
823 /// be truncated to Ty without losing bits.
824 static Value *dyn_castZExtVal(Value *V, Type *Ty) {
825 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
826 if (Z->getSrcTy() == Ty)
827 return Z->getOperand(0);
828 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
829 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
830 return ConstantExpr::getTrunc(C, Ty);
836 const unsigned MaxDepth = 6;
837 typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
838 const BinaryOperator &I,
841 /// \brief Used to maintain state for visitUDivOperand().
842 struct UDivFoldAction {
843 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
844 ///< operand. This can be zero if this action
845 ///< joins two actions together.
847 Value *OperandToFold; ///< Which operand to fold.
849 Instruction *FoldResult; ///< The instruction returned when FoldAction is
852 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
853 ///< joins two actions together.
856 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
857 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
858 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
859 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
863 // X udiv 2^C -> X >> C
864 static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
865 const BinaryOperator &I, InstCombiner &IC) {
866 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
867 BinaryOperator *LShr = BinaryOperator::CreateLShr(
868 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
874 // X udiv C, where C >= signbit
875 static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
876 const BinaryOperator &I, InstCombiner &IC) {
877 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
879 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
880 ConstantInt::get(I.getType(), 1));
883 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
884 static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
886 Instruction *ShiftLeft = cast<Instruction>(Op1);
887 if (isa<ZExtInst>(ShiftLeft))
888 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
891 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
892 Value *N = ShiftLeft->getOperand(1);
894 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
895 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
896 N = IC.Builder->CreateZExt(N, Z->getDestTy());
897 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
903 // \brief Recursively visits the possible right hand operands of a udiv
904 // instruction, seeing through select instructions, to determine if we can
905 // replace the udiv with something simpler. If we find that an operand is not
906 // able to simplify the udiv, we abort the entire transformation.
907 static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
908 SmallVectorImpl<UDivFoldAction> &Actions,
909 unsigned Depth = 0) {
910 // Check to see if this is an unsigned division with an exact power of 2,
911 // if so, convert to a right shift.
912 if (match(Op1, m_Power2())) {
913 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
914 return Actions.size();
917 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
918 // X udiv C, where C >= signbit
919 if (C->getValue().isNegative()) {
920 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
921 return Actions.size();
924 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
925 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
926 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
927 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
928 return Actions.size();
931 // The remaining tests are all recursive, so bail out if we hit the limit.
932 if (Depth++ == MaxDepth)
935 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
937 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
938 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
939 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
940 return Actions.size();
946 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
947 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
949 if (Value *V = SimplifyVectorOp(I))
950 return ReplaceInstUsesWith(I, V);
952 if (Value *V = SimplifyUDivInst(Op0, Op1, DL, TLI, DT, AT))
953 return ReplaceInstUsesWith(I, V);
955 // Handle the integer div common cases
956 if (Instruction *Common = commonIDivTransforms(I))
959 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
962 const APInt *C1, *C2;
963 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
964 match(Op1, m_APInt(C2))) {
966 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
968 return BinaryOperator::CreateUDiv(
969 X, ConstantInt::get(X->getType(), C2ShlC1));
973 // (zext A) udiv (zext B) --> zext (A udiv B)
974 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
975 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
977 Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", I.isExact()),
980 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
981 SmallVector<UDivFoldAction, 6> UDivActions;
982 if (visitUDivOperand(Op0, Op1, I, UDivActions))
983 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
984 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
985 Value *ActionOp1 = UDivActions[i].OperandToFold;
988 Inst = Action(Op0, ActionOp1, I, *this);
990 // This action joins two actions together. The RHS of this action is
991 // simply the last action we processed, we saved the LHS action index in
992 // the joining action.
993 size_t SelectRHSIdx = i - 1;
994 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
995 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
996 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
997 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
998 SelectLHS, SelectRHS);
1001 // If this is the last action to process, return it to the InstCombiner.
1002 // Otherwise, we insert it before the UDiv and record it so that we may
1003 // use it as part of a joining action (i.e., a SelectInst).
1005 Inst->insertBefore(&I);
1006 UDivActions[i].FoldResult = Inst;
1014 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1015 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1017 if (Value *V = SimplifyVectorOp(I))
1018 return ReplaceInstUsesWith(I, V);
1020 if (Value *V = SimplifySDivInst(Op0, Op1, DL, TLI, DT, AT))
1021 return ReplaceInstUsesWith(I, V);
1023 // Handle the integer div common cases
1024 if (Instruction *Common = commonIDivTransforms(I))
1028 if (match(Op1, m_AllOnes()))
1029 return BinaryOperator::CreateNeg(Op0);
1031 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1032 // sdiv X, C --> ashr exact X, log2(C)
1033 if (I.isExact() && RHS->getValue().isNonNegative() &&
1034 RHS->getValue().isPowerOf2()) {
1035 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1036 RHS->getValue().exactLogBase2());
1037 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1041 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
1042 // X/INT_MIN -> X == INT_MIN
1043 if (RHS->isMinSignedValue())
1044 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1046 // -X/C --> X/-C provided the negation doesn't overflow.
1047 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
1048 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
1049 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
1050 ConstantExpr::getNeg(RHS));
1053 // If the sign bits of both operands are zero (i.e. we can prove they are
1054 // unsigned inputs), turn this into a udiv.
1055 if (I.getType()->isIntegerTy()) {
1056 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1057 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1058 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
1059 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1060 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1063 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
1064 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1065 // Safe because the only negative value (1 << Y) can take on is
1066 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1067 // the sign bit set.
1068 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1076 /// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1078 /// 1) 1/C is exact, or
1079 /// 2) reciprocal is allowed.
1080 /// If the conversion was successful, the simplified expression "X * 1/C" is
1081 /// returned; otherwise, NULL is returned.
1083 static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
1084 bool AllowReciprocal) {
1085 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
1088 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
1089 APFloat Reciprocal(FpVal.getSemantics());
1090 bool Cvt = FpVal.getExactInverse(&Reciprocal);
1092 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
1093 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1094 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1095 Cvt = !Reciprocal.isDenormal();
1102 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1103 return BinaryOperator::CreateFMul(Dividend, R);
1106 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1107 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1109 if (Value *V = SimplifyVectorOp(I))
1110 return ReplaceInstUsesWith(I, V);
1112 if (Value *V = SimplifyFDivInst(Op0, Op1, DL, TLI, DT, AT))
1113 return ReplaceInstUsesWith(I, V);
1115 if (isa<Constant>(Op0))
1116 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1117 if (Instruction *R = FoldOpIntoSelect(I, SI))
1120 bool AllowReassociate = I.hasUnsafeAlgebra();
1121 bool AllowReciprocal = I.hasAllowReciprocal();
1123 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1124 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1125 if (Instruction *R = FoldOpIntoSelect(I, SI))
1128 if (AllowReassociate) {
1129 Constant *C1 = nullptr;
1130 Constant *C2 = Op1C;
1132 Instruction *Res = nullptr;
1134 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
1135 // (X*C1)/C2 => X * (C1/C2)
1137 Constant *C = ConstantExpr::getFDiv(C1, C2);
1139 Res = BinaryOperator::CreateFMul(X, C);
1140 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
1141 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1143 Constant *C = ConstantExpr::getFMul(C1, C2);
1144 if (isNormalFp(C)) {
1145 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
1147 Res = BinaryOperator::CreateFDiv(X, C);
1152 Res->setFastMathFlags(I.getFastMathFlags());
1158 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1159 T->copyFastMathFlags(&I);
1166 if (AllowReassociate && isa<Constant>(Op0)) {
1167 Constant *C1 = cast<Constant>(Op0), *C2;
1168 Constant *Fold = nullptr;
1170 bool CreateDiv = true;
1172 // C1 / (X*C2) => (C1/C2) / X
1173 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
1174 Fold = ConstantExpr::getFDiv(C1, C2);
1175 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
1176 // C1 / (X/C2) => (C1*C2) / X
1177 Fold = ConstantExpr::getFMul(C1, C2);
1178 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
1179 // C1 / (C2/X) => (C1/C2) * X
1180 Fold = ConstantExpr::getFDiv(C1, C2);
1184 if (Fold && isNormalFp(Fold)) {
1185 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1186 : BinaryOperator::CreateFMul(X, Fold);
1187 R->setFastMathFlags(I.getFastMathFlags());
1193 if (AllowReassociate) {
1195 Value *NewInst = nullptr;
1196 Instruction *SimpR = nullptr;
1198 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1199 // (X/Y) / Z => X / (Y*Z)
1201 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
1202 NewInst = Builder->CreateFMul(Y, Op1);
1203 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1204 FastMathFlags Flags = I.getFastMathFlags();
1205 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1206 RI->setFastMathFlags(Flags);
1208 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1210 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1211 // Z / (X/Y) => Z*Y / X
1213 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
1214 NewInst = Builder->CreateFMul(Op0, Y);
1215 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1216 FastMathFlags Flags = I.getFastMathFlags();
1217 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1218 RI->setFastMathFlags(Flags);
1220 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1225 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1226 T->setDebugLoc(I.getDebugLoc());
1227 SimpR->setFastMathFlags(I.getFastMathFlags());
1235 /// This function implements the transforms common to both integer remainder
1236 /// instructions (urem and srem). It is called by the visitors to those integer
1237 /// remainder instructions.
1238 /// @brief Common integer remainder transforms
1239 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1240 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1242 // The RHS is known non-zero.
1243 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
1248 // Handle cases involving: rem X, (select Cond, Y, Z)
1249 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1252 if (isa<Constant>(Op1)) {
1253 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1254 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1255 if (Instruction *R = FoldOpIntoSelect(I, SI))
1257 } else if (isa<PHINode>(Op0I)) {
1258 if (Instruction *NV = FoldOpIntoPhi(I))
1262 // See if we can fold away this rem instruction.
1263 if (SimplifyDemandedInstructionBits(I))
1271 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1272 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1274 if (Value *V = SimplifyVectorOp(I))
1275 return ReplaceInstUsesWith(I, V);
1277 if (Value *V = SimplifyURemInst(Op0, Op1, DL, TLI, DT, AT))
1278 return ReplaceInstUsesWith(I, V);
1280 if (Instruction *common = commonIRemTransforms(I))
1283 // (zext A) urem (zext B) --> zext (A urem B)
1284 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1285 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1286 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1289 // X urem Y -> X and Y-1, where Y is a power of 2,
1290 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, AT, &I, DT)) {
1291 Constant *N1 = Constant::getAllOnesValue(I.getType());
1292 Value *Add = Builder->CreateAdd(Op1, N1);
1293 return BinaryOperator::CreateAnd(Op0, Add);
1296 // 1 urem X -> zext(X != 1)
1297 if (match(Op0, m_One())) {
1298 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1299 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1300 return ReplaceInstUsesWith(I, Ext);
1306 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1307 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1309 if (Value *V = SimplifyVectorOp(I))
1310 return ReplaceInstUsesWith(I, V);
1312 if (Value *V = SimplifySRemInst(Op0, Op1, DL, TLI, DT, AT))
1313 return ReplaceInstUsesWith(I, V);
1315 // Handle the integer rem common cases
1316 if (Instruction *Common = commonIRemTransforms(I))
1322 if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
1323 Worklist.AddValue(I.getOperand(1));
1324 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
1329 // If the sign bits of both operands are zero (i.e. we can prove they are
1330 // unsigned inputs), turn this into a urem.
1331 if (I.getType()->isIntegerTy()) {
1332 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1333 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1334 MaskedValueIsZero(Op0, Mask, 0, &I)) {
1335 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1336 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1340 // If it's a constant vector, flip any negative values positive.
1341 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1342 Constant *C = cast<Constant>(Op1);
1343 unsigned VWidth = C->getType()->getVectorNumElements();
1345 bool hasNegative = false;
1346 bool hasMissing = false;
1347 for (unsigned i = 0; i != VWidth; ++i) {
1348 Constant *Elt = C->getAggregateElement(i);
1354 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
1355 if (RHS->isNegative())
1359 if (hasNegative && !hasMissing) {
1360 SmallVector<Constant *, 16> Elts(VWidth);
1361 for (unsigned i = 0; i != VWidth; ++i) {
1362 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
1363 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
1364 if (RHS->isNegative())
1365 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
1369 Constant *NewRHSV = ConstantVector::get(Elts);
1370 if (NewRHSV != C) { // Don't loop on -MININT
1371 Worklist.AddValue(I.getOperand(1));
1372 I.setOperand(1, NewRHSV);
1381 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
1382 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1384 if (Value *V = SimplifyVectorOp(I))
1385 return ReplaceInstUsesWith(I, V);
1387 if (Value *V = SimplifyFRemInst(Op0, Op1, DL, TLI, DT, AT))
1388 return ReplaceInstUsesWith(I, V);
1390 // Handle cases involving: rem X, (select Cond, Y, Z)
1391 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))