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