blob: 5ea25bf5c9dbb18692ccd2e88203bd626ee314ba [file] [log] [blame]
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001//===- InstCombineMulDivRem.cpp -------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visit functions for mul, fmul, sdiv, udiv, fdiv,
11// srem, urem, frem.
12//
13//===----------------------------------------------------------------------===//
14
15#include "InstCombine.h"
Duncan Sandsd0eb6d32010-12-21 14:00:22 +000016#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000018#include "llvm/IR/PatternMatch.h"
Chris Lattnerdc054bf2010-01-05 06:09:35 +000019using namespace llvm;
20using namespace PatternMatch;
21
Chandler Carruth964daaa2014-04-22 02:55:47 +000022#define DEBUG_TYPE "instcombine"
23
Chris Lattner7c99f192011-05-22 18:18:41 +000024
25/// simplifyValueKnownNonZero - The specific integer value is used in a context
26/// where it is known to be non-zero. If this allows us to simplify the
27/// computation, do so and return the new operand, otherwise return null.
Hal Finkel60db0582014-09-07 18:57:58 +000028static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC,
29 Instruction *CxtI) {
Chris Lattner7c99f192011-05-22 18:18:41 +000030 // If V has multiple uses, then we would have to do more analysis to determine
31 // if this is safe. For example, the use could be in dynamically unreached
32 // code.
Craig Topperf40110f2014-04-25 05:29:35 +000033 if (!V->hasOneUse()) return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000034
Chris Lattner388cb8a2011-05-23 00:32:19 +000035 bool MadeChange = false;
36
Chris Lattner7c99f192011-05-22 18:18:41 +000037 // ((1 << A) >>u B) --> (1 << (A-B))
38 // Because V cannot be zero, we know that B is less than A.
David Majnemerdad21032014-10-14 20:28:40 +000039 Value *A = nullptr, *B = nullptr, *One = nullptr;
40 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) &&
41 match(One, m_One())) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +000042 A = IC.Builder->CreateSub(A, B);
David Majnemerdad21032014-10-14 20:28:40 +000043 return IC.Builder->CreateShl(One, A);
Chris Lattner7c99f192011-05-22 18:18:41 +000044 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000045
Chris Lattner388cb8a2011-05-23 00:32:19 +000046 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
47 // inexact. Similarly for <<.
48 if (BinaryOperator *I = dyn_cast<BinaryOperator>(V))
Hal Finkel60db0582014-09-07 18:57:58 +000049 if (I->isLogicalShift() && isKnownToBeAPowerOfTwo(I->getOperand(0), false,
50 0, IC.getAssumptionTracker(),
51 CxtI,
52 IC.getDominatorTree())) {
Chris Lattner388cb8a2011-05-23 00:32:19 +000053 // We know that this is an exact/nuw shift and that the input is a
54 // non-zero context as well.
Hal Finkel60db0582014-09-07 18:57:58 +000055 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
Chris Lattner388cb8a2011-05-23 00:32:19 +000056 I->setOperand(0, V2);
57 MadeChange = true;
58 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000059
Chris Lattner388cb8a2011-05-23 00:32:19 +000060 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
61 I->setIsExact();
62 MadeChange = true;
63 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000064
Chris Lattner388cb8a2011-05-23 00:32:19 +000065 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
66 I->setHasNoUnsignedWrap();
67 MadeChange = true;
68 }
69 }
70
Chris Lattner162dfc32011-05-22 18:26:48 +000071 // TODO: Lots more we could do here:
Chris Lattner162dfc32011-05-22 18:26:48 +000072 // If V is a phi node, we can call this on each of its operands.
73 // "select cond, X, 0" can simplify to "X".
Jim Grosbachbdbd7342013-04-05 21:20:12 +000074
Craig Topperf40110f2014-04-25 05:29:35 +000075 return MadeChange ? V : nullptr;
Chris Lattner7c99f192011-05-22 18:18:41 +000076}
77
78
Chris Lattnerdc054bf2010-01-05 06:09:35 +000079/// MultiplyOverflows - True if the multiply can not be expressed in an int
80/// this size.
David Majnemer27adb122014-10-12 08:34:24 +000081static bool MultiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
82 bool IsSigned) {
83 bool Overflow;
84 if (IsSigned)
85 Product = C1.smul_ov(C2, Overflow);
86 else
87 Product = C1.umul_ov(C2, Overflow);
Jim Grosbachbdbd7342013-04-05 21:20:12 +000088
David Majnemer27adb122014-10-12 08:34:24 +000089 return Overflow;
Chris Lattnerdc054bf2010-01-05 06:09:35 +000090}
91
David Majnemerf9a095d2014-08-16 08:55:06 +000092/// \brief True if C2 is a multiple of C1. Quotient contains C2/C1.
93static bool IsMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
94 bool IsSigned) {
95 assert(C1.getBitWidth() == C2.getBitWidth() &&
96 "Inconsistent width of constants!");
97
98 APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
99 if (IsSigned)
100 APInt::sdivrem(C1, C2, Quotient, Remainder);
101 else
102 APInt::udivrem(C1, C2, Quotient, Remainder);
103
104 return Remainder.isMinValue();
105}
106
Rafael Espindola65281bf2013-05-31 14:27:15 +0000107/// \brief A helper routine of InstCombiner::visitMul().
108///
109/// If C is a vector of known powers of 2, then this function returns
110/// a new vector obtained from C replacing each element with its logBase2.
111/// Return a null pointer otherwise.
112static Constant *getLogBase2Vector(ConstantDataVector *CV) {
113 const APInt *IVal;
114 SmallVector<Constant *, 4> Elts;
115
116 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
117 Constant *Elt = CV->getElementAsConstant(I);
118 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
Craig Topperf40110f2014-04-25 05:29:35 +0000119 return nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000120 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
121 }
122
123 return ConstantVector::get(Elts);
124}
125
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000126Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000127 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000128 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
129
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000130 if (Value *V = SimplifyVectorOp(I))
131 return ReplaceInstUsesWith(I, V);
132
Hal Finkel60db0582014-09-07 18:57:58 +0000133 if (Value *V = SimplifyMulInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000134 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000135
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000136 if (Value *V = SimplifyUsingDistributiveLaws(I))
137 return ReplaceInstUsesWith(I, V);
138
David Majnemer027bc802014-11-22 04:52:38 +0000139 // X * -1 == 0 - X
140 if (match(Op1, m_AllOnes())) {
141 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
142 if (I.hasNoSignedWrap())
143 BO->setHasNoSignedWrap();
144 return BO;
145 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000146
Rafael Espindola65281bf2013-05-31 14:27:15 +0000147 // Also allow combining multiply instructions on vectors.
148 {
149 Value *NewOp;
150 Constant *C1, *C2;
151 const APInt *IVal;
152 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
153 m_Constant(C1))) &&
David Majnemerfd4a6d22014-11-22 04:52:52 +0000154 match(C1, m_APInt(IVal))) {
155 // ((X << C2)*C1) == (X * (C1 << C2))
156 Constant *Shl = ConstantExpr::getShl(C1, C2);
157 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
158 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
159 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
160 BO->setHasNoUnsignedWrap();
161 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
162 Shl->isNotMinSignedValue())
163 BO->setHasNoSignedWrap();
164 return BO;
165 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000166
Rafael Espindola65281bf2013-05-31 14:27:15 +0000167 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000168 Constant *NewCst = nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000169 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
170 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
171 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
172 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
173 // Replace X*(2^C) with X << C, where C is a vector of known
174 // constant powers of 2.
175 NewCst = getLogBase2Vector(CV);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000176
Rafael Espindola65281bf2013-05-31 14:27:15 +0000177 if (NewCst) {
178 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000179
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000180 if (I.hasNoUnsignedWrap())
181 Shl->setHasNoUnsignedWrap();
David Majnemer80c8f622014-11-22 04:52:55 +0000182 if (I.hasNoSignedWrap() && NewCst->isNotMinSignedValue())
183 Shl->setHasNoSignedWrap();
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000184
Rafael Espindola65281bf2013-05-31 14:27:15 +0000185 return Shl;
186 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000187 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000188 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000189
Rafael Espindola65281bf2013-05-31 14:27:15 +0000190 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Stuart Hastings23804832011-06-01 16:42:47 +0000191 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
192 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
193 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000194 {
195 const APInt & Val = CI->getValue();
196 const APInt &PosVal = Val.abs();
197 if (Val.isNegative() && PosVal.isPowerOf2()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000198 Value *X = nullptr, *Y = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000199 if (Op0->hasOneUse()) {
200 ConstantInt *C1;
Craig Topperf40110f2014-04-25 05:29:35 +0000201 Value *Sub = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000202 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
203 Sub = Builder->CreateSub(X, Y, "suba");
204 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
205 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
206 if (Sub)
207 return
208 BinaryOperator::CreateMul(Sub,
209 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000210 }
211 }
212 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000213 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000214
Chris Lattner6b657ae2011-02-10 05:36:31 +0000215 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000216 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000217 // Try to fold constant mul into select arguments.
218 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
219 if (Instruction *R = FoldOpIntoSelect(I, SI))
220 return R;
221
222 if (isa<PHINode>(Op0))
223 if (Instruction *NV = FoldOpIntoPhi(I))
224 return NV;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000225
226 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
227 {
228 Value *X;
229 Constant *C1;
230 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
David Majnemer6cf6c052014-06-19 07:14:33 +0000231 Value *Mul = Builder->CreateMul(C1, Op1);
232 // Only go forward with the transform if C1*CI simplifies to a tidier
233 // constant.
234 if (!match(Mul, m_Mul(m_Value(), m_Value())))
235 return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
Benjamin Kramer72196f32014-01-19 15:24:22 +0000236 }
237 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000238 }
239
240 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
241 if (Value *Op1v = dyn_castNegVal(Op1))
242 return BinaryOperator::CreateMul(Op0v, Op1v);
243
244 // (X / Y) * Y = X - (X % Y)
245 // (X / Y) * -Y = (X % Y) - X
246 {
247 Value *Op1C = Op1;
248 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
249 if (!BO ||
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000250 (BO->getOpcode() != Instruction::UDiv &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000251 BO->getOpcode() != Instruction::SDiv)) {
252 Op1C = Op0;
253 BO = dyn_cast<BinaryOperator>(Op1);
254 }
255 Value *Neg = dyn_castNegVal(Op1C);
256 if (BO && BO->hasOneUse() &&
257 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
258 (BO->getOpcode() == Instruction::UDiv ||
259 BO->getOpcode() == Instruction::SDiv)) {
260 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
261
Chris Lattner35315d02011-02-06 21:44:57 +0000262 // If the division is exact, X % Y is zero, so we end up with X or -X.
263 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000264 if (SDiv->isExact()) {
265 if (Op1BO == Op1C)
266 return ReplaceInstUsesWith(I, Op0BO);
267 return BinaryOperator::CreateNeg(Op0BO);
268 }
269
270 Value *Rem;
271 if (BO->getOpcode() == Instruction::UDiv)
272 Rem = Builder->CreateURem(Op0BO, Op1BO);
273 else
274 Rem = Builder->CreateSRem(Op0BO, Op1BO);
275 Rem->takeName(BO);
276
277 if (Op1BO == Op1C)
278 return BinaryOperator::CreateSub(Op0BO, Rem);
279 return BinaryOperator::CreateSub(Rem, Op0BO);
280 }
281 }
282
283 /// i1 mul -> i1 and.
Benjamin Kramer72196f32014-01-19 15:24:22 +0000284 if (I.getType()->getScalarType()->isIntegerTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000285 return BinaryOperator::CreateAnd(Op0, Op1);
286
287 // X*(1 << Y) --> X << Y
288 // (1 << Y)*X --> X << Y
289 {
290 Value *Y;
291 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
292 return BinaryOperator::CreateShl(Op1, Y);
293 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
294 return BinaryOperator::CreateShl(Op0, Y);
295 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000296
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000297 // If one of the operands of the multiply is a cast from a boolean value, then
298 // we know the bool is either zero or one, so this is a 'masking' multiply.
299 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands19d0b472010-02-16 11:11:14 +0000300 if (!I.getType()->isVectorTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000301 // -2 is "-1 << 1" so it is all bits set except the low one.
302 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000303
Craig Topperf40110f2014-04-25 05:29:35 +0000304 Value *BoolCast = nullptr, *OtherOp = nullptr;
Hal Finkel60db0582014-09-07 18:57:58 +0000305 if (MaskedValueIsZero(Op0, Negative2, 0, &I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000306 BoolCast = Op0, OtherOp = Op1;
Hal Finkel60db0582014-09-07 18:57:58 +0000307 else if (MaskedValueIsZero(Op1, Negative2, 0, &I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000308 BoolCast = Op1, OtherOp = Op0;
309
310 if (BoolCast) {
311 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000312 BoolCast);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000313 return BinaryOperator::CreateAnd(V, OtherOp);
314 }
315 }
316
Craig Topperf40110f2014-04-25 05:29:35 +0000317 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000318}
319
Sanjay Patel17045f72014-10-14 00:33:23 +0000320/// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
Pedro Artigas993acd02012-11-30 22:07:05 +0000321static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Sanjay Patel17045f72014-10-14 00:33:23 +0000322 if (!Op->hasOneUse())
323 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000324
Sanjay Patel17045f72014-10-14 00:33:23 +0000325 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
326 if (!II)
327 return;
328 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
329 return;
330 Log2 = II;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000331
Sanjay Patel17045f72014-10-14 00:33:23 +0000332 Value *OpLog2Of = II->getArgOperand(0);
333 if (!OpLog2Of->hasOneUse())
334 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000335
Sanjay Patel17045f72014-10-14 00:33:23 +0000336 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
337 if (!I)
338 return;
339 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
340 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000341
Sanjay Patel17045f72014-10-14 00:33:23 +0000342 if (match(I->getOperand(0), m_SpecificFP(0.5)))
343 Y = I->getOperand(1);
344 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
345 Y = I->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000346}
Pedro Artigas993acd02012-11-30 22:07:05 +0000347
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000348static bool isFiniteNonZeroFp(Constant *C) {
349 if (C->getType()->isVectorTy()) {
350 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
351 ++I) {
352 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
353 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
354 return false;
355 }
356 return true;
357 }
358
359 return isa<ConstantFP>(C) &&
360 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
361}
362
363static bool isNormalFp(Constant *C) {
364 if (C->getType()->isVectorTy()) {
365 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
366 ++I) {
367 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
368 if (!CFP || !CFP->getValueAPF().isNormal())
369 return false;
370 }
371 return true;
372 }
373
374 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
375}
376
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000377/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
378/// true iff the given value is FMul or FDiv with one and only one operand
379/// being a normal constant (i.e. not Zero/NaN/Infinity).
380static bool isFMulOrFDivWithConstant(Value *V) {
381 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000382 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yang80138662013-01-07 22:41:28 +0000383 I->getOpcode() != Instruction::FDiv))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000384 return false;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000385
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000386 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
387 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000388
389 if (C0 && C1)
390 return false;
391
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000392 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000393}
394
395/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
396/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
397/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000398/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000399/// resulting expression. Note that this function could return NULL in
400/// case the constants cannot be folded into a normal floating-point.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000401///
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000402Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yang80138662013-01-07 22:41:28 +0000403 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000404 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
405
406 Value *Opnd0 = FMulOrDiv->getOperand(0);
407 Value *Opnd1 = FMulOrDiv->getOperand(1);
408
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000409 Constant *C0 = dyn_cast<Constant>(Opnd0);
410 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000411
Craig Topperf40110f2014-04-25 05:29:35 +0000412 BinaryOperator *R = nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000413
414 // (X * C0) * C => X * (C0*C)
415 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
416 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000417 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000418 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
419 } else {
420 if (C0) {
421 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000422 if (FMulOrDiv->hasOneUse()) {
423 // It would otherwise introduce another div.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000424 Constant *F = ConstantExpr::getFMul(C0, C);
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000425 if (isNormalFp(F))
426 R = BinaryOperator::CreateFDiv(F, Opnd1);
427 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000428 } else {
429 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000430 Constant *F = ConstantExpr::getFDiv(C, C1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000431 if (isNormalFp(F)) {
432 R = BinaryOperator::CreateFMul(Opnd0, F);
433 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000434 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000435 Constant *F = ConstantExpr::getFDiv(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000436 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000437 R = BinaryOperator::CreateFDiv(Opnd0, F);
438 }
439 }
440 }
441
442 if (R) {
443 R->setHasUnsafeAlgebra(true);
444 InsertNewInstWith(R, *InsertBefore);
445 }
446
447 return R;
448}
449
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000450Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000451 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000452 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
453
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000454 if (Value *V = SimplifyVectorOp(I))
455 return ReplaceInstUsesWith(I, V);
456
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000457 if (isa<Constant>(Op0))
458 std::swap(Op0, Op1);
459
Hal Finkel60db0582014-09-07 18:57:58 +0000460 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL, TLI,
461 DT, AT))
Michael Ilsemand5787be2012-12-12 00:28:32 +0000462 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000463
Shuxin Yange8227452013-01-15 21:09:32 +0000464 bool AllowReassociate = I.hasUnsafeAlgebra();
465
Michael Ilsemand5787be2012-12-12 00:28:32 +0000466 // Simplify mul instructions with a constant RHS.
467 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000468 // Try to fold constant mul into select arguments.
469 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
470 if (Instruction *R = FoldOpIntoSelect(I, SI))
471 return R;
472
473 if (isa<PHINode>(Op0))
474 if (Instruction *NV = FoldOpIntoPhi(I))
475 return NV;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000476
Owen Andersonf74cfe02014-01-16 20:36:42 +0000477 // (fmul X, -1.0) --> (fsub -0.0, X)
Benjamin Kramerfea9ac92014-01-18 16:43:14 +0000478 if (match(Op1, m_SpecificFP(-1.0))) {
479 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
480 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000481 RI->copyFastMathFlags(&I);
482 return RI;
483 }
484
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000485 Constant *C = cast<Constant>(Op1);
486 if (AllowReassociate && isFiniteNonZeroFp(C)) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000487 // Let MDC denote an expression in one of these forms:
488 // X * C, C/X, X/C, where C is a constant.
489 //
490 // Try to simplify "MDC * Constant"
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000491 if (isFMulOrFDivWithConstant(Op0))
492 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000493 return ReplaceInstUsesWith(I, V);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000494
Quentin Colombete684a6d2013-02-28 21:12:40 +0000495 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000496 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
497 if (FAddSub &&
498 (FAddSub->getOpcode() == Instruction::FAdd ||
499 FAddSub->getOpcode() == Instruction::FSub)) {
500 Value *Opnd0 = FAddSub->getOperand(0);
501 Value *Opnd1 = FAddSub->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000502 Constant *C0 = dyn_cast<Constant>(Opnd0);
503 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000504 bool Swap = false;
505 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000506 std::swap(C0, C1);
507 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000508 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000509 }
510
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000511 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000512 Value *M1 = ConstantExpr::getFMul(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000513 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000514 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
Craig Topperf40110f2014-04-25 05:29:35 +0000515 nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000516 if (M0 && M1) {
517 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
518 std::swap(M0, M1);
519
Benjamin Kramer67485762013-09-30 15:39:59 +0000520 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
521 ? BinaryOperator::CreateFAdd(M0, M1)
522 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000523 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000524 return RI;
525 }
526 }
527 }
528 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000529 }
530
Sanjay Patel12d1ce52014-10-02 21:10:54 +0000531 // sqrt(X) * sqrt(X) -> X
532 if (AllowReassociate && (Op0 == Op1))
533 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0))
534 if (II->getIntrinsicID() == Intrinsic::sqrt)
535 return ReplaceInstUsesWith(I, II->getOperand(0));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000536
Pedro Artigasd8795042012-11-30 19:09:41 +0000537 // Under unsafe algebra do:
538 // X * log2(0.5*Y) = X*log2(Y) - X
Sanjay Patelb41d4612014-10-02 15:20:45 +0000539 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +0000540 Value *OpX = nullptr;
541 Value *OpY = nullptr;
Pedro Artigasd8795042012-11-30 19:09:41 +0000542 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000543 detectLog2OfHalf(Op0, OpY, Log2);
544 if (OpY) {
545 OpX = Op1;
546 } else {
547 detectLog2OfHalf(Op1, OpY, Log2);
548 if (OpY) {
549 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000550 }
551 }
552 // if pattern detected emit alternate sequence
553 if (OpX && OpY) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000554 BuilderTy::FastMathFlagGuard Guard(*Builder);
555 Builder->SetFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000556 Log2->setArgOperand(0, OpY);
557 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
Benjamin Kramer67485762013-09-30 15:39:59 +0000558 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
559 FSub->takeName(&I);
560 return ReplaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000561 }
562 }
563
Shuxin Yange8227452013-01-15 21:09:32 +0000564 // Handle symmetric situation in a 2-iteration loop
565 Value *Opnd0 = Op0;
566 Value *Opnd1 = Op1;
567 for (int i = 0; i < 2; i++) {
568 bool IgnoreZeroSign = I.hasNoSignedZeros();
569 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000570 BuilderTy::FastMathFlagGuard Guard(*Builder);
571 Builder->SetFastMathFlags(I.getFastMathFlags());
572
Shuxin Yange8227452013-01-15 21:09:32 +0000573 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
574 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000575
Shuxin Yange8227452013-01-15 21:09:32 +0000576 // -X * -Y => X*Y
Owen Andersone8537fc2014-01-16 20:59:41 +0000577 if (N1) {
578 Value *FMul = Builder->CreateFMul(N0, N1);
579 FMul->takeName(&I);
580 return ReplaceInstUsesWith(I, FMul);
581 }
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000582
Shuxin Yange8227452013-01-15 21:09:32 +0000583 if (Opnd0->hasOneUse()) {
584 // -X * Y => -(X*Y) (Promote negation as high as possible)
585 Value *T = Builder->CreateFMul(N0, Opnd1);
Benjamin Kramer67485762013-09-30 15:39:59 +0000586 Value *Neg = Builder->CreateFNeg(T);
587 Neg->takeName(&I);
588 return ReplaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000589 }
590 }
Shuxin Yange8227452013-01-15 21:09:32 +0000591
592 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000593 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000594 // 1) to form a power expression (of X).
595 // 2) potentially shorten the critical path: After transformation, the
596 // latency of the instruction Y is amortized by the expression of X*X,
597 // and therefore Y is in a "less critical" position compared to what it
598 // was before the transformation.
599 //
600 if (AllowReassociate) {
601 Value *Opnd0_0, *Opnd0_1;
602 if (Opnd0->hasOneUse() &&
603 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000604 Value *Y = nullptr;
Shuxin Yange8227452013-01-15 21:09:32 +0000605 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
606 Y = Opnd0_1;
607 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
608 Y = Opnd0_0;
609
610 if (Y) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000611 BuilderTy::FastMathFlagGuard Guard(*Builder);
612 Builder->SetFastMathFlags(I.getFastMathFlags());
613 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
Shuxin Yange8227452013-01-15 21:09:32 +0000614
Benjamin Kramer67485762013-09-30 15:39:59 +0000615 Value *R = Builder->CreateFMul(T, Y);
616 R->takeName(&I);
617 return ReplaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000618 }
619 }
620 }
621
622 if (!isa<Constant>(Op1))
623 std::swap(Opnd0, Opnd1);
624 else
625 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000626 }
627
Craig Topperf40110f2014-04-25 05:29:35 +0000628 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000629}
630
631/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
632/// instruction.
633bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
634 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000635
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000636 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
637 int NonNullOperand = -1;
638 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
639 if (ST->isNullValue())
640 NonNullOperand = 2;
641 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
642 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
643 if (ST->isNullValue())
644 NonNullOperand = 1;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000645
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000646 if (NonNullOperand == -1)
647 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000648
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000649 Value *SelectCond = SI->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000650
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000651 // Change the div/rem to use 'Y' instead of the select.
652 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000653
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000654 // Okay, we know we replace the operand of the div/rem with 'Y' with no
655 // problem. However, the select, or the condition of the select may have
656 // multiple uses. Based on our knowledge that the operand must be non-zero,
657 // propagate the known value for the select into other uses of it, and
658 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000659
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000660 // If the select and condition only have a single use, don't bother with this,
661 // early exit.
662 if (SI->use_empty() && SelectCond->hasOneUse())
663 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000664
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000665 // Scan the current block backward, looking for other uses of SI.
666 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000667
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000668 while (BBI != BBFront) {
669 --BBI;
670 // If we found a call to a function, we can't assume it will return, so
671 // information from below it cannot be propagated above it.
672 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
673 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000674
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000675 // Replace uses of the select or its condition with the known values.
676 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
677 I != E; ++I) {
678 if (*I == SI) {
679 *I = SI->getOperand(NonNullOperand);
680 Worklist.Add(BBI);
681 } else if (*I == SelectCond) {
Jakub Staszak96ff4d62013-06-06 23:34:59 +0000682 *I = Builder->getInt1(NonNullOperand == 1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000683 Worklist.Add(BBI);
684 }
685 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000686
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000687 // If we past the instruction, quit looking for it.
688 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000689 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000690 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000691 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000692
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000693 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000694 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000695 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000696
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000697 }
698 return true;
699}
700
701
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000702/// This function implements the transforms common to both integer division
703/// instructions (udiv and sdiv). It is called by the visitors to those integer
704/// division instructions.
705/// @brief Common integer divide transforms
706Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
707 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
708
Chris Lattner7c99f192011-05-22 18:18:41 +0000709 // The RHS is known non-zero.
Hal Finkel60db0582014-09-07 18:57:58 +0000710 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +0000711 I.setOperand(1, V);
712 return &I;
713 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000714
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000715 // Handle cases involving: [su]div X, (select Cond, Y, Z)
716 // This does not apply for fdiv.
717 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
718 return &I;
719
David Majnemer27adb122014-10-12 08:34:24 +0000720 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
721 const APInt *C2;
722 if (match(Op1, m_APInt(C2))) {
David Majnemerf9a095d2014-08-16 08:55:06 +0000723 Value *X;
David Majnemer27adb122014-10-12 08:34:24 +0000724 const APInt *C1;
725 bool IsSigned = I.getOpcode() == Instruction::SDiv;
David Majnemerf9a095d2014-08-16 08:55:06 +0000726
David Majnemer27adb122014-10-12 08:34:24 +0000727 // (X / C1) / C2 -> X / (C1*C2)
728 if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
729 (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
730 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
731 if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
732 return BinaryOperator::Create(I.getOpcode(), X,
733 ConstantInt::get(I.getType(), Product));
734 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000735
David Majnemer27adb122014-10-12 08:34:24 +0000736 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
737 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
738 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
739
740 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
741 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
742 BinaryOperator *BO = BinaryOperator::Create(
743 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
744 BO->setIsExact(I.isExact());
745 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000746 }
747
David Majnemer27adb122014-10-12 08:34:24 +0000748 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
749 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
750 BinaryOperator *BO = BinaryOperator::Create(
751 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
752 BO->setHasNoUnsignedWrap(
753 !IsSigned &&
754 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
755 BO->setHasNoSignedWrap(
756 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
757 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000758 }
759 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000760
David Majnemer27adb122014-10-12 08:34:24 +0000761 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
762 *C1 != C1->getBitWidth() - 1) ||
763 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
764 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
765 APInt C1Shifted = APInt::getOneBitSet(
766 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
767
768 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
769 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
770 BinaryOperator *BO = BinaryOperator::Create(
771 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
772 BO->setIsExact(I.isExact());
773 return BO;
774 }
775
776 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
777 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
778 BinaryOperator *BO = BinaryOperator::Create(
779 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
780 BO->setHasNoUnsignedWrap(
781 !IsSigned &&
782 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
783 BO->setHasNoSignedWrap(
784 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
785 return BO;
786 }
787 }
788
789 if (*C2 != 0) { // avoid X udiv 0
790 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
791 if (Instruction *R = FoldOpIntoSelect(I, SI))
792 return R;
793 if (isa<PHINode>(Op0))
794 if (Instruction *NV = FoldOpIntoPhi(I))
795 return NV;
796 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000797 }
798 }
799
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000800 if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
801 if (One->isOne() && !I.getType()->isIntegerTy(1)) {
802 bool isSigned = I.getOpcode() == Instruction::SDiv;
803 if (isSigned) {
804 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
805 // result is one, if Op1 is -1 then the result is minus one, otherwise
806 // it's zero.
807 Value *Inc = Builder->CreateAdd(Op1, One);
808 Value *Cmp = Builder->CreateICmpULT(
809 Inc, ConstantInt::get(I.getType(), 3));
810 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
811 } else {
812 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
813 // result is one, otherwise it's zero.
814 return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
815 }
816 }
817 }
818
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000819 // See if we can fold away this div instruction.
820 if (SimplifyDemandedInstructionBits(I))
821 return &I;
822
Duncan Sands771e82a2011-01-28 16:51:11 +0000823 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Craig Topperf40110f2014-04-25 05:29:35 +0000824 Value *X = nullptr, *Z = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +0000825 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
826 bool isSigned = I.getOpcode() == Instruction::SDiv;
827 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
828 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
829 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000830 }
831
Craig Topperf40110f2014-04-25 05:29:35 +0000832 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000833}
834
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000835/// dyn_castZExtVal - Checks if V is a zext or constant that can
836/// be truncated to Ty without losing bits.
Chris Lattner229907c2011-07-18 04:54:35 +0000837static Value *dyn_castZExtVal(Value *V, Type *Ty) {
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000838 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
839 if (Z->getSrcTy() == Ty)
840 return Z->getOperand(0);
841 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
842 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
843 return ConstantExpr::getTrunc(C, Ty);
844 }
Craig Topperf40110f2014-04-25 05:29:35 +0000845 return nullptr;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000846}
847
David Majnemer37f8f442013-07-04 21:17:49 +0000848namespace {
849const unsigned MaxDepth = 6;
850typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
851 const BinaryOperator &I,
852 InstCombiner &IC);
853
854/// \brief Used to maintain state for visitUDivOperand().
855struct UDivFoldAction {
856 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
857 ///< operand. This can be zero if this action
858 ///< joins two actions together.
859
860 Value *OperandToFold; ///< Which operand to fold.
861 union {
862 Instruction *FoldResult; ///< The instruction returned when FoldAction is
863 ///< invoked.
864
865 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
866 ///< joins two actions together.
867 };
868
869 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +0000870 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +0000871 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
872 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
873};
874}
875
876// X udiv 2^C -> X >> C
877static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
878 const BinaryOperator &I, InstCombiner &IC) {
879 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
880 BinaryOperator *LShr = BinaryOperator::CreateLShr(
881 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000882 if (I.isExact())
883 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000884 return LShr;
885}
886
887// X udiv C, where C >= signbit
888static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
889 const BinaryOperator &I, InstCombiner &IC) {
890 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
891
892 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
893 ConstantInt::get(I.getType(), 1));
894}
895
896// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
897static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
898 InstCombiner &IC) {
899 Instruction *ShiftLeft = cast<Instruction>(Op1);
900 if (isa<ZExtInst>(ShiftLeft))
901 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
902
903 const APInt &CI =
904 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
905 Value *N = ShiftLeft->getOperand(1);
906 if (CI != 1)
907 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
908 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
909 N = IC.Builder->CreateZExt(N, Z->getDestTy());
910 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000911 if (I.isExact())
912 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000913 return LShr;
914}
915
916// \brief Recursively visits the possible right hand operands of a udiv
917// instruction, seeing through select instructions, to determine if we can
918// replace the udiv with something simpler. If we find that an operand is not
919// able to simplify the udiv, we abort the entire transformation.
920static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
921 SmallVectorImpl<UDivFoldAction> &Actions,
922 unsigned Depth = 0) {
923 // Check to see if this is an unsigned division with an exact power of 2,
924 // if so, convert to a right shift.
925 if (match(Op1, m_Power2())) {
926 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
927 return Actions.size();
928 }
929
930 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
931 // X udiv C, where C >= signbit
932 if (C->getValue().isNegative()) {
933 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
934 return Actions.size();
935 }
936
937 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
938 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
939 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
940 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
941 return Actions.size();
942 }
943
944 // The remaining tests are all recursive, so bail out if we hit the limit.
945 if (Depth++ == MaxDepth)
946 return 0;
947
948 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
David Majnemer492e6122014-08-30 09:19:05 +0000949 if (size_t LHSIdx =
950 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
951 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
952 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
David Majnemer37f8f442013-07-04 21:17:49 +0000953 return Actions.size();
954 }
955
956 return 0;
957}
958
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000959Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
960 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
961
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000962 if (Value *V = SimplifyVectorOp(I))
963 return ReplaceInstUsesWith(I, V);
964
Hal Finkel60db0582014-09-07 18:57:58 +0000965 if (Value *V = SimplifyUDivInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sands771e82a2011-01-28 16:51:11 +0000966 return ReplaceInstUsesWith(I, V);
967
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000968 // Handle the integer div common cases
969 if (Instruction *Common = commonIDivTransforms(I))
970 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000971
Benjamin Kramerd4a64712012-08-30 15:07:40 +0000972 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
David Majnemera2521382014-10-13 21:48:30 +0000973 {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +0000974 Value *X;
David Majnemera2521382014-10-13 21:48:30 +0000975 const APInt *C1, *C2;
976 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
977 match(Op1, m_APInt(C2))) {
978 bool Overflow;
979 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
980 if (!Overflow)
981 return BinaryOperator::CreateUDiv(
982 X, ConstantInt::get(X->getType(), C2ShlC1));
983 }
Nadav Rotem11935b22012-08-28 10:01:43 +0000984 }
985
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000986 // (zext A) udiv (zext B) --> zext (A udiv B)
987 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
988 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
Suyog Sardaea205512014-10-07 11:56:06 +0000989 return new ZExtInst(
990 Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", I.isExact()),
991 I.getType());
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000992
David Majnemer37f8f442013-07-04 21:17:49 +0000993 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
994 SmallVector<UDivFoldAction, 6> UDivActions;
995 if (visitUDivOperand(Op0, Op1, I, UDivActions))
996 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
997 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
998 Value *ActionOp1 = UDivActions[i].OperandToFold;
999 Instruction *Inst;
1000 if (Action)
1001 Inst = Action(Op0, ActionOp1, I, *this);
1002 else {
1003 // This action joins two actions together. The RHS of this action is
1004 // simply the last action we processed, we saved the LHS action index in
1005 // the joining action.
1006 size_t SelectRHSIdx = i - 1;
1007 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1008 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1009 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1010 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1011 SelectLHS, SelectRHS);
1012 }
1013
1014 // If this is the last action to process, return it to the InstCombiner.
1015 // Otherwise, we insert it before the UDiv and record it so that we may
1016 // use it as part of a joining action (i.e., a SelectInst).
1017 if (e - i != 1) {
1018 Inst->insertBefore(&I);
1019 UDivActions[i].FoldResult = Inst;
1020 } else
1021 return Inst;
1022 }
1023
Craig Topperf40110f2014-04-25 05:29:35 +00001024 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001025}
1026
1027Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1028 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1029
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001030 if (Value *V = SimplifyVectorOp(I))
1031 return ReplaceInstUsesWith(I, V);
1032
Hal Finkel60db0582014-09-07 18:57:58 +00001033 if (Value *V = SimplifySDivInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sands771e82a2011-01-28 16:51:11 +00001034 return ReplaceInstUsesWith(I, V);
1035
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001036 // Handle the integer div common cases
1037 if (Instruction *Common = commonIDivTransforms(I))
1038 return Common;
1039
Benjamin Kramer72196f32014-01-19 15:24:22 +00001040 // sdiv X, -1 == -X
1041 if (match(Op1, m_AllOnes()))
1042 return BinaryOperator::CreateNeg(Op0);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001043
Benjamin Kramer72196f32014-01-19 15:24:22 +00001044 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001045 // sdiv X, C --> ashr exact X, log2(C)
1046 if (I.isExact() && RHS->getValue().isNonNegative() &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001047 RHS->getValue().isPowerOf2()) {
1048 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1049 RHS->getValue().exactLogBase2());
Chris Lattner6b657ae2011-02-10 05:36:31 +00001050 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001051 }
Benjamin Kramer72196f32014-01-19 15:24:22 +00001052 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001053
Benjamin Kramer72196f32014-01-19 15:24:22 +00001054 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
David Majnemerf28e2a42014-07-02 06:42:13 +00001055 // X/INT_MIN -> X == INT_MIN
1056 if (RHS->isMinSignedValue())
1057 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1058
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001059 // -X/C --> X/-C provided the negation doesn't overflow.
1060 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
Chris Lattner6b657ae2011-02-10 05:36:31 +00001061 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001062 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
1063 ConstantExpr::getNeg(RHS));
1064 }
1065
1066 // If the sign bits of both operands are zero (i.e. we can prove they are
1067 // unsigned inputs), turn this into a udiv.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001068 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001069 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001070 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1071 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001072 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001073 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1074 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001075
Chris Lattner6b657ae2011-02-10 05:36:31 +00001076 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001077 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1078 // Safe because the only negative value (1 << Y) can take on is
1079 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1080 // the sign bit set.
1081 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1082 }
1083 }
1084 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001085
Craig Topperf40110f2014-04-25 05:29:35 +00001086 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001087}
1088
Shuxin Yang320f52a2013-01-14 22:48:41 +00001089/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1090/// FP value and:
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001091/// 1) 1/C is exact, or
Shuxin Yang320f52a2013-01-14 22:48:41 +00001092/// 2) reciprocal is allowed.
Sylvestre Ledru149e2812013-05-14 23:36:24 +00001093/// If the conversion was successful, the simplified expression "X * 1/C" is
Shuxin Yang320f52a2013-01-14 22:48:41 +00001094/// returned; otherwise, NULL is returned.
1095///
Suyog Sardaea205512014-10-07 11:56:06 +00001096static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
Shuxin Yang320f52a2013-01-14 22:48:41 +00001097 bool AllowReciprocal) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001098 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001099 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001100
1101 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001102 APFloat Reciprocal(FpVal.getSemantics());
1103 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001104
Michael Gottesman3cb77ab2013-06-19 21:23:18 +00001105 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001106 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1107 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1108 Cvt = !Reciprocal.isDenormal();
1109 }
1110
1111 if (!Cvt)
Craig Topperf40110f2014-04-25 05:29:35 +00001112 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001113
1114 ConstantFP *R;
1115 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1116 return BinaryOperator::CreateFMul(Dividend, R);
1117}
1118
Frits van Bommel2a559512011-01-29 17:50:27 +00001119Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1120 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1121
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001122 if (Value *V = SimplifyVectorOp(I))
1123 return ReplaceInstUsesWith(I, V);
1124
Hal Finkel60db0582014-09-07 18:57:58 +00001125 if (Value *V = SimplifyFDivInst(Op0, Op1, DL, TLI, DT, AT))
Frits van Bommel2a559512011-01-29 17:50:27 +00001126 return ReplaceInstUsesWith(I, V);
1127
Stephen Lina9b57f62013-07-20 07:13:13 +00001128 if (isa<Constant>(Op0))
1129 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1130 if (Instruction *R = FoldOpIntoSelect(I, SI))
1131 return R;
1132
Shuxin Yang320f52a2013-01-14 22:48:41 +00001133 bool AllowReassociate = I.hasUnsafeAlgebra();
1134 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001135
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001136 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001137 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1138 if (Instruction *R = FoldOpIntoSelect(I, SI))
1139 return R;
1140
Shuxin Yang320f52a2013-01-14 22:48:41 +00001141 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +00001142 Constant *C1 = nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001143 Constant *C2 = Op1C;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001144 Value *X;
Craig Topperf40110f2014-04-25 05:29:35 +00001145 Instruction *Res = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001146
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001147 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001148 // (X*C1)/C2 => X * (C1/C2)
1149 //
1150 Constant *C = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001151 if (isNormalFp(C))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001152 Res = BinaryOperator::CreateFMul(X, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001153 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001154 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1155 //
1156 Constant *C = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001157 if (isNormalFp(C)) {
1158 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001159 if (!Res)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001160 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001161 }
1162 }
1163
1164 if (Res) {
1165 Res->setFastMathFlags(I.getFastMathFlags());
1166 return Res;
1167 }
1168 }
1169
1170 // X / C => X * 1/C
Owen Anderson4557a152014-01-16 21:07:52 +00001171 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1172 T->copyFastMathFlags(&I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001173 return T;
Owen Anderson4557a152014-01-16 21:07:52 +00001174 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001175
Craig Topperf40110f2014-04-25 05:29:35 +00001176 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001177 }
1178
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001179 if (AllowReassociate && isa<Constant>(Op0)) {
1180 Constant *C1 = cast<Constant>(Op0), *C2;
Craig Topperf40110f2014-04-25 05:29:35 +00001181 Constant *Fold = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001182 Value *X;
1183 bool CreateDiv = true;
1184
1185 // C1 / (X*C2) => (C1/C2) / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001186 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001187 Fold = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001188 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001189 // C1 / (X/C2) => (C1*C2) / X
1190 Fold = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001191 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001192 // C1 / (C2/X) => (C1/C2) * X
1193 Fold = ConstantExpr::getFDiv(C1, C2);
1194 CreateDiv = false;
1195 }
1196
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001197 if (Fold && isNormalFp(Fold)) {
1198 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1199 : BinaryOperator::CreateFMul(X, Fold);
1200 R->setFastMathFlags(I.getFastMathFlags());
1201 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001202 }
Craig Topperf40110f2014-04-25 05:29:35 +00001203 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001204 }
1205
1206 if (AllowReassociate) {
1207 Value *X, *Y;
Craig Topperf40110f2014-04-25 05:29:35 +00001208 Value *NewInst = nullptr;
1209 Instruction *SimpR = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001210
1211 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1212 // (X/Y) / Z => X / (Y*Z)
1213 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001214 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001215 NewInst = Builder->CreateFMul(Y, Op1);
Owen Anderson1664dc82014-01-20 07:44:53 +00001216 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1217 FastMathFlags Flags = I.getFastMathFlags();
1218 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1219 RI->setFastMathFlags(Flags);
1220 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001221 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1222 }
1223 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1224 // Z / (X/Y) => Z*Y / X
1225 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001226 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001227 NewInst = Builder->CreateFMul(Op0, Y);
Owen Anderson1664dc82014-01-20 07:44:53 +00001228 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1229 FastMathFlags Flags = I.getFastMathFlags();
1230 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1231 RI->setFastMathFlags(Flags);
1232 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001233 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1234 }
1235 }
1236
1237 if (NewInst) {
1238 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1239 T->setDebugLoc(I.getDebugLoc());
1240 SimpR->setFastMathFlags(I.getFastMathFlags());
1241 return SimpR;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001242 }
1243 }
1244
Craig Topperf40110f2014-04-25 05:29:35 +00001245 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001246}
1247
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001248/// This function implements the transforms common to both integer remainder
1249/// instructions (urem and srem). It is called by the visitors to those integer
1250/// remainder instructions.
1251/// @brief Common integer remainder transforms
1252Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1253 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1254
Chris Lattner7c99f192011-05-22 18:18:41 +00001255 // The RHS is known non-zero.
Hal Finkel60db0582014-09-07 18:57:58 +00001256 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +00001257 I.setOperand(1, V);
1258 return &I;
1259 }
1260
Duncan Sandsa3e36992011-05-02 16:27:02 +00001261 // Handle cases involving: rem X, (select Cond, Y, Z)
1262 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1263 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001264
Benjamin Kramer72196f32014-01-19 15:24:22 +00001265 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001266 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1267 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1268 if (Instruction *R = FoldOpIntoSelect(I, SI))
1269 return R;
1270 } else if (isa<PHINode>(Op0I)) {
1271 if (Instruction *NV = FoldOpIntoPhi(I))
1272 return NV;
1273 }
1274
1275 // See if we can fold away this rem instruction.
1276 if (SimplifyDemandedInstructionBits(I))
1277 return &I;
1278 }
1279 }
1280
Craig Topperf40110f2014-04-25 05:29:35 +00001281 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001282}
1283
1284Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1285 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1286
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001287 if (Value *V = SimplifyVectorOp(I))
1288 return ReplaceInstUsesWith(I, V);
1289
Hal Finkel60db0582014-09-07 18:57:58 +00001290 if (Value *V = SimplifyURemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001291 return ReplaceInstUsesWith(I, V);
1292
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001293 if (Instruction *common = commonIRemTransforms(I))
1294 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001295
David Majnemer6c30f492013-05-12 00:07:05 +00001296 // (zext A) urem (zext B) --> zext (A urem B)
1297 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1298 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1299 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1300 I.getType());
1301
David Majnemer470b0772013-05-11 09:01:28 +00001302 // X urem Y -> X and Y-1, where Y is a power of 2,
Hal Finkel60db0582014-09-07 18:57:58 +00001303 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, AT, &I, DT)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001304 Constant *N1 = Constant::getAllOnesValue(I.getType());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001305 Value *Add = Builder->CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001306 return BinaryOperator::CreateAnd(Op0, Add);
1307 }
1308
Nick Lewycky7459be62013-07-13 01:16:47 +00001309 // 1 urem X -> zext(X != 1)
1310 if (match(Op0, m_One())) {
1311 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1312 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1313 return ReplaceInstUsesWith(I, Ext);
1314 }
1315
Craig Topperf40110f2014-04-25 05:29:35 +00001316 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001317}
1318
1319Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1320 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1321
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001322 if (Value *V = SimplifyVectorOp(I))
1323 return ReplaceInstUsesWith(I, V);
1324
Hal Finkel60db0582014-09-07 18:57:58 +00001325 if (Value *V = SimplifySRemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001326 return ReplaceInstUsesWith(I, V);
1327
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001328 // Handle the integer rem common cases
1329 if (Instruction *Common = commonIRemTransforms(I))
1330 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001331
David Majnemerdb077302014-10-13 22:37:51 +00001332 {
1333 const APInt *Y;
1334 // X % -Y -> X % Y
1335 if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001336 Worklist.AddValue(I.getOperand(1));
David Majnemerdb077302014-10-13 22:37:51 +00001337 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001338 return &I;
1339 }
David Majnemerdb077302014-10-13 22:37:51 +00001340 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001341
1342 // If the sign bits of both operands are zero (i.e. we can prove they are
1343 // unsigned inputs), turn this into a urem.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001344 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001345 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001346 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1347 MaskedValueIsZero(Op0, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001348 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001349 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1350 }
1351 }
1352
1353 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001354 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1355 Constant *C = cast<Constant>(Op1);
1356 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001357
1358 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001359 bool hasMissing = false;
1360 for (unsigned i = 0; i != VWidth; ++i) {
1361 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001362 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001363 hasMissing = true;
1364 break;
1365 }
1366
1367 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001368 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001369 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001370 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001371
Chris Lattner0256be92012-01-27 03:08:05 +00001372 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001373 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001374 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001375 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001376 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001377 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001378 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001379 }
1380 }
1381
1382 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001383 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001384 Worklist.AddValue(I.getOperand(1));
1385 I.setOperand(1, NewRHSV);
1386 return &I;
1387 }
1388 }
1389 }
1390
Craig Topperf40110f2014-04-25 05:29:35 +00001391 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001392}
1393
1394Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001395 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001396
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001397 if (Value *V = SimplifyVectorOp(I))
1398 return ReplaceInstUsesWith(I, V);
1399
Hal Finkel60db0582014-09-07 18:57:58 +00001400 if (Value *V = SimplifyFRemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001401 return ReplaceInstUsesWith(I, V);
1402
1403 // Handle cases involving: rem X, (select Cond, Y, Z)
1404 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1405 return &I;
1406
Craig Topperf40110f2014-04-25 05:29:35 +00001407 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001408}