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