blob: c96c2d62255c5a0ac3a7c79fc67efbffcb543cde [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))) &&
154 match(C1, m_APInt(IVal)))
155 // ((X << C1)*C2) == (X * (C2 << C1))
156 return BinaryOperator::CreateMul(NewOp, ConstantExpr::getShl(C1, C2));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000157
Rafael Espindola65281bf2013-05-31 14:27:15 +0000158 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000159 Constant *NewCst = nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000160 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
161 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
162 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
163 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
164 // Replace X*(2^C) with X << C, where C is a vector of known
165 // constant powers of 2.
166 NewCst = getLogBase2Vector(CV);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000167
Rafael Espindola65281bf2013-05-31 14:27:15 +0000168 if (NewCst) {
169 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000170
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000171 if (I.hasNoUnsignedWrap())
172 Shl->setHasNoUnsignedWrap();
173
Rafael Espindola65281bf2013-05-31 14:27:15 +0000174 return Shl;
175 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000176 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000177 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000178
Rafael Espindola65281bf2013-05-31 14:27:15 +0000179 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Stuart Hastings23804832011-06-01 16:42:47 +0000180 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
181 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
182 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000183 {
184 const APInt & Val = CI->getValue();
185 const APInt &PosVal = Val.abs();
186 if (Val.isNegative() && PosVal.isPowerOf2()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000187 Value *X = nullptr, *Y = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000188 if (Op0->hasOneUse()) {
189 ConstantInt *C1;
Craig Topperf40110f2014-04-25 05:29:35 +0000190 Value *Sub = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000191 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
192 Sub = Builder->CreateSub(X, Y, "suba");
193 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
194 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
195 if (Sub)
196 return
197 BinaryOperator::CreateMul(Sub,
198 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000199 }
200 }
201 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000202 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000203
Chris Lattner6b657ae2011-02-10 05:36:31 +0000204 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000205 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000206 // Try to fold constant mul into select arguments.
207 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
208 if (Instruction *R = FoldOpIntoSelect(I, SI))
209 return R;
210
211 if (isa<PHINode>(Op0))
212 if (Instruction *NV = FoldOpIntoPhi(I))
213 return NV;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000214
215 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
216 {
217 Value *X;
218 Constant *C1;
219 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
David Majnemer6cf6c052014-06-19 07:14:33 +0000220 Value *Mul = Builder->CreateMul(C1, Op1);
221 // Only go forward with the transform if C1*CI simplifies to a tidier
222 // constant.
223 if (!match(Mul, m_Mul(m_Value(), m_Value())))
224 return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
Benjamin Kramer72196f32014-01-19 15:24:22 +0000225 }
226 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000227 }
228
229 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
230 if (Value *Op1v = dyn_castNegVal(Op1))
231 return BinaryOperator::CreateMul(Op0v, Op1v);
232
233 // (X / Y) * Y = X - (X % Y)
234 // (X / Y) * -Y = (X % Y) - X
235 {
236 Value *Op1C = Op1;
237 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
238 if (!BO ||
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000239 (BO->getOpcode() != Instruction::UDiv &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000240 BO->getOpcode() != Instruction::SDiv)) {
241 Op1C = Op0;
242 BO = dyn_cast<BinaryOperator>(Op1);
243 }
244 Value *Neg = dyn_castNegVal(Op1C);
245 if (BO && BO->hasOneUse() &&
246 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
247 (BO->getOpcode() == Instruction::UDiv ||
248 BO->getOpcode() == Instruction::SDiv)) {
249 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
250
Chris Lattner35315d02011-02-06 21:44:57 +0000251 // If the division is exact, X % Y is zero, so we end up with X or -X.
252 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000253 if (SDiv->isExact()) {
254 if (Op1BO == Op1C)
255 return ReplaceInstUsesWith(I, Op0BO);
256 return BinaryOperator::CreateNeg(Op0BO);
257 }
258
259 Value *Rem;
260 if (BO->getOpcode() == Instruction::UDiv)
261 Rem = Builder->CreateURem(Op0BO, Op1BO);
262 else
263 Rem = Builder->CreateSRem(Op0BO, Op1BO);
264 Rem->takeName(BO);
265
266 if (Op1BO == Op1C)
267 return BinaryOperator::CreateSub(Op0BO, Rem);
268 return BinaryOperator::CreateSub(Rem, Op0BO);
269 }
270 }
271
272 /// i1 mul -> i1 and.
Benjamin Kramer72196f32014-01-19 15:24:22 +0000273 if (I.getType()->getScalarType()->isIntegerTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000274 return BinaryOperator::CreateAnd(Op0, Op1);
275
276 // X*(1 << Y) --> X << Y
277 // (1 << Y)*X --> X << Y
278 {
279 Value *Y;
280 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
281 return BinaryOperator::CreateShl(Op1, Y);
282 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
283 return BinaryOperator::CreateShl(Op0, Y);
284 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000285
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000286 // If one of the operands of the multiply is a cast from a boolean value, then
287 // we know the bool is either zero or one, so this is a 'masking' multiply.
288 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands19d0b472010-02-16 11:11:14 +0000289 if (!I.getType()->isVectorTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000290 // -2 is "-1 << 1" so it is all bits set except the low one.
291 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000292
Craig Topperf40110f2014-04-25 05:29:35 +0000293 Value *BoolCast = nullptr, *OtherOp = nullptr;
Hal Finkel60db0582014-09-07 18:57:58 +0000294 if (MaskedValueIsZero(Op0, Negative2, 0, &I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000295 BoolCast = Op0, OtherOp = Op1;
Hal Finkel60db0582014-09-07 18:57:58 +0000296 else if (MaskedValueIsZero(Op1, Negative2, 0, &I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000297 BoolCast = Op1, OtherOp = Op0;
298
299 if (BoolCast) {
300 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000301 BoolCast);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000302 return BinaryOperator::CreateAnd(V, OtherOp);
303 }
304 }
305
Craig Topperf40110f2014-04-25 05:29:35 +0000306 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000307}
308
Sanjay Patel17045f72014-10-14 00:33:23 +0000309/// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
Pedro Artigas993acd02012-11-30 22:07:05 +0000310static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Sanjay Patel17045f72014-10-14 00:33:23 +0000311 if (!Op->hasOneUse())
312 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000313
Sanjay Patel17045f72014-10-14 00:33:23 +0000314 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
315 if (!II)
316 return;
317 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
318 return;
319 Log2 = II;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000320
Sanjay Patel17045f72014-10-14 00:33:23 +0000321 Value *OpLog2Of = II->getArgOperand(0);
322 if (!OpLog2Of->hasOneUse())
323 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000324
Sanjay Patel17045f72014-10-14 00:33:23 +0000325 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
326 if (!I)
327 return;
328 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
329 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000330
Sanjay Patel17045f72014-10-14 00:33:23 +0000331 if (match(I->getOperand(0), m_SpecificFP(0.5)))
332 Y = I->getOperand(1);
333 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
334 Y = I->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000335}
Pedro Artigas993acd02012-11-30 22:07:05 +0000336
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000337static bool isFiniteNonZeroFp(Constant *C) {
338 if (C->getType()->isVectorTy()) {
339 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
340 ++I) {
341 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
342 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
343 return false;
344 }
345 return true;
346 }
347
348 return isa<ConstantFP>(C) &&
349 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
350}
351
352static bool isNormalFp(Constant *C) {
353 if (C->getType()->isVectorTy()) {
354 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
355 ++I) {
356 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
357 if (!CFP || !CFP->getValueAPF().isNormal())
358 return false;
359 }
360 return true;
361 }
362
363 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
364}
365
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000366/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
367/// true iff the given value is FMul or FDiv with one and only one operand
368/// being a normal constant (i.e. not Zero/NaN/Infinity).
369static bool isFMulOrFDivWithConstant(Value *V) {
370 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000371 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yang80138662013-01-07 22:41:28 +0000372 I->getOpcode() != Instruction::FDiv))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000373 return false;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000374
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000375 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
376 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000377
378 if (C0 && C1)
379 return false;
380
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000381 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000382}
383
384/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
385/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
386/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000387/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000388/// resulting expression. Note that this function could return NULL in
389/// case the constants cannot be folded into a normal floating-point.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000390///
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000391Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yang80138662013-01-07 22:41:28 +0000392 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000393 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
394
395 Value *Opnd0 = FMulOrDiv->getOperand(0);
396 Value *Opnd1 = FMulOrDiv->getOperand(1);
397
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000398 Constant *C0 = dyn_cast<Constant>(Opnd0);
399 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000400
Craig Topperf40110f2014-04-25 05:29:35 +0000401 BinaryOperator *R = nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000402
403 // (X * C0) * C => X * (C0*C)
404 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
405 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000406 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000407 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
408 } else {
409 if (C0) {
410 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000411 if (FMulOrDiv->hasOneUse()) {
412 // It would otherwise introduce another div.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000413 Constant *F = ConstantExpr::getFMul(C0, C);
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000414 if (isNormalFp(F))
415 R = BinaryOperator::CreateFDiv(F, Opnd1);
416 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000417 } else {
418 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000419 Constant *F = ConstantExpr::getFDiv(C, C1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000420 if (isNormalFp(F)) {
421 R = BinaryOperator::CreateFMul(Opnd0, F);
422 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000423 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000424 Constant *F = ConstantExpr::getFDiv(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000425 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000426 R = BinaryOperator::CreateFDiv(Opnd0, F);
427 }
428 }
429 }
430
431 if (R) {
432 R->setHasUnsafeAlgebra(true);
433 InsertNewInstWith(R, *InsertBefore);
434 }
435
436 return R;
437}
438
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000439Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000440 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000441 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
442
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000443 if (Value *V = SimplifyVectorOp(I))
444 return ReplaceInstUsesWith(I, V);
445
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000446 if (isa<Constant>(Op0))
447 std::swap(Op0, Op1);
448
Hal Finkel60db0582014-09-07 18:57:58 +0000449 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL, TLI,
450 DT, AT))
Michael Ilsemand5787be2012-12-12 00:28:32 +0000451 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000452
Shuxin Yange8227452013-01-15 21:09:32 +0000453 bool AllowReassociate = I.hasUnsafeAlgebra();
454
Michael Ilsemand5787be2012-12-12 00:28:32 +0000455 // Simplify mul instructions with a constant RHS.
456 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000457 // Try to fold constant mul into select arguments.
458 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
459 if (Instruction *R = FoldOpIntoSelect(I, SI))
460 return R;
461
462 if (isa<PHINode>(Op0))
463 if (Instruction *NV = FoldOpIntoPhi(I))
464 return NV;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000465
Owen Andersonf74cfe02014-01-16 20:36:42 +0000466 // (fmul X, -1.0) --> (fsub -0.0, X)
Benjamin Kramerfea9ac92014-01-18 16:43:14 +0000467 if (match(Op1, m_SpecificFP(-1.0))) {
468 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
469 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000470 RI->copyFastMathFlags(&I);
471 return RI;
472 }
473
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000474 Constant *C = cast<Constant>(Op1);
475 if (AllowReassociate && isFiniteNonZeroFp(C)) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000476 // Let MDC denote an expression in one of these forms:
477 // X * C, C/X, X/C, where C is a constant.
478 //
479 // Try to simplify "MDC * Constant"
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000480 if (isFMulOrFDivWithConstant(Op0))
481 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000482 return ReplaceInstUsesWith(I, V);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000483
Quentin Colombete684a6d2013-02-28 21:12:40 +0000484 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000485 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
486 if (FAddSub &&
487 (FAddSub->getOpcode() == Instruction::FAdd ||
488 FAddSub->getOpcode() == Instruction::FSub)) {
489 Value *Opnd0 = FAddSub->getOperand(0);
490 Value *Opnd1 = FAddSub->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000491 Constant *C0 = dyn_cast<Constant>(Opnd0);
492 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000493 bool Swap = false;
494 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000495 std::swap(C0, C1);
496 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000497 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000498 }
499
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000500 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000501 Value *M1 = ConstantExpr::getFMul(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000502 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000503 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
Craig Topperf40110f2014-04-25 05:29:35 +0000504 nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000505 if (M0 && M1) {
506 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
507 std::swap(M0, M1);
508
Benjamin Kramer67485762013-09-30 15:39:59 +0000509 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
510 ? BinaryOperator::CreateFAdd(M0, M1)
511 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000512 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000513 return RI;
514 }
515 }
516 }
517 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000518 }
519
Sanjay Patel12d1ce52014-10-02 21:10:54 +0000520 // sqrt(X) * sqrt(X) -> X
521 if (AllowReassociate && (Op0 == Op1))
522 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0))
523 if (II->getIntrinsicID() == Intrinsic::sqrt)
524 return ReplaceInstUsesWith(I, II->getOperand(0));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000525
Pedro Artigasd8795042012-11-30 19:09:41 +0000526 // Under unsafe algebra do:
527 // X * log2(0.5*Y) = X*log2(Y) - X
Sanjay Patelb41d4612014-10-02 15:20:45 +0000528 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +0000529 Value *OpX = nullptr;
530 Value *OpY = nullptr;
Pedro Artigasd8795042012-11-30 19:09:41 +0000531 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000532 detectLog2OfHalf(Op0, OpY, Log2);
533 if (OpY) {
534 OpX = Op1;
535 } else {
536 detectLog2OfHalf(Op1, OpY, Log2);
537 if (OpY) {
538 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000539 }
540 }
541 // if pattern detected emit alternate sequence
542 if (OpX && OpY) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000543 BuilderTy::FastMathFlagGuard Guard(*Builder);
544 Builder->SetFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000545 Log2->setArgOperand(0, OpY);
546 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
Benjamin Kramer67485762013-09-30 15:39:59 +0000547 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
548 FSub->takeName(&I);
549 return ReplaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000550 }
551 }
552
Shuxin Yange8227452013-01-15 21:09:32 +0000553 // Handle symmetric situation in a 2-iteration loop
554 Value *Opnd0 = Op0;
555 Value *Opnd1 = Op1;
556 for (int i = 0; i < 2; i++) {
557 bool IgnoreZeroSign = I.hasNoSignedZeros();
558 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000559 BuilderTy::FastMathFlagGuard Guard(*Builder);
560 Builder->SetFastMathFlags(I.getFastMathFlags());
561
Shuxin Yange8227452013-01-15 21:09:32 +0000562 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
563 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000564
Shuxin Yange8227452013-01-15 21:09:32 +0000565 // -X * -Y => X*Y
Owen Andersone8537fc2014-01-16 20:59:41 +0000566 if (N1) {
567 Value *FMul = Builder->CreateFMul(N0, N1);
568 FMul->takeName(&I);
569 return ReplaceInstUsesWith(I, FMul);
570 }
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000571
Shuxin Yange8227452013-01-15 21:09:32 +0000572 if (Opnd0->hasOneUse()) {
573 // -X * Y => -(X*Y) (Promote negation as high as possible)
574 Value *T = Builder->CreateFMul(N0, Opnd1);
Benjamin Kramer67485762013-09-30 15:39:59 +0000575 Value *Neg = Builder->CreateFNeg(T);
576 Neg->takeName(&I);
577 return ReplaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000578 }
579 }
Shuxin Yange8227452013-01-15 21:09:32 +0000580
581 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000582 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000583 // 1) to form a power expression (of X).
584 // 2) potentially shorten the critical path: After transformation, the
585 // latency of the instruction Y is amortized by the expression of X*X,
586 // and therefore Y is in a "less critical" position compared to what it
587 // was before the transformation.
588 //
589 if (AllowReassociate) {
590 Value *Opnd0_0, *Opnd0_1;
591 if (Opnd0->hasOneUse() &&
592 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000593 Value *Y = nullptr;
Shuxin Yange8227452013-01-15 21:09:32 +0000594 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
595 Y = Opnd0_1;
596 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
597 Y = Opnd0_0;
598
599 if (Y) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000600 BuilderTy::FastMathFlagGuard Guard(*Builder);
601 Builder->SetFastMathFlags(I.getFastMathFlags());
602 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
Shuxin Yange8227452013-01-15 21:09:32 +0000603
Benjamin Kramer67485762013-09-30 15:39:59 +0000604 Value *R = Builder->CreateFMul(T, Y);
605 R->takeName(&I);
606 return ReplaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000607 }
608 }
609 }
610
611 if (!isa<Constant>(Op1))
612 std::swap(Opnd0, Opnd1);
613 else
614 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000615 }
616
Craig Topperf40110f2014-04-25 05:29:35 +0000617 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000618}
619
620/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
621/// instruction.
622bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
623 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000624
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000625 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
626 int NonNullOperand = -1;
627 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
628 if (ST->isNullValue())
629 NonNullOperand = 2;
630 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
631 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
632 if (ST->isNullValue())
633 NonNullOperand = 1;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000634
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000635 if (NonNullOperand == -1)
636 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000637
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000638 Value *SelectCond = SI->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000639
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000640 // Change the div/rem to use 'Y' instead of the select.
641 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000642
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000643 // Okay, we know we replace the operand of the div/rem with 'Y' with no
644 // problem. However, the select, or the condition of the select may have
645 // multiple uses. Based on our knowledge that the operand must be non-zero,
646 // propagate the known value for the select into other uses of it, and
647 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000648
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000649 // If the select and condition only have a single use, don't bother with this,
650 // early exit.
651 if (SI->use_empty() && SelectCond->hasOneUse())
652 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000653
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000654 // Scan the current block backward, looking for other uses of SI.
655 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000656
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000657 while (BBI != BBFront) {
658 --BBI;
659 // If we found a call to a function, we can't assume it will return, so
660 // information from below it cannot be propagated above it.
661 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
662 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000663
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000664 // Replace uses of the select or its condition with the known values.
665 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
666 I != E; ++I) {
667 if (*I == SI) {
668 *I = SI->getOperand(NonNullOperand);
669 Worklist.Add(BBI);
670 } else if (*I == SelectCond) {
Jakub Staszak96ff4d62013-06-06 23:34:59 +0000671 *I = Builder->getInt1(NonNullOperand == 1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000672 Worklist.Add(BBI);
673 }
674 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000675
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000676 // If we past the instruction, quit looking for it.
677 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000678 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000679 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000680 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000681
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000682 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000683 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000684 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000685
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000686 }
687 return true;
688}
689
690
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000691/// This function implements the transforms common to both integer division
692/// instructions (udiv and sdiv). It is called by the visitors to those integer
693/// division instructions.
694/// @brief Common integer divide transforms
695Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
696 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
697
Chris Lattner7c99f192011-05-22 18:18:41 +0000698 // The RHS is known non-zero.
Hal Finkel60db0582014-09-07 18:57:58 +0000699 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +0000700 I.setOperand(1, V);
701 return &I;
702 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000703
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000704 // Handle cases involving: [su]div X, (select Cond, Y, Z)
705 // This does not apply for fdiv.
706 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
707 return &I;
708
David Majnemer27adb122014-10-12 08:34:24 +0000709 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
710 const APInt *C2;
711 if (match(Op1, m_APInt(C2))) {
David Majnemerf9a095d2014-08-16 08:55:06 +0000712 Value *X;
David Majnemer27adb122014-10-12 08:34:24 +0000713 const APInt *C1;
714 bool IsSigned = I.getOpcode() == Instruction::SDiv;
David Majnemerf9a095d2014-08-16 08:55:06 +0000715
David Majnemer27adb122014-10-12 08:34:24 +0000716 // (X / C1) / C2 -> X / (C1*C2)
717 if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
718 (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
719 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
720 if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
721 return BinaryOperator::Create(I.getOpcode(), X,
722 ConstantInt::get(I.getType(), Product));
723 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000724
David Majnemer27adb122014-10-12 08:34:24 +0000725 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
726 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
727 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
728
729 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
730 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
731 BinaryOperator *BO = BinaryOperator::Create(
732 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
733 BO->setIsExact(I.isExact());
734 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000735 }
736
David Majnemer27adb122014-10-12 08:34:24 +0000737 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
738 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
739 BinaryOperator *BO = BinaryOperator::Create(
740 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
741 BO->setHasNoUnsignedWrap(
742 !IsSigned &&
743 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
744 BO->setHasNoSignedWrap(
745 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
746 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000747 }
748 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000749
David Majnemer27adb122014-10-12 08:34:24 +0000750 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
751 *C1 != C1->getBitWidth() - 1) ||
752 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
753 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
754 APInt C1Shifted = APInt::getOneBitSet(
755 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
756
757 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
758 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
759 BinaryOperator *BO = BinaryOperator::Create(
760 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
761 BO->setIsExact(I.isExact());
762 return BO;
763 }
764
765 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
766 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
767 BinaryOperator *BO = BinaryOperator::Create(
768 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
769 BO->setHasNoUnsignedWrap(
770 !IsSigned &&
771 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
772 BO->setHasNoSignedWrap(
773 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
774 return BO;
775 }
776 }
777
778 if (*C2 != 0) { // avoid X udiv 0
779 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
780 if (Instruction *R = FoldOpIntoSelect(I, SI))
781 return R;
782 if (isa<PHINode>(Op0))
783 if (Instruction *NV = FoldOpIntoPhi(I))
784 return NV;
785 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000786 }
787 }
788
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000789 if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
790 if (One->isOne() && !I.getType()->isIntegerTy(1)) {
791 bool isSigned = I.getOpcode() == Instruction::SDiv;
792 if (isSigned) {
793 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
794 // result is one, if Op1 is -1 then the result is minus one, otherwise
795 // it's zero.
796 Value *Inc = Builder->CreateAdd(Op1, One);
797 Value *Cmp = Builder->CreateICmpULT(
798 Inc, ConstantInt::get(I.getType(), 3));
799 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
800 } else {
801 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
802 // result is one, otherwise it's zero.
803 return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
804 }
805 }
806 }
807
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000808 // See if we can fold away this div instruction.
809 if (SimplifyDemandedInstructionBits(I))
810 return &I;
811
Duncan Sands771e82a2011-01-28 16:51:11 +0000812 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Craig Topperf40110f2014-04-25 05:29:35 +0000813 Value *X = nullptr, *Z = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +0000814 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
815 bool isSigned = I.getOpcode() == Instruction::SDiv;
816 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
817 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
818 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000819 }
820
Craig Topperf40110f2014-04-25 05:29:35 +0000821 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000822}
823
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000824/// dyn_castZExtVal - Checks if V is a zext or constant that can
825/// be truncated to Ty without losing bits.
Chris Lattner229907c2011-07-18 04:54:35 +0000826static Value *dyn_castZExtVal(Value *V, Type *Ty) {
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000827 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
828 if (Z->getSrcTy() == Ty)
829 return Z->getOperand(0);
830 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
831 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
832 return ConstantExpr::getTrunc(C, Ty);
833 }
Craig Topperf40110f2014-04-25 05:29:35 +0000834 return nullptr;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000835}
836
David Majnemer37f8f442013-07-04 21:17:49 +0000837namespace {
838const unsigned MaxDepth = 6;
839typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
840 const BinaryOperator &I,
841 InstCombiner &IC);
842
843/// \brief Used to maintain state for visitUDivOperand().
844struct UDivFoldAction {
845 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
846 ///< operand. This can be zero if this action
847 ///< joins two actions together.
848
849 Value *OperandToFold; ///< Which operand to fold.
850 union {
851 Instruction *FoldResult; ///< The instruction returned when FoldAction is
852 ///< invoked.
853
854 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
855 ///< joins two actions together.
856 };
857
858 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +0000859 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +0000860 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
861 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
862};
863}
864
865// X udiv 2^C -> X >> C
866static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
867 const BinaryOperator &I, InstCombiner &IC) {
868 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
869 BinaryOperator *LShr = BinaryOperator::CreateLShr(
870 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000871 if (I.isExact())
872 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000873 return LShr;
874}
875
876// X udiv C, where C >= signbit
877static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
878 const BinaryOperator &I, InstCombiner &IC) {
879 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
880
881 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
882 ConstantInt::get(I.getType(), 1));
883}
884
885// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
886static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
887 InstCombiner &IC) {
888 Instruction *ShiftLeft = cast<Instruction>(Op1);
889 if (isa<ZExtInst>(ShiftLeft))
890 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
891
892 const APInt &CI =
893 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
894 Value *N = ShiftLeft->getOperand(1);
895 if (CI != 1)
896 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
897 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
898 N = IC.Builder->CreateZExt(N, Z->getDestTy());
899 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000900 if (I.isExact())
901 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000902 return LShr;
903}
904
905// \brief Recursively visits the possible right hand operands of a udiv
906// instruction, seeing through select instructions, to determine if we can
907// replace the udiv with something simpler. If we find that an operand is not
908// able to simplify the udiv, we abort the entire transformation.
909static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
910 SmallVectorImpl<UDivFoldAction> &Actions,
911 unsigned Depth = 0) {
912 // Check to see if this is an unsigned division with an exact power of 2,
913 // if so, convert to a right shift.
914 if (match(Op1, m_Power2())) {
915 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
916 return Actions.size();
917 }
918
919 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
920 // X udiv C, where C >= signbit
921 if (C->getValue().isNegative()) {
922 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
923 return Actions.size();
924 }
925
926 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
927 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
928 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
929 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
930 return Actions.size();
931 }
932
933 // The remaining tests are all recursive, so bail out if we hit the limit.
934 if (Depth++ == MaxDepth)
935 return 0;
936
937 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
David Majnemer492e6122014-08-30 09:19:05 +0000938 if (size_t LHSIdx =
939 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
940 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
941 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
David Majnemer37f8f442013-07-04 21:17:49 +0000942 return Actions.size();
943 }
944
945 return 0;
946}
947
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000948Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
949 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
950
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000951 if (Value *V = SimplifyVectorOp(I))
952 return ReplaceInstUsesWith(I, V);
953
Hal Finkel60db0582014-09-07 18:57:58 +0000954 if (Value *V = SimplifyUDivInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sands771e82a2011-01-28 16:51:11 +0000955 return ReplaceInstUsesWith(I, V);
956
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000957 // Handle the integer div common cases
958 if (Instruction *Common = commonIDivTransforms(I))
959 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000960
Benjamin Kramerd4a64712012-08-30 15:07:40 +0000961 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
David Majnemera2521382014-10-13 21:48:30 +0000962 {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +0000963 Value *X;
David Majnemera2521382014-10-13 21:48:30 +0000964 const APInt *C1, *C2;
965 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
966 match(Op1, m_APInt(C2))) {
967 bool Overflow;
968 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
969 if (!Overflow)
970 return BinaryOperator::CreateUDiv(
971 X, ConstantInt::get(X->getType(), C2ShlC1));
972 }
Nadav Rotem11935b22012-08-28 10:01:43 +0000973 }
974
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000975 // (zext A) udiv (zext B) --> zext (A udiv B)
976 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
977 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
Suyog Sardaea205512014-10-07 11:56:06 +0000978 return new ZExtInst(
979 Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", I.isExact()),
980 I.getType());
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000981
David Majnemer37f8f442013-07-04 21:17:49 +0000982 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
983 SmallVector<UDivFoldAction, 6> UDivActions;
984 if (visitUDivOperand(Op0, Op1, I, UDivActions))
985 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
986 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
987 Value *ActionOp1 = UDivActions[i].OperandToFold;
988 Instruction *Inst;
989 if (Action)
990 Inst = Action(Op0, ActionOp1, I, *this);
991 else {
992 // This action joins two actions together. The RHS of this action is
993 // simply the last action we processed, we saved the LHS action index in
994 // the joining action.
995 size_t SelectRHSIdx = i - 1;
996 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
997 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
998 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
999 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1000 SelectLHS, SelectRHS);
1001 }
1002
1003 // If this is the last action to process, return it to the InstCombiner.
1004 // Otherwise, we insert it before the UDiv and record it so that we may
1005 // use it as part of a joining action (i.e., a SelectInst).
1006 if (e - i != 1) {
1007 Inst->insertBefore(&I);
1008 UDivActions[i].FoldResult = Inst;
1009 } else
1010 return Inst;
1011 }
1012
Craig Topperf40110f2014-04-25 05:29:35 +00001013 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001014}
1015
1016Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1017 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1018
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001019 if (Value *V = SimplifyVectorOp(I))
1020 return ReplaceInstUsesWith(I, V);
1021
Hal Finkel60db0582014-09-07 18:57:58 +00001022 if (Value *V = SimplifySDivInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sands771e82a2011-01-28 16:51:11 +00001023 return ReplaceInstUsesWith(I, V);
1024
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001025 // Handle the integer div common cases
1026 if (Instruction *Common = commonIDivTransforms(I))
1027 return Common;
1028
Benjamin Kramer72196f32014-01-19 15:24:22 +00001029 // sdiv X, -1 == -X
1030 if (match(Op1, m_AllOnes()))
1031 return BinaryOperator::CreateNeg(Op0);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001032
Benjamin Kramer72196f32014-01-19 15:24:22 +00001033 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001034 // sdiv X, C --> ashr exact X, log2(C)
1035 if (I.isExact() && RHS->getValue().isNonNegative() &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001036 RHS->getValue().isPowerOf2()) {
1037 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1038 RHS->getValue().exactLogBase2());
Chris Lattner6b657ae2011-02-10 05:36:31 +00001039 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001040 }
Benjamin Kramer72196f32014-01-19 15:24:22 +00001041 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001042
Benjamin Kramer72196f32014-01-19 15:24:22 +00001043 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
David Majnemerf28e2a42014-07-02 06:42:13 +00001044 // X/INT_MIN -> X == INT_MIN
1045 if (RHS->isMinSignedValue())
1046 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1047
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001048 // -X/C --> X/-C provided the negation doesn't overflow.
1049 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
Chris Lattner6b657ae2011-02-10 05:36:31 +00001050 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001051 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
1052 ConstantExpr::getNeg(RHS));
1053 }
1054
1055 // If the sign bits of both operands are zero (i.e. we can prove they are
1056 // unsigned inputs), turn this into a udiv.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001057 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001058 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001059 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1060 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001061 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001062 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1063 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001064
Chris Lattner6b657ae2011-02-10 05:36:31 +00001065 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001066 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1067 // Safe because the only negative value (1 << Y) can take on is
1068 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1069 // the sign bit set.
1070 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1071 }
1072 }
1073 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001074
Craig Topperf40110f2014-04-25 05:29:35 +00001075 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001076}
1077
Shuxin Yang320f52a2013-01-14 22:48:41 +00001078/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1079/// FP value and:
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001080/// 1) 1/C is exact, or
Shuxin Yang320f52a2013-01-14 22:48:41 +00001081/// 2) reciprocal is allowed.
Sylvestre Ledru149e2812013-05-14 23:36:24 +00001082/// If the conversion was successful, the simplified expression "X * 1/C" is
Shuxin Yang320f52a2013-01-14 22:48:41 +00001083/// returned; otherwise, NULL is returned.
1084///
Suyog Sardaea205512014-10-07 11:56:06 +00001085static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
Shuxin Yang320f52a2013-01-14 22:48:41 +00001086 bool AllowReciprocal) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001087 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001088 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001089
1090 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001091 APFloat Reciprocal(FpVal.getSemantics());
1092 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001093
Michael Gottesman3cb77ab2013-06-19 21:23:18 +00001094 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001095 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1096 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1097 Cvt = !Reciprocal.isDenormal();
1098 }
1099
1100 if (!Cvt)
Craig Topperf40110f2014-04-25 05:29:35 +00001101 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001102
1103 ConstantFP *R;
1104 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1105 return BinaryOperator::CreateFMul(Dividend, R);
1106}
1107
Frits van Bommel2a559512011-01-29 17:50:27 +00001108Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1109 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1110
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001111 if (Value *V = SimplifyVectorOp(I))
1112 return ReplaceInstUsesWith(I, V);
1113
Hal Finkel60db0582014-09-07 18:57:58 +00001114 if (Value *V = SimplifyFDivInst(Op0, Op1, DL, TLI, DT, AT))
Frits van Bommel2a559512011-01-29 17:50:27 +00001115 return ReplaceInstUsesWith(I, V);
1116
Stephen Lina9b57f62013-07-20 07:13:13 +00001117 if (isa<Constant>(Op0))
1118 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1119 if (Instruction *R = FoldOpIntoSelect(I, SI))
1120 return R;
1121
Shuxin Yang320f52a2013-01-14 22:48:41 +00001122 bool AllowReassociate = I.hasUnsafeAlgebra();
1123 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001124
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001125 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001126 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1127 if (Instruction *R = FoldOpIntoSelect(I, SI))
1128 return R;
1129
Shuxin Yang320f52a2013-01-14 22:48:41 +00001130 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +00001131 Constant *C1 = nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001132 Constant *C2 = Op1C;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001133 Value *X;
Craig Topperf40110f2014-04-25 05:29:35 +00001134 Instruction *Res = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001135
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001136 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001137 // (X*C1)/C2 => X * (C1/C2)
1138 //
1139 Constant *C = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001140 if (isNormalFp(C))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001141 Res = BinaryOperator::CreateFMul(X, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001142 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001143 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1144 //
1145 Constant *C = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001146 if (isNormalFp(C)) {
1147 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001148 if (!Res)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001149 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001150 }
1151 }
1152
1153 if (Res) {
1154 Res->setFastMathFlags(I.getFastMathFlags());
1155 return Res;
1156 }
1157 }
1158
1159 // X / C => X * 1/C
Owen Anderson4557a152014-01-16 21:07:52 +00001160 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1161 T->copyFastMathFlags(&I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001162 return T;
Owen Anderson4557a152014-01-16 21:07:52 +00001163 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001164
Craig Topperf40110f2014-04-25 05:29:35 +00001165 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001166 }
1167
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001168 if (AllowReassociate && isa<Constant>(Op0)) {
1169 Constant *C1 = cast<Constant>(Op0), *C2;
Craig Topperf40110f2014-04-25 05:29:35 +00001170 Constant *Fold = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001171 Value *X;
1172 bool CreateDiv = true;
1173
1174 // C1 / (X*C2) => (C1/C2) / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001175 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001176 Fold = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001177 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001178 // C1 / (X/C2) => (C1*C2) / X
1179 Fold = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001180 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001181 // C1 / (C2/X) => (C1/C2) * X
1182 Fold = ConstantExpr::getFDiv(C1, C2);
1183 CreateDiv = false;
1184 }
1185
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001186 if (Fold && isNormalFp(Fold)) {
1187 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1188 : BinaryOperator::CreateFMul(X, Fold);
1189 R->setFastMathFlags(I.getFastMathFlags());
1190 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001191 }
Craig Topperf40110f2014-04-25 05:29:35 +00001192 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001193 }
1194
1195 if (AllowReassociate) {
1196 Value *X, *Y;
Craig Topperf40110f2014-04-25 05:29:35 +00001197 Value *NewInst = nullptr;
1198 Instruction *SimpR = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001199
1200 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1201 // (X/Y) / Z => X / (Y*Z)
1202 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001203 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001204 NewInst = Builder->CreateFMul(Y, Op1);
Owen Anderson1664dc82014-01-20 07:44:53 +00001205 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1206 FastMathFlags Flags = I.getFastMathFlags();
1207 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1208 RI->setFastMathFlags(Flags);
1209 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001210 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1211 }
1212 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1213 // Z / (X/Y) => Z*Y / X
1214 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001215 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001216 NewInst = Builder->CreateFMul(Op0, Y);
Owen Anderson1664dc82014-01-20 07:44:53 +00001217 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1218 FastMathFlags Flags = I.getFastMathFlags();
1219 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1220 RI->setFastMathFlags(Flags);
1221 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001222 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1223 }
1224 }
1225
1226 if (NewInst) {
1227 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1228 T->setDebugLoc(I.getDebugLoc());
1229 SimpR->setFastMathFlags(I.getFastMathFlags());
1230 return SimpR;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001231 }
1232 }
1233
Craig Topperf40110f2014-04-25 05:29:35 +00001234 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001235}
1236
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001237/// This function implements the transforms common to both integer remainder
1238/// instructions (urem and srem). It is called by the visitors to those integer
1239/// remainder instructions.
1240/// @brief Common integer remainder transforms
1241Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1242 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1243
Chris Lattner7c99f192011-05-22 18:18:41 +00001244 // The RHS is known non-zero.
Hal Finkel60db0582014-09-07 18:57:58 +00001245 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +00001246 I.setOperand(1, V);
1247 return &I;
1248 }
1249
Duncan Sandsa3e36992011-05-02 16:27:02 +00001250 // Handle cases involving: rem X, (select Cond, Y, Z)
1251 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1252 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001253
Benjamin Kramer72196f32014-01-19 15:24:22 +00001254 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001255 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1256 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1257 if (Instruction *R = FoldOpIntoSelect(I, SI))
1258 return R;
1259 } else if (isa<PHINode>(Op0I)) {
1260 if (Instruction *NV = FoldOpIntoPhi(I))
1261 return NV;
1262 }
1263
1264 // See if we can fold away this rem instruction.
1265 if (SimplifyDemandedInstructionBits(I))
1266 return &I;
1267 }
1268 }
1269
Craig Topperf40110f2014-04-25 05:29:35 +00001270 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001271}
1272
1273Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1274 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1275
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001276 if (Value *V = SimplifyVectorOp(I))
1277 return ReplaceInstUsesWith(I, V);
1278
Hal Finkel60db0582014-09-07 18:57:58 +00001279 if (Value *V = SimplifyURemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001280 return ReplaceInstUsesWith(I, V);
1281
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001282 if (Instruction *common = commonIRemTransforms(I))
1283 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001284
David Majnemer6c30f492013-05-12 00:07:05 +00001285 // (zext A) urem (zext B) --> zext (A urem B)
1286 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1287 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1288 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1289 I.getType());
1290
David Majnemer470b0772013-05-11 09:01:28 +00001291 // X urem Y -> X and Y-1, where Y is a power of 2,
Hal Finkel60db0582014-09-07 18:57:58 +00001292 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, AT, &I, DT)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001293 Constant *N1 = Constant::getAllOnesValue(I.getType());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001294 Value *Add = Builder->CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001295 return BinaryOperator::CreateAnd(Op0, Add);
1296 }
1297
Nick Lewycky7459be62013-07-13 01:16:47 +00001298 // 1 urem X -> zext(X != 1)
1299 if (match(Op0, m_One())) {
1300 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1301 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1302 return ReplaceInstUsesWith(I, Ext);
1303 }
1304
Craig Topperf40110f2014-04-25 05:29:35 +00001305 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001306}
1307
1308Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1309 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1310
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001311 if (Value *V = SimplifyVectorOp(I))
1312 return ReplaceInstUsesWith(I, V);
1313
Hal Finkel60db0582014-09-07 18:57:58 +00001314 if (Value *V = SimplifySRemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001315 return ReplaceInstUsesWith(I, V);
1316
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001317 // Handle the integer rem common cases
1318 if (Instruction *Common = commonIRemTransforms(I))
1319 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001320
David Majnemerdb077302014-10-13 22:37:51 +00001321 {
1322 const APInt *Y;
1323 // X % -Y -> X % Y
1324 if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001325 Worklist.AddValue(I.getOperand(1));
David Majnemerdb077302014-10-13 22:37:51 +00001326 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001327 return &I;
1328 }
David Majnemerdb077302014-10-13 22:37:51 +00001329 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001330
1331 // If the sign bits of both operands are zero (i.e. we can prove they are
1332 // unsigned inputs), turn this into a urem.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001333 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001334 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001335 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1336 MaskedValueIsZero(Op0, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001337 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001338 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1339 }
1340 }
1341
1342 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001343 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1344 Constant *C = cast<Constant>(Op1);
1345 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001346
1347 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001348 bool hasMissing = false;
1349 for (unsigned i = 0; i != VWidth; ++i) {
1350 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001351 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001352 hasMissing = true;
1353 break;
1354 }
1355
1356 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001357 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001358 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001359 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001360
Chris Lattner0256be92012-01-27 03:08:05 +00001361 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001362 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001363 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001364 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001365 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001366 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001367 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001368 }
1369 }
1370
1371 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001372 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001373 Worklist.AddValue(I.getOperand(1));
1374 I.setOperand(1, NewRHSV);
1375 return &I;
1376 }
1377 }
1378 }
1379
Craig Topperf40110f2014-04-25 05:29:35 +00001380 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001381}
1382
1383Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001384 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001385
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001386 if (Value *V = SimplifyVectorOp(I))
1387 return ReplaceInstUsesWith(I, V);
1388
Hal Finkel60db0582014-09-07 18:57:58 +00001389 if (Value *V = SimplifyFRemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001390 return ReplaceInstUsesWith(I, V);
1391
1392 // Handle cases involving: rem X, (select Cond, Y, Z)
1393 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1394 return &I;
1395
Craig Topperf40110f2014-04-25 05:29:35 +00001396 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001397}