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