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