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