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 "InstCombineInternal.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 /// The specific integer value is used in a context where it is known to be
26 /// non-zero.  If this allows us to simplify the computation, do so and return
27 /// 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   BinaryOperator *I = dyn_cast<BinaryOperator>(V);
49   if (I && I->isLogicalShift() &&
50       IC.isKnownToBeAPowerOfTwo(I->getOperand(0), false, 0, &CxtI)) {
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, CxtI)) {
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 /// True if the multiply can not be expressed in an int this size.
78 static bool MultiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
79                               bool IsSigned) {
80   bool Overflow;
81   if (IsSigned)
82     Product = C1.smul_ov(C2, Overflow);
83   else
84     Product = C1.umul_ov(C2, Overflow);
85 
86   return Overflow;
87 }
88 
89 /// \brief True if C2 is a multiple of C1. Quotient contains C2/C1.
90 static bool IsMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
91                        bool IsSigned) {
92   assert(C1.getBitWidth() == C2.getBitWidth() &&
93          "Inconsistent width of constants!");
94 
95   // Bail if we will divide by zero.
96   if (C2.isMinValue())
97     return false;
98 
99   // Bail if we would divide INT_MIN by -1.
100   if (IsSigned && C1.isMinSignedValue() && C2.isAllOnesValue())
101     return false;
102 
103   APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
104   if (IsSigned)
105     APInt::sdivrem(C1, C2, Quotient, Remainder);
106   else
107     APInt::udivrem(C1, C2, Quotient, Remainder);
108 
109   return Remainder.isMinValue();
110 }
111 
112 /// \brief A helper routine of InstCombiner::visitMul().
113 ///
114 /// If C is a vector of known powers of 2, then this function returns
115 /// a new vector obtained from C replacing each element with its logBase2.
116 /// Return a null pointer otherwise.
117 static Constant *getLogBase2Vector(ConstantDataVector *CV) {
118   const APInt *IVal;
119   SmallVector<Constant *, 4> Elts;
120 
121   for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
122     Constant *Elt = CV->getElementAsConstant(I);
123     if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
124       return nullptr;
125     Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
126   }
127 
128   return ConstantVector::get(Elts);
129 }
130 
131 /// \brief Return true if we can prove that:
132 ///    (mul LHS, RHS)  === (mul nsw LHS, RHS)
133 bool InstCombiner::willNotOverflowSignedMul(const Value *LHS,
134                                             const Value *RHS,
135                                             const Instruction &CxtI) const {
136   // Multiplying n * m significant bits yields a result of n + m significant
137   // bits. If the total number of significant bits does not exceed the
138   // result bit width (minus 1), there is no overflow.
139   // This means if we have enough leading sign bits in the operands
140   // we can guarantee that the result does not overflow.
141   // Ref: "Hacker's Delight" by Henry Warren
142   unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
143 
144   // Note that underestimating the number of sign bits gives a more
145   // conservative answer.
146   unsigned SignBits =
147       ComputeNumSignBits(LHS, 0, &CxtI) + ComputeNumSignBits(RHS, 0, &CxtI);
148 
149   // First handle the easy case: if we have enough sign bits there's
150   // definitely no overflow.
151   if (SignBits > BitWidth + 1)
152     return true;
153 
154   // There are two ambiguous cases where there can be no overflow:
155   //   SignBits == BitWidth + 1    and
156   //   SignBits == BitWidth
157   // The second case is difficult to check, therefore we only handle the
158   // first case.
159   if (SignBits == BitWidth + 1) {
160     // It overflows only when both arguments are negative and the true
161     // product is exactly the minimum negative number.
162     // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
163     // For simplicity we just check if at least one side is not negative.
164     KnownBits LHSKnown = computeKnownBits(LHS, /*Depth=*/0, &CxtI);
165     KnownBits RHSKnown = computeKnownBits(RHS, /*Depth=*/0, &CxtI);
166     if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
167       return true;
168   }
169   return false;
170 }
171 
172 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
173   bool Changed = SimplifyAssociativeOrCommutative(I);
174   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
175 
176   if (Value *V = SimplifyVectorOp(I))
177     return replaceInstUsesWith(I, V);
178 
179   if (Value *V = SimplifyMulInst(Op0, Op1, SQ.getWithInstruction(&I)))
180     return replaceInstUsesWith(I, V);
181 
182   if (Value *V = SimplifyUsingDistributiveLaws(I))
183     return replaceInstUsesWith(I, V);
184 
185   // X * -1 == 0 - X
186   if (match(Op1, m_AllOnes())) {
187     BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
188     if (I.hasNoSignedWrap())
189       BO->setHasNoSignedWrap();
190     return BO;
191   }
192 
193   // Also allow combining multiply instructions on vectors.
194   {
195     Value *NewOp;
196     Constant *C1, *C2;
197     const APInt *IVal;
198     if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
199                         m_Constant(C1))) &&
200         match(C1, m_APInt(IVal))) {
201       // ((X << C2)*C1) == (X * (C1 << C2))
202       Constant *Shl = ConstantExpr::getShl(C1, C2);
203       BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
204       BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
205       if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
206         BO->setHasNoUnsignedWrap();
207       if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
208           Shl->isNotMinSignedValue())
209         BO->setHasNoSignedWrap();
210       return BO;
211     }
212 
213     if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
214       Constant *NewCst = nullptr;
215       if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
216         // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
217         NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
218       else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
219         // Replace X*(2^C) with X << C, where C is a vector of known
220         // constant powers of 2.
221         NewCst = getLogBase2Vector(CV);
222 
223       if (NewCst) {
224         unsigned Width = NewCst->getType()->getPrimitiveSizeInBits();
225         BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
226 
227         if (I.hasNoUnsignedWrap())
228           Shl->setHasNoUnsignedWrap();
229         if (I.hasNoSignedWrap()) {
230           const APInt *V;
231           if (match(NewCst, m_APInt(V)) && *V != Width - 1)
232             Shl->setHasNoSignedWrap();
233         }
234 
235         return Shl;
236       }
237     }
238   }
239 
240   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
241     // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
242     // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
243     // The "* (2**n)" thus becomes a potential shifting opportunity.
244     {
245       const APInt &   Val = CI->getValue();
246       const APInt &PosVal = Val.abs();
247       if (Val.isNegative() && PosVal.isPowerOf2()) {
248         Value *X = nullptr, *Y = nullptr;
249         if (Op0->hasOneUse()) {
250           ConstantInt *C1;
251           Value *Sub = nullptr;
252           if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
253             Sub = Builder.CreateSub(X, Y, "suba");
254           else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
255             Sub = Builder.CreateSub(Builder.CreateNeg(C1), Y, "subc");
256           if (Sub)
257             return
258               BinaryOperator::CreateMul(Sub,
259                                         ConstantInt::get(Y->getType(), PosVal));
260         }
261       }
262     }
263   }
264 
265   // Simplify mul instructions with a constant RHS.
266   if (isa<Constant>(Op1)) {
267     if (Instruction *FoldedMul = foldOpWithConstantIntoOperand(I))
268       return FoldedMul;
269 
270     // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
271     {
272       Value *X;
273       Constant *C1;
274       if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
275         Value *Mul = Builder.CreateMul(C1, Op1);
276         // Only go forward with the transform if C1*CI simplifies to a tidier
277         // constant.
278         if (!match(Mul, m_Mul(m_Value(), m_Value())))
279           return BinaryOperator::CreateAdd(Builder.CreateMul(X, Op1), Mul);
280       }
281     }
282   }
283 
284   if (Value *Op0v = dyn_castNegVal(Op0)) {   // -X * -Y = X*Y
285     if (Value *Op1v = dyn_castNegVal(Op1)) {
286       BinaryOperator *BO = BinaryOperator::CreateMul(Op0v, Op1v);
287       if (I.hasNoSignedWrap() &&
288           match(Op0, m_NSWSub(m_Value(), m_Value())) &&
289           match(Op1, m_NSWSub(m_Value(), m_Value())))
290         BO->setHasNoSignedWrap();
291       return BO;
292     }
293   }
294 
295   // (X / Y) *  Y = X - (X % Y)
296   // (X / Y) * -Y = (X % Y) - X
297   {
298     Value *Y = Op1;
299     BinaryOperator *Div = dyn_cast<BinaryOperator>(Op0);
300     if (!Div || (Div->getOpcode() != Instruction::UDiv &&
301                  Div->getOpcode() != Instruction::SDiv)) {
302       Y = Op0;
303       Div = dyn_cast<BinaryOperator>(Op1);
304     }
305     Value *Neg = dyn_castNegVal(Y);
306     if (Div && Div->hasOneUse() &&
307         (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) &&
308         (Div->getOpcode() == Instruction::UDiv ||
309          Div->getOpcode() == Instruction::SDiv)) {
310       Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1);
311 
312       // If the division is exact, X % Y is zero, so we end up with X or -X.
313       if (Div->isExact()) {
314         if (DivOp1 == Y)
315           return replaceInstUsesWith(I, X);
316         return BinaryOperator::CreateNeg(X);
317       }
318 
319       auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
320                                                           : Instruction::SRem;
321       Value *Rem = Builder.CreateBinOp(RemOpc, X, DivOp1);
322       if (DivOp1 == Y)
323         return BinaryOperator::CreateSub(X, Rem);
324       return BinaryOperator::CreateSub(Rem, X);
325     }
326   }
327 
328   /// i1 mul -> i1 and.
329   if (I.getType()->isIntOrIntVectorTy(1))
330     return BinaryOperator::CreateAnd(Op0, Op1);
331 
332   // X*(1 << Y) --> X << Y
333   // (1 << Y)*X --> X << Y
334   {
335     Value *Y;
336     BinaryOperator *BO = nullptr;
337     bool ShlNSW = false;
338     if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
339       BO = BinaryOperator::CreateShl(Op1, Y);
340       ShlNSW = cast<ShlOperator>(Op0)->hasNoSignedWrap();
341     } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
342       BO = BinaryOperator::CreateShl(Op0, Y);
343       ShlNSW = cast<ShlOperator>(Op1)->hasNoSignedWrap();
344     }
345     if (BO) {
346       if (I.hasNoUnsignedWrap())
347         BO->setHasNoUnsignedWrap();
348       if (I.hasNoSignedWrap() && ShlNSW)
349         BO->setHasNoSignedWrap();
350       return BO;
351     }
352   }
353 
354   // If one of the operands of the multiply is a cast from a boolean value, then
355   // we know the bool is either zero or one, so this is a 'masking' multiply.
356   //   X * Y (where Y is 0 or 1) -> X & (0-Y)
357   if (!I.getType()->isVectorTy()) {
358     // -2 is "-1 << 1" so it is all bits set except the low one.
359     APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
360 
361     Value *BoolCast = nullptr, *OtherOp = nullptr;
362     if (MaskedValueIsZero(Op0, Negative2, 0, &I)) {
363       BoolCast = Op0;
364       OtherOp = Op1;
365     } else if (MaskedValueIsZero(Op1, Negative2, 0, &I)) {
366       BoolCast = Op1;
367       OtherOp = Op0;
368     }
369 
370     if (BoolCast) {
371       Value *V = Builder.CreateSub(Constant::getNullValue(I.getType()),
372                                     BoolCast);
373       return BinaryOperator::CreateAnd(V, OtherOp);
374     }
375   }
376 
377   // Check for (mul (sext x), y), see if we can merge this into an
378   // integer mul followed by a sext.
379   if (SExtInst *Op0Conv = dyn_cast<SExtInst>(Op0)) {
380     // (mul (sext x), cst) --> (sext (mul x, cst'))
381     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
382       if (Op0Conv->hasOneUse()) {
383         Constant *CI =
384             ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
385         if (ConstantExpr::getSExt(CI, I.getType()) == Op1C &&
386             willNotOverflowSignedMul(Op0Conv->getOperand(0), CI, I)) {
387           // Insert the new, smaller mul.
388           Value *NewMul =
389               Builder.CreateNSWMul(Op0Conv->getOperand(0), CI, "mulconv");
390           return new SExtInst(NewMul, I.getType());
391         }
392       }
393     }
394 
395     // (mul (sext x), (sext y)) --> (sext (mul int x, y))
396     if (SExtInst *Op1Conv = dyn_cast<SExtInst>(Op1)) {
397       // Only do this if x/y have the same type, if at last one of them has a
398       // single use (so we don't increase the number of sexts), and if the
399       // integer mul will not overflow.
400       if (Op0Conv->getOperand(0)->getType() ==
401               Op1Conv->getOperand(0)->getType() &&
402           (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
403           willNotOverflowSignedMul(Op0Conv->getOperand(0),
404                                    Op1Conv->getOperand(0), I)) {
405         // Insert the new integer mul.
406         Value *NewMul = Builder.CreateNSWMul(
407             Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
408         return new SExtInst(NewMul, I.getType());
409       }
410     }
411   }
412 
413   // Check for (mul (zext x), y), see if we can merge this into an
414   // integer mul followed by a zext.
415   if (auto *Op0Conv = dyn_cast<ZExtInst>(Op0)) {
416     // (mul (zext x), cst) --> (zext (mul x, cst'))
417     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
418       if (Op0Conv->hasOneUse()) {
419         Constant *CI =
420             ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
421         if (ConstantExpr::getZExt(CI, I.getType()) == Op1C &&
422             willNotOverflowUnsignedMul(Op0Conv->getOperand(0), CI, I)) {
423           // Insert the new, smaller mul.
424           Value *NewMul =
425               Builder.CreateNUWMul(Op0Conv->getOperand(0), CI, "mulconv");
426           return new ZExtInst(NewMul, I.getType());
427         }
428       }
429     }
430 
431     // (mul (zext x), (zext y)) --> (zext (mul int x, y))
432     if (auto *Op1Conv = dyn_cast<ZExtInst>(Op1)) {
433       // Only do this if x/y have the same type, if at last one of them has a
434       // single use (so we don't increase the number of zexts), and if the
435       // integer mul will not overflow.
436       if (Op0Conv->getOperand(0)->getType() ==
437               Op1Conv->getOperand(0)->getType() &&
438           (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
439           willNotOverflowUnsignedMul(Op0Conv->getOperand(0),
440                                      Op1Conv->getOperand(0), I)) {
441         // Insert the new integer mul.
442         Value *NewMul = Builder.CreateNUWMul(
443             Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
444         return new ZExtInst(NewMul, I.getType());
445       }
446     }
447   }
448 
449   if (!I.hasNoSignedWrap() && willNotOverflowSignedMul(Op0, Op1, I)) {
450     Changed = true;
451     I.setHasNoSignedWrap(true);
452   }
453 
454   if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedMul(Op0, Op1, I)) {
455     Changed = true;
456     I.setHasNoUnsignedWrap(true);
457   }
458 
459   return Changed ? &I : nullptr;
460 }
461 
462 /// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
463 static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
464   if (!Op->hasOneUse())
465     return;
466 
467   IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
468   if (!II)
469     return;
470   if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
471     return;
472   Log2 = II;
473 
474   Value *OpLog2Of = II->getArgOperand(0);
475   if (!OpLog2Of->hasOneUse())
476     return;
477 
478   Instruction *I = dyn_cast<Instruction>(OpLog2Of);
479   if (!I)
480     return;
481   if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
482     return;
483 
484   if (match(I->getOperand(0), m_SpecificFP(0.5)))
485     Y = I->getOperand(1);
486   else if (match(I->getOperand(1), m_SpecificFP(0.5)))
487     Y = I->getOperand(0);
488 }
489 
490 static bool isFiniteNonZeroFp(Constant *C) {
491   if (C->getType()->isVectorTy()) {
492     for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
493          ++I) {
494       ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
495       if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
496         return false;
497     }
498     return true;
499   }
500 
501   return isa<ConstantFP>(C) &&
502          cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
503 }
504 
505 static bool isNormalFp(Constant *C) {
506   if (C->getType()->isVectorTy()) {
507     for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
508          ++I) {
509       ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
510       if (!CFP || !CFP->getValueAPF().isNormal())
511         return false;
512     }
513     return true;
514   }
515 
516   return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
517 }
518 
519 /// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
520 /// true iff the given value is FMul or FDiv with one and only one operand
521 /// being a normal constant (i.e. not Zero/NaN/Infinity).
522 static bool isFMulOrFDivWithConstant(Value *V) {
523   Instruction *I = dyn_cast<Instruction>(V);
524   if (!I || (I->getOpcode() != Instruction::FMul &&
525              I->getOpcode() != Instruction::FDiv))
526     return false;
527 
528   Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
529   Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
530 
531   if (C0 && C1)
532     return false;
533 
534   return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
535 }
536 
537 /// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
538 /// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
539 /// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
540 /// This function is to simplify "FMulOrDiv * C" and returns the
541 /// resulting expression. Note that this function could return NULL in
542 /// case the constants cannot be folded into a normal floating-point.
543 ///
544 Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
545                                    Instruction *InsertBefore) {
546   assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
547 
548   Value *Opnd0 = FMulOrDiv->getOperand(0);
549   Value *Opnd1 = FMulOrDiv->getOperand(1);
550 
551   Constant *C0 = dyn_cast<Constant>(Opnd0);
552   Constant *C1 = dyn_cast<Constant>(Opnd1);
553 
554   BinaryOperator *R = nullptr;
555 
556   // (X * C0) * C => X * (C0*C)
557   if (FMulOrDiv->getOpcode() == Instruction::FMul) {
558     Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
559     if (isNormalFp(F))
560       R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
561   } else {
562     if (C0) {
563       // (C0 / X) * C => (C0 * C) / X
564       if (FMulOrDiv->hasOneUse()) {
565         // It would otherwise introduce another div.
566         Constant *F = ConstantExpr::getFMul(C0, C);
567         if (isNormalFp(F))
568           R = BinaryOperator::CreateFDiv(F, Opnd1);
569       }
570     } else {
571       // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
572       Constant *F = ConstantExpr::getFDiv(C, C1);
573       if (isNormalFp(F)) {
574         R = BinaryOperator::CreateFMul(Opnd0, F);
575       } else {
576         // (X / C1) * C => X / (C1/C)
577         Constant *F = ConstantExpr::getFDiv(C1, C);
578         if (isNormalFp(F))
579           R = BinaryOperator::CreateFDiv(Opnd0, F);
580       }
581     }
582   }
583 
584   if (R) {
585     R->setHasUnsafeAlgebra(true);
586     InsertNewInstWith(R, *InsertBefore);
587   }
588 
589   return R;
590 }
591 
592 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
593   bool Changed = SimplifyAssociativeOrCommutative(I);
594   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
595 
596   if (Value *V = SimplifyVectorOp(I))
597     return replaceInstUsesWith(I, V);
598 
599   if (isa<Constant>(Op0))
600     std::swap(Op0, Op1);
601 
602   if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(),
603                                   SQ.getWithInstruction(&I)))
604     return replaceInstUsesWith(I, V);
605 
606   bool AllowReassociate = I.hasUnsafeAlgebra();
607 
608   // Simplify mul instructions with a constant RHS.
609   if (isa<Constant>(Op1)) {
610     if (Instruction *FoldedMul = foldOpWithConstantIntoOperand(I))
611       return FoldedMul;
612 
613     // (fmul X, -1.0) --> (fsub -0.0, X)
614     if (match(Op1, m_SpecificFP(-1.0))) {
615       Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
616       Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
617       RI->copyFastMathFlags(&I);
618       return RI;
619     }
620 
621     Constant *C = cast<Constant>(Op1);
622     if (AllowReassociate && isFiniteNonZeroFp(C)) {
623       // Let MDC denote an expression in one of these forms:
624       // X * C, C/X, X/C, where C is a constant.
625       //
626       // Try to simplify "MDC * Constant"
627       if (isFMulOrFDivWithConstant(Op0))
628         if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
629           return replaceInstUsesWith(I, V);
630 
631       // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
632       Instruction *FAddSub = dyn_cast<Instruction>(Op0);
633       if (FAddSub &&
634           (FAddSub->getOpcode() == Instruction::FAdd ||
635            FAddSub->getOpcode() == Instruction::FSub)) {
636         Value *Opnd0 = FAddSub->getOperand(0);
637         Value *Opnd1 = FAddSub->getOperand(1);
638         Constant *C0 = dyn_cast<Constant>(Opnd0);
639         Constant *C1 = dyn_cast<Constant>(Opnd1);
640         bool Swap = false;
641         if (C0) {
642           std::swap(C0, C1);
643           std::swap(Opnd0, Opnd1);
644           Swap = true;
645         }
646 
647         if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
648           Value *M1 = ConstantExpr::getFMul(C1, C);
649           Value *M0 = isNormalFp(cast<Constant>(M1)) ?
650                       foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
651                       nullptr;
652           if (M0 && M1) {
653             if (Swap && FAddSub->getOpcode() == Instruction::FSub)
654               std::swap(M0, M1);
655 
656             Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
657                                   ? BinaryOperator::CreateFAdd(M0, M1)
658                                   : BinaryOperator::CreateFSub(M0, M1);
659             RI->copyFastMathFlags(&I);
660             return RI;
661           }
662         }
663       }
664     }
665   }
666 
667   if (Op0 == Op1) {
668     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
669       // sqrt(X) * sqrt(X) -> X
670       if (AllowReassociate && II->getIntrinsicID() == Intrinsic::sqrt)
671         return replaceInstUsesWith(I, II->getOperand(0));
672 
673       // fabs(X) * fabs(X) -> X * X
674       if (II->getIntrinsicID() == Intrinsic::fabs) {
675         Instruction *FMulVal = BinaryOperator::CreateFMul(II->getOperand(0),
676                                                           II->getOperand(0),
677                                                           I.getName());
678         FMulVal->copyFastMathFlags(&I);
679         return FMulVal;
680       }
681     }
682   }
683 
684   // Under unsafe algebra do:
685   // X * log2(0.5*Y) = X*log2(Y) - X
686   if (AllowReassociate) {
687     Value *OpX = nullptr;
688     Value *OpY = nullptr;
689     IntrinsicInst *Log2;
690     detectLog2OfHalf(Op0, OpY, Log2);
691     if (OpY) {
692       OpX = Op1;
693     } else {
694       detectLog2OfHalf(Op1, OpY, Log2);
695       if (OpY) {
696         OpX = Op0;
697       }
698     }
699     // if pattern detected emit alternate sequence
700     if (OpX && OpY) {
701       BuilderTy::FastMathFlagGuard Guard(Builder);
702       Builder.setFastMathFlags(Log2->getFastMathFlags());
703       Log2->setArgOperand(0, OpY);
704       Value *FMulVal = Builder.CreateFMul(OpX, Log2);
705       Value *FSub = Builder.CreateFSub(FMulVal, OpX);
706       FSub->takeName(&I);
707       return replaceInstUsesWith(I, FSub);
708     }
709   }
710 
711   // Handle symmetric situation in a 2-iteration loop
712   Value *Opnd0 = Op0;
713   Value *Opnd1 = Op1;
714   for (int i = 0; i < 2; i++) {
715     bool IgnoreZeroSign = I.hasNoSignedZeros();
716     if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
717       BuilderTy::FastMathFlagGuard Guard(Builder);
718       Builder.setFastMathFlags(I.getFastMathFlags());
719 
720       Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
721       Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
722 
723       // -X * -Y => X*Y
724       if (N1) {
725         Value *FMul = Builder.CreateFMul(N0, N1);
726         FMul->takeName(&I);
727         return replaceInstUsesWith(I, FMul);
728       }
729 
730       if (Opnd0->hasOneUse()) {
731         // -X * Y => -(X*Y) (Promote negation as high as possible)
732         Value *T = Builder.CreateFMul(N0, Opnd1);
733         Value *Neg = Builder.CreateFNeg(T);
734         Neg->takeName(&I);
735         return replaceInstUsesWith(I, Neg);
736       }
737     }
738 
739     // Handle specials cases for FMul with selects feeding the operation
740     if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
741       return replaceInstUsesWith(I, V);
742 
743     // (X*Y) * X => (X*X) * Y where Y != X
744     //  The purpose is two-fold:
745     //   1) to form a power expression (of X).
746     //   2) potentially shorten the critical path: After transformation, the
747     //  latency of the instruction Y is amortized by the expression of X*X,
748     //  and therefore Y is in a "less critical" position compared to what it
749     //  was before the transformation.
750     //
751     if (AllowReassociate) {
752       Value *Opnd0_0, *Opnd0_1;
753       if (Opnd0->hasOneUse() &&
754           match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
755         Value *Y = nullptr;
756         if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
757           Y = Opnd0_1;
758         else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
759           Y = Opnd0_0;
760 
761         if (Y) {
762           BuilderTy::FastMathFlagGuard Guard(Builder);
763           Builder.setFastMathFlags(I.getFastMathFlags());
764           Value *T = Builder.CreateFMul(Opnd1, Opnd1);
765           Value *R = Builder.CreateFMul(T, Y);
766           R->takeName(&I);
767           return replaceInstUsesWith(I, R);
768         }
769       }
770     }
771 
772     if (!isa<Constant>(Op1))
773       std::swap(Opnd0, Opnd1);
774     else
775       break;
776   }
777 
778   return Changed ? &I : nullptr;
779 }
780 
781 /// Fold a divide or remainder with a select instruction divisor when one of the
782 /// select operands is zero. In that case, we can use the other select operand
783 /// because div/rem by zero is undefined.
784 bool InstCombiner::simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I) {
785   SelectInst *SI = dyn_cast<SelectInst>(I.getOperand(1));
786   if (!SI)
787     return false;
788 
789   int NonNullOperand;
790   if (match(SI->getTrueValue(), m_Zero()))
791     // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
792     NonNullOperand = 2;
793   else if (match(SI->getFalseValue(), m_Zero()))
794     // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
795     NonNullOperand = 1;
796   else
797     return false;
798 
799   // Change the div/rem to use 'Y' instead of the select.
800   I.setOperand(1, SI->getOperand(NonNullOperand));
801 
802   // Okay, we know we replace the operand of the div/rem with 'Y' with no
803   // problem.  However, the select, or the condition of the select may have
804   // multiple uses.  Based on our knowledge that the operand must be non-zero,
805   // propagate the known value for the select into other uses of it, and
806   // propagate a known value of the condition into its other users.
807 
808   // If the select and condition only have a single use, don't bother with this,
809   // early exit.
810   Value *SelectCond = SI->getCondition();
811   if (SI->use_empty() && SelectCond->hasOneUse())
812     return true;
813 
814   // Scan the current block backward, looking for other uses of SI.
815   BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
816   Type *CondTy = SelectCond->getType();
817   while (BBI != BBFront) {
818     --BBI;
819     // If we found a call to a function, we can't assume it will return, so
820     // information from below it cannot be propagated above it.
821     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
822       break;
823 
824     // Replace uses of the select or its condition with the known values.
825     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
826          I != E; ++I) {
827       if (*I == SI) {
828         *I = SI->getOperand(NonNullOperand);
829         Worklist.Add(&*BBI);
830       } else if (*I == SelectCond) {
831         *I = NonNullOperand == 1 ? ConstantInt::getTrue(CondTy)
832                                  : ConstantInt::getFalse(CondTy);
833         Worklist.Add(&*BBI);
834       }
835     }
836 
837     // If we past the instruction, quit looking for it.
838     if (&*BBI == SI)
839       SI = nullptr;
840     if (&*BBI == SelectCond)
841       SelectCond = nullptr;
842 
843     // If we ran out of things to eliminate, break out of the loop.
844     if (!SelectCond && !SI)
845       break;
846 
847   }
848   return true;
849 }
850 
851 
852 /// This function implements the transforms common to both integer division
853 /// instructions (udiv and sdiv). It is called by the visitors to those integer
854 /// division instructions.
855 /// @brief Common integer divide transforms
856 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
857   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
858 
859   // The RHS is known non-zero.
860   if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
861     I.setOperand(1, V);
862     return &I;
863   }
864 
865   // Handle cases involving: [su]div X, (select Cond, Y, Z)
866   // This does not apply for fdiv.
867   if (simplifyDivRemOfSelectWithZeroOp(I))
868     return &I;
869 
870   if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
871     const APInt *C2;
872     if (match(Op1, m_APInt(C2))) {
873       Value *X;
874       const APInt *C1;
875       bool IsSigned = I.getOpcode() == Instruction::SDiv;
876 
877       // (X / C1) / C2  -> X / (C1*C2)
878       if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
879           (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
880         APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
881         if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
882           return BinaryOperator::Create(I.getOpcode(), X,
883                                         ConstantInt::get(I.getType(), Product));
884       }
885 
886       if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
887           (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
888         APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
889 
890         // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
891         if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
892           BinaryOperator *BO = BinaryOperator::Create(
893               I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
894           BO->setIsExact(I.isExact());
895           return BO;
896         }
897 
898         // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
899         if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
900           BinaryOperator *BO = BinaryOperator::Create(
901               Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
902           BO->setHasNoUnsignedWrap(
903               !IsSigned &&
904               cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
905           BO->setHasNoSignedWrap(
906               cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
907           return BO;
908         }
909       }
910 
911       if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
912            *C1 != C1->getBitWidth() - 1) ||
913           (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
914         APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
915         APInt C1Shifted = APInt::getOneBitSet(
916             C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
917 
918         // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
919         if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
920           BinaryOperator *BO = BinaryOperator::Create(
921               I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
922           BO->setIsExact(I.isExact());
923           return BO;
924         }
925 
926         // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
927         if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
928           BinaryOperator *BO = BinaryOperator::Create(
929               Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
930           BO->setHasNoUnsignedWrap(
931               !IsSigned &&
932               cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
933           BO->setHasNoSignedWrap(
934               cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
935           return BO;
936         }
937       }
938 
939       if (!C2->isNullValue()) // avoid X udiv 0
940         if (Instruction *FoldedDiv = foldOpWithConstantIntoOperand(I))
941           return FoldedDiv;
942     }
943   }
944 
945   if (match(Op0, m_One())) {
946     assert(!I.getType()->isIntOrIntVectorTy(1) && "i1 divide not removed?");
947     if (I.getOpcode() == Instruction::SDiv) {
948       // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
949       // result is one, if Op1 is -1 then the result is minus one, otherwise
950       // it's zero.
951       Value *Inc = Builder.CreateAdd(Op1, Op0);
952       Value *Cmp = Builder.CreateICmpULT(Inc, ConstantInt::get(I.getType(), 3));
953       return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
954     } else {
955       // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
956       // result is one, otherwise it's zero.
957       return new ZExtInst(Builder.CreateICmpEQ(Op1, Op0), I.getType());
958     }
959   }
960 
961   // See if we can fold away this div instruction.
962   if (SimplifyDemandedInstructionBits(I))
963     return &I;
964 
965   // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
966   Value *X = nullptr, *Z = nullptr;
967   if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
968     bool isSigned = I.getOpcode() == Instruction::SDiv;
969     if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
970         (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
971       return BinaryOperator::Create(I.getOpcode(), X, Op1);
972   }
973 
974   return nullptr;
975 }
976 
977 namespace {
978 const unsigned MaxDepth = 6;
979 typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
980                                           const BinaryOperator &I,
981                                           InstCombiner &IC);
982 
983 /// \brief Used to maintain state for visitUDivOperand().
984 struct UDivFoldAction {
985   FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
986                                 ///< operand.  This can be zero if this action
987                                 ///< joins two actions together.
988 
989   Value *OperandToFold;         ///< Which operand to fold.
990   union {
991     Instruction *FoldResult;    ///< The instruction returned when FoldAction is
992                                 ///< invoked.
993 
994     size_t SelectLHSIdx;        ///< Stores the LHS action index if this action
995                                 ///< joins two actions together.
996   };
997 
998   UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
999       : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
1000   UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
1001       : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
1002 };
1003 }
1004 
1005 // X udiv 2^C -> X >> C
1006 static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
1007                                     const BinaryOperator &I, InstCombiner &IC) {
1008   const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
1009   BinaryOperator *LShr = BinaryOperator::CreateLShr(
1010       Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
1011   if (I.isExact())
1012     LShr->setIsExact();
1013   return LShr;
1014 }
1015 
1016 // X udiv C, where C >= signbit
1017 static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
1018                                    const BinaryOperator &I, InstCombiner &IC) {
1019   Value *ICI = IC.Builder.CreateICmpULT(Op0, cast<ConstantInt>(Op1));
1020 
1021   return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
1022                             ConstantInt::get(I.getType(), 1));
1023 }
1024 
1025 // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
1026 // X udiv (zext (C1 << N)), where C1 is "1<<C2"  -->  X >> (N+C2)
1027 static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
1028                                 InstCombiner &IC) {
1029   Value *ShiftLeft;
1030   if (!match(Op1, m_ZExt(m_Value(ShiftLeft))))
1031     ShiftLeft = Op1;
1032 
1033   const APInt *CI;
1034   Value *N;
1035   if (!match(ShiftLeft, m_Shl(m_APInt(CI), m_Value(N))))
1036     llvm_unreachable("match should never fail here!");
1037   if (*CI != 1)
1038     N = IC.Builder.CreateAdd(N, ConstantInt::get(N->getType(), CI->logBase2()));
1039   if (Op1 != ShiftLeft)
1040     N = IC.Builder.CreateZExt(N, Op1->getType());
1041   BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
1042   if (I.isExact())
1043     LShr->setIsExact();
1044   return LShr;
1045 }
1046 
1047 // \brief Recursively visits the possible right hand operands of a udiv
1048 // instruction, seeing through select instructions, to determine if we can
1049 // replace the udiv with something simpler.  If we find that an operand is not
1050 // able to simplify the udiv, we abort the entire transformation.
1051 static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
1052                                SmallVectorImpl<UDivFoldAction> &Actions,
1053                                unsigned Depth = 0) {
1054   // Check to see if this is an unsigned division with an exact power of 2,
1055   // if so, convert to a right shift.
1056   if (match(Op1, m_Power2())) {
1057     Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
1058     return Actions.size();
1059   }
1060 
1061   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
1062     // X udiv C, where C >= signbit
1063     if (C->getValue().isNegative()) {
1064       Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
1065       return Actions.size();
1066     }
1067 
1068   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
1069   if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
1070       match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
1071     Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
1072     return Actions.size();
1073   }
1074 
1075   // The remaining tests are all recursive, so bail out if we hit the limit.
1076   if (Depth++ == MaxDepth)
1077     return 0;
1078 
1079   if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1080     if (size_t LHSIdx =
1081             visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
1082       if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
1083         Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
1084         return Actions.size();
1085       }
1086 
1087   return 0;
1088 }
1089 
1090 /// If we have zero-extended operands of an unsigned div or rem, we may be able
1091 /// to narrow the operation (sink the zext below the math).
1092 static Instruction *narrowUDivURem(BinaryOperator &I,
1093                                    InstCombiner::BuilderTy &Builder) {
1094   Instruction::BinaryOps Opcode = I.getOpcode();
1095   Value *N = I.getOperand(0);
1096   Value *D = I.getOperand(1);
1097   Type *Ty = I.getType();
1098   Value *X, *Y;
1099   if (match(N, m_ZExt(m_Value(X))) && match(D, m_ZExt(m_Value(Y))) &&
1100       X->getType() == Y->getType() && (N->hasOneUse() || D->hasOneUse())) {
1101     // udiv (zext X), (zext Y) --> zext (udiv X, Y)
1102     // urem (zext X), (zext Y) --> zext (urem X, Y)
1103     Value *NarrowOp = Builder.CreateBinOp(Opcode, X, Y);
1104     return new ZExtInst(NarrowOp, Ty);
1105   }
1106 
1107   Constant *C;
1108   if ((match(N, m_OneUse(m_ZExt(m_Value(X)))) && match(D, m_Constant(C))) ||
1109       (match(D, m_OneUse(m_ZExt(m_Value(X)))) && match(N, m_Constant(C)))) {
1110     // If the constant is the same in the smaller type, use the narrow version.
1111     Constant *TruncC = ConstantExpr::getTrunc(C, X->getType());
1112     if (ConstantExpr::getZExt(TruncC, Ty) != C)
1113       return nullptr;
1114 
1115     // udiv (zext X), C --> zext (udiv X, C')
1116     // urem (zext X), C --> zext (urem X, C')
1117     // udiv C, (zext X) --> zext (udiv C', X)
1118     // urem C, (zext X) --> zext (urem C', X)
1119     Value *NarrowOp = isa<Constant>(D) ? Builder.CreateBinOp(Opcode, X, TruncC)
1120                                        : Builder.CreateBinOp(Opcode, TruncC, X);
1121     return new ZExtInst(NarrowOp, Ty);
1122   }
1123 
1124   return nullptr;
1125 }
1126 
1127 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
1128   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1129 
1130   if (Value *V = SimplifyVectorOp(I))
1131     return replaceInstUsesWith(I, V);
1132 
1133   if (Value *V = SimplifyUDivInst(Op0, Op1, SQ.getWithInstruction(&I)))
1134     return replaceInstUsesWith(I, V);
1135 
1136   // Handle the integer div common cases
1137   if (Instruction *Common = commonIDivTransforms(I))
1138     return Common;
1139 
1140   // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
1141   {
1142     Value *X;
1143     const APInt *C1, *C2;
1144     if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
1145         match(Op1, m_APInt(C2))) {
1146       bool Overflow;
1147       APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
1148       if (!Overflow) {
1149         bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1150         BinaryOperator *BO = BinaryOperator::CreateUDiv(
1151             X, ConstantInt::get(X->getType(), C2ShlC1));
1152         if (IsExact)
1153           BO->setIsExact();
1154         return BO;
1155       }
1156     }
1157   }
1158 
1159   if (Instruction *NarrowDiv = narrowUDivURem(I, Builder))
1160     return NarrowDiv;
1161 
1162   // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1163   SmallVector<UDivFoldAction, 6> UDivActions;
1164   if (visitUDivOperand(Op0, Op1, I, UDivActions))
1165     for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1166       FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1167       Value *ActionOp1 = UDivActions[i].OperandToFold;
1168       Instruction *Inst;
1169       if (Action)
1170         Inst = Action(Op0, ActionOp1, I, *this);
1171       else {
1172         // This action joins two actions together.  The RHS of this action is
1173         // simply the last action we processed, we saved the LHS action index in
1174         // the joining action.
1175         size_t SelectRHSIdx = i - 1;
1176         Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1177         size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1178         Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1179         Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1180                                   SelectLHS, SelectRHS);
1181       }
1182 
1183       // If this is the last action to process, return it to the InstCombiner.
1184       // Otherwise, we insert it before the UDiv and record it so that we may
1185       // use it as part of a joining action (i.e., a SelectInst).
1186       if (e - i != 1) {
1187         Inst->insertBefore(&I);
1188         UDivActions[i].FoldResult = Inst;
1189       } else
1190         return Inst;
1191     }
1192 
1193   return nullptr;
1194 }
1195 
1196 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1197   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1198 
1199   if (Value *V = SimplifyVectorOp(I))
1200     return replaceInstUsesWith(I, V);
1201 
1202   if (Value *V = SimplifySDivInst(Op0, Op1, SQ.getWithInstruction(&I)))
1203     return replaceInstUsesWith(I, V);
1204 
1205   // Handle the integer div common cases
1206   if (Instruction *Common = commonIDivTransforms(I))
1207     return Common;
1208 
1209   const APInt *Op1C;
1210   if (match(Op1, m_APInt(Op1C))) {
1211     // sdiv X, -1 == -X
1212     if (Op1C->isAllOnesValue())
1213       return BinaryOperator::CreateNeg(Op0);
1214 
1215     // sdiv exact X, C  -->  ashr exact X, log2(C)
1216     if (I.isExact() && Op1C->isNonNegative() && Op1C->isPowerOf2()) {
1217       Value *ShAmt = ConstantInt::get(Op1->getType(), Op1C->exactLogBase2());
1218       return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1219     }
1220 
1221     // If the dividend is sign-extended and the constant divisor is small enough
1222     // to fit in the source type, shrink the division to the narrower type:
1223     // (sext X) sdiv C --> sext (X sdiv C)
1224     Value *Op0Src;
1225     if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1226         Op0Src->getType()->getScalarSizeInBits() >= Op1C->getMinSignedBits()) {
1227 
1228       // In the general case, we need to make sure that the dividend is not the
1229       // minimum signed value because dividing that by -1 is UB. But here, we
1230       // know that the -1 divisor case is already handled above.
1231 
1232       Constant *NarrowDivisor =
1233           ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType());
1234       Value *NarrowOp = Builder.CreateSDiv(Op0Src, NarrowDivisor);
1235       return new SExtInst(NarrowOp, Op0->getType());
1236     }
1237   }
1238 
1239   if (Constant *RHS = dyn_cast<Constant>(Op1)) {
1240     // X/INT_MIN -> X == INT_MIN
1241     if (RHS->isMinSignedValue())
1242       return new ZExtInst(Builder.CreateICmpEQ(Op0, Op1), I.getType());
1243 
1244     // -X/C  -->  X/-C  provided the negation doesn't overflow.
1245     Value *X;
1246     if (match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1247       auto *BO = BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(RHS));
1248       BO->setIsExact(I.isExact());
1249       return BO;
1250     }
1251   }
1252 
1253   // If the sign bits of both operands are zero (i.e. we can prove they are
1254   // unsigned inputs), turn this into a udiv.
1255   APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
1256   if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1257     if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
1258       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1259       auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1260       BO->setIsExact(I.isExact());
1261       return BO;
1262     }
1263 
1264     if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
1265       // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1266       // Safe because the only negative value (1 << Y) can take on is
1267       // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1268       // the sign bit set.
1269       auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1270       BO->setIsExact(I.isExact());
1271       return BO;
1272     }
1273   }
1274 
1275   return nullptr;
1276 }
1277 
1278 /// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1279 /// FP value and:
1280 ///    1) 1/C is exact, or
1281 ///    2) reciprocal is allowed.
1282 /// If the conversion was successful, the simplified expression "X * 1/C" is
1283 /// returned; otherwise, NULL is returned.
1284 ///
1285 static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
1286                                              bool AllowReciprocal) {
1287   if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
1288     return nullptr;
1289 
1290   const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
1291   APFloat Reciprocal(FpVal.getSemantics());
1292   bool Cvt = FpVal.getExactInverse(&Reciprocal);
1293 
1294   if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
1295     Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1296     (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1297     Cvt = !Reciprocal.isDenormal();
1298   }
1299 
1300   if (!Cvt)
1301     return nullptr;
1302 
1303   ConstantFP *R;
1304   R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1305   return BinaryOperator::CreateFMul(Dividend, R);
1306 }
1307 
1308 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1309   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1310 
1311   if (Value *V = SimplifyVectorOp(I))
1312     return replaceInstUsesWith(I, V);
1313 
1314   if (Value *V = SimplifyFDivInst(Op0, Op1, I.getFastMathFlags(),
1315                                   SQ.getWithInstruction(&I)))
1316     return replaceInstUsesWith(I, V);
1317 
1318   if (isa<Constant>(Op0))
1319     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1320       if (Instruction *R = FoldOpIntoSelect(I, SI))
1321         return R;
1322 
1323   bool AllowReassociate = I.hasUnsafeAlgebra();
1324   bool AllowReciprocal = I.hasAllowReciprocal();
1325 
1326   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1327     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1328       if (Instruction *R = FoldOpIntoSelect(I, SI))
1329         return R;
1330 
1331     if (AllowReassociate) {
1332       Constant *C1 = nullptr;
1333       Constant *C2 = Op1C;
1334       Value *X;
1335       Instruction *Res = nullptr;
1336 
1337       if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
1338         // (X*C1)/C2 => X * (C1/C2)
1339         //
1340         Constant *C = ConstantExpr::getFDiv(C1, C2);
1341         if (isNormalFp(C))
1342           Res = BinaryOperator::CreateFMul(X, C);
1343       } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
1344         // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1345         //
1346         Constant *C = ConstantExpr::getFMul(C1, C2);
1347         if (isNormalFp(C)) {
1348           Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
1349           if (!Res)
1350             Res = BinaryOperator::CreateFDiv(X, C);
1351         }
1352       }
1353 
1354       if (Res) {
1355         Res->setFastMathFlags(I.getFastMathFlags());
1356         return Res;
1357       }
1358     }
1359 
1360     // X / C => X * 1/C
1361     if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1362       T->copyFastMathFlags(&I);
1363       return T;
1364     }
1365 
1366     return nullptr;
1367   }
1368 
1369   if (AllowReassociate && isa<Constant>(Op0)) {
1370     Constant *C1 = cast<Constant>(Op0), *C2;
1371     Constant *Fold = nullptr;
1372     Value *X;
1373     bool CreateDiv = true;
1374 
1375     // C1 / (X*C2) => (C1/C2) / X
1376     if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
1377       Fold = ConstantExpr::getFDiv(C1, C2);
1378     else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
1379       // C1 / (X/C2) => (C1*C2) / X
1380       Fold = ConstantExpr::getFMul(C1, C2);
1381     } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
1382       // C1 / (C2/X) => (C1/C2) * X
1383       Fold = ConstantExpr::getFDiv(C1, C2);
1384       CreateDiv = false;
1385     }
1386 
1387     if (Fold && isNormalFp(Fold)) {
1388       Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1389                                  : BinaryOperator::CreateFMul(X, Fold);
1390       R->setFastMathFlags(I.getFastMathFlags());
1391       return R;
1392     }
1393     return nullptr;
1394   }
1395 
1396   if (AllowReassociate) {
1397     Value *X, *Y;
1398     Value *NewInst = nullptr;
1399     Instruction *SimpR = nullptr;
1400 
1401     if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1402       // (X/Y) / Z => X / (Y*Z)
1403       //
1404       if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
1405         NewInst = Builder.CreateFMul(Y, Op1);
1406         if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1407           FastMathFlags Flags = I.getFastMathFlags();
1408           Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1409           RI->setFastMathFlags(Flags);
1410         }
1411         SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1412       }
1413     } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1414       // Z / (X/Y) => Z*Y / X
1415       //
1416       if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
1417         NewInst = Builder.CreateFMul(Op0, Y);
1418         if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1419           FastMathFlags Flags = I.getFastMathFlags();
1420           Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1421           RI->setFastMathFlags(Flags);
1422         }
1423         SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1424       }
1425     }
1426 
1427     if (NewInst) {
1428       if (Instruction *T = dyn_cast<Instruction>(NewInst))
1429         T->setDebugLoc(I.getDebugLoc());
1430       SimpR->setFastMathFlags(I.getFastMathFlags());
1431       return SimpR;
1432     }
1433   }
1434 
1435   Value *LHS;
1436   Value *RHS;
1437 
1438   // -x / -y -> x / y
1439   if (match(Op0, m_FNeg(m_Value(LHS))) && match(Op1, m_FNeg(m_Value(RHS)))) {
1440     I.setOperand(0, LHS);
1441     I.setOperand(1, RHS);
1442     return &I;
1443   }
1444 
1445   return nullptr;
1446 }
1447 
1448 /// This function implements the transforms common to both integer remainder
1449 /// instructions (urem and srem). It is called by the visitors to those integer
1450 /// remainder instructions.
1451 /// @brief Common integer remainder transforms
1452 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1453   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1454 
1455   // The RHS is known non-zero.
1456   if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
1457     I.setOperand(1, V);
1458     return &I;
1459   }
1460 
1461   // Handle cases involving: rem X, (select Cond, Y, Z)
1462   if (simplifyDivRemOfSelectWithZeroOp(I))
1463     return &I;
1464 
1465   if (isa<Constant>(Op1)) {
1466     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1467       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1468         if (Instruction *R = FoldOpIntoSelect(I, SI))
1469           return R;
1470       } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
1471         using namespace llvm::PatternMatch;
1472         const APInt *Op1Int;
1473         if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
1474             (I.getOpcode() == Instruction::URem ||
1475              !Op1Int->isMinSignedValue())) {
1476           // foldOpIntoPhi will speculate instructions to the end of the PHI's
1477           // predecessor blocks, so do this only if we know the srem or urem
1478           // will not fault.
1479           if (Instruction *NV = foldOpIntoPhi(I, PN))
1480             return NV;
1481         }
1482       }
1483 
1484       // See if we can fold away this rem instruction.
1485       if (SimplifyDemandedInstructionBits(I))
1486         return &I;
1487     }
1488   }
1489 
1490   return nullptr;
1491 }
1492 
1493 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1494   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1495 
1496   if (Value *V = SimplifyVectorOp(I))
1497     return replaceInstUsesWith(I, V);
1498 
1499   if (Value *V = SimplifyURemInst(Op0, Op1, SQ.getWithInstruction(&I)))
1500     return replaceInstUsesWith(I, V);
1501 
1502   if (Instruction *common = commonIRemTransforms(I))
1503     return common;
1504 
1505   if (Instruction *NarrowRem = narrowUDivURem(I, Builder))
1506     return NarrowRem;
1507 
1508   // X urem Y -> X and Y-1, where Y is a power of 2,
1509   if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/ true, 0, &I)) {
1510     Constant *N1 = Constant::getAllOnesValue(I.getType());
1511     Value *Add = Builder.CreateAdd(Op1, N1);
1512     return BinaryOperator::CreateAnd(Op0, Add);
1513   }
1514 
1515   // 1 urem X -> zext(X != 1)
1516   if (match(Op0, m_One())) {
1517     Value *Cmp = Builder.CreateICmpNE(Op1, Op0);
1518     Value *Ext = Builder.CreateZExt(Cmp, I.getType());
1519     return replaceInstUsesWith(I, Ext);
1520   }
1521 
1522   // X urem C -> X < C ? X : X - C, where C >= signbit.
1523   const APInt *DivisorC;
1524   if (match(Op1, m_APInt(DivisorC)) && DivisorC->isNegative()) {
1525     Value *Cmp = Builder.CreateICmpULT(Op0, Op1);
1526     Value *Sub = Builder.CreateSub(Op0, Op1);
1527     return SelectInst::Create(Cmp, Op0, Sub);
1528   }
1529 
1530   return nullptr;
1531 }
1532 
1533 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1534   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1535 
1536   if (Value *V = SimplifyVectorOp(I))
1537     return replaceInstUsesWith(I, V);
1538 
1539   if (Value *V = SimplifySRemInst(Op0, Op1, SQ.getWithInstruction(&I)))
1540     return replaceInstUsesWith(I, V);
1541 
1542   // Handle the integer rem common cases
1543   if (Instruction *Common = commonIRemTransforms(I))
1544     return Common;
1545 
1546   {
1547     const APInt *Y;
1548     // X % -Y -> X % Y
1549     if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
1550       Worklist.AddValue(I.getOperand(1));
1551       I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
1552       return &I;
1553     }
1554   }
1555 
1556   // If the sign bits of both operands are zero (i.e. we can prove they are
1557   // unsigned inputs), turn this into a urem.
1558   APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
1559   if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1560       MaskedValueIsZero(Op0, Mask, 0, &I)) {
1561     // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1562     return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1563   }
1564 
1565   // If it's a constant vector, flip any negative values positive.
1566   if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1567     Constant *C = cast<Constant>(Op1);
1568     unsigned VWidth = C->getType()->getVectorNumElements();
1569 
1570     bool hasNegative = false;
1571     bool hasMissing = false;
1572     for (unsigned i = 0; i != VWidth; ++i) {
1573       Constant *Elt = C->getAggregateElement(i);
1574       if (!Elt) {
1575         hasMissing = true;
1576         break;
1577       }
1578 
1579       if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
1580         if (RHS->isNegative())
1581           hasNegative = true;
1582     }
1583 
1584     if (hasNegative && !hasMissing) {
1585       SmallVector<Constant *, 16> Elts(VWidth);
1586       for (unsigned i = 0; i != VWidth; ++i) {
1587         Elts[i] = C->getAggregateElement(i);  // Handle undef, etc.
1588         if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
1589           if (RHS->isNegative())
1590             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
1591         }
1592       }
1593 
1594       Constant *NewRHSV = ConstantVector::get(Elts);
1595       if (NewRHSV != C) {  // Don't loop on -MININT
1596         Worklist.AddValue(I.getOperand(1));
1597         I.setOperand(1, NewRHSV);
1598         return &I;
1599       }
1600     }
1601   }
1602 
1603   return nullptr;
1604 }
1605 
1606 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
1607   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1608 
1609   if (Value *V = SimplifyVectorOp(I))
1610     return replaceInstUsesWith(I, V);
1611 
1612   if (Value *V = SimplifyFRemInst(Op0, Op1, I.getFastMathFlags(),
1613                                   SQ.getWithInstruction(&I)))
1614     return replaceInstUsesWith(I, V);
1615 
1616   // Handle cases involving: rem X, (select Cond, Y, Z)
1617   if (simplifyDivRemOfSelectWithZeroOp(I))
1618     return &I;
1619 
1620   return nullptr;
1621 }
1622