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