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