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