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