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