[SROA] Make the computation of adjusted pointers not leak GEP
[oota-llvm.git] / lib / Transforms / InstCombine / InstCombineMulDivRem.cpp
1 //===- InstCombineMulDivRem.cpp -------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the visit functions for mul, fmul, sdiv, udiv, fdiv,
11 // srem, urem, frem.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "InstCombine.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/IR/IntrinsicInst.h"
18 #include "llvm/IR/PatternMatch.h"
19 using namespace llvm;
20 using namespace PatternMatch;
21
22 #define DEBUG_TYPE "instcombine"
23
24
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                                         Instruction *CxtI) {
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
32   // code.
33   if (!V->hasOneUse()) return nullptr;
34
35   bool MadeChange = false;
36
37   // ((1 << A) >>u B) --> (1 << (A-B))
38   // Because V cannot be zero, we know that B is less than A.
39   Value *A = nullptr, *B = nullptr, *One = nullptr;
40   if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) &&
41       match(One, m_One())) {
42     A = IC.Builder->CreateSub(A, B);
43     return IC.Builder->CreateShl(One, A);
44   }
45
46   // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
47   // inexact.  Similarly for <<.
48   if (BinaryOperator *I = dyn_cast<BinaryOperator>(V))
49     if (I->isLogicalShift() && isKnownToBeAPowerOfTwo(I->getOperand(0), false,
50                                                       0, IC.getAssumptionTracker(),
51                                                       CxtI,
52                                                       IC.getDominatorTree())) {
53       // We know that this is an exact/nuw shift and that the input is a
54       // non-zero context as well.
55       if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
56         I->setOperand(0, V2);
57         MadeChange = true;
58       }
59
60       if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
61         I->setIsExact();
62         MadeChange = true;
63       }
64
65       if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
66         I->setHasNoUnsignedWrap();
67         MadeChange = true;
68       }
69     }
70
71   // TODO: Lots more we could do here:
72   //    If V is a phi node, we can call this on each of its operands.
73   //    "select cond, X, 0" can simplify to "X".
74
75   return MadeChange ? V : nullptr;
76 }
77
78
79 /// MultiplyOverflows - True if the multiply can not be expressed in an int
80 /// this size.
81 static bool MultiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
82                               bool IsSigned) {
83   bool Overflow;
84   if (IsSigned)
85     Product = C1.smul_ov(C2, Overflow);
86   else
87     Product = C1.umul_ov(C2, Overflow);
88
89   return Overflow;
90 }
91
92 /// \brief True if C2 is a multiple of C1. Quotient contains C2/C1.
93 static bool IsMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
94                        bool IsSigned) {
95   assert(C1.getBitWidth() == C2.getBitWidth() &&
96          "Inconsistent width of constants!");
97
98   APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
99   if (IsSigned)
100     APInt::sdivrem(C1, C2, Quotient, Remainder);
101   else
102     APInt::udivrem(C1, C2, Quotient, Remainder);
103
104   return Remainder.isMinValue();
105 }
106
107 /// \brief A helper routine of InstCombiner::visitMul().
108 ///
109 /// If C is a vector of known powers of 2, then this function returns
110 /// a new vector obtained from C replacing each element with its logBase2.
111 /// Return a null pointer otherwise.
112 static Constant *getLogBase2Vector(ConstantDataVector *CV) {
113   const APInt *IVal;
114   SmallVector<Constant *, 4> Elts;
115
116   for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
117     Constant *Elt = CV->getElementAsConstant(I);
118     if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
119       return nullptr;
120     Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
121   }
122
123   return ConstantVector::get(Elts);
124 }
125
126 /// \brief Return true if we can prove that:
127 ///    (mul LHS, RHS)  === (mul nsw LHS, RHS)
128 bool InstCombiner::WillNotOverflowSignedMul(Value *LHS, Value *RHS,
129                                             Instruction *CxtI) {
130   // Multiplying n * m significant bits yields a result of n + m significant
131   // bits. If the total number of significant bits does not exceed the
132   // result bit width (minus 1), there is no overflow.
133   // This means if we have enough leading sign bits in the operands
134   // we can guarantee that the result does not overflow.
135   // Ref: "Hacker's Delight" by Henry Warren
136   unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
137
138   // Note that underestimating the number of sign bits gives a more
139   // conservative answer.
140   unsigned SignBits = ComputeNumSignBits(LHS, 0, CxtI) +
141                       ComputeNumSignBits(RHS, 0, CxtI);
142
143   // First handle the easy case: if we have enough sign bits there's
144   // definitely no overflow.
145   if (SignBits > BitWidth + 1)
146     return true;
147
148   // There are two ambiguous cases where there can be no overflow:
149   //   SignBits == BitWidth + 1    and
150   //   SignBits == BitWidth
151   // The second case is difficult to check, therefore we only handle the
152   // first case.
153   if (SignBits == BitWidth + 1) {
154     // It overflows only when both arguments are negative and the true
155     // product is exactly the minimum negative number.
156     // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
157     // For simplicity we just check if at least one side is not negative.
158     bool LHSNonNegative, LHSNegative;
159     bool RHSNonNegative, RHSNegative;
160     ComputeSignBit(LHS, LHSNonNegative, LHSNegative, /*Depth=*/0, CxtI);
161     ComputeSignBit(RHS, RHSNonNegative, RHSNegative, /*Depth=*/0, CxtI);
162     if (LHSNonNegative || RHSNonNegative)
163       return true;
164   }
165   return false;
166 }
167
168 /// \brief Return true if we can prove that:
169 ///    (mul LHS, RHS)  === (mul nuw LHS, RHS)
170 bool InstCombiner::WillNotOverflowUnsignedMul(Value *LHS, Value *RHS,
171                                               Instruction *CxtI) {
172   // Multiplying n * m significant bits yields a result of n + m significant
173   // bits. If the total number of significant bits does not exceed the
174   // result bit width (minus 1), there is no overflow.
175   // This means if we have enough leading zero bits in the operands
176   // we can guarantee that the result does not overflow.
177   // Ref: "Hacker's Delight" by Henry Warren
178   unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
179   APInt LHSKnownZero(BitWidth, 0);
180   APInt RHSKnownZero(BitWidth, 0);
181   APInt TmpKnownOne(BitWidth, 0);
182   computeKnownBits(LHS, LHSKnownZero, TmpKnownOne, 0, CxtI);
183   computeKnownBits(RHS, RHSKnownZero, TmpKnownOne, 0, CxtI);
184   // Note that underestimating the number of zero bits gives a more
185   // conservative answer.
186   unsigned ZeroBits = LHSKnownZero.countLeadingOnes() +
187                       RHSKnownZero.countLeadingOnes();
188   // First handle the easy case: if we have enough zero bits there's
189   // definitely no overflow.
190   if (ZeroBits >= BitWidth)
191     return true;
192
193   // There is an ambiguous cases where there can be no overflow:
194   //   ZeroBits == BitWidth - 1
195   // However, determining overflow requires calculating the sign bit of
196   // LHS * RHS/2.
197
198   return false;
199 }
200
201 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
202   bool Changed = SimplifyAssociativeOrCommutative(I);
203   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
204
205   if (Value *V = SimplifyVectorOp(I))
206     return ReplaceInstUsesWith(I, V);
207
208   if (Value *V = SimplifyMulInst(Op0, Op1, DL, TLI, DT, AT))
209     return ReplaceInstUsesWith(I, V);
210
211   if (Value *V = SimplifyUsingDistributiveLaws(I))
212     return ReplaceInstUsesWith(I, V);
213
214   // X * -1 == 0 - X
215   if (match(Op1, m_AllOnes())) {
216     BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
217     if (I.hasNoSignedWrap())
218       BO->setHasNoSignedWrap();
219     return BO;
220   }
221
222   // Also allow combining multiply instructions on vectors.
223   {
224     Value *NewOp;
225     Constant *C1, *C2;
226     const APInt *IVal;
227     if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
228                         m_Constant(C1))) &&
229         match(C1, m_APInt(IVal))) {
230       // ((X << C2)*C1) == (X * (C1 << C2))
231       Constant *Shl = ConstantExpr::getShl(C1, C2);
232       BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
233       BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
234       if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
235         BO->setHasNoUnsignedWrap();
236       if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
237           Shl->isNotMinSignedValue())
238         BO->setHasNoSignedWrap();
239       return BO;
240     }
241
242     if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
243       Constant *NewCst = nullptr;
244       if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
245         // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
246         NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
247       else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
248         // Replace X*(2^C) with X << C, where C is a vector of known
249         // constant powers of 2.
250         NewCst = getLogBase2Vector(CV);
251
252       if (NewCst) {
253         BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
254
255         if (I.hasNoUnsignedWrap())
256           Shl->setHasNoUnsignedWrap();
257         if (I.hasNoSignedWrap() && NewCst->isNotMinSignedValue())
258           Shl->setHasNoSignedWrap();
259
260         return Shl;
261       }
262     }
263   }
264
265   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
266     // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
267     // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
268     // The "* (2**n)" thus becomes a potential shifting opportunity.
269     {
270       const APInt &   Val = CI->getValue();
271       const APInt &PosVal = Val.abs();
272       if (Val.isNegative() && PosVal.isPowerOf2()) {
273         Value *X = nullptr, *Y = nullptr;
274         if (Op0->hasOneUse()) {
275           ConstantInt *C1;
276           Value *Sub = nullptr;
277           if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
278             Sub = Builder->CreateSub(X, Y, "suba");
279           else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
280             Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
281           if (Sub)
282             return
283               BinaryOperator::CreateMul(Sub,
284                                         ConstantInt::get(Y->getType(), PosVal));
285         }
286       }
287     }
288   }
289
290   // Simplify mul instructions with a constant RHS.
291   if (isa<Constant>(Op1)) {
292     // Try to fold constant mul into select arguments.
293     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
294       if (Instruction *R = FoldOpIntoSelect(I, SI))
295         return R;
296
297     if (isa<PHINode>(Op0))
298       if (Instruction *NV = FoldOpIntoPhi(I))
299         return NV;
300
301     // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
302     {
303       Value *X;
304       Constant *C1;
305       if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
306         Value *Mul = Builder->CreateMul(C1, Op1);
307         // Only go forward with the transform if C1*CI simplifies to a tidier
308         // constant.
309         if (!match(Mul, m_Mul(m_Value(), m_Value())))
310           return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
311       }
312     }
313   }
314
315   if (Value *Op0v = dyn_castNegVal(Op0)) {   // -X * -Y = X*Y
316     if (Value *Op1v = dyn_castNegVal(Op1)) {
317       BinaryOperator *BO = BinaryOperator::CreateMul(Op0v, Op1v);
318       if (I.hasNoSignedWrap() &&
319           match(Op0, m_NSWSub(m_Value(), m_Value())) &&
320           match(Op1, m_NSWSub(m_Value(), m_Value())))
321         BO->setHasNoSignedWrap();
322       return BO;
323     }
324   }
325
326   // (X / Y) *  Y = X - (X % Y)
327   // (X / Y) * -Y = (X % Y) - X
328   {
329     Value *Op1C = Op1;
330     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
331     if (!BO ||
332         (BO->getOpcode() != Instruction::UDiv &&
333          BO->getOpcode() != Instruction::SDiv)) {
334       Op1C = Op0;
335       BO = dyn_cast<BinaryOperator>(Op1);
336     }
337     Value *Neg = dyn_castNegVal(Op1C);
338     if (BO && BO->hasOneUse() &&
339         (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
340         (BO->getOpcode() == Instruction::UDiv ||
341          BO->getOpcode() == Instruction::SDiv)) {
342       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
343
344       // If the division is exact, X % Y is zero, so we end up with X or -X.
345       if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
346         if (SDiv->isExact()) {
347           if (Op1BO == Op1C)
348             return ReplaceInstUsesWith(I, Op0BO);
349           return BinaryOperator::CreateNeg(Op0BO);
350         }
351
352       Value *Rem;
353       if (BO->getOpcode() == Instruction::UDiv)
354         Rem = Builder->CreateURem(Op0BO, Op1BO);
355       else
356         Rem = Builder->CreateSRem(Op0BO, Op1BO);
357       Rem->takeName(BO);
358
359       if (Op1BO == Op1C)
360         return BinaryOperator::CreateSub(Op0BO, Rem);
361       return BinaryOperator::CreateSub(Rem, Op0BO);
362     }
363   }
364
365   /// i1 mul -> i1 and.
366   if (I.getType()->getScalarType()->isIntegerTy(1))
367     return BinaryOperator::CreateAnd(Op0, Op1);
368
369   // X*(1 << Y) --> X << Y
370   // (1 << Y)*X --> X << Y
371   {
372     Value *Y;
373     BinaryOperator *BO = nullptr;
374     bool ShlNSW = false;
375     if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
376       BO = BinaryOperator::CreateShl(Op1, Y);
377       ShlNSW = cast<BinaryOperator>(Op0)->hasNoSignedWrap();
378     } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
379       BO = BinaryOperator::CreateShl(Op0, Y);
380       ShlNSW = cast<BinaryOperator>(Op1)->hasNoSignedWrap();
381     }
382     if (BO) {
383       if (I.hasNoUnsignedWrap())
384         BO->setHasNoUnsignedWrap();
385       if (I.hasNoSignedWrap() && ShlNSW)
386         BO->setHasNoSignedWrap();
387       return BO;
388     }
389   }
390
391   // If one of the operands of the multiply is a cast from a boolean value, then
392   // we know the bool is either zero or one, so this is a 'masking' multiply.
393   //   X * Y (where Y is 0 or 1) -> X & (0-Y)
394   if (!I.getType()->isVectorTy()) {
395     // -2 is "-1 << 1" so it is all bits set except the low one.
396     APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
397
398     Value *BoolCast = nullptr, *OtherOp = nullptr;
399     if (MaskedValueIsZero(Op0, Negative2, 0, &I))
400       BoolCast = Op0, OtherOp = Op1;
401     else if (MaskedValueIsZero(Op1, Negative2, 0, &I))
402       BoolCast = Op1, OtherOp = Op0;
403
404     if (BoolCast) {
405       Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
406                                     BoolCast);
407       return BinaryOperator::CreateAnd(V, OtherOp);
408     }
409   }
410
411   if (!I.hasNoSignedWrap() && WillNotOverflowSignedMul(Op0, Op1, &I)) {
412     Changed = true;
413     I.setHasNoSignedWrap(true);
414   }
415
416   if (!I.hasNoUnsignedWrap() && WillNotOverflowUnsignedMul(Op0, Op1, &I)) {
417     Changed = true;
418     I.setHasNoUnsignedWrap(true);
419   }
420
421   return Changed ? &I : nullptr;
422 }
423
424 /// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
425 static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
426   if (!Op->hasOneUse())
427     return;
428
429   IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
430   if (!II)
431     return;
432   if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
433     return;
434   Log2 = II;
435
436   Value *OpLog2Of = II->getArgOperand(0);
437   if (!OpLog2Of->hasOneUse())
438     return;
439
440   Instruction *I = dyn_cast<Instruction>(OpLog2Of);
441   if (!I)
442     return;
443   if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
444     return;
445
446   if (match(I->getOperand(0), m_SpecificFP(0.5)))
447     Y = I->getOperand(1);
448   else if (match(I->getOperand(1), m_SpecificFP(0.5)))
449     Y = I->getOperand(0);
450 }
451
452 static bool isFiniteNonZeroFp(Constant *C) {
453   if (C->getType()->isVectorTy()) {
454     for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
455          ++I) {
456       ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
457       if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
458         return false;
459     }
460     return true;
461   }
462
463   return isa<ConstantFP>(C) &&
464          cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
465 }
466
467 static bool isNormalFp(Constant *C) {
468   if (C->getType()->isVectorTy()) {
469     for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
470          ++I) {
471       ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
472       if (!CFP || !CFP->getValueAPF().isNormal())
473         return false;
474     }
475     return true;
476   }
477
478   return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
479 }
480
481 /// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
482 /// true iff the given value is FMul or FDiv with one and only one operand
483 /// being a normal constant (i.e. not Zero/NaN/Infinity).
484 static bool isFMulOrFDivWithConstant(Value *V) {
485   Instruction *I = dyn_cast<Instruction>(V);
486   if (!I || (I->getOpcode() != Instruction::FMul &&
487              I->getOpcode() != Instruction::FDiv))
488     return false;
489
490   Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
491   Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
492
493   if (C0 && C1)
494     return false;
495
496   return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
497 }
498
499 /// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
500 /// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
501 /// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
502 /// This function is to simplify "FMulOrDiv * C" and returns the
503 /// resulting expression. Note that this function could return NULL in
504 /// case the constants cannot be folded into a normal floating-point.
505 ///
506 Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
507                                    Instruction *InsertBefore) {
508   assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
509
510   Value *Opnd0 = FMulOrDiv->getOperand(0);
511   Value *Opnd1 = FMulOrDiv->getOperand(1);
512
513   Constant *C0 = dyn_cast<Constant>(Opnd0);
514   Constant *C1 = dyn_cast<Constant>(Opnd1);
515
516   BinaryOperator *R = nullptr;
517
518   // (X * C0) * C => X * (C0*C)
519   if (FMulOrDiv->getOpcode() == Instruction::FMul) {
520     Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
521     if (isNormalFp(F))
522       R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
523   } else {
524     if (C0) {
525       // (C0 / X) * C => (C0 * C) / X
526       if (FMulOrDiv->hasOneUse()) {
527         // It would otherwise introduce another div.
528         Constant *F = ConstantExpr::getFMul(C0, C);
529         if (isNormalFp(F))
530           R = BinaryOperator::CreateFDiv(F, Opnd1);
531       }
532     } else {
533       // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
534       Constant *F = ConstantExpr::getFDiv(C, C1);
535       if (isNormalFp(F)) {
536         R = BinaryOperator::CreateFMul(Opnd0, F);
537       } else {
538         // (X / C1) * C => X / (C1/C)
539         Constant *F = ConstantExpr::getFDiv(C1, C);
540         if (isNormalFp(F))
541           R = BinaryOperator::CreateFDiv(Opnd0, F);
542       }
543     }
544   }
545
546   if (R) {
547     R->setHasUnsafeAlgebra(true);
548     InsertNewInstWith(R, *InsertBefore);
549   }
550
551   return R;
552 }
553
554 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
555   bool Changed = SimplifyAssociativeOrCommutative(I);
556   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
557
558   if (Value *V = SimplifyVectorOp(I))
559     return ReplaceInstUsesWith(I, V);
560
561   if (isa<Constant>(Op0))
562     std::swap(Op0, Op1);
563
564   if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL, TLI,
565                                   DT, AT))
566     return ReplaceInstUsesWith(I, V);
567
568   bool AllowReassociate = I.hasUnsafeAlgebra();
569
570   // Simplify mul instructions with a constant RHS.
571   if (isa<Constant>(Op1)) {
572     // Try to fold constant mul into select arguments.
573     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
574       if (Instruction *R = FoldOpIntoSelect(I, SI))
575         return R;
576
577     if (isa<PHINode>(Op0))
578       if (Instruction *NV = FoldOpIntoPhi(I))
579         return NV;
580
581     // (fmul X, -1.0) --> (fsub -0.0, X)
582     if (match(Op1, m_SpecificFP(-1.0))) {
583       Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
584       Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
585       RI->copyFastMathFlags(&I);
586       return RI;
587     }
588
589     Constant *C = cast<Constant>(Op1);
590     if (AllowReassociate && isFiniteNonZeroFp(C)) {
591       // Let MDC denote an expression in one of these forms:
592       // X * C, C/X, X/C, where C is a constant.
593       //
594       // Try to simplify "MDC * Constant"
595       if (isFMulOrFDivWithConstant(Op0))
596         if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
597           return ReplaceInstUsesWith(I, V);
598
599       // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
600       Instruction *FAddSub = dyn_cast<Instruction>(Op0);
601       if (FAddSub &&
602           (FAddSub->getOpcode() == Instruction::FAdd ||
603            FAddSub->getOpcode() == Instruction::FSub)) {
604         Value *Opnd0 = FAddSub->getOperand(0);
605         Value *Opnd1 = FAddSub->getOperand(1);
606         Constant *C0 = dyn_cast<Constant>(Opnd0);
607         Constant *C1 = dyn_cast<Constant>(Opnd1);
608         bool Swap = false;
609         if (C0) {
610           std::swap(C0, C1);
611           std::swap(Opnd0, Opnd1);
612           Swap = true;
613         }
614
615         if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
616           Value *M1 = ConstantExpr::getFMul(C1, C);
617           Value *M0 = isNormalFp(cast<Constant>(M1)) ?
618                       foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
619                       nullptr;
620           if (M0 && M1) {
621             if (Swap && FAddSub->getOpcode() == Instruction::FSub)
622               std::swap(M0, M1);
623
624             Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
625                                   ? BinaryOperator::CreateFAdd(M0, M1)
626                                   : BinaryOperator::CreateFSub(M0, M1);
627             RI->copyFastMathFlags(&I);
628             return RI;
629           }
630         }
631       }
632     }
633   }
634
635   // sqrt(X) * sqrt(X) -> X
636   if (AllowReassociate && (Op0 == Op1))
637     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0))
638       if (II->getIntrinsicID() == Intrinsic::sqrt)
639         return ReplaceInstUsesWith(I, II->getOperand(0));
640
641   // Under unsafe algebra do:
642   // X * log2(0.5*Y) = X*log2(Y) - X
643   if (AllowReassociate) {
644     Value *OpX = nullptr;
645     Value *OpY = nullptr;
646     IntrinsicInst *Log2;
647     detectLog2OfHalf(Op0, OpY, Log2);
648     if (OpY) {
649       OpX = Op1;
650     } else {
651       detectLog2OfHalf(Op1, OpY, Log2);
652       if (OpY) {
653         OpX = Op0;
654       }
655     }
656     // if pattern detected emit alternate sequence
657     if (OpX && OpY) {
658       BuilderTy::FastMathFlagGuard Guard(*Builder);
659       Builder->SetFastMathFlags(Log2->getFastMathFlags());
660       Log2->setArgOperand(0, OpY);
661       Value *FMulVal = Builder->CreateFMul(OpX, Log2);
662       Value *FSub = Builder->CreateFSub(FMulVal, OpX);
663       FSub->takeName(&I);
664       return ReplaceInstUsesWith(I, FSub);
665     }
666   }
667
668   // Handle symmetric situation in a 2-iteration loop
669   Value *Opnd0 = Op0;
670   Value *Opnd1 = Op1;
671   for (int i = 0; i < 2; i++) {
672     bool IgnoreZeroSign = I.hasNoSignedZeros();
673     if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
674       BuilderTy::FastMathFlagGuard Guard(*Builder);
675       Builder->SetFastMathFlags(I.getFastMathFlags());
676
677       Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
678       Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
679
680       // -X * -Y => X*Y
681       if (N1) {
682         Value *FMul = Builder->CreateFMul(N0, N1);
683         FMul->takeName(&I);
684         return ReplaceInstUsesWith(I, FMul);
685       }
686
687       if (Opnd0->hasOneUse()) {
688         // -X * Y => -(X*Y) (Promote negation as high as possible)
689         Value *T = Builder->CreateFMul(N0, Opnd1);
690         Value *Neg = Builder->CreateFNeg(T);
691         Neg->takeName(&I);
692         return ReplaceInstUsesWith(I, Neg);
693       }
694     }
695
696     // (X*Y) * X => (X*X) * Y where Y != X
697     //  The purpose is two-fold:
698     //   1) to form a power expression (of X).
699     //   2) potentially shorten the critical path: After transformation, the
700     //  latency of the instruction Y is amortized by the expression of X*X,
701     //  and therefore Y is in a "less critical" position compared to what it
702     //  was before the transformation.
703     //
704     if (AllowReassociate) {
705       Value *Opnd0_0, *Opnd0_1;
706       if (Opnd0->hasOneUse() &&
707           match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
708         Value *Y = nullptr;
709         if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
710           Y = Opnd0_1;
711         else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
712           Y = Opnd0_0;
713
714         if (Y) {
715           BuilderTy::FastMathFlagGuard Guard(*Builder);
716           Builder->SetFastMathFlags(I.getFastMathFlags());
717           Value *T = Builder->CreateFMul(Opnd1, Opnd1);
718
719           Value *R = Builder->CreateFMul(T, Y);
720           R->takeName(&I);
721           return ReplaceInstUsesWith(I, R);
722         }
723       }
724     }
725
726     if (!isa<Constant>(Op1))
727       std::swap(Opnd0, Opnd1);
728     else
729       break;
730   }
731
732   return Changed ? &I : nullptr;
733 }
734
735 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
736 /// instruction.
737 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
738   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
739
740   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
741   int NonNullOperand = -1;
742   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
743     if (ST->isNullValue())
744       NonNullOperand = 2;
745   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
746   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
747     if (ST->isNullValue())
748       NonNullOperand = 1;
749
750   if (NonNullOperand == -1)
751     return false;
752
753   Value *SelectCond = SI->getOperand(0);
754
755   // Change the div/rem to use 'Y' instead of the select.
756   I.setOperand(1, SI->getOperand(NonNullOperand));
757
758   // Okay, we know we replace the operand of the div/rem with 'Y' with no
759   // problem.  However, the select, or the condition of the select may have
760   // multiple uses.  Based on our knowledge that the operand must be non-zero,
761   // propagate the known value for the select into other uses of it, and
762   // propagate a known value of the condition into its other users.
763
764   // If the select and condition only have a single use, don't bother with this,
765   // early exit.
766   if (SI->use_empty() && SelectCond->hasOneUse())
767     return true;
768
769   // Scan the current block backward, looking for other uses of SI.
770   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
771
772   while (BBI != BBFront) {
773     --BBI;
774     // If we found a call to a function, we can't assume it will return, so
775     // information from below it cannot be propagated above it.
776     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
777       break;
778
779     // Replace uses of the select or its condition with the known values.
780     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
781          I != E; ++I) {
782       if (*I == SI) {
783         *I = SI->getOperand(NonNullOperand);
784         Worklist.Add(BBI);
785       } else if (*I == SelectCond) {
786         *I = Builder->getInt1(NonNullOperand == 1);
787         Worklist.Add(BBI);
788       }
789     }
790
791     // If we past the instruction, quit looking for it.
792     if (&*BBI == SI)
793       SI = nullptr;
794     if (&*BBI == SelectCond)
795       SelectCond = nullptr;
796
797     // If we ran out of things to eliminate, break out of the loop.
798     if (!SelectCond && !SI)
799       break;
800
801   }
802   return true;
803 }
804
805
806 /// This function implements the transforms common to both integer division
807 /// instructions (udiv and sdiv). It is called by the visitors to those integer
808 /// division instructions.
809 /// @brief Common integer divide transforms
810 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
811   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
812
813   // The RHS is known non-zero.
814   if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
815     I.setOperand(1, V);
816     return &I;
817   }
818
819   // Handle cases involving: [su]div X, (select Cond, Y, Z)
820   // This does not apply for fdiv.
821   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
822     return &I;
823
824   if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
825     const APInt *C2;
826     if (match(Op1, m_APInt(C2))) {
827       Value *X;
828       const APInt *C1;
829       bool IsSigned = I.getOpcode() == Instruction::SDiv;
830
831       // (X / C1) / C2  -> X / (C1*C2)
832       if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
833           (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
834         APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
835         if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
836           return BinaryOperator::Create(I.getOpcode(), X,
837                                         ConstantInt::get(I.getType(), Product));
838       }
839
840       if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
841           (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
842         APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
843
844         // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
845         if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
846           BinaryOperator *BO = BinaryOperator::Create(
847               I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
848           BO->setIsExact(I.isExact());
849           return BO;
850         }
851
852         // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
853         if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
854           BinaryOperator *BO = BinaryOperator::Create(
855               Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
856           BO->setHasNoUnsignedWrap(
857               !IsSigned &&
858               cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
859           BO->setHasNoSignedWrap(
860               cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
861           return BO;
862         }
863       }
864
865       if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
866            *C1 != C1->getBitWidth() - 1) ||
867           (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
868         APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
869         APInt C1Shifted = APInt::getOneBitSet(
870             C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
871
872         // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
873         if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
874           BinaryOperator *BO = BinaryOperator::Create(
875               I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
876           BO->setIsExact(I.isExact());
877           return BO;
878         }
879
880         // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
881         if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
882           BinaryOperator *BO = BinaryOperator::Create(
883               Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
884           BO->setHasNoUnsignedWrap(
885               !IsSigned &&
886               cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
887           BO->setHasNoSignedWrap(
888               cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
889           return BO;
890         }
891       }
892
893       if (*C2 != 0) { // avoid X udiv 0
894         if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
895           if (Instruction *R = FoldOpIntoSelect(I, SI))
896             return R;
897         if (isa<PHINode>(Op0))
898           if (Instruction *NV = FoldOpIntoPhi(I))
899             return NV;
900       }
901     }
902   }
903
904   if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
905     if (One->isOne() && !I.getType()->isIntegerTy(1)) {
906       bool isSigned = I.getOpcode() == Instruction::SDiv;
907       if (isSigned) {
908         // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
909         // result is one, if Op1 is -1 then the result is minus one, otherwise
910         // it's zero.
911         Value *Inc = Builder->CreateAdd(Op1, One);
912         Value *Cmp = Builder->CreateICmpULT(
913                          Inc, ConstantInt::get(I.getType(), 3));
914         return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
915       } else {
916         // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
917         // result is one, otherwise it's zero.
918         return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
919       }
920     }
921   }
922
923   // See if we can fold away this div instruction.
924   if (SimplifyDemandedInstructionBits(I))
925     return &I;
926
927   // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
928   Value *X = nullptr, *Z = nullptr;
929   if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
930     bool isSigned = I.getOpcode() == Instruction::SDiv;
931     if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
932         (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
933       return BinaryOperator::Create(I.getOpcode(), X, Op1);
934   }
935
936   return nullptr;
937 }
938
939 /// dyn_castZExtVal - Checks if V is a zext or constant that can
940 /// be truncated to Ty without losing bits.
941 static Value *dyn_castZExtVal(Value *V, Type *Ty) {
942   if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
943     if (Z->getSrcTy() == Ty)
944       return Z->getOperand(0);
945   } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
946     if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
947       return ConstantExpr::getTrunc(C, Ty);
948   }
949   return nullptr;
950 }
951
952 namespace {
953 const unsigned MaxDepth = 6;
954 typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
955                                           const BinaryOperator &I,
956                                           InstCombiner &IC);
957
958 /// \brief Used to maintain state for visitUDivOperand().
959 struct UDivFoldAction {
960   FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
961                                 ///< operand.  This can be zero if this action
962                                 ///< joins two actions together.
963
964   Value *OperandToFold;         ///< Which operand to fold.
965   union {
966     Instruction *FoldResult;    ///< The instruction returned when FoldAction is
967                                 ///< invoked.
968
969     size_t SelectLHSIdx;        ///< Stores the LHS action index if this action
970                                 ///< joins two actions together.
971   };
972
973   UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
974       : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
975   UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
976       : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
977 };
978 }
979
980 // X udiv 2^C -> X >> C
981 static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
982                                     const BinaryOperator &I, InstCombiner &IC) {
983   const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
984   BinaryOperator *LShr = BinaryOperator::CreateLShr(
985       Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
986   if (I.isExact())
987     LShr->setIsExact();
988   return LShr;
989 }
990
991 // X udiv C, where C >= signbit
992 static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
993                                    const BinaryOperator &I, InstCombiner &IC) {
994   Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
995
996   return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
997                             ConstantInt::get(I.getType(), 1));
998 }
999
1000 // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
1001 static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
1002                                 InstCombiner &IC) {
1003   Instruction *ShiftLeft = cast<Instruction>(Op1);
1004   if (isa<ZExtInst>(ShiftLeft))
1005     ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
1006
1007   const APInt &CI =
1008       cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
1009   Value *N = ShiftLeft->getOperand(1);
1010   if (CI != 1)
1011     N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
1012   if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
1013     N = IC.Builder->CreateZExt(N, Z->getDestTy());
1014   BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
1015   if (I.isExact())
1016     LShr->setIsExact();
1017   return LShr;
1018 }
1019
1020 // \brief Recursively visits the possible right hand operands of a udiv
1021 // instruction, seeing through select instructions, to determine if we can
1022 // replace the udiv with something simpler.  If we find that an operand is not
1023 // able to simplify the udiv, we abort the entire transformation.
1024 static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
1025                                SmallVectorImpl<UDivFoldAction> &Actions,
1026                                unsigned Depth = 0) {
1027   // Check to see if this is an unsigned division with an exact power of 2,
1028   // if so, convert to a right shift.
1029   if (match(Op1, m_Power2())) {
1030     Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
1031     return Actions.size();
1032   }
1033
1034   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
1035     // X udiv C, where C >= signbit
1036     if (C->getValue().isNegative()) {
1037       Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
1038       return Actions.size();
1039     }
1040
1041   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
1042   if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
1043       match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
1044     Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
1045     return Actions.size();
1046   }
1047
1048   // The remaining tests are all recursive, so bail out if we hit the limit.
1049   if (Depth++ == MaxDepth)
1050     return 0;
1051
1052   if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1053     if (size_t LHSIdx =
1054             visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
1055       if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
1056         Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
1057         return Actions.size();
1058       }
1059
1060   return 0;
1061 }
1062
1063 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
1064   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1065
1066   if (Value *V = SimplifyVectorOp(I))
1067     return ReplaceInstUsesWith(I, V);
1068
1069   if (Value *V = SimplifyUDivInst(Op0, Op1, DL, TLI, DT, AT))
1070     return ReplaceInstUsesWith(I, V);
1071
1072   // Handle the integer div common cases
1073   if (Instruction *Common = commonIDivTransforms(I))
1074     return Common;
1075
1076   // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
1077   {
1078     Value *X;
1079     const APInt *C1, *C2;
1080     if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
1081         match(Op1, m_APInt(C2))) {
1082       bool Overflow;
1083       APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
1084       if (!Overflow) {
1085         bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1086         BinaryOperator *BO = BinaryOperator::CreateUDiv(
1087             X, ConstantInt::get(X->getType(), C2ShlC1));
1088         if (IsExact)
1089           BO->setIsExact();
1090         return BO;
1091       }
1092     }
1093   }
1094
1095   // (zext A) udiv (zext B) --> zext (A udiv B)
1096   if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1097     if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1098       return new ZExtInst(
1099           Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", I.isExact()),
1100           I.getType());
1101
1102   // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1103   SmallVector<UDivFoldAction, 6> UDivActions;
1104   if (visitUDivOperand(Op0, Op1, I, UDivActions))
1105     for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1106       FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1107       Value *ActionOp1 = UDivActions[i].OperandToFold;
1108       Instruction *Inst;
1109       if (Action)
1110         Inst = Action(Op0, ActionOp1, I, *this);
1111       else {
1112         // This action joins two actions together.  The RHS of this action is
1113         // simply the last action we processed, we saved the LHS action index in
1114         // the joining action.
1115         size_t SelectRHSIdx = i - 1;
1116         Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1117         size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1118         Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1119         Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1120                                   SelectLHS, SelectRHS);
1121       }
1122
1123       // If this is the last action to process, return it to the InstCombiner.
1124       // Otherwise, we insert it before the UDiv and record it so that we may
1125       // use it as part of a joining action (i.e., a SelectInst).
1126       if (e - i != 1) {
1127         Inst->insertBefore(&I);
1128         UDivActions[i].FoldResult = Inst;
1129       } else
1130         return Inst;
1131     }
1132
1133   return nullptr;
1134 }
1135
1136 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1137   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1138
1139   if (Value *V = SimplifyVectorOp(I))
1140     return ReplaceInstUsesWith(I, V);
1141
1142   if (Value *V = SimplifySDivInst(Op0, Op1, DL, TLI, DT, AT))
1143     return ReplaceInstUsesWith(I, V);
1144
1145   // Handle the integer div common cases
1146   if (Instruction *Common = commonIDivTransforms(I))
1147     return Common;
1148
1149   // sdiv X, -1 == -X
1150   if (match(Op1, m_AllOnes()))
1151     return BinaryOperator::CreateNeg(Op0);
1152
1153   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1154     // sdiv X, C  -->  ashr exact X, log2(C)
1155     if (I.isExact() && RHS->getValue().isNonNegative() &&
1156         RHS->getValue().isPowerOf2()) {
1157       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1158                                             RHS->getValue().exactLogBase2());
1159       return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1160     }
1161   }
1162
1163   if (Constant *RHS = dyn_cast<Constant>(Op1)) {
1164     // X/INT_MIN -> X == INT_MIN
1165     if (RHS->isMinSignedValue())
1166       return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1167
1168     // -X/C  -->  X/-C  provided the negation doesn't overflow.
1169     Value *X;
1170     if (match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1171       auto *BO = BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(RHS));
1172       BO->setIsExact(I.isExact());
1173       return BO;
1174     }
1175   }
1176
1177   // If the sign bits of both operands are zero (i.e. we can prove they are
1178   // unsigned inputs), turn this into a udiv.
1179   if (I.getType()->isIntegerTy()) {
1180     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1181     if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1182       if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
1183         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1184         auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1185         BO->setIsExact(I.isExact());
1186         return BO;
1187       }
1188
1189       if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, AT, &I, DT)) {
1190         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1191         // Safe because the only negative value (1 << Y) can take on is
1192         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1193         // the sign bit set.
1194         auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1195         BO->setIsExact(I.isExact());
1196         return BO;
1197       }
1198     }
1199   }
1200
1201   return nullptr;
1202 }
1203
1204 /// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1205 /// FP value and:
1206 ///    1) 1/C is exact, or
1207 ///    2) reciprocal is allowed.
1208 /// If the conversion was successful, the simplified expression "X * 1/C" is
1209 /// returned; otherwise, NULL is returned.
1210 ///
1211 static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
1212                                              bool AllowReciprocal) {
1213   if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
1214     return nullptr;
1215
1216   const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
1217   APFloat Reciprocal(FpVal.getSemantics());
1218   bool Cvt = FpVal.getExactInverse(&Reciprocal);
1219
1220   if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
1221     Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1222     (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1223     Cvt = !Reciprocal.isDenormal();
1224   }
1225
1226   if (!Cvt)
1227     return nullptr;
1228
1229   ConstantFP *R;
1230   R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1231   return BinaryOperator::CreateFMul(Dividend, R);
1232 }
1233
1234 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1235   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1236
1237   if (Value *V = SimplifyVectorOp(I))
1238     return ReplaceInstUsesWith(I, V);
1239
1240   if (Value *V = SimplifyFDivInst(Op0, Op1, DL, TLI, DT, AT))
1241     return ReplaceInstUsesWith(I, V);
1242
1243   if (isa<Constant>(Op0))
1244     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1245       if (Instruction *R = FoldOpIntoSelect(I, SI))
1246         return R;
1247
1248   bool AllowReassociate = I.hasUnsafeAlgebra();
1249   bool AllowReciprocal = I.hasAllowReciprocal();
1250
1251   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1252     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1253       if (Instruction *R = FoldOpIntoSelect(I, SI))
1254         return R;
1255
1256     if (AllowReassociate) {
1257       Constant *C1 = nullptr;
1258       Constant *C2 = Op1C;
1259       Value *X;
1260       Instruction *Res = nullptr;
1261
1262       if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
1263         // (X*C1)/C2 => X * (C1/C2)
1264         //
1265         Constant *C = ConstantExpr::getFDiv(C1, C2);
1266         if (isNormalFp(C))
1267           Res = BinaryOperator::CreateFMul(X, C);
1268       } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
1269         // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1270         //
1271         Constant *C = ConstantExpr::getFMul(C1, C2);
1272         if (isNormalFp(C)) {
1273           Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
1274           if (!Res)
1275             Res = BinaryOperator::CreateFDiv(X, C);
1276         }
1277       }
1278
1279       if (Res) {
1280         Res->setFastMathFlags(I.getFastMathFlags());
1281         return Res;
1282       }
1283     }
1284
1285     // X / C => X * 1/C
1286     if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1287       T->copyFastMathFlags(&I);
1288       return T;
1289     }
1290
1291     return nullptr;
1292   }
1293
1294   if (AllowReassociate && isa<Constant>(Op0)) {
1295     Constant *C1 = cast<Constant>(Op0), *C2;
1296     Constant *Fold = nullptr;
1297     Value *X;
1298     bool CreateDiv = true;
1299
1300     // C1 / (X*C2) => (C1/C2) / X
1301     if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
1302       Fold = ConstantExpr::getFDiv(C1, C2);
1303     else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
1304       // C1 / (X/C2) => (C1*C2) / X
1305       Fold = ConstantExpr::getFMul(C1, C2);
1306     } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
1307       // C1 / (C2/X) => (C1/C2) * X
1308       Fold = ConstantExpr::getFDiv(C1, C2);
1309       CreateDiv = false;
1310     }
1311
1312     if (Fold && isNormalFp(Fold)) {
1313       Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1314                                  : BinaryOperator::CreateFMul(X, Fold);
1315       R->setFastMathFlags(I.getFastMathFlags());
1316       return R;
1317     }
1318     return nullptr;
1319   }
1320
1321   if (AllowReassociate) {
1322     Value *X, *Y;
1323     Value *NewInst = nullptr;
1324     Instruction *SimpR = nullptr;
1325
1326     if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1327       // (X/Y) / Z => X / (Y*Z)
1328       //
1329       if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
1330         NewInst = Builder->CreateFMul(Y, Op1);
1331         if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1332           FastMathFlags Flags = I.getFastMathFlags();
1333           Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1334           RI->setFastMathFlags(Flags);
1335         }
1336         SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1337       }
1338     } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1339       // Z / (X/Y) => Z*Y / X
1340       //
1341       if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
1342         NewInst = Builder->CreateFMul(Op0, Y);
1343         if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1344           FastMathFlags Flags = I.getFastMathFlags();
1345           Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1346           RI->setFastMathFlags(Flags);
1347         }
1348         SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1349       }
1350     }
1351
1352     if (NewInst) {
1353       if (Instruction *T = dyn_cast<Instruction>(NewInst))
1354         T->setDebugLoc(I.getDebugLoc());
1355       SimpR->setFastMathFlags(I.getFastMathFlags());
1356       return SimpR;
1357     }
1358   }
1359
1360   return nullptr;
1361 }
1362
1363 /// This function implements the transforms common to both integer remainder
1364 /// instructions (urem and srem). It is called by the visitors to those integer
1365 /// remainder instructions.
1366 /// @brief Common integer remainder transforms
1367 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1368   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1369
1370   // The RHS is known non-zero.
1371   if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
1372     I.setOperand(1, V);
1373     return &I;
1374   }
1375
1376   // Handle cases involving: rem X, (select Cond, Y, Z)
1377   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1378     return &I;
1379
1380   if (isa<Constant>(Op1)) {
1381     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1382       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1383         if (Instruction *R = FoldOpIntoSelect(I, SI))
1384           return R;
1385       } else if (isa<PHINode>(Op0I)) {
1386         if (Instruction *NV = FoldOpIntoPhi(I))
1387           return NV;
1388       }
1389
1390       // See if we can fold away this rem instruction.
1391       if (SimplifyDemandedInstructionBits(I))
1392         return &I;
1393     }
1394   }
1395
1396   return nullptr;
1397 }
1398
1399 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1400   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1401
1402   if (Value *V = SimplifyVectorOp(I))
1403     return ReplaceInstUsesWith(I, V);
1404
1405   if (Value *V = SimplifyURemInst(Op0, Op1, DL, TLI, DT, AT))
1406     return ReplaceInstUsesWith(I, V);
1407
1408   if (Instruction *common = commonIRemTransforms(I))
1409     return common;
1410
1411   // (zext A) urem (zext B) --> zext (A urem B)
1412   if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1413     if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1414       return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1415                           I.getType());
1416
1417   // X urem Y -> X and Y-1, where Y is a power of 2,
1418   if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, AT, &I, DT)) {
1419     Constant *N1 = Constant::getAllOnesValue(I.getType());
1420     Value *Add = Builder->CreateAdd(Op1, N1);
1421     return BinaryOperator::CreateAnd(Op0, Add);
1422   }
1423
1424   // 1 urem X -> zext(X != 1)
1425   if (match(Op0, m_One())) {
1426     Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1427     Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1428     return ReplaceInstUsesWith(I, Ext);
1429   }
1430
1431   return nullptr;
1432 }
1433
1434 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1435   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1436
1437   if (Value *V = SimplifyVectorOp(I))
1438     return ReplaceInstUsesWith(I, V);
1439
1440   if (Value *V = SimplifySRemInst(Op0, Op1, DL, TLI, DT, AT))
1441     return ReplaceInstUsesWith(I, V);
1442
1443   // Handle the integer rem common cases
1444   if (Instruction *Common = commonIRemTransforms(I))
1445     return Common;
1446
1447   {
1448     const APInt *Y;
1449     // X % -Y -> X % Y
1450     if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
1451       Worklist.AddValue(I.getOperand(1));
1452       I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
1453       return &I;
1454     }
1455   }
1456
1457   // If the sign bits of both operands are zero (i.e. we can prove they are
1458   // unsigned inputs), turn this into a urem.
1459   if (I.getType()->isIntegerTy()) {
1460     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1461     if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1462         MaskedValueIsZero(Op0, Mask, 0, &I)) {
1463       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1464       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1465     }
1466   }
1467
1468   // If it's a constant vector, flip any negative values positive.
1469   if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1470     Constant *C = cast<Constant>(Op1);
1471     unsigned VWidth = C->getType()->getVectorNumElements();
1472
1473     bool hasNegative = false;
1474     bool hasMissing = false;
1475     for (unsigned i = 0; i != VWidth; ++i) {
1476       Constant *Elt = C->getAggregateElement(i);
1477       if (!Elt) {
1478         hasMissing = true;
1479         break;
1480       }
1481
1482       if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
1483         if (RHS->isNegative())
1484           hasNegative = true;
1485     }
1486
1487     if (hasNegative && !hasMissing) {
1488       SmallVector<Constant *, 16> Elts(VWidth);
1489       for (unsigned i = 0; i != VWidth; ++i) {
1490         Elts[i] = C->getAggregateElement(i);  // Handle undef, etc.
1491         if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
1492           if (RHS->isNegative())
1493             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
1494         }
1495       }
1496
1497       Constant *NewRHSV = ConstantVector::get(Elts);
1498       if (NewRHSV != C) {  // Don't loop on -MININT
1499         Worklist.AddValue(I.getOperand(1));
1500         I.setOperand(1, NewRHSV);
1501         return &I;
1502       }
1503     }
1504   }
1505
1506   return nullptr;
1507 }
1508
1509 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
1510   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1511
1512   if (Value *V = SimplifyVectorOp(I))
1513     return ReplaceInstUsesWith(I, V);
1514
1515   if (Value *V = SimplifyFRemInst(Op0, Op1, DL, TLI, DT, AT))
1516     return ReplaceInstUsesWith(I, V);
1517
1518   // Handle cases involving: rem X, (select Cond, Y, Z)
1519   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1520     return &I;
1521
1522   return nullptr;
1523 }