blob: 010625a715716e7debf88df3245ab98db442315e [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
David Majnemer8279a7502014-11-22 07:25:19 +0000240 if (Value *Op0v = dyn_castNegVal(Op0)) { // -X * -Y = X*Y
241 if (Value *Op1v = dyn_castNegVal(Op1)) {
242 BinaryOperator *BO = BinaryOperator::CreateMul(Op0v, Op1v);
243 if (I.hasNoSignedWrap() &&
244 match(Op0, m_NSWSub(m_Value(), m_Value())) &&
245 match(Op1, m_NSWSub(m_Value(), m_Value())))
246 BO->setHasNoSignedWrap();
247 return BO;
248 }
249 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000250
251 // (X / Y) * Y = X - (X % Y)
252 // (X / Y) * -Y = (X % Y) - X
253 {
254 Value *Op1C = Op1;
255 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
256 if (!BO ||
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000257 (BO->getOpcode() != Instruction::UDiv &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000258 BO->getOpcode() != Instruction::SDiv)) {
259 Op1C = Op0;
260 BO = dyn_cast<BinaryOperator>(Op1);
261 }
262 Value *Neg = dyn_castNegVal(Op1C);
263 if (BO && BO->hasOneUse() &&
264 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
265 (BO->getOpcode() == Instruction::UDiv ||
266 BO->getOpcode() == Instruction::SDiv)) {
267 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
268
Chris Lattner35315d02011-02-06 21:44:57 +0000269 // If the division is exact, X % Y is zero, so we end up with X or -X.
270 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000271 if (SDiv->isExact()) {
272 if (Op1BO == Op1C)
273 return ReplaceInstUsesWith(I, Op0BO);
274 return BinaryOperator::CreateNeg(Op0BO);
275 }
276
277 Value *Rem;
278 if (BO->getOpcode() == Instruction::UDiv)
279 Rem = Builder->CreateURem(Op0BO, Op1BO);
280 else
281 Rem = Builder->CreateSRem(Op0BO, Op1BO);
282 Rem->takeName(BO);
283
284 if (Op1BO == Op1C)
285 return BinaryOperator::CreateSub(Op0BO, Rem);
286 return BinaryOperator::CreateSub(Rem, Op0BO);
287 }
288 }
289
290 /// i1 mul -> i1 and.
Benjamin Kramer72196f32014-01-19 15:24:22 +0000291 if (I.getType()->getScalarType()->isIntegerTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000292 return BinaryOperator::CreateAnd(Op0, Op1);
293
294 // X*(1 << Y) --> X << Y
295 // (1 << Y)*X --> X << Y
296 {
297 Value *Y;
David Majnemer546f8102014-11-22 08:57:02 +0000298 BinaryOperator *BO = nullptr;
299 bool ShlNSW = false;
300 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
301 BO = BinaryOperator::CreateShl(Op1, Y);
302 ShlNSW = cast<BinaryOperator>(Op0)->hasNoSignedWrap();
303 }
304 if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
305 BO = BinaryOperator::CreateShl(Op0, Y);
306 ShlNSW = cast<BinaryOperator>(Op1)->hasNoSignedWrap();
307 }
308 if (BO) {
309 if (I.hasNoUnsignedWrap())
310 BO->setHasNoUnsignedWrap();
311 if (I.hasNoSignedWrap() && ShlNSW)
312 BO->setHasNoSignedWrap();
313 return BO;
314 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000315 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000316
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000317 // If one of the operands of the multiply is a cast from a boolean value, then
318 // we know the bool is either zero or one, so this is a 'masking' multiply.
319 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands19d0b472010-02-16 11:11:14 +0000320 if (!I.getType()->isVectorTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000321 // -2 is "-1 << 1" so it is all bits set except the low one.
322 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000323
Craig Topperf40110f2014-04-25 05:29:35 +0000324 Value *BoolCast = nullptr, *OtherOp = nullptr;
Hal Finkel60db0582014-09-07 18:57:58 +0000325 if (MaskedValueIsZero(Op0, Negative2, 0, &I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000326 BoolCast = Op0, OtherOp = Op1;
Hal Finkel60db0582014-09-07 18:57:58 +0000327 else if (MaskedValueIsZero(Op1, Negative2, 0, &I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000328 BoolCast = Op1, OtherOp = Op0;
329
330 if (BoolCast) {
331 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000332 BoolCast);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000333 return BinaryOperator::CreateAnd(V, OtherOp);
334 }
335 }
336
Craig Topperf40110f2014-04-25 05:29:35 +0000337 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000338}
339
Sanjay Patel17045f72014-10-14 00:33:23 +0000340/// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
Pedro Artigas993acd02012-11-30 22:07:05 +0000341static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Sanjay Patel17045f72014-10-14 00:33:23 +0000342 if (!Op->hasOneUse())
343 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000344
Sanjay Patel17045f72014-10-14 00:33:23 +0000345 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
346 if (!II)
347 return;
348 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
349 return;
350 Log2 = II;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000351
Sanjay Patel17045f72014-10-14 00:33:23 +0000352 Value *OpLog2Of = II->getArgOperand(0);
353 if (!OpLog2Of->hasOneUse())
354 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000355
Sanjay Patel17045f72014-10-14 00:33:23 +0000356 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
357 if (!I)
358 return;
359 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
360 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000361
Sanjay Patel17045f72014-10-14 00:33:23 +0000362 if (match(I->getOperand(0), m_SpecificFP(0.5)))
363 Y = I->getOperand(1);
364 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
365 Y = I->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000366}
Pedro Artigas993acd02012-11-30 22:07:05 +0000367
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000368static bool isFiniteNonZeroFp(Constant *C) {
369 if (C->getType()->isVectorTy()) {
370 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
371 ++I) {
372 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
373 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
374 return false;
375 }
376 return true;
377 }
378
379 return isa<ConstantFP>(C) &&
380 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
381}
382
383static bool isNormalFp(Constant *C) {
384 if (C->getType()->isVectorTy()) {
385 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
386 ++I) {
387 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
388 if (!CFP || !CFP->getValueAPF().isNormal())
389 return false;
390 }
391 return true;
392 }
393
394 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
395}
396
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000397/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
398/// true iff the given value is FMul or FDiv with one and only one operand
399/// being a normal constant (i.e. not Zero/NaN/Infinity).
400static bool isFMulOrFDivWithConstant(Value *V) {
401 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000402 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yang80138662013-01-07 22:41:28 +0000403 I->getOpcode() != Instruction::FDiv))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000404 return false;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000405
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000406 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
407 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000408
409 if (C0 && C1)
410 return false;
411
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000412 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000413}
414
415/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
416/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
417/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000418/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000419/// resulting expression. Note that this function could return NULL in
420/// case the constants cannot be folded into a normal floating-point.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000421///
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000422Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yang80138662013-01-07 22:41:28 +0000423 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000424 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
425
426 Value *Opnd0 = FMulOrDiv->getOperand(0);
427 Value *Opnd1 = FMulOrDiv->getOperand(1);
428
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000429 Constant *C0 = dyn_cast<Constant>(Opnd0);
430 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000431
Craig Topperf40110f2014-04-25 05:29:35 +0000432 BinaryOperator *R = nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000433
434 // (X * C0) * C => X * (C0*C)
435 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
436 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000437 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000438 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
439 } else {
440 if (C0) {
441 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000442 if (FMulOrDiv->hasOneUse()) {
443 // It would otherwise introduce another div.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000444 Constant *F = ConstantExpr::getFMul(C0, C);
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000445 if (isNormalFp(F))
446 R = BinaryOperator::CreateFDiv(F, Opnd1);
447 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000448 } else {
449 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000450 Constant *F = ConstantExpr::getFDiv(C, C1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000451 if (isNormalFp(F)) {
452 R = BinaryOperator::CreateFMul(Opnd0, F);
453 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000454 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000455 Constant *F = ConstantExpr::getFDiv(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000456 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000457 R = BinaryOperator::CreateFDiv(Opnd0, F);
458 }
459 }
460 }
461
462 if (R) {
463 R->setHasUnsafeAlgebra(true);
464 InsertNewInstWith(R, *InsertBefore);
465 }
466
467 return R;
468}
469
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000470Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000471 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000472 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
473
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000474 if (Value *V = SimplifyVectorOp(I))
475 return ReplaceInstUsesWith(I, V);
476
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000477 if (isa<Constant>(Op0))
478 std::swap(Op0, Op1);
479
Hal Finkel60db0582014-09-07 18:57:58 +0000480 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL, TLI,
481 DT, AT))
Michael Ilsemand5787be2012-12-12 00:28:32 +0000482 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000483
Shuxin Yange8227452013-01-15 21:09:32 +0000484 bool AllowReassociate = I.hasUnsafeAlgebra();
485
Michael Ilsemand5787be2012-12-12 00:28:32 +0000486 // Simplify mul instructions with a constant RHS.
487 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000488 // Try to fold constant mul into select arguments.
489 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
490 if (Instruction *R = FoldOpIntoSelect(I, SI))
491 return R;
492
493 if (isa<PHINode>(Op0))
494 if (Instruction *NV = FoldOpIntoPhi(I))
495 return NV;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000496
Owen Andersonf74cfe02014-01-16 20:36:42 +0000497 // (fmul X, -1.0) --> (fsub -0.0, X)
Benjamin Kramerfea9ac92014-01-18 16:43:14 +0000498 if (match(Op1, m_SpecificFP(-1.0))) {
499 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
500 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000501 RI->copyFastMathFlags(&I);
502 return RI;
503 }
504
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000505 Constant *C = cast<Constant>(Op1);
506 if (AllowReassociate && isFiniteNonZeroFp(C)) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000507 // Let MDC denote an expression in one of these forms:
508 // X * C, C/X, X/C, where C is a constant.
509 //
510 // Try to simplify "MDC * Constant"
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000511 if (isFMulOrFDivWithConstant(Op0))
512 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000513 return ReplaceInstUsesWith(I, V);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000514
Quentin Colombete684a6d2013-02-28 21:12:40 +0000515 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000516 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
517 if (FAddSub &&
518 (FAddSub->getOpcode() == Instruction::FAdd ||
519 FAddSub->getOpcode() == Instruction::FSub)) {
520 Value *Opnd0 = FAddSub->getOperand(0);
521 Value *Opnd1 = FAddSub->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000522 Constant *C0 = dyn_cast<Constant>(Opnd0);
523 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000524 bool Swap = false;
525 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000526 std::swap(C0, C1);
527 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000528 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000529 }
530
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000531 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000532 Value *M1 = ConstantExpr::getFMul(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000533 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000534 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
Craig Topperf40110f2014-04-25 05:29:35 +0000535 nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000536 if (M0 && M1) {
537 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
538 std::swap(M0, M1);
539
Benjamin Kramer67485762013-09-30 15:39:59 +0000540 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
541 ? BinaryOperator::CreateFAdd(M0, M1)
542 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000543 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000544 return RI;
545 }
546 }
547 }
548 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000549 }
550
Sanjay Patel12d1ce52014-10-02 21:10:54 +0000551 // sqrt(X) * sqrt(X) -> X
552 if (AllowReassociate && (Op0 == Op1))
553 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0))
554 if (II->getIntrinsicID() == Intrinsic::sqrt)
555 return ReplaceInstUsesWith(I, II->getOperand(0));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000556
Pedro Artigasd8795042012-11-30 19:09:41 +0000557 // Under unsafe algebra do:
558 // X * log2(0.5*Y) = X*log2(Y) - X
Sanjay Patelb41d4612014-10-02 15:20:45 +0000559 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +0000560 Value *OpX = nullptr;
561 Value *OpY = nullptr;
Pedro Artigasd8795042012-11-30 19:09:41 +0000562 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000563 detectLog2OfHalf(Op0, OpY, Log2);
564 if (OpY) {
565 OpX = Op1;
566 } else {
567 detectLog2OfHalf(Op1, OpY, Log2);
568 if (OpY) {
569 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000570 }
571 }
572 // if pattern detected emit alternate sequence
573 if (OpX && OpY) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000574 BuilderTy::FastMathFlagGuard Guard(*Builder);
575 Builder->SetFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000576 Log2->setArgOperand(0, OpY);
577 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
Benjamin Kramer67485762013-09-30 15:39:59 +0000578 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
579 FSub->takeName(&I);
580 return ReplaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000581 }
582 }
583
Shuxin Yange8227452013-01-15 21:09:32 +0000584 // Handle symmetric situation in a 2-iteration loop
585 Value *Opnd0 = Op0;
586 Value *Opnd1 = Op1;
587 for (int i = 0; i < 2; i++) {
588 bool IgnoreZeroSign = I.hasNoSignedZeros();
589 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000590 BuilderTy::FastMathFlagGuard Guard(*Builder);
591 Builder->SetFastMathFlags(I.getFastMathFlags());
592
Shuxin Yange8227452013-01-15 21:09:32 +0000593 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
594 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000595
Shuxin Yange8227452013-01-15 21:09:32 +0000596 // -X * -Y => X*Y
Owen Andersone8537fc2014-01-16 20:59:41 +0000597 if (N1) {
598 Value *FMul = Builder->CreateFMul(N0, N1);
599 FMul->takeName(&I);
600 return ReplaceInstUsesWith(I, FMul);
601 }
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000602
Shuxin Yange8227452013-01-15 21:09:32 +0000603 if (Opnd0->hasOneUse()) {
604 // -X * Y => -(X*Y) (Promote negation as high as possible)
605 Value *T = Builder->CreateFMul(N0, Opnd1);
Benjamin Kramer67485762013-09-30 15:39:59 +0000606 Value *Neg = Builder->CreateFNeg(T);
607 Neg->takeName(&I);
608 return ReplaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000609 }
610 }
Shuxin Yange8227452013-01-15 21:09:32 +0000611
612 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000613 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000614 // 1) to form a power expression (of X).
615 // 2) potentially shorten the critical path: After transformation, the
616 // latency of the instruction Y is amortized by the expression of X*X,
617 // and therefore Y is in a "less critical" position compared to what it
618 // was before the transformation.
619 //
620 if (AllowReassociate) {
621 Value *Opnd0_0, *Opnd0_1;
622 if (Opnd0->hasOneUse() &&
623 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000624 Value *Y = nullptr;
Shuxin Yange8227452013-01-15 21:09:32 +0000625 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
626 Y = Opnd0_1;
627 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
628 Y = Opnd0_0;
629
630 if (Y) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000631 BuilderTy::FastMathFlagGuard Guard(*Builder);
632 Builder->SetFastMathFlags(I.getFastMathFlags());
633 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
Shuxin Yange8227452013-01-15 21:09:32 +0000634
Benjamin Kramer67485762013-09-30 15:39:59 +0000635 Value *R = Builder->CreateFMul(T, Y);
636 R->takeName(&I);
637 return ReplaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000638 }
639 }
640 }
641
642 if (!isa<Constant>(Op1))
643 std::swap(Opnd0, Opnd1);
644 else
645 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000646 }
647
Craig Topperf40110f2014-04-25 05:29:35 +0000648 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000649}
650
651/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
652/// instruction.
653bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
654 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000655
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000656 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
657 int NonNullOperand = -1;
658 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
659 if (ST->isNullValue())
660 NonNullOperand = 2;
661 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
662 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
663 if (ST->isNullValue())
664 NonNullOperand = 1;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000665
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000666 if (NonNullOperand == -1)
667 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000668
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000669 Value *SelectCond = SI->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000670
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000671 // Change the div/rem to use 'Y' instead of the select.
672 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000673
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000674 // Okay, we know we replace the operand of the div/rem with 'Y' with no
675 // problem. However, the select, or the condition of the select may have
676 // multiple uses. Based on our knowledge that the operand must be non-zero,
677 // propagate the known value for the select into other uses of it, and
678 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000679
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000680 // If the select and condition only have a single use, don't bother with this,
681 // early exit.
682 if (SI->use_empty() && SelectCond->hasOneUse())
683 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000684
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000685 // Scan the current block backward, looking for other uses of SI.
686 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000687
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000688 while (BBI != BBFront) {
689 --BBI;
690 // If we found a call to a function, we can't assume it will return, so
691 // information from below it cannot be propagated above it.
692 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
693 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000694
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000695 // Replace uses of the select or its condition with the known values.
696 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
697 I != E; ++I) {
698 if (*I == SI) {
699 *I = SI->getOperand(NonNullOperand);
700 Worklist.Add(BBI);
701 } else if (*I == SelectCond) {
Jakub Staszak96ff4d62013-06-06 23:34:59 +0000702 *I = Builder->getInt1(NonNullOperand == 1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000703 Worklist.Add(BBI);
704 }
705 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000706
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000707 // If we past the instruction, quit looking for it.
708 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000709 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000710 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000711 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000712
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000713 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000714 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000715 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000716
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000717 }
718 return true;
719}
720
721
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000722/// This function implements the transforms common to both integer division
723/// instructions (udiv and sdiv). It is called by the visitors to those integer
724/// division instructions.
725/// @brief Common integer divide transforms
726Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
727 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
728
Chris Lattner7c99f192011-05-22 18:18:41 +0000729 // The RHS is known non-zero.
Hal Finkel60db0582014-09-07 18:57:58 +0000730 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +0000731 I.setOperand(1, V);
732 return &I;
733 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000734
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000735 // Handle cases involving: [su]div X, (select Cond, Y, Z)
736 // This does not apply for fdiv.
737 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
738 return &I;
739
David Majnemer27adb122014-10-12 08:34:24 +0000740 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
741 const APInt *C2;
742 if (match(Op1, m_APInt(C2))) {
David Majnemerf9a095d2014-08-16 08:55:06 +0000743 Value *X;
David Majnemer27adb122014-10-12 08:34:24 +0000744 const APInt *C1;
745 bool IsSigned = I.getOpcode() == Instruction::SDiv;
David Majnemerf9a095d2014-08-16 08:55:06 +0000746
David Majnemer27adb122014-10-12 08:34:24 +0000747 // (X / C1) / C2 -> X / (C1*C2)
748 if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
749 (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
750 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
751 if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
752 return BinaryOperator::Create(I.getOpcode(), X,
753 ConstantInt::get(I.getType(), Product));
754 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000755
David Majnemer27adb122014-10-12 08:34:24 +0000756 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
757 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
758 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
759
760 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
761 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
762 BinaryOperator *BO = BinaryOperator::Create(
763 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
764 BO->setIsExact(I.isExact());
765 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000766 }
767
David Majnemer27adb122014-10-12 08:34:24 +0000768 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
769 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
770 BinaryOperator *BO = BinaryOperator::Create(
771 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
772 BO->setHasNoUnsignedWrap(
773 !IsSigned &&
774 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
775 BO->setHasNoSignedWrap(
776 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
777 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000778 }
779 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000780
David Majnemer27adb122014-10-12 08:34:24 +0000781 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
782 *C1 != C1->getBitWidth() - 1) ||
783 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
784 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
785 APInt C1Shifted = APInt::getOneBitSet(
786 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
787
788 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
789 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
790 BinaryOperator *BO = BinaryOperator::Create(
791 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
792 BO->setIsExact(I.isExact());
793 return BO;
794 }
795
796 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
797 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
798 BinaryOperator *BO = BinaryOperator::Create(
799 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
800 BO->setHasNoUnsignedWrap(
801 !IsSigned &&
802 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
803 BO->setHasNoSignedWrap(
804 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
805 return BO;
806 }
807 }
808
809 if (*C2 != 0) { // avoid X udiv 0
810 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
811 if (Instruction *R = FoldOpIntoSelect(I, SI))
812 return R;
813 if (isa<PHINode>(Op0))
814 if (Instruction *NV = FoldOpIntoPhi(I))
815 return NV;
816 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000817 }
818 }
819
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000820 if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
821 if (One->isOne() && !I.getType()->isIntegerTy(1)) {
822 bool isSigned = I.getOpcode() == Instruction::SDiv;
823 if (isSigned) {
824 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
825 // result is one, if Op1 is -1 then the result is minus one, otherwise
826 // it's zero.
827 Value *Inc = Builder->CreateAdd(Op1, One);
828 Value *Cmp = Builder->CreateICmpULT(
829 Inc, ConstantInt::get(I.getType(), 3));
830 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
831 } else {
832 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
833 // result is one, otherwise it's zero.
834 return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
835 }
836 }
837 }
838
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000839 // See if we can fold away this div instruction.
840 if (SimplifyDemandedInstructionBits(I))
841 return &I;
842
Duncan Sands771e82a2011-01-28 16:51:11 +0000843 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Craig Topperf40110f2014-04-25 05:29:35 +0000844 Value *X = nullptr, *Z = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +0000845 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
846 bool isSigned = I.getOpcode() == Instruction::SDiv;
847 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
848 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
849 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000850 }
851
Craig Topperf40110f2014-04-25 05:29:35 +0000852 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000853}
854
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000855/// dyn_castZExtVal - Checks if V is a zext or constant that can
856/// be truncated to Ty without losing bits.
Chris Lattner229907c2011-07-18 04:54:35 +0000857static Value *dyn_castZExtVal(Value *V, Type *Ty) {
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000858 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
859 if (Z->getSrcTy() == Ty)
860 return Z->getOperand(0);
861 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
862 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
863 return ConstantExpr::getTrunc(C, Ty);
864 }
Craig Topperf40110f2014-04-25 05:29:35 +0000865 return nullptr;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000866}
867
David Majnemer37f8f442013-07-04 21:17:49 +0000868namespace {
869const unsigned MaxDepth = 6;
870typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
871 const BinaryOperator &I,
872 InstCombiner &IC);
873
874/// \brief Used to maintain state for visitUDivOperand().
875struct UDivFoldAction {
876 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
877 ///< operand. This can be zero if this action
878 ///< joins two actions together.
879
880 Value *OperandToFold; ///< Which operand to fold.
881 union {
882 Instruction *FoldResult; ///< The instruction returned when FoldAction is
883 ///< invoked.
884
885 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
886 ///< joins two actions together.
887 };
888
889 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +0000890 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +0000891 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
892 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
893};
894}
895
896// X udiv 2^C -> X >> C
897static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
898 const BinaryOperator &I, InstCombiner &IC) {
899 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
900 BinaryOperator *LShr = BinaryOperator::CreateLShr(
901 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000902 if (I.isExact())
903 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000904 return LShr;
905}
906
907// X udiv C, where C >= signbit
908static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
909 const BinaryOperator &I, InstCombiner &IC) {
910 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
911
912 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
913 ConstantInt::get(I.getType(), 1));
914}
915
916// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
917static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
918 InstCombiner &IC) {
919 Instruction *ShiftLeft = cast<Instruction>(Op1);
920 if (isa<ZExtInst>(ShiftLeft))
921 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
922
923 const APInt &CI =
924 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
925 Value *N = ShiftLeft->getOperand(1);
926 if (CI != 1)
927 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
928 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
929 N = IC.Builder->CreateZExt(N, Z->getDestTy());
930 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000931 if (I.isExact())
932 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000933 return LShr;
934}
935
936// \brief Recursively visits the possible right hand operands of a udiv
937// instruction, seeing through select instructions, to determine if we can
938// replace the udiv with something simpler. If we find that an operand is not
939// able to simplify the udiv, we abort the entire transformation.
940static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
941 SmallVectorImpl<UDivFoldAction> &Actions,
942 unsigned Depth = 0) {
943 // Check to see if this is an unsigned division with an exact power of 2,
944 // if so, convert to a right shift.
945 if (match(Op1, m_Power2())) {
946 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
947 return Actions.size();
948 }
949
950 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
951 // X udiv C, where C >= signbit
952 if (C->getValue().isNegative()) {
953 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
954 return Actions.size();
955 }
956
957 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
958 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
959 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
960 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
961 return Actions.size();
962 }
963
964 // The remaining tests are all recursive, so bail out if we hit the limit.
965 if (Depth++ == MaxDepth)
966 return 0;
967
968 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
David Majnemer492e6122014-08-30 09:19:05 +0000969 if (size_t LHSIdx =
970 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
971 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
972 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
David Majnemer37f8f442013-07-04 21:17:49 +0000973 return Actions.size();
974 }
975
976 return 0;
977}
978
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000979Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
980 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
981
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000982 if (Value *V = SimplifyVectorOp(I))
983 return ReplaceInstUsesWith(I, V);
984
Hal Finkel60db0582014-09-07 18:57:58 +0000985 if (Value *V = SimplifyUDivInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sands771e82a2011-01-28 16:51:11 +0000986 return ReplaceInstUsesWith(I, V);
987
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000988 // Handle the integer div common cases
989 if (Instruction *Common = commonIDivTransforms(I))
990 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000991
Benjamin Kramerd4a64712012-08-30 15:07:40 +0000992 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
David Majnemera2521382014-10-13 21:48:30 +0000993 {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +0000994 Value *X;
David Majnemera2521382014-10-13 21:48:30 +0000995 const APInt *C1, *C2;
996 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
997 match(Op1, m_APInt(C2))) {
998 bool Overflow;
999 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
1000 if (!Overflow)
1001 return BinaryOperator::CreateUDiv(
1002 X, ConstantInt::get(X->getType(), C2ShlC1));
1003 }
Nadav Rotem11935b22012-08-28 10:01:43 +00001004 }
1005
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001006 // (zext A) udiv (zext B) --> zext (A udiv B)
1007 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1008 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
Suyog Sardaea205512014-10-07 11:56:06 +00001009 return new ZExtInst(
1010 Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", I.isExact()),
1011 I.getType());
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001012
David Majnemer37f8f442013-07-04 21:17:49 +00001013 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1014 SmallVector<UDivFoldAction, 6> UDivActions;
1015 if (visitUDivOperand(Op0, Op1, I, UDivActions))
1016 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1017 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1018 Value *ActionOp1 = UDivActions[i].OperandToFold;
1019 Instruction *Inst;
1020 if (Action)
1021 Inst = Action(Op0, ActionOp1, I, *this);
1022 else {
1023 // This action joins two actions together. The RHS of this action is
1024 // simply the last action we processed, we saved the LHS action index in
1025 // the joining action.
1026 size_t SelectRHSIdx = i - 1;
1027 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1028 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1029 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1030 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1031 SelectLHS, SelectRHS);
1032 }
1033
1034 // If this is the last action to process, return it to the InstCombiner.
1035 // Otherwise, we insert it before the UDiv and record it so that we may
1036 // use it as part of a joining action (i.e., a SelectInst).
1037 if (e - i != 1) {
1038 Inst->insertBefore(&I);
1039 UDivActions[i].FoldResult = Inst;
1040 } else
1041 return Inst;
1042 }
1043
Craig Topperf40110f2014-04-25 05:29:35 +00001044 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001045}
1046
1047Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1048 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1049
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001050 if (Value *V = SimplifyVectorOp(I))
1051 return ReplaceInstUsesWith(I, V);
1052
Hal Finkel60db0582014-09-07 18:57:58 +00001053 if (Value *V = SimplifySDivInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sands771e82a2011-01-28 16:51:11 +00001054 return ReplaceInstUsesWith(I, V);
1055
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001056 // Handle the integer div common cases
1057 if (Instruction *Common = commonIDivTransforms(I))
1058 return Common;
1059
Benjamin Kramer72196f32014-01-19 15:24:22 +00001060 // sdiv X, -1 == -X
1061 if (match(Op1, m_AllOnes()))
1062 return BinaryOperator::CreateNeg(Op0);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001063
Benjamin Kramer72196f32014-01-19 15:24:22 +00001064 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001065 // sdiv X, C --> ashr exact X, log2(C)
1066 if (I.isExact() && RHS->getValue().isNonNegative() &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001067 RHS->getValue().isPowerOf2()) {
1068 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1069 RHS->getValue().exactLogBase2());
Chris Lattner6b657ae2011-02-10 05:36:31 +00001070 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001071 }
Benjamin Kramer72196f32014-01-19 15:24:22 +00001072 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001073
Benjamin Kramer72196f32014-01-19 15:24:22 +00001074 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
David Majnemerf28e2a42014-07-02 06:42:13 +00001075 // X/INT_MIN -> X == INT_MIN
1076 if (RHS->isMinSignedValue())
1077 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1078
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001079 // -X/C --> X/-C provided the negation doesn't overflow.
1080 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
Chris Lattner6b657ae2011-02-10 05:36:31 +00001081 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001082 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
1083 ConstantExpr::getNeg(RHS));
1084 }
1085
1086 // If the sign bits of both operands are zero (i.e. we can prove they are
1087 // unsigned inputs), turn this into a udiv.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001088 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001089 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001090 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1091 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001092 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001093 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1094 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001095
Chris Lattner6b657ae2011-02-10 05:36:31 +00001096 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001097 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1098 // Safe because the only negative value (1 << Y) can take on is
1099 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1100 // the sign bit set.
1101 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1102 }
1103 }
1104 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001105
Craig Topperf40110f2014-04-25 05:29:35 +00001106 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001107}
1108
Shuxin Yang320f52a2013-01-14 22:48:41 +00001109/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1110/// FP value and:
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001111/// 1) 1/C is exact, or
Shuxin Yang320f52a2013-01-14 22:48:41 +00001112/// 2) reciprocal is allowed.
Sylvestre Ledru149e2812013-05-14 23:36:24 +00001113/// If the conversion was successful, the simplified expression "X * 1/C" is
Shuxin Yang320f52a2013-01-14 22:48:41 +00001114/// returned; otherwise, NULL is returned.
1115///
Suyog Sardaea205512014-10-07 11:56:06 +00001116static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
Shuxin Yang320f52a2013-01-14 22:48:41 +00001117 bool AllowReciprocal) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001118 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001119 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001120
1121 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001122 APFloat Reciprocal(FpVal.getSemantics());
1123 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001124
Michael Gottesman3cb77ab2013-06-19 21:23:18 +00001125 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001126 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1127 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1128 Cvt = !Reciprocal.isDenormal();
1129 }
1130
1131 if (!Cvt)
Craig Topperf40110f2014-04-25 05:29:35 +00001132 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001133
1134 ConstantFP *R;
1135 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1136 return BinaryOperator::CreateFMul(Dividend, R);
1137}
1138
Frits van Bommel2a559512011-01-29 17:50:27 +00001139Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1140 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1141
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001142 if (Value *V = SimplifyVectorOp(I))
1143 return ReplaceInstUsesWith(I, V);
1144
Hal Finkel60db0582014-09-07 18:57:58 +00001145 if (Value *V = SimplifyFDivInst(Op0, Op1, DL, TLI, DT, AT))
Frits van Bommel2a559512011-01-29 17:50:27 +00001146 return ReplaceInstUsesWith(I, V);
1147
Stephen Lina9b57f62013-07-20 07:13:13 +00001148 if (isa<Constant>(Op0))
1149 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1150 if (Instruction *R = FoldOpIntoSelect(I, SI))
1151 return R;
1152
Shuxin Yang320f52a2013-01-14 22:48:41 +00001153 bool AllowReassociate = I.hasUnsafeAlgebra();
1154 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001155
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001156 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001157 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1158 if (Instruction *R = FoldOpIntoSelect(I, SI))
1159 return R;
1160
Shuxin Yang320f52a2013-01-14 22:48:41 +00001161 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +00001162 Constant *C1 = nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001163 Constant *C2 = Op1C;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001164 Value *X;
Craig Topperf40110f2014-04-25 05:29:35 +00001165 Instruction *Res = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001166
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001167 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001168 // (X*C1)/C2 => X * (C1/C2)
1169 //
1170 Constant *C = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001171 if (isNormalFp(C))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001172 Res = BinaryOperator::CreateFMul(X, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001173 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001174 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1175 //
1176 Constant *C = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001177 if (isNormalFp(C)) {
1178 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001179 if (!Res)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001180 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001181 }
1182 }
1183
1184 if (Res) {
1185 Res->setFastMathFlags(I.getFastMathFlags());
1186 return Res;
1187 }
1188 }
1189
1190 // X / C => X * 1/C
Owen Anderson4557a152014-01-16 21:07:52 +00001191 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1192 T->copyFastMathFlags(&I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001193 return T;
Owen Anderson4557a152014-01-16 21:07:52 +00001194 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001195
Craig Topperf40110f2014-04-25 05:29:35 +00001196 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001197 }
1198
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001199 if (AllowReassociate && isa<Constant>(Op0)) {
1200 Constant *C1 = cast<Constant>(Op0), *C2;
Craig Topperf40110f2014-04-25 05:29:35 +00001201 Constant *Fold = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001202 Value *X;
1203 bool CreateDiv = true;
1204
1205 // C1 / (X*C2) => (C1/C2) / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001206 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001207 Fold = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001208 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001209 // C1 / (X/C2) => (C1*C2) / X
1210 Fold = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001211 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001212 // C1 / (C2/X) => (C1/C2) * X
1213 Fold = ConstantExpr::getFDiv(C1, C2);
1214 CreateDiv = false;
1215 }
1216
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001217 if (Fold && isNormalFp(Fold)) {
1218 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1219 : BinaryOperator::CreateFMul(X, Fold);
1220 R->setFastMathFlags(I.getFastMathFlags());
1221 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001222 }
Craig Topperf40110f2014-04-25 05:29:35 +00001223 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001224 }
1225
1226 if (AllowReassociate) {
1227 Value *X, *Y;
Craig Topperf40110f2014-04-25 05:29:35 +00001228 Value *NewInst = nullptr;
1229 Instruction *SimpR = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001230
1231 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1232 // (X/Y) / Z => X / (Y*Z)
1233 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001234 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001235 NewInst = Builder->CreateFMul(Y, Op1);
Owen Anderson1664dc82014-01-20 07:44:53 +00001236 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1237 FastMathFlags Flags = I.getFastMathFlags();
1238 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1239 RI->setFastMathFlags(Flags);
1240 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001241 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1242 }
1243 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1244 // Z / (X/Y) => Z*Y / X
1245 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001246 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001247 NewInst = Builder->CreateFMul(Op0, Y);
Owen Anderson1664dc82014-01-20 07:44:53 +00001248 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1249 FastMathFlags Flags = I.getFastMathFlags();
1250 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1251 RI->setFastMathFlags(Flags);
1252 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001253 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1254 }
1255 }
1256
1257 if (NewInst) {
1258 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1259 T->setDebugLoc(I.getDebugLoc());
1260 SimpR->setFastMathFlags(I.getFastMathFlags());
1261 return SimpR;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001262 }
1263 }
1264
Craig Topperf40110f2014-04-25 05:29:35 +00001265 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001266}
1267
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001268/// This function implements the transforms common to both integer remainder
1269/// instructions (urem and srem). It is called by the visitors to those integer
1270/// remainder instructions.
1271/// @brief Common integer remainder transforms
1272Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1273 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1274
Chris Lattner7c99f192011-05-22 18:18:41 +00001275 // The RHS is known non-zero.
Hal Finkel60db0582014-09-07 18:57:58 +00001276 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +00001277 I.setOperand(1, V);
1278 return &I;
1279 }
1280
Duncan Sandsa3e36992011-05-02 16:27:02 +00001281 // Handle cases involving: rem X, (select Cond, Y, Z)
1282 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1283 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001284
Benjamin Kramer72196f32014-01-19 15:24:22 +00001285 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001286 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1287 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1288 if (Instruction *R = FoldOpIntoSelect(I, SI))
1289 return R;
1290 } else if (isa<PHINode>(Op0I)) {
1291 if (Instruction *NV = FoldOpIntoPhi(I))
1292 return NV;
1293 }
1294
1295 // See if we can fold away this rem instruction.
1296 if (SimplifyDemandedInstructionBits(I))
1297 return &I;
1298 }
1299 }
1300
Craig Topperf40110f2014-04-25 05:29:35 +00001301 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001302}
1303
1304Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1305 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1306
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001307 if (Value *V = SimplifyVectorOp(I))
1308 return ReplaceInstUsesWith(I, V);
1309
Hal Finkel60db0582014-09-07 18:57:58 +00001310 if (Value *V = SimplifyURemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001311 return ReplaceInstUsesWith(I, V);
1312
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001313 if (Instruction *common = commonIRemTransforms(I))
1314 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001315
David Majnemer6c30f492013-05-12 00:07:05 +00001316 // (zext A) urem (zext B) --> zext (A urem B)
1317 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1318 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1319 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1320 I.getType());
1321
David Majnemer470b0772013-05-11 09:01:28 +00001322 // X urem Y -> X and Y-1, where Y is a power of 2,
Hal Finkel60db0582014-09-07 18:57:58 +00001323 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, AT, &I, DT)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001324 Constant *N1 = Constant::getAllOnesValue(I.getType());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001325 Value *Add = Builder->CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001326 return BinaryOperator::CreateAnd(Op0, Add);
1327 }
1328
Nick Lewycky7459be62013-07-13 01:16:47 +00001329 // 1 urem X -> zext(X != 1)
1330 if (match(Op0, m_One())) {
1331 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1332 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1333 return ReplaceInstUsesWith(I, Ext);
1334 }
1335
Craig Topperf40110f2014-04-25 05:29:35 +00001336 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001337}
1338
1339Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1340 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1341
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001342 if (Value *V = SimplifyVectorOp(I))
1343 return ReplaceInstUsesWith(I, V);
1344
Hal Finkel60db0582014-09-07 18:57:58 +00001345 if (Value *V = SimplifySRemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001346 return ReplaceInstUsesWith(I, V);
1347
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001348 // Handle the integer rem common cases
1349 if (Instruction *Common = commonIRemTransforms(I))
1350 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001351
David Majnemerdb077302014-10-13 22:37:51 +00001352 {
1353 const APInt *Y;
1354 // X % -Y -> X % Y
1355 if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001356 Worklist.AddValue(I.getOperand(1));
David Majnemerdb077302014-10-13 22:37:51 +00001357 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001358 return &I;
1359 }
David Majnemerdb077302014-10-13 22:37:51 +00001360 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001361
1362 // If the sign bits of both operands are zero (i.e. we can prove they are
1363 // unsigned inputs), turn this into a urem.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001364 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001365 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001366 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1367 MaskedValueIsZero(Op0, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001368 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001369 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1370 }
1371 }
1372
1373 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001374 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1375 Constant *C = cast<Constant>(Op1);
1376 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001377
1378 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001379 bool hasMissing = false;
1380 for (unsigned i = 0; i != VWidth; ++i) {
1381 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001382 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001383 hasMissing = true;
1384 break;
1385 }
1386
1387 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001388 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001389 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001390 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001391
Chris Lattner0256be92012-01-27 03:08:05 +00001392 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001393 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001394 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001395 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001396 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001397 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001398 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001399 }
1400 }
1401
1402 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001403 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001404 Worklist.AddValue(I.getOperand(1));
1405 I.setOperand(1, NewRHSV);
1406 return &I;
1407 }
1408 }
1409 }
1410
Craig Topperf40110f2014-04-25 05:29:35 +00001411 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001412}
1413
1414Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001415 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001416
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001417 if (Value *V = SimplifyVectorOp(I))
1418 return ReplaceInstUsesWith(I, V);
1419
Hal Finkel60db0582014-09-07 18:57:58 +00001420 if (Value *V = SimplifyFRemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001421 return ReplaceInstUsesWith(I, V);
1422
1423 // Handle cases involving: rem X, (select Cond, Y, Z)
1424 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1425 return &I;
1426
Craig Topperf40110f2014-04-25 05:29:35 +00001427 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001428}