This change is to implement following rules:
[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 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
99   bool Changed = SimplifyAssociativeOrCommutative(I);
100   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
101
102   if (Value *V = SimplifyMulInst(Op0, Op1, TD))
103     return ReplaceInstUsesWith(I, V);
104
105   if (Value *V = SimplifyUsingDistributiveLaws(I))
106     return ReplaceInstUsesWith(I, V);
107
108   if (match(Op1, m_AllOnes()))  // X * -1 == 0 - X
109     return BinaryOperator::CreateNeg(Op0, I.getName());
110   
111   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
112     
113     // ((X << C1)*C2) == (X * (C2 << C1))
114     if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
115       if (SI->getOpcode() == Instruction::Shl)
116         if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
117           return BinaryOperator::CreateMul(SI->getOperand(0),
118                                            ConstantExpr::getShl(CI, ShOp));
119     
120     const APInt &Val = CI->getValue();
121     if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
122       Constant *NewCst = ConstantInt::get(Op0->getType(), Val.logBase2());
123       BinaryOperator *Shl = BinaryOperator::CreateShl(Op0, NewCst);
124       if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap();
125       if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap();
126       return Shl;
127     }
128     
129     // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
130     { Value *X; ConstantInt *C1;
131       if (Op0->hasOneUse() &&
132           match(Op0, m_Add(m_Value(X), m_ConstantInt(C1)))) {
133         Value *Add = Builder->CreateMul(X, CI);
134         return BinaryOperator::CreateAdd(Add, Builder->CreateMul(C1, CI));
135       }
136     }
137
138     // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
139     // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
140     // The "* (2**n)" thus becomes a potential shifting opportunity.
141     {
142       const APInt &   Val = CI->getValue();
143       const APInt &PosVal = Val.abs();
144       if (Val.isNegative() && PosVal.isPowerOf2()) {
145         Value *X = 0, *Y = 0;
146         if (Op0->hasOneUse()) {
147           ConstantInt *C1;
148           Value *Sub = 0;
149           if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
150             Sub = Builder->CreateSub(X, Y, "suba");
151           else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
152             Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
153           if (Sub)
154             return
155               BinaryOperator::CreateMul(Sub,
156                                         ConstantInt::get(Y->getType(), PosVal));
157         }
158       }
159     }
160   }
161   
162   // Simplify mul instructions with a constant RHS.
163   if (isa<Constant>(Op1)) {    
164     // Try to fold constant mul into select arguments.
165     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
166       if (Instruction *R = FoldOpIntoSelect(I, SI))
167         return R;
168
169     if (isa<PHINode>(Op0))
170       if (Instruction *NV = FoldOpIntoPhi(I))
171         return NV;
172   }
173
174   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
175     if (Value *Op1v = dyn_castNegVal(Op1))
176       return BinaryOperator::CreateMul(Op0v, Op1v);
177
178   // (X / Y) *  Y = X - (X % Y)
179   // (X / Y) * -Y = (X % Y) - X
180   {
181     Value *Op1C = Op1;
182     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
183     if (!BO ||
184         (BO->getOpcode() != Instruction::UDiv && 
185          BO->getOpcode() != Instruction::SDiv)) {
186       Op1C = Op0;
187       BO = dyn_cast<BinaryOperator>(Op1);
188     }
189     Value *Neg = dyn_castNegVal(Op1C);
190     if (BO && BO->hasOneUse() &&
191         (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
192         (BO->getOpcode() == Instruction::UDiv ||
193          BO->getOpcode() == Instruction::SDiv)) {
194       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
195
196       // If the division is exact, X % Y is zero, so we end up with X or -X.
197       if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
198         if (SDiv->isExact()) {
199           if (Op1BO == Op1C)
200             return ReplaceInstUsesWith(I, Op0BO);
201           return BinaryOperator::CreateNeg(Op0BO);
202         }
203
204       Value *Rem;
205       if (BO->getOpcode() == Instruction::UDiv)
206         Rem = Builder->CreateURem(Op0BO, Op1BO);
207       else
208         Rem = Builder->CreateSRem(Op0BO, Op1BO);
209       Rem->takeName(BO);
210
211       if (Op1BO == Op1C)
212         return BinaryOperator::CreateSub(Op0BO, Rem);
213       return BinaryOperator::CreateSub(Rem, Op0BO);
214     }
215   }
216
217   /// i1 mul -> i1 and.
218   if (I.getType()->isIntegerTy(1))
219     return BinaryOperator::CreateAnd(Op0, Op1);
220
221   // X*(1 << Y) --> X << Y
222   // (1 << Y)*X --> X << Y
223   {
224     Value *Y;
225     if (match(Op0, m_Shl(m_One(), m_Value(Y))))
226       return BinaryOperator::CreateShl(Op1, Y);
227     if (match(Op1, m_Shl(m_One(), m_Value(Y))))
228       return BinaryOperator::CreateShl(Op0, Y);
229   }
230   
231   // If one of the operands of the multiply is a cast from a boolean value, then
232   // we know the bool is either zero or one, so this is a 'masking' multiply.
233   //   X * Y (where Y is 0 or 1) -> X & (0-Y)
234   if (!I.getType()->isVectorTy()) {
235     // -2 is "-1 << 1" so it is all bits set except the low one.
236     APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
237     
238     Value *BoolCast = 0, *OtherOp = 0;
239     if (MaskedValueIsZero(Op0, Negative2))
240       BoolCast = Op0, OtherOp = Op1;
241     else if (MaskedValueIsZero(Op1, Negative2))
242       BoolCast = Op1, OtherOp = Op0;
243
244     if (BoolCast) {
245       Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
246                                     BoolCast);
247       return BinaryOperator::CreateAnd(V, OtherOp);
248     }
249   }
250
251   return Changed ? &I : 0;
252 }
253
254 //
255 // Detect pattern:
256 //
257 // log2(Y*0.5)
258 //
259 // And check for corresponding fast math flags
260 //
261
262 static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
263
264    if (!Op->hasOneUse())
265      return;
266
267    IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
268    if (!II)
269      return;
270    if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
271      return;
272    Log2 = II;
273
274    Value *OpLog2Of = II->getArgOperand(0);
275    if (!OpLog2Of->hasOneUse())
276      return;
277
278    Instruction *I = dyn_cast<Instruction>(OpLog2Of);
279    if (!I)
280      return;
281    if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
282      return;
283               
284    ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(0));
285    if (CFP && CFP->isExactlyValue(0.5)) {
286      Y = I->getOperand(1);
287      return;
288    }
289    CFP = dyn_cast<ConstantFP>(I->getOperand(1));
290    if (CFP && CFP->isExactlyValue(0.5))
291      Y = I->getOperand(0);
292
293
294 /// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
295 /// true iff the given value is FMul or FDiv with one and only one operand
296 /// being a normal constant (i.e. not Zero/NaN/Infinity).
297 static bool isFMulOrFDivWithConstant(Value *V) {
298   Instruction *I = dyn_cast<Instruction>(V);
299   if (!I || (I->getOpcode() != Instruction::FMul && 
300              I->getOpcode() != Instruction::FDiv)) {
301     return false;
302   }
303
304   ConstantFP *C0 = dyn_cast<ConstantFP>(I->getOperand(0));
305   ConstantFP *C1 = dyn_cast<ConstantFP>(I->getOperand(1));
306
307   if (C0 && C1)
308     return false;
309
310   return (C0 && C0->getValueAPF().isNormal()) ||
311          (C1 && C1->getValueAPF().isNormal());
312 }
313
314 static bool isNormalFp(const ConstantFP *C) {
315   const APFloat &Flt = C->getValueAPF();
316   return Flt.isNormal() && !Flt.isDenormal();
317 }
318
319 /// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
320 /// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
321 /// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
322 /// This function is to simplify "FMulOrDiv * C" and returns the 
323 /// resulting expression. Note that this function could return NULL in
324 /// case the constants cannot be folded into a normal floating-point.
325 /// 
326 Value *InstCombiner::foldFMulConst
327   (Instruction *FMulOrDiv, ConstantFP *C, Instruction *InsertBefore) {
328   assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
329
330   Value *Opnd0 = FMulOrDiv->getOperand(0);
331   Value *Opnd1 = FMulOrDiv->getOperand(1);
332
333   ConstantFP *C0 = dyn_cast<ConstantFP>(Opnd0);
334   ConstantFP *C1 = dyn_cast<ConstantFP>(Opnd1);
335
336   BinaryOperator *R = 0;
337
338   // (X * C0) * C => X * (C0*C)
339   if (FMulOrDiv->getOpcode() == Instruction::FMul) {
340     Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
341     if (isNormalFp(cast<ConstantFP>(F)))
342       R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
343   } else {
344     if (C0) {
345       // (C0 / X) * C => (C0 * C) / X
346       ConstantFP *F = cast<ConstantFP>(ConstantExpr::getFMul(C0, C));
347       if (isNormalFp(F))
348         R = BinaryOperator::CreateFDiv(F, Opnd1);
349     } else {
350       // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
351       ConstantFP *F = cast<ConstantFP>(ConstantExpr::getFDiv(C, C1));
352       if (isNormalFp(F)) {
353         R = BinaryOperator::CreateFMul(Opnd0, F);
354       } else {
355         // (X / C1) * C => X / (C1/C) 
356         Constant *F = ConstantExpr::getFDiv(C1, C);
357         if (isNormalFp(cast<ConstantFP>(F)))
358           R = BinaryOperator::CreateFDiv(Opnd0, F);
359       }
360     }
361   }
362
363   if (R) {
364     R->setHasUnsafeAlgebra(true);
365     InsertNewInstWith(R, *InsertBefore);
366   }
367
368   return R;
369 }
370
371 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
372   bool Changed = SimplifyAssociativeOrCommutative(I);
373   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
374
375   if (isa<Constant>(Op0))
376     std::swap(Op0, Op1);
377
378   if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), TD))
379     return ReplaceInstUsesWith(I, V);
380
381   // Simplify mul instructions with a constant RHS.
382   if (isa<Constant>(Op1)) {
383     // Try to fold constant mul into select arguments.
384     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
385       if (Instruction *R = FoldOpIntoSelect(I, SI))
386         return R;
387
388     if (isa<PHINode>(Op0))
389       if (Instruction *NV = FoldOpIntoPhi(I))
390         return NV;
391
392     ConstantFP *C = dyn_cast<ConstantFP>(Op1);
393     if (C && I.hasUnsafeAlgebra() && C->getValueAPF().isNormal()) {
394       // Let MDC denote an expression in one of these forms:
395       // X * C, C/X, X/C, where C is a constant.
396       //
397       // Try to simplify "MDC * Constant"
398       if (isFMulOrFDivWithConstant(Op0)) {
399         Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I);
400         if (V)
401           return ReplaceInstUsesWith(I, V);
402       }
403
404       // (MDC +/- C1) * C2 => (MDC * C2) +/- (C1 * C2)
405       Instruction *FAddSub = dyn_cast<Instruction>(Op0);
406       if (FAddSub &&
407           (FAddSub->getOpcode() == Instruction::FAdd ||
408            FAddSub->getOpcode() == Instruction::FSub)) {
409         Value *Opnd0 = FAddSub->getOperand(0);
410         Value *Opnd1 = FAddSub->getOperand(1);
411         ConstantFP *C0 = dyn_cast<ConstantFP>(Opnd0);
412         ConstantFP *C1 = dyn_cast<ConstantFP>(Opnd1);
413         bool Swap = false;
414         if (C0) {
415           std::swap(C0, C1); std::swap(Opnd0, Opnd1); Swap = true; 
416         }
417
418         if (C1 && C1->getValueAPF().isNormal() &&
419             isFMulOrFDivWithConstant(Opnd0)) {
420           Value *M0 = ConstantExpr::getFMul(C1, C);
421           Value *M1 = isNormalFp(cast<ConstantFP>(M0)) ? 
422                       foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
423                       0;
424           if (M0 && M1) {
425             if (Swap && FAddSub->getOpcode() == Instruction::FSub)
426               std::swap(M0, M1);
427
428             Value *R = (FAddSub->getOpcode() == Instruction::FAdd) ?
429                         BinaryOperator::CreateFAdd(M0, M1) :
430                         BinaryOperator::CreateFSub(M0, M1);
431             Instruction *RI = cast<Instruction>(R);
432             RI->setHasUnsafeAlgebra(true);
433             return RI;
434           }
435         }
436       }
437     }
438   }
439
440   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
441     if (Value *Op1v = dyn_castFNegVal(Op1))
442       return BinaryOperator::CreateFMul(Op0v, Op1v);
443
444   // Under unsafe algebra do:
445   // X * log2(0.5*Y) = X*log2(Y) - X
446   if (I.hasUnsafeAlgebra()) {
447     Value *OpX = NULL;
448     Value *OpY = NULL;
449     IntrinsicInst *Log2;
450     detectLog2OfHalf(Op0, OpY, Log2);
451     if (OpY) {
452       OpX = Op1;
453     } else {
454       detectLog2OfHalf(Op1, OpY, Log2);
455       if (OpY) {
456         OpX = Op0;
457       }
458     }
459     // if pattern detected emit alternate sequence
460     if (OpX && OpY) {
461       Log2->setArgOperand(0, OpY);
462       Value *FMulVal = Builder->CreateFMul(OpX, Log2);
463       Instruction *FMul = cast<Instruction>(FMulVal);
464       FMul->copyFastMathFlags(Log2);
465       Instruction *FSub = BinaryOperator::CreateFSub(FMulVal, OpX);
466       FSub->copyFastMathFlags(Log2);
467       return FSub;
468     }
469   }
470
471   // X * cond ? 1.0 : 0.0 => cond ? X : 0.0
472   if (I.hasNoNaNs() && I.hasNoSignedZeros()) {
473     Value *V0 = I.getOperand(0);
474     Value *V1 = I.getOperand(1);
475     Value *Cond, *SLHS, *SRHS;
476     bool Match = false;
477
478     if (match(V0, m_Select(m_Value(Cond), m_Value(SLHS), m_Value(SRHS)))) {
479       Match = true;
480     } else if (match(V1, m_Select(m_Value(Cond), m_Value(SLHS), 
481                      m_Value(SRHS)))) {
482       Match = true;
483       std::swap(V0, V1);
484     }
485
486     if (Match) {
487       ConstantFP *C0 = dyn_cast<ConstantFP>(SLHS);
488       ConstantFP *C1 = dyn_cast<ConstantFP>(SRHS);
489
490       if (C0 && C1 &&
491           ((C0->isZero() && C1->isExactlyValue(1.0)) ||
492            (C1->isZero() && C0->isExactlyValue(1.0)))) {
493         Value *T;
494         if (C0->isZero())
495           T = Builder->CreateSelect(Cond, SLHS, V1);
496         else
497           T = Builder->CreateSelect(Cond, V1, SRHS);
498         return ReplaceInstUsesWith(I, T);
499       }
500     }
501   }
502
503   return Changed ? &I : 0;
504 }
505
506 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
507 /// instruction.
508 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
509   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
510   
511   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
512   int NonNullOperand = -1;
513   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
514     if (ST->isNullValue())
515       NonNullOperand = 2;
516   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
517   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
518     if (ST->isNullValue())
519       NonNullOperand = 1;
520   
521   if (NonNullOperand == -1)
522     return false;
523   
524   Value *SelectCond = SI->getOperand(0);
525   
526   // Change the div/rem to use 'Y' instead of the select.
527   I.setOperand(1, SI->getOperand(NonNullOperand));
528   
529   // Okay, we know we replace the operand of the div/rem with 'Y' with no
530   // problem.  However, the select, or the condition of the select may have
531   // multiple uses.  Based on our knowledge that the operand must be non-zero,
532   // propagate the known value for the select into other uses of it, and
533   // propagate a known value of the condition into its other users.
534   
535   // If the select and condition only have a single use, don't bother with this,
536   // early exit.
537   if (SI->use_empty() && SelectCond->hasOneUse())
538     return true;
539   
540   // Scan the current block backward, looking for other uses of SI.
541   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
542   
543   while (BBI != BBFront) {
544     --BBI;
545     // If we found a call to a function, we can't assume it will return, so
546     // information from below it cannot be propagated above it.
547     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
548       break;
549     
550     // Replace uses of the select or its condition with the known values.
551     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
552          I != E; ++I) {
553       if (*I == SI) {
554         *I = SI->getOperand(NonNullOperand);
555         Worklist.Add(BBI);
556       } else if (*I == SelectCond) {
557         *I = NonNullOperand == 1 ? ConstantInt::getTrue(BBI->getContext()) :
558                                    ConstantInt::getFalse(BBI->getContext());
559         Worklist.Add(BBI);
560       }
561     }
562     
563     // If we past the instruction, quit looking for it.
564     if (&*BBI == SI)
565       SI = 0;
566     if (&*BBI == SelectCond)
567       SelectCond = 0;
568     
569     // If we ran out of things to eliminate, break out of the loop.
570     if (SelectCond == 0 && SI == 0)
571       break;
572     
573   }
574   return true;
575 }
576
577
578 /// This function implements the transforms common to both integer division
579 /// instructions (udiv and sdiv). It is called by the visitors to those integer
580 /// division instructions.
581 /// @brief Common integer divide transforms
582 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
583   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
584
585   // The RHS is known non-zero.
586   if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
587     I.setOperand(1, V);
588     return &I;
589   }
590   
591   // Handle cases involving: [su]div X, (select Cond, Y, Z)
592   // This does not apply for fdiv.
593   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
594     return &I;
595
596   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
597     // (X / C1) / C2  -> X / (C1*C2)
598     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
599       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
600         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
601           if (MultiplyOverflows(RHS, LHSRHS,
602                                 I.getOpcode()==Instruction::SDiv))
603             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
604           return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
605                                         ConstantExpr::getMul(RHS, LHSRHS));
606         }
607
608     if (!RHS->isZero()) { // avoid X udiv 0
609       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
610         if (Instruction *R = FoldOpIntoSelect(I, SI))
611           return R;
612       if (isa<PHINode>(Op0))
613         if (Instruction *NV = FoldOpIntoPhi(I))
614           return NV;
615     }
616   }
617
618   // See if we can fold away this div instruction.
619   if (SimplifyDemandedInstructionBits(I))
620     return &I;
621
622   // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
623   Value *X = 0, *Z = 0;
624   if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
625     bool isSigned = I.getOpcode() == Instruction::SDiv;
626     if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
627         (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
628       return BinaryOperator::Create(I.getOpcode(), X, Op1);
629   }
630
631   return 0;
632 }
633
634 /// dyn_castZExtVal - Checks if V is a zext or constant that can
635 /// be truncated to Ty without losing bits.
636 static Value *dyn_castZExtVal(Value *V, Type *Ty) {
637   if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
638     if (Z->getSrcTy() == Ty)
639       return Z->getOperand(0);
640   } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
641     if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
642       return ConstantExpr::getTrunc(C, Ty);
643   }
644   return 0;
645 }
646
647 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
648   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
649
650   if (Value *V = SimplifyUDivInst(Op0, Op1, TD))
651     return ReplaceInstUsesWith(I, V);
652
653   // Handle the integer div common cases
654   if (Instruction *Common = commonIDivTransforms(I))
655     return Common;
656   
657   { 
658     // X udiv 2^C -> X >> C
659     // Check to see if this is an unsigned division with an exact power of 2,
660     // if so, convert to a right shift.
661     const APInt *C;
662     if (match(Op1, m_Power2(C))) {
663       BinaryOperator *LShr =
664       BinaryOperator::CreateLShr(Op0, 
665                                  ConstantInt::get(Op0->getType(), 
666                                                   C->logBase2()));
667       if (I.isExact()) LShr->setIsExact();
668       return LShr;
669     }
670   }
671
672   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
673     // X udiv C, where C >= signbit
674     if (C->getValue().isNegative()) {
675       Value *IC = Builder->CreateICmpULT(Op0, C);
676       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
677                                 ConstantInt::get(I.getType(), 1));
678     }
679   }
680
681   // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
682   if (ConstantInt *C2 = dyn_cast<ConstantInt>(Op1)) {
683     Value *X;
684     ConstantInt *C1;
685     if (match(Op0, m_LShr(m_Value(X), m_ConstantInt(C1)))) {
686       APInt NC = C2->getValue().shl(C1->getLimitedValue(C1->getBitWidth()-1));
687       return BinaryOperator::CreateUDiv(X, Builder->getInt(NC));
688     }
689   }
690
691   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
692   { const APInt *CI; Value *N;
693     if (match(Op1, m_Shl(m_Power2(CI), m_Value(N))) ||
694         match(Op1, m_ZExt(m_Shl(m_Power2(CI), m_Value(N))))) {
695       if (*CI != 1)
696         N = Builder->CreateAdd(N,
697                                ConstantInt::get(N->getType(), CI->logBase2()));
698       if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
699         N = Builder->CreateZExt(N, Z->getDestTy());
700       if (I.isExact())
701         return BinaryOperator::CreateExactLShr(Op0, N);
702       return BinaryOperator::CreateLShr(Op0, N);
703     }
704   }
705   
706   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
707   // where C1&C2 are powers of two.
708   { Value *Cond; const APInt *C1, *C2;
709     if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) {
710       // Construct the "on true" case of the select
711       Value *TSI = Builder->CreateLShr(Op0, C1->logBase2(), Op1->getName()+".t",
712                                        I.isExact());
713   
714       // Construct the "on false" case of the select
715       Value *FSI = Builder->CreateLShr(Op0, C2->logBase2(), Op1->getName()+".f",
716                                        I.isExact());
717       
718       // construct the select instruction and return it.
719       return SelectInst::Create(Cond, TSI, FSI);
720     }
721   }
722
723   // (zext A) udiv (zext B) --> zext (A udiv B)
724   if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
725     if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
726       return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
727                                               I.isExact()),
728                           I.getType());
729
730   return 0;
731 }
732
733 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
734   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
735
736   if (Value *V = SimplifySDivInst(Op0, Op1, TD))
737     return ReplaceInstUsesWith(I, V);
738
739   // Handle the integer div common cases
740   if (Instruction *Common = commonIDivTransforms(I))
741     return Common;
742
743   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
744     // sdiv X, -1 == -X
745     if (RHS->isAllOnesValue())
746       return BinaryOperator::CreateNeg(Op0);
747
748     // sdiv X, C  -->  ashr exact X, log2(C)
749     if (I.isExact() && RHS->getValue().isNonNegative() &&
750         RHS->getValue().isPowerOf2()) {
751       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
752                                             RHS->getValue().exactLogBase2());
753       return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
754     }
755
756     // -X/C  -->  X/-C  provided the negation doesn't overflow.
757     if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
758       if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
759         return BinaryOperator::CreateSDiv(Sub->getOperand(1),
760                                           ConstantExpr::getNeg(RHS));
761   }
762
763   // If the sign bits of both operands are zero (i.e. we can prove they are
764   // unsigned inputs), turn this into a udiv.
765   if (I.getType()->isIntegerTy()) {
766     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
767     if (MaskedValueIsZero(Op0, Mask)) {
768       if (MaskedValueIsZero(Op1, Mask)) {
769         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
770         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
771       }
772       
773       if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
774         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
775         // Safe because the only negative value (1 << Y) can take on is
776         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
777         // the sign bit set.
778         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
779       }
780     }
781   }
782   
783   return 0;
784 }
785
786 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
787   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
788
789   if (Value *V = SimplifyFDivInst(Op0, Op1, TD))
790     return ReplaceInstUsesWith(I, V);
791
792   if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
793     const APFloat &Op1F = Op1C->getValueAPF();
794
795     // If the divisor has an exact multiplicative inverse we can turn the fdiv
796     // into a cheaper fmul.
797     APFloat Reciprocal(Op1F.getSemantics());
798     if (Op1F.getExactInverse(&Reciprocal)) {
799       ConstantFP *RFP = ConstantFP::get(Builder->getContext(), Reciprocal);
800       return BinaryOperator::CreateFMul(Op0, RFP);
801     }
802   }
803
804   return 0;
805 }
806
807 /// This function implements the transforms common to both integer remainder
808 /// instructions (urem and srem). It is called by the visitors to those integer
809 /// remainder instructions.
810 /// @brief Common integer remainder transforms
811 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
812   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
813
814   // The RHS is known non-zero.
815   if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
816     I.setOperand(1, V);
817     return &I;
818   }
819
820   // Handle cases involving: rem X, (select Cond, Y, Z)
821   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
822     return &I;
823
824   if (isa<ConstantInt>(Op1)) {
825     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
826       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
827         if (Instruction *R = FoldOpIntoSelect(I, SI))
828           return R;
829       } else if (isa<PHINode>(Op0I)) {
830         if (Instruction *NV = FoldOpIntoPhi(I))
831           return NV;
832       }
833
834       // See if we can fold away this rem instruction.
835       if (SimplifyDemandedInstructionBits(I))
836         return &I;
837     }
838   }
839
840   return 0;
841 }
842
843 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
844   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
845
846   if (Value *V = SimplifyURemInst(Op0, Op1, TD))
847     return ReplaceInstUsesWith(I, V);
848
849   if (Instruction *common = commonIRemTransforms(I))
850     return common;
851   
852   // X urem C^2 -> X and C-1
853   { const APInt *C;
854     if (match(Op1, m_Power2(C)))
855       return BinaryOperator::CreateAnd(Op0,
856                                        ConstantInt::get(I.getType(), *C-1));
857   }
858
859   // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
860   if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
861     Constant *N1 = Constant::getAllOnesValue(I.getType());
862     Value *Add = Builder->CreateAdd(Op1, N1);
863     return BinaryOperator::CreateAnd(Op0, Add);
864   }
865
866   // urem X, (select Cond, 2^C1, 2^C2) -->
867   //    select Cond, (and X, C1-1), (and X, C2-1)
868   // when C1&C2 are powers of two.
869   { Value *Cond; const APInt *C1, *C2;
870     if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) {
871       Value *TrueAnd = Builder->CreateAnd(Op0, *C1-1, Op1->getName()+".t");
872       Value *FalseAnd = Builder->CreateAnd(Op0, *C2-1, Op1->getName()+".f");
873       return SelectInst::Create(Cond, TrueAnd, FalseAnd);
874     }
875   }
876
877   // (zext A) urem (zext B) --> zext (A urem B)
878   if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
879     if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
880       return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
881                           I.getType());
882
883   return 0;
884 }
885
886 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
887   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
888
889   if (Value *V = SimplifySRemInst(Op0, Op1, TD))
890     return ReplaceInstUsesWith(I, V);
891
892   // Handle the integer rem common cases
893   if (Instruction *Common = commonIRemTransforms(I))
894     return Common;
895   
896   if (Value *RHSNeg = dyn_castNegVal(Op1))
897     if (!isa<Constant>(RHSNeg) ||
898         (isa<ConstantInt>(RHSNeg) &&
899          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
900       // X % -Y -> X % Y
901       Worklist.AddValue(I.getOperand(1));
902       I.setOperand(1, RHSNeg);
903       return &I;
904     }
905
906   // If the sign bits of both operands are zero (i.e. we can prove they are
907   // unsigned inputs), turn this into a urem.
908   if (I.getType()->isIntegerTy()) {
909     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
910     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
911       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
912       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
913     }
914   }
915
916   // If it's a constant vector, flip any negative values positive.
917   if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
918     Constant *C = cast<Constant>(Op1);
919     unsigned VWidth = C->getType()->getVectorNumElements();
920
921     bool hasNegative = false;
922     bool hasMissing = false;
923     for (unsigned i = 0; i != VWidth; ++i) {
924       Constant *Elt = C->getAggregateElement(i);
925       if (Elt == 0) {
926         hasMissing = true;
927         break;
928       }
929
930       if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
931         if (RHS->isNegative())
932           hasNegative = true;
933     }
934
935     if (hasNegative && !hasMissing) {
936       SmallVector<Constant *, 16> Elts(VWidth);
937       for (unsigned i = 0; i != VWidth; ++i) {
938         Elts[i] = C->getAggregateElement(i);  // Handle undef, etc.
939         if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
940           if (RHS->isNegative())
941             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
942         }
943       }
944
945       Constant *NewRHSV = ConstantVector::get(Elts);
946       if (NewRHSV != C) {  // Don't loop on -MININT
947         Worklist.AddValue(I.getOperand(1));
948         I.setOperand(1, NewRHSV);
949         return &I;
950       }
951     }
952   }
953
954   return 0;
955 }
956
957 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
958   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
959
960   if (Value *V = SimplifyFRemInst(Op0, Op1, TD))
961     return ReplaceInstUsesWith(I, V);
962
963   // Handle cases involving: rem X, (select Cond, Y, Z)
964   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
965     return &I;
966
967   return 0;
968 }