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 A helper routine of InstCombiner::visitMul().
102 /// If C is a vector of known powers of 2, then this function returns
103 /// a new vector obtained from C replacing each element with its logBase2.
104 /// Return a null pointer otherwise.
105 static Constant *getLogBase2Vector(ConstantDataVector *CV) {
107 SmallVector<Constant *, 4> Elts;
109 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
110 Constant *Elt = CV->getElementAsConstant(I);
111 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
113 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
116 return ConstantVector::get(Elts);
119 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
120 bool Changed = SimplifyAssociativeOrCommutative(I);
121 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
123 if (Value *V = SimplifyVectorOp(I))
124 return ReplaceInstUsesWith(I, V);
126 if (Value *V = SimplifyMulInst(Op0, Op1, DL))
127 return ReplaceInstUsesWith(I, V);
129 if (Value *V = SimplifyUsingDistributiveLaws(I))
130 return ReplaceInstUsesWith(I, V);
132 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X
133 return BinaryOperator::CreateNeg(Op0, I.getName());
135 // Also allow combining multiply instructions on vectors.
140 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
142 match(C1, m_APInt(IVal)))
143 // ((X << C1)*C2) == (X * (C2 << C1))
144 return BinaryOperator::CreateMul(NewOp, ConstantExpr::getShl(C1, C2));
146 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
147 Constant *NewCst = nullptr;
148 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
149 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
150 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
151 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
152 // Replace X*(2^C) with X << C, where C is a vector of known
153 // constant powers of 2.
154 NewCst = getLogBase2Vector(CV);
157 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
158 if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap();
159 if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap();
165 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
166 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
167 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
168 // The "* (2**n)" thus becomes a potential shifting opportunity.
170 const APInt & Val = CI->getValue();
171 const APInt &PosVal = Val.abs();
172 if (Val.isNegative() && PosVal.isPowerOf2()) {
173 Value *X = nullptr, *Y = nullptr;
174 if (Op0->hasOneUse()) {
176 Value *Sub = nullptr;
177 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
178 Sub = Builder->CreateSub(X, Y, "suba");
179 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
180 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
183 BinaryOperator::CreateMul(Sub,
184 ConstantInt::get(Y->getType(), PosVal));
190 // Simplify mul instructions with a constant RHS.
191 if (isa<Constant>(Op1)) {
192 // Try to fold constant mul into select arguments.
193 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
194 if (Instruction *R = FoldOpIntoSelect(I, SI))
197 if (isa<PHINode>(Op0))
198 if (Instruction *NV = FoldOpIntoPhi(I))
201 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
205 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
206 Value *Mul = Builder->CreateMul(C1, Op1);
207 // Only go forward with the transform if C1*CI simplifies to a tidier
209 if (!match(Mul, m_Mul(m_Value(), m_Value())))
210 return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
215 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
216 if (Value *Op1v = dyn_castNegVal(Op1))
217 return BinaryOperator::CreateMul(Op0v, Op1v);
219 // (X / Y) * Y = X - (X % Y)
220 // (X / Y) * -Y = (X % Y) - X
223 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
225 (BO->getOpcode() != Instruction::UDiv &&
226 BO->getOpcode() != Instruction::SDiv)) {
228 BO = dyn_cast<BinaryOperator>(Op1);
230 Value *Neg = dyn_castNegVal(Op1C);
231 if (BO && BO->hasOneUse() &&
232 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
233 (BO->getOpcode() == Instruction::UDiv ||
234 BO->getOpcode() == Instruction::SDiv)) {
235 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
237 // If the division is exact, X % Y is zero, so we end up with X or -X.
238 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
239 if (SDiv->isExact()) {
241 return ReplaceInstUsesWith(I, Op0BO);
242 return BinaryOperator::CreateNeg(Op0BO);
246 if (BO->getOpcode() == Instruction::UDiv)
247 Rem = Builder->CreateURem(Op0BO, Op1BO);
249 Rem = Builder->CreateSRem(Op0BO, Op1BO);
253 return BinaryOperator::CreateSub(Op0BO, Rem);
254 return BinaryOperator::CreateSub(Rem, Op0BO);
258 /// i1 mul -> i1 and.
259 if (I.getType()->getScalarType()->isIntegerTy(1))
260 return BinaryOperator::CreateAnd(Op0, Op1);
262 // X*(1 << Y) --> X << Y
263 // (1 << Y)*X --> X << Y
266 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
267 return BinaryOperator::CreateShl(Op1, Y);
268 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
269 return BinaryOperator::CreateShl(Op0, Y);
272 // If one of the operands of the multiply is a cast from a boolean value, then
273 // we know the bool is either zero or one, so this is a 'masking' multiply.
274 // X * Y (where Y is 0 or 1) -> X & (0-Y)
275 if (!I.getType()->isVectorTy()) {
276 // -2 is "-1 << 1" so it is all bits set except the low one.
277 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
279 Value *BoolCast = nullptr, *OtherOp = nullptr;
280 if (MaskedValueIsZero(Op0, Negative2))
281 BoolCast = Op0, OtherOp = Op1;
282 else if (MaskedValueIsZero(Op1, Negative2))
283 BoolCast = Op1, OtherOp = Op0;
286 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
288 return BinaryOperator::CreateAnd(V, OtherOp);
292 return Changed ? &I : nullptr;
300 // And check for corresponding fast math flags
303 static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
305 if (!Op->hasOneUse())
308 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
311 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
315 Value *OpLog2Of = II->getArgOperand(0);
316 if (!OpLog2Of->hasOneUse())
319 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
322 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
325 if (match(I->getOperand(0), m_SpecificFP(0.5)))
326 Y = I->getOperand(1);
327 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
328 Y = I->getOperand(0);
331 static bool isFiniteNonZeroFp(Constant *C) {
332 if (C->getType()->isVectorTy()) {
333 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
335 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
336 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
342 return isa<ConstantFP>(C) &&
343 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
346 static bool isNormalFp(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().isNormal())
357 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
360 /// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
361 /// true iff the given value is FMul or FDiv with one and only one operand
362 /// being a normal constant (i.e. not Zero/NaN/Infinity).
363 static bool isFMulOrFDivWithConstant(Value *V) {
364 Instruction *I = dyn_cast<Instruction>(V);
365 if (!I || (I->getOpcode() != Instruction::FMul &&
366 I->getOpcode() != Instruction::FDiv))
369 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
370 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
375 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
378 /// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
379 /// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
380 /// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
381 /// This function is to simplify "FMulOrDiv * C" and returns the
382 /// resulting expression. Note that this function could return NULL in
383 /// case the constants cannot be folded into a normal floating-point.
385 Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
386 Instruction *InsertBefore) {
387 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
389 Value *Opnd0 = FMulOrDiv->getOperand(0);
390 Value *Opnd1 = FMulOrDiv->getOperand(1);
392 Constant *C0 = dyn_cast<Constant>(Opnd0);
393 Constant *C1 = dyn_cast<Constant>(Opnd1);
395 BinaryOperator *R = nullptr;
397 // (X * C0) * C => X * (C0*C)
398 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
399 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
401 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
404 // (C0 / X) * C => (C0 * C) / X
405 if (FMulOrDiv->hasOneUse()) {
406 // It would otherwise introduce another div.
407 Constant *F = ConstantExpr::getFMul(C0, C);
409 R = BinaryOperator::CreateFDiv(F, Opnd1);
412 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
413 Constant *F = ConstantExpr::getFDiv(C, C1);
415 R = BinaryOperator::CreateFMul(Opnd0, F);
417 // (X / C1) * C => X / (C1/C)
418 Constant *F = ConstantExpr::getFDiv(C1, C);
420 R = BinaryOperator::CreateFDiv(Opnd0, F);
426 R->setHasUnsafeAlgebra(true);
427 InsertNewInstWith(R, *InsertBefore);
433 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
434 bool Changed = SimplifyAssociativeOrCommutative(I);
435 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
437 if (Value *V = SimplifyVectorOp(I))
438 return ReplaceInstUsesWith(I, V);
440 if (isa<Constant>(Op0))
443 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL))
444 return ReplaceInstUsesWith(I, V);
446 bool AllowReassociate = I.hasUnsafeAlgebra();
448 // Simplify mul instructions with a constant RHS.
449 if (isa<Constant>(Op1)) {
450 // Try to fold constant mul into select arguments.
451 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
452 if (Instruction *R = FoldOpIntoSelect(I, SI))
455 if (isa<PHINode>(Op0))
456 if (Instruction *NV = FoldOpIntoPhi(I))
459 // (fmul X, -1.0) --> (fsub -0.0, X)
460 if (match(Op1, m_SpecificFP(-1.0))) {
461 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
462 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
463 RI->copyFastMathFlags(&I);
467 Constant *C = cast<Constant>(Op1);
468 if (AllowReassociate && isFiniteNonZeroFp(C)) {
469 // Let MDC denote an expression in one of these forms:
470 // X * C, C/X, X/C, where C is a constant.
472 // Try to simplify "MDC * Constant"
473 if (isFMulOrFDivWithConstant(Op0))
474 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
475 return ReplaceInstUsesWith(I, V);
477 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
478 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
480 (FAddSub->getOpcode() == Instruction::FAdd ||
481 FAddSub->getOpcode() == Instruction::FSub)) {
482 Value *Opnd0 = FAddSub->getOperand(0);
483 Value *Opnd1 = FAddSub->getOperand(1);
484 Constant *C0 = dyn_cast<Constant>(Opnd0);
485 Constant *C1 = dyn_cast<Constant>(Opnd1);
489 std::swap(Opnd0, Opnd1);
493 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
494 Value *M1 = ConstantExpr::getFMul(C1, C);
495 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
496 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
499 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
502 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
503 ? BinaryOperator::CreateFAdd(M0, M1)
504 : BinaryOperator::CreateFSub(M0, M1);
505 RI->copyFastMathFlags(&I);
514 // Under unsafe algebra do:
515 // X * log2(0.5*Y) = X*log2(Y) - X
516 if (I.hasUnsafeAlgebra()) {
517 Value *OpX = nullptr;
518 Value *OpY = nullptr;
520 detectLog2OfHalf(Op0, OpY, Log2);
524 detectLog2OfHalf(Op1, OpY, Log2);
529 // if pattern detected emit alternate sequence
531 BuilderTy::FastMathFlagGuard Guard(*Builder);
532 Builder->SetFastMathFlags(Log2->getFastMathFlags());
533 Log2->setArgOperand(0, OpY);
534 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
535 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
537 return ReplaceInstUsesWith(I, FSub);
541 // Handle symmetric situation in a 2-iteration loop
544 for (int i = 0; i < 2; i++) {
545 bool IgnoreZeroSign = I.hasNoSignedZeros();
546 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
547 BuilderTy::FastMathFlagGuard Guard(*Builder);
548 Builder->SetFastMathFlags(I.getFastMathFlags());
550 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
551 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
555 Value *FMul = Builder->CreateFMul(N0, N1);
557 return ReplaceInstUsesWith(I, FMul);
560 if (Opnd0->hasOneUse()) {
561 // -X * Y => -(X*Y) (Promote negation as high as possible)
562 Value *T = Builder->CreateFMul(N0, Opnd1);
563 Value *Neg = Builder->CreateFNeg(T);
565 return ReplaceInstUsesWith(I, Neg);
569 // (X*Y) * X => (X*X) * Y where Y != X
570 // The purpose is two-fold:
571 // 1) to form a power expression (of X).
572 // 2) potentially shorten the critical path: After transformation, the
573 // latency of the instruction Y is amortized by the expression of X*X,
574 // and therefore Y is in a "less critical" position compared to what it
575 // was before the transformation.
577 if (AllowReassociate) {
578 Value *Opnd0_0, *Opnd0_1;
579 if (Opnd0->hasOneUse() &&
580 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
582 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
584 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
588 BuilderTy::FastMathFlagGuard Guard(*Builder);
589 Builder->SetFastMathFlags(I.getFastMathFlags());
590 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
592 Value *R = Builder->CreateFMul(T, Y);
594 return ReplaceInstUsesWith(I, R);
599 // B * (uitofp i1 C) -> select C, B, 0
600 if (I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) {
601 Value *LHS = Op0, *RHS = Op1;
603 if (!match(RHS, m_UIToFP(m_Value(C))))
606 if (match(RHS, m_UIToFP(m_Value(C))) &&
607 C->getType()->getScalarType()->isIntegerTy(1)) {
609 Value *Zero = ConstantFP::getNegativeZero(B->getType());
610 return SelectInst::Create(C, B, Zero);
614 // A * (1 - uitofp i1 C) -> select C, 0, A
615 if (I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) {
616 Value *LHS = Op0, *RHS = Op1;
618 if (!match(RHS, m_FSub(m_FPOne(), m_UIToFP(m_Value(C)))))
621 if (match(RHS, m_FSub(m_FPOne(), m_UIToFP(m_Value(C)))) &&
622 C->getType()->getScalarType()->isIntegerTy(1)) {
624 Value *Zero = ConstantFP::getNegativeZero(A->getType());
625 return SelectInst::Create(C, Zero, A);
629 if (!isa<Constant>(Op1))
630 std::swap(Opnd0, Opnd1);
635 return Changed ? &I : nullptr;
638 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
640 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
641 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
643 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
644 int NonNullOperand = -1;
645 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
646 if (ST->isNullValue())
648 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
649 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
650 if (ST->isNullValue())
653 if (NonNullOperand == -1)
656 Value *SelectCond = SI->getOperand(0);
658 // Change the div/rem to use 'Y' instead of the select.
659 I.setOperand(1, SI->getOperand(NonNullOperand));
661 // Okay, we know we replace the operand of the div/rem with 'Y' with no
662 // problem. However, the select, or the condition of the select may have
663 // multiple uses. Based on our knowledge that the operand must be non-zero,
664 // propagate the known value for the select into other uses of it, and
665 // propagate a known value of the condition into its other users.
667 // If the select and condition only have a single use, don't bother with this,
669 if (SI->use_empty() && SelectCond->hasOneUse())
672 // Scan the current block backward, looking for other uses of SI.
673 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
675 while (BBI != BBFront) {
677 // If we found a call to a function, we can't assume it will return, so
678 // information from below it cannot be propagated above it.
679 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
682 // Replace uses of the select or its condition with the known values.
683 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
686 *I = SI->getOperand(NonNullOperand);
688 } else if (*I == SelectCond) {
689 *I = Builder->getInt1(NonNullOperand == 1);
694 // If we past the instruction, quit looking for it.
697 if (&*BBI == SelectCond)
698 SelectCond = nullptr;
700 // If we ran out of things to eliminate, break out of the loop.
701 if (!SelectCond && !SI)
709 /// This function implements the transforms common to both integer division
710 /// instructions (udiv and sdiv). It is called by the visitors to those integer
711 /// division instructions.
712 /// @brief Common integer divide transforms
713 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
714 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
716 // The RHS is known non-zero.
717 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
722 // Handle cases involving: [su]div X, (select Cond, Y, Z)
723 // This does not apply for fdiv.
724 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
727 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
728 // (X / C1) / C2 -> X / (C1*C2)
729 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
730 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
731 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
732 if (MultiplyOverflows(RHS, LHSRHS,
733 I.getOpcode() == Instruction::SDiv))
734 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
735 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
736 ConstantExpr::getMul(RHS, LHSRHS));
739 if (!RHS->isZero()) { // avoid X udiv 0
740 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
741 if (Instruction *R = FoldOpIntoSelect(I, SI))
743 if (isa<PHINode>(Op0))
744 if (Instruction *NV = FoldOpIntoPhi(I))
749 if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
750 if (One->isOne() && !I.getType()->isIntegerTy(1)) {
751 bool isSigned = I.getOpcode() == Instruction::SDiv;
753 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
754 // result is one, if Op1 is -1 then the result is minus one, otherwise
756 Value *Inc = Builder->CreateAdd(Op1, One);
757 Value *Cmp = Builder->CreateICmpULT(
758 Inc, ConstantInt::get(I.getType(), 3));
759 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
761 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
762 // result is one, otherwise it's zero.
763 return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
768 // See if we can fold away this div instruction.
769 if (SimplifyDemandedInstructionBits(I))
772 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
773 Value *X = nullptr, *Z = nullptr;
774 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
775 bool isSigned = I.getOpcode() == Instruction::SDiv;
776 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
777 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
778 return BinaryOperator::Create(I.getOpcode(), X, Op1);
784 /// dyn_castZExtVal - Checks if V is a zext or constant that can
785 /// be truncated to Ty without losing bits.
786 static Value *dyn_castZExtVal(Value *V, Type *Ty) {
787 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
788 if (Z->getSrcTy() == Ty)
789 return Z->getOperand(0);
790 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
791 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
792 return ConstantExpr::getTrunc(C, Ty);
798 const unsigned MaxDepth = 6;
799 typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
800 const BinaryOperator &I,
803 /// \brief Used to maintain state for visitUDivOperand().
804 struct UDivFoldAction {
805 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
806 ///< operand. This can be zero if this action
807 ///< joins two actions together.
809 Value *OperandToFold; ///< Which operand to fold.
811 Instruction *FoldResult; ///< The instruction returned when FoldAction is
814 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
815 ///< joins two actions together.
818 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
819 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
820 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
821 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
825 // X udiv 2^C -> X >> C
826 static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
827 const BinaryOperator &I, InstCombiner &IC) {
828 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
829 BinaryOperator *LShr = BinaryOperator::CreateLShr(
830 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
831 if (I.isExact()) LShr->setIsExact();
835 // X udiv C, where C >= signbit
836 static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
837 const BinaryOperator &I, InstCombiner &IC) {
838 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
840 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
841 ConstantInt::get(I.getType(), 1));
844 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
845 static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
847 Instruction *ShiftLeft = cast<Instruction>(Op1);
848 if (isa<ZExtInst>(ShiftLeft))
849 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
852 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
853 Value *N = ShiftLeft->getOperand(1);
855 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
856 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
857 N = IC.Builder->CreateZExt(N, Z->getDestTy());
858 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
859 if (I.isExact()) LShr->setIsExact();
863 // \brief Recursively visits the possible right hand operands of a udiv
864 // instruction, seeing through select instructions, to determine if we can
865 // replace the udiv with something simpler. If we find that an operand is not
866 // able to simplify the udiv, we abort the entire transformation.
867 static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
868 SmallVectorImpl<UDivFoldAction> &Actions,
869 unsigned Depth = 0) {
870 // Check to see if this is an unsigned division with an exact power of 2,
871 // if so, convert to a right shift.
872 if (match(Op1, m_Power2())) {
873 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
874 return Actions.size();
877 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
878 // X udiv C, where C >= signbit
879 if (C->getValue().isNegative()) {
880 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
881 return Actions.size();
884 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
885 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
886 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
887 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
888 return Actions.size();
891 // The remaining tests are all recursive, so bail out if we hit the limit.
892 if (Depth++ == MaxDepth)
895 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
896 if (size_t LHSIdx = visitUDivOperand(Op0, SI->getOperand(1), I, Actions))
897 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions)) {
898 Actions.push_back(UDivFoldAction((FoldUDivOperandCb)nullptr, Op1,
900 return Actions.size();
906 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
907 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
909 if (Value *V = SimplifyVectorOp(I))
910 return ReplaceInstUsesWith(I, V);
912 if (Value *V = SimplifyUDivInst(Op0, Op1, DL))
913 return ReplaceInstUsesWith(I, V);
915 // Handle the integer div common cases
916 if (Instruction *Common = commonIDivTransforms(I))
919 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
920 if (Constant *C2 = dyn_cast<Constant>(Op1)) {
923 if (match(Op0, m_LShr(m_Value(X), m_Constant(C1))))
924 return BinaryOperator::CreateUDiv(X, ConstantExpr::getShl(C2, C1));
927 // (zext A) udiv (zext B) --> zext (A udiv B)
928 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
929 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
930 return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
934 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
935 SmallVector<UDivFoldAction, 6> UDivActions;
936 if (visitUDivOperand(Op0, Op1, I, UDivActions))
937 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
938 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
939 Value *ActionOp1 = UDivActions[i].OperandToFold;
942 Inst = Action(Op0, ActionOp1, I, *this);
944 // This action joins two actions together. The RHS of this action is
945 // simply the last action we processed, we saved the LHS action index in
946 // the joining action.
947 size_t SelectRHSIdx = i - 1;
948 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
949 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
950 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
951 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
952 SelectLHS, SelectRHS);
955 // If this is the last action to process, return it to the InstCombiner.
956 // Otherwise, we insert it before the UDiv and record it so that we may
957 // use it as part of a joining action (i.e., a SelectInst).
959 Inst->insertBefore(&I);
960 UDivActions[i].FoldResult = Inst;
968 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
969 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
971 if (Value *V = SimplifyVectorOp(I))
972 return ReplaceInstUsesWith(I, V);
974 if (Value *V = SimplifySDivInst(Op0, Op1, DL))
975 return ReplaceInstUsesWith(I, V);
977 // Handle the integer div common cases
978 if (Instruction *Common = commonIDivTransforms(I))
982 if (match(Op1, m_AllOnes()))
983 return BinaryOperator::CreateNeg(Op0);
985 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
986 // sdiv X, C --> ashr exact X, log2(C)
987 if (I.isExact() && RHS->getValue().isNonNegative() &&
988 RHS->getValue().isPowerOf2()) {
989 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
990 RHS->getValue().exactLogBase2());
991 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
995 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
996 // X/INT_MIN -> X == INT_MIN
997 if (RHS->isMinSignedValue())
998 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1000 // -X/C --> X/-C provided the negation doesn't overflow.
1001 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
1002 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
1003 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
1004 ConstantExpr::getNeg(RHS));
1007 // If the sign bits of both operands are zero (i.e. we can prove they are
1008 // unsigned inputs), turn this into a udiv.
1009 if (I.getType()->isIntegerTy()) {
1010 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1011 if (MaskedValueIsZero(Op0, Mask)) {
1012 if (MaskedValueIsZero(Op1, Mask)) {
1013 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1014 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1017 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
1018 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1019 // Safe because the only negative value (1 << Y) can take on is
1020 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1021 // the sign bit set.
1022 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1030 /// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1032 /// 1) 1/C is exact, or
1033 /// 2) reciprocal is allowed.
1034 /// If the conversion was successful, the simplified expression "X * 1/C" is
1035 /// returned; otherwise, NULL is returned.
1037 static Instruction *CvtFDivConstToReciprocal(Value *Dividend,
1039 bool AllowReciprocal) {
1040 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
1043 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
1044 APFloat Reciprocal(FpVal.getSemantics());
1045 bool Cvt = FpVal.getExactInverse(&Reciprocal);
1047 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
1048 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1049 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1050 Cvt = !Reciprocal.isDenormal();
1057 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1058 return BinaryOperator::CreateFMul(Dividend, R);
1061 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1062 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1064 if (Value *V = SimplifyVectorOp(I))
1065 return ReplaceInstUsesWith(I, V);
1067 if (Value *V = SimplifyFDivInst(Op0, Op1, DL))
1068 return ReplaceInstUsesWith(I, V);
1070 if (isa<Constant>(Op0))
1071 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1072 if (Instruction *R = FoldOpIntoSelect(I, SI))
1075 bool AllowReassociate = I.hasUnsafeAlgebra();
1076 bool AllowReciprocal = I.hasAllowReciprocal();
1078 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1079 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1080 if (Instruction *R = FoldOpIntoSelect(I, SI))
1083 if (AllowReassociate) {
1084 Constant *C1 = nullptr;
1085 Constant *C2 = Op1C;
1087 Instruction *Res = nullptr;
1089 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
1090 // (X*C1)/C2 => X * (C1/C2)
1092 Constant *C = ConstantExpr::getFDiv(C1, C2);
1094 Res = BinaryOperator::CreateFMul(X, C);
1095 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
1096 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1098 Constant *C = ConstantExpr::getFMul(C1, C2);
1099 if (isNormalFp(C)) {
1100 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
1102 Res = BinaryOperator::CreateFDiv(X, C);
1107 Res->setFastMathFlags(I.getFastMathFlags());
1113 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1114 T->copyFastMathFlags(&I);
1121 if (AllowReassociate && isa<Constant>(Op0)) {
1122 Constant *C1 = cast<Constant>(Op0), *C2;
1123 Constant *Fold = nullptr;
1125 bool CreateDiv = true;
1127 // C1 / (X*C2) => (C1/C2) / X
1128 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
1129 Fold = ConstantExpr::getFDiv(C1, C2);
1130 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
1131 // C1 / (X/C2) => (C1*C2) / X
1132 Fold = ConstantExpr::getFMul(C1, C2);
1133 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
1134 // C1 / (C2/X) => (C1/C2) * X
1135 Fold = ConstantExpr::getFDiv(C1, C2);
1139 if (Fold && isNormalFp(Fold)) {
1140 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1141 : BinaryOperator::CreateFMul(X, Fold);
1142 R->setFastMathFlags(I.getFastMathFlags());
1148 if (AllowReassociate) {
1150 Value *NewInst = nullptr;
1151 Instruction *SimpR = nullptr;
1153 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1154 // (X/Y) / Z => X / (Y*Z)
1156 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
1157 NewInst = Builder->CreateFMul(Y, Op1);
1158 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1159 FastMathFlags Flags = I.getFastMathFlags();
1160 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1161 RI->setFastMathFlags(Flags);
1163 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1165 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1166 // Z / (X/Y) => Z*Y / X
1168 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
1169 NewInst = Builder->CreateFMul(Op0, Y);
1170 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1171 FastMathFlags Flags = I.getFastMathFlags();
1172 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1173 RI->setFastMathFlags(Flags);
1175 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1180 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1181 T->setDebugLoc(I.getDebugLoc());
1182 SimpR->setFastMathFlags(I.getFastMathFlags());
1190 /// This function implements the transforms common to both integer remainder
1191 /// instructions (urem and srem). It is called by the visitors to those integer
1192 /// remainder instructions.
1193 /// @brief Common integer remainder transforms
1194 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1195 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1197 // The RHS is known non-zero.
1198 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
1203 // Handle cases involving: rem X, (select Cond, Y, Z)
1204 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1207 if (isa<Constant>(Op1)) {
1208 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1209 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1210 if (Instruction *R = FoldOpIntoSelect(I, SI))
1212 } else if (isa<PHINode>(Op0I)) {
1213 if (Instruction *NV = FoldOpIntoPhi(I))
1217 // See if we can fold away this rem instruction.
1218 if (SimplifyDemandedInstructionBits(I))
1226 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1227 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1229 if (Value *V = SimplifyVectorOp(I))
1230 return ReplaceInstUsesWith(I, V);
1232 if (Value *V = SimplifyURemInst(Op0, Op1, DL))
1233 return ReplaceInstUsesWith(I, V);
1235 if (Instruction *common = commonIRemTransforms(I))
1238 // (zext A) urem (zext B) --> zext (A urem B)
1239 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1240 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1241 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1244 // X urem Y -> X and Y-1, where Y is a power of 2,
1245 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true)) {
1246 Constant *N1 = Constant::getAllOnesValue(I.getType());
1247 Value *Add = Builder->CreateAdd(Op1, N1);
1248 return BinaryOperator::CreateAnd(Op0, Add);
1251 // 1 urem X -> zext(X != 1)
1252 if (match(Op0, m_One())) {
1253 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1254 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1255 return ReplaceInstUsesWith(I, Ext);
1261 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1262 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1264 if (Value *V = SimplifyVectorOp(I))
1265 return ReplaceInstUsesWith(I, V);
1267 if (Value *V = SimplifySRemInst(Op0, Op1, DL))
1268 return ReplaceInstUsesWith(I, V);
1270 // Handle the integer rem common cases
1271 if (Instruction *Common = commonIRemTransforms(I))
1274 if (Value *RHSNeg = dyn_castNegVal(Op1))
1275 if (!isa<Constant>(RHSNeg) ||
1276 (isa<ConstantInt>(RHSNeg) &&
1277 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
1279 Worklist.AddValue(I.getOperand(1));
1280 I.setOperand(1, RHSNeg);
1284 // If the sign bits of both operands are zero (i.e. we can prove they are
1285 // unsigned inputs), turn this into a urem.
1286 if (I.getType()->isIntegerTy()) {
1287 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1288 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
1289 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1290 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1294 // If it's a constant vector, flip any negative values positive.
1295 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1296 Constant *C = cast<Constant>(Op1);
1297 unsigned VWidth = C->getType()->getVectorNumElements();
1299 bool hasNegative = false;
1300 bool hasMissing = false;
1301 for (unsigned i = 0; i != VWidth; ++i) {
1302 Constant *Elt = C->getAggregateElement(i);
1308 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
1309 if (RHS->isNegative())
1313 if (hasNegative && !hasMissing) {
1314 SmallVector<Constant *, 16> Elts(VWidth);
1315 for (unsigned i = 0; i != VWidth; ++i) {
1316 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
1317 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
1318 if (RHS->isNegative())
1319 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
1323 Constant *NewRHSV = ConstantVector::get(Elts);
1324 if (NewRHSV != C) { // Don't loop on -MININT
1325 Worklist.AddValue(I.getOperand(1));
1326 I.setOperand(1, NewRHSV);
1335 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
1336 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1338 if (Value *V = SimplifyVectorOp(I))
1339 return ReplaceInstUsesWith(I, V);
1341 if (Value *V = SimplifyFRemInst(Op0, Op1, DL))
1342 return ReplaceInstUsesWith(I, V);
1344 // Handle cases involving: rem X, (select Cond, Y, Z)
1345 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))