blob: 0a19a4880f29f4791e228969adedf3c1ac7d450c [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.
Craig Topperf40110f2014-04-25 05:29:35 +000039 Value *A = nullptr, *B = nullptr, *PowerOf2 = nullptr;
Chris Lattner321c58f2011-05-23 00:09:55 +000040 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(PowerOf2), m_Value(A))),
Chris Lattner7c99f192011-05-22 18:18:41 +000041 m_Value(B))) &&
42 // The "1" can be any value known to be a power of 2.
Hal Finkel60db0582014-09-07 18:57:58 +000043 isKnownToBeAPowerOfTwo(PowerOf2, false, 0, IC.getAssumptionTracker(),
44 CxtI, IC.getDominatorTree())) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +000045 A = IC.Builder->CreateSub(A, B);
Chris Lattner321c58f2011-05-23 00:09:55 +000046 return IC.Builder->CreateShl(PowerOf2, A);
Chris Lattner7c99f192011-05-22 18:18:41 +000047 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000048
Chris Lattner388cb8a2011-05-23 00:32:19 +000049 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
50 // inexact. Similarly for <<.
51 if (BinaryOperator *I = dyn_cast<BinaryOperator>(V))
Hal Finkel60db0582014-09-07 18:57:58 +000052 if (I->isLogicalShift() && isKnownToBeAPowerOfTwo(I->getOperand(0), false,
53 0, IC.getAssumptionTracker(),
54 CxtI,
55 IC.getDominatorTree())) {
Chris Lattner388cb8a2011-05-23 00:32:19 +000056 // We know that this is an exact/nuw shift and that the input is a
57 // non-zero context as well.
Hal Finkel60db0582014-09-07 18:57:58 +000058 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
Chris Lattner388cb8a2011-05-23 00:32:19 +000059 I->setOperand(0, V2);
60 MadeChange = true;
61 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000062
Chris Lattner388cb8a2011-05-23 00:32:19 +000063 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
64 I->setIsExact();
65 MadeChange = true;
66 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000067
Chris Lattner388cb8a2011-05-23 00:32:19 +000068 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
69 I->setHasNoUnsignedWrap();
70 MadeChange = true;
71 }
72 }
73
Chris Lattner162dfc32011-05-22 18:26:48 +000074 // TODO: Lots more we could do here:
Chris Lattner162dfc32011-05-22 18:26:48 +000075 // If V is a phi node, we can call this on each of its operands.
76 // "select cond, X, 0" can simplify to "X".
Jim Grosbachbdbd7342013-04-05 21:20:12 +000077
Craig Topperf40110f2014-04-25 05:29:35 +000078 return MadeChange ? V : nullptr;
Chris Lattner7c99f192011-05-22 18:18:41 +000079}
80
81
Chris Lattnerdc054bf2010-01-05 06:09:35 +000082/// MultiplyOverflows - True if the multiply can not be expressed in an int
83/// this size.
84static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
85 uint32_t W = C1->getBitWidth();
86 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
87 if (sign) {
Jay Foad583abbc2010-12-07 08:25:19 +000088 LHSExt = LHSExt.sext(W * 2);
89 RHSExt = RHSExt.sext(W * 2);
Chris Lattnerdc054bf2010-01-05 06:09:35 +000090 } else {
Jay Foad583abbc2010-12-07 08:25:19 +000091 LHSExt = LHSExt.zext(W * 2);
92 RHSExt = RHSExt.zext(W * 2);
Chris Lattnerdc054bf2010-01-05 06:09:35 +000093 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000094
Chris Lattnerdc054bf2010-01-05 06:09:35 +000095 APInt MulExt = LHSExt * RHSExt;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000096
Chris Lattnerdc054bf2010-01-05 06:09:35 +000097 if (!sign)
98 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
Jim Grosbachbdbd7342013-04-05 21:20:12 +000099
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000100 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
101 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
102 return MulExt.slt(Min) || MulExt.sgt(Max);
103}
104
David Majnemerf9a095d2014-08-16 08:55:06 +0000105/// \brief True if C2 is a multiple of C1. Quotient contains C2/C1.
106static bool IsMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
107 bool IsSigned) {
108 assert(C1.getBitWidth() == C2.getBitWidth() &&
109 "Inconsistent width of constants!");
110
111 APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
112 if (IsSigned)
113 APInt::sdivrem(C1, C2, Quotient, Remainder);
114 else
115 APInt::udivrem(C1, C2, Quotient, Remainder);
116
117 return Remainder.isMinValue();
118}
119
Rafael Espindola65281bf2013-05-31 14:27:15 +0000120/// \brief A helper routine of InstCombiner::visitMul().
121///
122/// If C is a vector of known powers of 2, then this function returns
123/// a new vector obtained from C replacing each element with its logBase2.
124/// Return a null pointer otherwise.
125static Constant *getLogBase2Vector(ConstantDataVector *CV) {
126 const APInt *IVal;
127 SmallVector<Constant *, 4> Elts;
128
129 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
130 Constant *Elt = CV->getElementAsConstant(I);
131 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
Craig Topperf40110f2014-04-25 05:29:35 +0000132 return nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000133 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
134 }
135
136 return ConstantVector::get(Elts);
137}
138
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000139Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000140 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000141 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
142
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000143 if (Value *V = SimplifyVectorOp(I))
144 return ReplaceInstUsesWith(I, V);
145
Hal Finkel60db0582014-09-07 18:57:58 +0000146 if (Value *V = SimplifyMulInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000147 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000148
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000149 if (Value *V = SimplifyUsingDistributiveLaws(I))
150 return ReplaceInstUsesWith(I, V);
151
Chris Lattner6b657ae2011-02-10 05:36:31 +0000152 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X
153 return BinaryOperator::CreateNeg(Op0, I.getName());
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000154
Rafael Espindola65281bf2013-05-31 14:27:15 +0000155 // Also allow combining multiply instructions on vectors.
156 {
157 Value *NewOp;
158 Constant *C1, *C2;
159 const APInt *IVal;
160 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
161 m_Constant(C1))) &&
162 match(C1, m_APInt(IVal)))
163 // ((X << C1)*C2) == (X * (C2 << C1))
164 return BinaryOperator::CreateMul(NewOp, ConstantExpr::getShl(C1, C2));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000165
Rafael Espindola65281bf2013-05-31 14:27:15 +0000166 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000167 Constant *NewCst = nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000168 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
169 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
170 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
171 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
172 // Replace X*(2^C) with X << C, where C is a vector of known
173 // constant powers of 2.
174 NewCst = getLogBase2Vector(CV);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000175
Rafael Espindola65281bf2013-05-31 14:27:15 +0000176 if (NewCst) {
177 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
178 if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap();
179 if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap();
180 return Shl;
181 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000182 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000183 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000184
Rafael Espindola65281bf2013-05-31 14:27:15 +0000185 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Stuart Hastings23804832011-06-01 16:42:47 +0000186 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
187 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
188 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000189 {
190 const APInt & Val = CI->getValue();
191 const APInt &PosVal = Val.abs();
192 if (Val.isNegative() && PosVal.isPowerOf2()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000193 Value *X = nullptr, *Y = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000194 if (Op0->hasOneUse()) {
195 ConstantInt *C1;
Craig Topperf40110f2014-04-25 05:29:35 +0000196 Value *Sub = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000197 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
198 Sub = Builder->CreateSub(X, Y, "suba");
199 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
200 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
201 if (Sub)
202 return
203 BinaryOperator::CreateMul(Sub,
204 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000205 }
206 }
207 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000208 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000209
Chris Lattner6b657ae2011-02-10 05:36:31 +0000210 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000211 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000212 // Try to fold constant mul into select arguments.
213 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
214 if (Instruction *R = FoldOpIntoSelect(I, SI))
215 return R;
216
217 if (isa<PHINode>(Op0))
218 if (Instruction *NV = FoldOpIntoPhi(I))
219 return NV;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000220
221 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
222 {
223 Value *X;
224 Constant *C1;
225 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
David Majnemer6cf6c052014-06-19 07:14:33 +0000226 Value *Mul = Builder->CreateMul(C1, Op1);
227 // Only go forward with the transform if C1*CI simplifies to a tidier
228 // constant.
229 if (!match(Mul, m_Mul(m_Value(), m_Value())))
230 return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
Benjamin Kramer72196f32014-01-19 15:24:22 +0000231 }
232 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000233 }
234
235 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
236 if (Value *Op1v = dyn_castNegVal(Op1))
237 return BinaryOperator::CreateMul(Op0v, Op1v);
238
239 // (X / Y) * Y = X - (X % Y)
240 // (X / Y) * -Y = (X % Y) - X
241 {
242 Value *Op1C = Op1;
243 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
244 if (!BO ||
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000245 (BO->getOpcode() != Instruction::UDiv &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000246 BO->getOpcode() != Instruction::SDiv)) {
247 Op1C = Op0;
248 BO = dyn_cast<BinaryOperator>(Op1);
249 }
250 Value *Neg = dyn_castNegVal(Op1C);
251 if (BO && BO->hasOneUse() &&
252 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
253 (BO->getOpcode() == Instruction::UDiv ||
254 BO->getOpcode() == Instruction::SDiv)) {
255 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
256
Chris Lattner35315d02011-02-06 21:44:57 +0000257 // If the division is exact, X % Y is zero, so we end up with X or -X.
258 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000259 if (SDiv->isExact()) {
260 if (Op1BO == Op1C)
261 return ReplaceInstUsesWith(I, Op0BO);
262 return BinaryOperator::CreateNeg(Op0BO);
263 }
264
265 Value *Rem;
266 if (BO->getOpcode() == Instruction::UDiv)
267 Rem = Builder->CreateURem(Op0BO, Op1BO);
268 else
269 Rem = Builder->CreateSRem(Op0BO, Op1BO);
270 Rem->takeName(BO);
271
272 if (Op1BO == Op1C)
273 return BinaryOperator::CreateSub(Op0BO, Rem);
274 return BinaryOperator::CreateSub(Rem, Op0BO);
275 }
276 }
277
278 /// i1 mul -> i1 and.
Benjamin Kramer72196f32014-01-19 15:24:22 +0000279 if (I.getType()->getScalarType()->isIntegerTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000280 return BinaryOperator::CreateAnd(Op0, Op1);
281
282 // X*(1 << Y) --> X << Y
283 // (1 << Y)*X --> X << Y
284 {
285 Value *Y;
286 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
287 return BinaryOperator::CreateShl(Op1, Y);
288 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
289 return BinaryOperator::CreateShl(Op0, Y);
290 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000291
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000292 // If one of the operands of the multiply is a cast from a boolean value, then
293 // we know the bool is either zero or one, so this is a 'masking' multiply.
294 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands19d0b472010-02-16 11:11:14 +0000295 if (!I.getType()->isVectorTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000296 // -2 is "-1 << 1" so it is all bits set except the low one.
297 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000298
Craig Topperf40110f2014-04-25 05:29:35 +0000299 Value *BoolCast = nullptr, *OtherOp = nullptr;
Hal Finkel60db0582014-09-07 18:57:58 +0000300 if (MaskedValueIsZero(Op0, Negative2, 0, &I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000301 BoolCast = Op0, OtherOp = Op1;
Hal Finkel60db0582014-09-07 18:57:58 +0000302 else if (MaskedValueIsZero(Op1, Negative2, 0, &I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000303 BoolCast = Op1, OtherOp = Op0;
304
305 if (BoolCast) {
306 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000307 BoolCast);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000308 return BinaryOperator::CreateAnd(V, OtherOp);
309 }
310 }
311
Craig Topperf40110f2014-04-25 05:29:35 +0000312 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000313}
314
Pedro Artigas993acd02012-11-30 22:07:05 +0000315//
316// Detect pattern:
317//
318// log2(Y*0.5)
319//
320// And check for corresponding fast math flags
321//
322
323static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Pedro Artigas00b83c92012-11-30 22:47:15 +0000324
325 if (!Op->hasOneUse())
326 return;
327
328 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
329 if (!II)
330 return;
331 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
332 return;
333 Log2 = II;
334
335 Value *OpLog2Of = II->getArgOperand(0);
336 if (!OpLog2Of->hasOneUse())
337 return;
338
339 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
340 if (!I)
341 return;
342 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
343 return;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000344
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000345 if (match(I->getOperand(0), m_SpecificFP(0.5)))
Pedro Artigas00b83c92012-11-30 22:47:15 +0000346 Y = I->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000347 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
Pedro Artigas00b83c92012-11-30 22:47:15 +0000348 Y = I->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000349}
Pedro Artigas993acd02012-11-30 22:07:05 +0000350
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000351static bool isFiniteNonZeroFp(Constant *C) {
352 if (C->getType()->isVectorTy()) {
353 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
354 ++I) {
355 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
356 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
357 return false;
358 }
359 return true;
360 }
361
362 return isa<ConstantFP>(C) &&
363 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
364}
365
366static bool isNormalFp(Constant *C) {
367 if (C->getType()->isVectorTy()) {
368 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
369 ++I) {
370 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
371 if (!CFP || !CFP->getValueAPF().isNormal())
372 return false;
373 }
374 return true;
375 }
376
377 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
378}
379
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000380/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
381/// true iff the given value is FMul or FDiv with one and only one operand
382/// being a normal constant (i.e. not Zero/NaN/Infinity).
383static bool isFMulOrFDivWithConstant(Value *V) {
384 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000385 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yang80138662013-01-07 22:41:28 +0000386 I->getOpcode() != Instruction::FDiv))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000387 return false;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000388
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000389 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
390 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000391
392 if (C0 && C1)
393 return false;
394
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000395 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000396}
397
398/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
399/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
400/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000401/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000402/// resulting expression. Note that this function could return NULL in
403/// case the constants cannot be folded into a normal floating-point.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000404///
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000405Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yang80138662013-01-07 22:41:28 +0000406 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000407 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
408
409 Value *Opnd0 = FMulOrDiv->getOperand(0);
410 Value *Opnd1 = FMulOrDiv->getOperand(1);
411
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000412 Constant *C0 = dyn_cast<Constant>(Opnd0);
413 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000414
Craig Topperf40110f2014-04-25 05:29:35 +0000415 BinaryOperator *R = nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000416
417 // (X * C0) * C => X * (C0*C)
418 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
419 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000420 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000421 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
422 } else {
423 if (C0) {
424 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000425 if (FMulOrDiv->hasOneUse()) {
426 // It would otherwise introduce another div.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000427 Constant *F = ConstantExpr::getFMul(C0, C);
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000428 if (isNormalFp(F))
429 R = BinaryOperator::CreateFDiv(F, Opnd1);
430 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000431 } else {
432 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000433 Constant *F = ConstantExpr::getFDiv(C, C1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000434 if (isNormalFp(F)) {
435 R = BinaryOperator::CreateFMul(Opnd0, F);
436 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000437 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000438 Constant *F = ConstantExpr::getFDiv(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000439 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000440 R = BinaryOperator::CreateFDiv(Opnd0, F);
441 }
442 }
443 }
444
445 if (R) {
446 R->setHasUnsafeAlgebra(true);
447 InsertNewInstWith(R, *InsertBefore);
448 }
449
450 return R;
451}
452
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000453Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000454 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000455 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
456
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000457 if (Value *V = SimplifyVectorOp(I))
458 return ReplaceInstUsesWith(I, V);
459
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000460 if (isa<Constant>(Op0))
461 std::swap(Op0, Op1);
462
Hal Finkel60db0582014-09-07 18:57:58 +0000463 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL, TLI,
464 DT, AT))
Michael Ilsemand5787be2012-12-12 00:28:32 +0000465 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000466
Shuxin Yange8227452013-01-15 21:09:32 +0000467 bool AllowReassociate = I.hasUnsafeAlgebra();
468
Michael Ilsemand5787be2012-12-12 00:28:32 +0000469 // Simplify mul instructions with a constant RHS.
470 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000471 // Try to fold constant mul into select arguments.
472 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
473 if (Instruction *R = FoldOpIntoSelect(I, SI))
474 return R;
475
476 if (isa<PHINode>(Op0))
477 if (Instruction *NV = FoldOpIntoPhi(I))
478 return NV;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000479
Owen Andersonf74cfe02014-01-16 20:36:42 +0000480 // (fmul X, -1.0) --> (fsub -0.0, X)
Benjamin Kramerfea9ac92014-01-18 16:43:14 +0000481 if (match(Op1, m_SpecificFP(-1.0))) {
482 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
483 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000484 RI->copyFastMathFlags(&I);
485 return RI;
486 }
487
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000488 Constant *C = cast<Constant>(Op1);
489 if (AllowReassociate && isFiniteNonZeroFp(C)) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000490 // Let MDC denote an expression in one of these forms:
491 // X * C, C/X, X/C, where C is a constant.
492 //
493 // Try to simplify "MDC * Constant"
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000494 if (isFMulOrFDivWithConstant(Op0))
495 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000496 return ReplaceInstUsesWith(I, V);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000497
Quentin Colombete684a6d2013-02-28 21:12:40 +0000498 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000499 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
500 if (FAddSub &&
501 (FAddSub->getOpcode() == Instruction::FAdd ||
502 FAddSub->getOpcode() == Instruction::FSub)) {
503 Value *Opnd0 = FAddSub->getOperand(0);
504 Value *Opnd1 = FAddSub->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000505 Constant *C0 = dyn_cast<Constant>(Opnd0);
506 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000507 bool Swap = false;
508 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000509 std::swap(C0, C1);
510 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000511 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000512 }
513
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000514 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000515 Value *M1 = ConstantExpr::getFMul(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000516 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000517 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
Craig Topperf40110f2014-04-25 05:29:35 +0000518 nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000519 if (M0 && M1) {
520 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
521 std::swap(M0, M1);
522
Benjamin Kramer67485762013-09-30 15:39:59 +0000523 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
524 ? BinaryOperator::CreateFAdd(M0, M1)
525 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000526 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000527 return RI;
528 }
529 }
530 }
531 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000532 }
533
Sanjay Patel12d1ce52014-10-02 21:10:54 +0000534 // sqrt(X) * sqrt(X) -> X
535 if (AllowReassociate && (Op0 == Op1))
536 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0))
537 if (II->getIntrinsicID() == Intrinsic::sqrt)
538 return ReplaceInstUsesWith(I, II->getOperand(0));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000539
Pedro Artigasd8795042012-11-30 19:09:41 +0000540 // Under unsafe algebra do:
541 // X * log2(0.5*Y) = X*log2(Y) - X
Sanjay Patelb41d4612014-10-02 15:20:45 +0000542 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +0000543 Value *OpX = nullptr;
544 Value *OpY = nullptr;
Pedro Artigasd8795042012-11-30 19:09:41 +0000545 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000546 detectLog2OfHalf(Op0, OpY, Log2);
547 if (OpY) {
548 OpX = Op1;
549 } else {
550 detectLog2OfHalf(Op1, OpY, Log2);
551 if (OpY) {
552 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000553 }
554 }
555 // if pattern detected emit alternate sequence
556 if (OpX && OpY) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000557 BuilderTy::FastMathFlagGuard Guard(*Builder);
558 Builder->SetFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000559 Log2->setArgOperand(0, OpY);
560 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
Benjamin Kramer67485762013-09-30 15:39:59 +0000561 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
562 FSub->takeName(&I);
563 return ReplaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000564 }
565 }
566
Shuxin Yange8227452013-01-15 21:09:32 +0000567 // Handle symmetric situation in a 2-iteration loop
568 Value *Opnd0 = Op0;
569 Value *Opnd1 = Op1;
570 for (int i = 0; i < 2; i++) {
571 bool IgnoreZeroSign = I.hasNoSignedZeros();
572 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000573 BuilderTy::FastMathFlagGuard Guard(*Builder);
574 Builder->SetFastMathFlags(I.getFastMathFlags());
575
Shuxin Yange8227452013-01-15 21:09:32 +0000576 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
577 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000578
Shuxin Yange8227452013-01-15 21:09:32 +0000579 // -X * -Y => X*Y
Owen Andersone8537fc2014-01-16 20:59:41 +0000580 if (N1) {
581 Value *FMul = Builder->CreateFMul(N0, N1);
582 FMul->takeName(&I);
583 return ReplaceInstUsesWith(I, FMul);
584 }
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000585
Shuxin Yange8227452013-01-15 21:09:32 +0000586 if (Opnd0->hasOneUse()) {
587 // -X * Y => -(X*Y) (Promote negation as high as possible)
588 Value *T = Builder->CreateFMul(N0, Opnd1);
Benjamin Kramer67485762013-09-30 15:39:59 +0000589 Value *Neg = Builder->CreateFNeg(T);
590 Neg->takeName(&I);
591 return ReplaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000592 }
593 }
Shuxin Yange8227452013-01-15 21:09:32 +0000594
595 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000596 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000597 // 1) to form a power expression (of X).
598 // 2) potentially shorten the critical path: After transformation, the
599 // latency of the instruction Y is amortized by the expression of X*X,
600 // and therefore Y is in a "less critical" position compared to what it
601 // was before the transformation.
602 //
603 if (AllowReassociate) {
604 Value *Opnd0_0, *Opnd0_1;
605 if (Opnd0->hasOneUse() &&
606 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000607 Value *Y = nullptr;
Shuxin Yange8227452013-01-15 21:09:32 +0000608 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
609 Y = Opnd0_1;
610 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
611 Y = Opnd0_0;
612
613 if (Y) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000614 BuilderTy::FastMathFlagGuard Guard(*Builder);
615 Builder->SetFastMathFlags(I.getFastMathFlags());
616 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
Shuxin Yange8227452013-01-15 21:09:32 +0000617
Benjamin Kramer67485762013-09-30 15:39:59 +0000618 Value *R = Builder->CreateFMul(T, Y);
619 R->takeName(&I);
620 return ReplaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000621 }
622 }
623 }
624
625 if (!isa<Constant>(Op1))
626 std::swap(Opnd0, Opnd1);
627 else
628 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000629 }
630
Craig Topperf40110f2014-04-25 05:29:35 +0000631 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000632}
633
634/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
635/// instruction.
636bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
637 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000638
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000639 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
640 int NonNullOperand = -1;
641 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
642 if (ST->isNullValue())
643 NonNullOperand = 2;
644 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
645 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
646 if (ST->isNullValue())
647 NonNullOperand = 1;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000648
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000649 if (NonNullOperand == -1)
650 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000651
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000652 Value *SelectCond = SI->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000653
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000654 // Change the div/rem to use 'Y' instead of the select.
655 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000656
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000657 // Okay, we know we replace the operand of the div/rem with 'Y' with no
658 // problem. However, the select, or the condition of the select may have
659 // multiple uses. Based on our knowledge that the operand must be non-zero,
660 // propagate the known value for the select into other uses of it, and
661 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000662
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000663 // If the select and condition only have a single use, don't bother with this,
664 // early exit.
665 if (SI->use_empty() && SelectCond->hasOneUse())
666 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000667
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000668 // Scan the current block backward, looking for other uses of SI.
669 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000670
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000671 while (BBI != BBFront) {
672 --BBI;
673 // If we found a call to a function, we can't assume it will return, so
674 // information from below it cannot be propagated above it.
675 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
676 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000677
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000678 // Replace uses of the select or its condition with the known values.
679 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
680 I != E; ++I) {
681 if (*I == SI) {
682 *I = SI->getOperand(NonNullOperand);
683 Worklist.Add(BBI);
684 } else if (*I == SelectCond) {
Jakub Staszak96ff4d62013-06-06 23:34:59 +0000685 *I = Builder->getInt1(NonNullOperand == 1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000686 Worklist.Add(BBI);
687 }
688 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000689
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000690 // If we past the instruction, quit looking for it.
691 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000692 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000693 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000694 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000695
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000696 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000697 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000698 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000699
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000700 }
701 return true;
702}
703
704
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000705/// This function implements the transforms common to both integer division
706/// instructions (udiv and sdiv). It is called by the visitors to those integer
707/// division instructions.
708/// @brief Common integer divide transforms
709Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
710 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
711
Chris Lattner7c99f192011-05-22 18:18:41 +0000712 // The RHS is known non-zero.
Hal Finkel60db0582014-09-07 18:57:58 +0000713 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +0000714 I.setOperand(1, V);
715 return &I;
716 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000717
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000718 // Handle cases involving: [su]div X, (select Cond, Y, Z)
719 // This does not apply for fdiv.
720 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
721 return &I;
722
723 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
David Majnemerf9a095d2014-08-16 08:55:06 +0000724 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
725 // (X / C1) / C2 -> X / (C1*C2)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000726 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
727 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
728 if (MultiplyOverflows(RHS, LHSRHS,
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000729 I.getOpcode() == Instruction::SDiv))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000730 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner6b657ae2011-02-10 05:36:31 +0000731 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
732 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000733 }
734
David Majnemerf9a095d2014-08-16 08:55:06 +0000735 Value *X;
736 const APInt *C1, *C2;
737 if (match(RHS, m_APInt(C2))) {
738 bool IsSigned = I.getOpcode() == Instruction::SDiv;
739 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
740 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
741 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
742
743 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
744 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
745 BinaryOperator *BO = BinaryOperator::Create(
746 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
747 BO->setIsExact(I.isExact());
748 return BO;
749 }
750
751 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
752 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
753 BinaryOperator *BO = BinaryOperator::Create(
754 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
755 BO->setHasNoUnsignedWrap(
756 !IsSigned &&
757 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
758 BO->setHasNoSignedWrap(
759 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
760 return BO;
761 }
762 }
763
764 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1)))) ||
765 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
766 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
767 APInt C1Shifted = APInt::getOneBitSet(
768 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
769
770 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
771 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
772 BinaryOperator *BO = BinaryOperator::Create(
773 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
774 BO->setIsExact(I.isExact());
775 return BO;
776 }
777
778 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
779 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
780 BinaryOperator *BO = BinaryOperator::Create(
781 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
782 BO->setHasNoUnsignedWrap(
783 !IsSigned &&
784 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
785 BO->setHasNoSignedWrap(
786 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
787 return BO;
788 }
789 }
790 }
791 }
792
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000793 if (!RHS->isZero()) { // avoid X udiv 0
794 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
795 if (Instruction *R = FoldOpIntoSelect(I, SI))
796 return R;
797 if (isa<PHINode>(Op0))
798 if (Instruction *NV = FoldOpIntoPhi(I))
799 return NV;
800 }
801 }
802
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000803 if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
804 if (One->isOne() && !I.getType()->isIntegerTy(1)) {
805 bool isSigned = I.getOpcode() == Instruction::SDiv;
806 if (isSigned) {
807 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
808 // result is one, if Op1 is -1 then the result is minus one, otherwise
809 // it's zero.
810 Value *Inc = Builder->CreateAdd(Op1, One);
811 Value *Cmp = Builder->CreateICmpULT(
812 Inc, ConstantInt::get(I.getType(), 3));
813 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
814 } else {
815 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
816 // result is one, otherwise it's zero.
817 return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
818 }
819 }
820 }
821
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000822 // See if we can fold away this div instruction.
823 if (SimplifyDemandedInstructionBits(I))
824 return &I;
825
Duncan Sands771e82a2011-01-28 16:51:11 +0000826 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Craig Topperf40110f2014-04-25 05:29:35 +0000827 Value *X = nullptr, *Z = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +0000828 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
829 bool isSigned = I.getOpcode() == Instruction::SDiv;
830 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
831 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
832 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000833 }
834
Craig Topperf40110f2014-04-25 05:29:35 +0000835 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000836}
837
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000838/// dyn_castZExtVal - Checks if V is a zext or constant that can
839/// be truncated to Ty without losing bits.
Chris Lattner229907c2011-07-18 04:54:35 +0000840static Value *dyn_castZExtVal(Value *V, Type *Ty) {
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000841 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
842 if (Z->getSrcTy() == Ty)
843 return Z->getOperand(0);
844 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
845 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
846 return ConstantExpr::getTrunc(C, Ty);
847 }
Craig Topperf40110f2014-04-25 05:29:35 +0000848 return nullptr;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000849}
850
David Majnemer37f8f442013-07-04 21:17:49 +0000851namespace {
852const unsigned MaxDepth = 6;
853typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
854 const BinaryOperator &I,
855 InstCombiner &IC);
856
857/// \brief Used to maintain state for visitUDivOperand().
858struct UDivFoldAction {
859 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
860 ///< operand. This can be zero if this action
861 ///< joins two actions together.
862
863 Value *OperandToFold; ///< Which operand to fold.
864 union {
865 Instruction *FoldResult; ///< The instruction returned when FoldAction is
866 ///< invoked.
867
868 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
869 ///< joins two actions together.
870 };
871
872 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +0000873 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +0000874 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
875 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
876};
877}
878
879// X udiv 2^C -> X >> C
880static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
881 const BinaryOperator &I, InstCombiner &IC) {
882 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
883 BinaryOperator *LShr = BinaryOperator::CreateLShr(
884 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
885 if (I.isExact()) LShr->setIsExact();
886 return LShr;
887}
888
889// X udiv C, where C >= signbit
890static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
891 const BinaryOperator &I, InstCombiner &IC) {
892 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
893
894 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
895 ConstantInt::get(I.getType(), 1));
896}
897
898// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
899static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
900 InstCombiner &IC) {
901 Instruction *ShiftLeft = cast<Instruction>(Op1);
902 if (isa<ZExtInst>(ShiftLeft))
903 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
904
905 const APInt &CI =
906 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
907 Value *N = ShiftLeft->getOperand(1);
908 if (CI != 1)
909 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
910 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
911 N = IC.Builder->CreateZExt(N, Z->getDestTy());
912 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
913 if (I.isExact()) LShr->setIsExact();
914 return LShr;
915}
916
917// \brief Recursively visits the possible right hand operands of a udiv
918// instruction, seeing through select instructions, to determine if we can
919// replace the udiv with something simpler. If we find that an operand is not
920// able to simplify the udiv, we abort the entire transformation.
921static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
922 SmallVectorImpl<UDivFoldAction> &Actions,
923 unsigned Depth = 0) {
924 // Check to see if this is an unsigned division with an exact power of 2,
925 // if so, convert to a right shift.
926 if (match(Op1, m_Power2())) {
927 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
928 return Actions.size();
929 }
930
931 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
932 // X udiv C, where C >= signbit
933 if (C->getValue().isNegative()) {
934 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
935 return Actions.size();
936 }
937
938 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
939 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
940 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
941 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
942 return Actions.size();
943 }
944
945 // The remaining tests are all recursive, so bail out if we hit the limit.
946 if (Depth++ == MaxDepth)
947 return 0;
948
949 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
David Majnemer492e6122014-08-30 09:19:05 +0000950 if (size_t LHSIdx =
951 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
952 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
953 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
David Majnemer37f8f442013-07-04 21:17:49 +0000954 return Actions.size();
955 }
956
957 return 0;
958}
959
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000960Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
961 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
962
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000963 if (Value *V = SimplifyVectorOp(I))
964 return ReplaceInstUsesWith(I, V);
965
Hal Finkel60db0582014-09-07 18:57:58 +0000966 if (Value *V = SimplifyUDivInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sands771e82a2011-01-28 16:51:11 +0000967 return ReplaceInstUsesWith(I, V);
968
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000969 // Handle the integer div common cases
970 if (Instruction *Common = commonIDivTransforms(I))
971 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000972
Benjamin Kramerd4a64712012-08-30 15:07:40 +0000973 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
Benjamin Kramer72196f32014-01-19 15:24:22 +0000974 if (Constant *C2 = dyn_cast<Constant>(Op1)) {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +0000975 Value *X;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000976 Constant *C1;
977 if (match(Op0, m_LShr(m_Value(X), m_Constant(C1))))
978 return BinaryOperator::CreateUDiv(X, ConstantExpr::getShl(C2, C1));
Nadav Rotem11935b22012-08-28 10:01:43 +0000979 }
980
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000981 // (zext A) udiv (zext B) --> zext (A udiv B)
982 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
983 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
984 return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
985 I.isExact()),
986 I.getType());
987
David Majnemer37f8f442013-07-04 21:17:49 +0000988 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
989 SmallVector<UDivFoldAction, 6> UDivActions;
990 if (visitUDivOperand(Op0, Op1, I, UDivActions))
991 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
992 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
993 Value *ActionOp1 = UDivActions[i].OperandToFold;
994 Instruction *Inst;
995 if (Action)
996 Inst = Action(Op0, ActionOp1, I, *this);
997 else {
998 // This action joins two actions together. The RHS of this action is
999 // simply the last action we processed, we saved the LHS action index in
1000 // the joining action.
1001 size_t SelectRHSIdx = i - 1;
1002 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1003 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1004 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1005 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1006 SelectLHS, SelectRHS);
1007 }
1008
1009 // If this is the last action to process, return it to the InstCombiner.
1010 // Otherwise, we insert it before the UDiv and record it so that we may
1011 // use it as part of a joining action (i.e., a SelectInst).
1012 if (e - i != 1) {
1013 Inst->insertBefore(&I);
1014 UDivActions[i].FoldResult = Inst;
1015 } else
1016 return Inst;
1017 }
1018
Craig Topperf40110f2014-04-25 05:29:35 +00001019 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001020}
1021
1022Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1023 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1024
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001025 if (Value *V = SimplifyVectorOp(I))
1026 return ReplaceInstUsesWith(I, V);
1027
Hal Finkel60db0582014-09-07 18:57:58 +00001028 if (Value *V = SimplifySDivInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sands771e82a2011-01-28 16:51:11 +00001029 return ReplaceInstUsesWith(I, V);
1030
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001031 // Handle the integer div common cases
1032 if (Instruction *Common = commonIDivTransforms(I))
1033 return Common;
1034
Benjamin Kramer72196f32014-01-19 15:24:22 +00001035 // sdiv X, -1 == -X
1036 if (match(Op1, m_AllOnes()))
1037 return BinaryOperator::CreateNeg(Op0);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001038
Benjamin Kramer72196f32014-01-19 15:24:22 +00001039 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001040 // sdiv X, C --> ashr exact X, log2(C)
1041 if (I.isExact() && RHS->getValue().isNonNegative() &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001042 RHS->getValue().isPowerOf2()) {
1043 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1044 RHS->getValue().exactLogBase2());
Chris Lattner6b657ae2011-02-10 05:36:31 +00001045 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001046 }
Benjamin Kramer72196f32014-01-19 15:24:22 +00001047 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001048
Benjamin Kramer72196f32014-01-19 15:24:22 +00001049 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
David Majnemerf28e2a42014-07-02 06:42:13 +00001050 // X/INT_MIN -> X == INT_MIN
1051 if (RHS->isMinSignedValue())
1052 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1053
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001054 // -X/C --> X/-C provided the negation doesn't overflow.
1055 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
Chris Lattner6b657ae2011-02-10 05:36:31 +00001056 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001057 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
1058 ConstantExpr::getNeg(RHS));
1059 }
1060
1061 // If the sign bits of both operands are zero (i.e. we can prove they are
1062 // unsigned inputs), turn this into a udiv.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001063 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001064 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001065 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1066 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001067 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001068 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1069 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001070
Chris Lattner6b657ae2011-02-10 05:36:31 +00001071 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001072 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1073 // Safe because the only negative value (1 << Y) can take on is
1074 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1075 // the sign bit set.
1076 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1077 }
1078 }
1079 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001080
Craig Topperf40110f2014-04-25 05:29:35 +00001081 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001082}
1083
Shuxin Yang320f52a2013-01-14 22:48:41 +00001084/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1085/// FP value and:
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001086/// 1) 1/C is exact, or
Shuxin Yang320f52a2013-01-14 22:48:41 +00001087/// 2) reciprocal is allowed.
Sylvestre Ledru149e2812013-05-14 23:36:24 +00001088/// If the conversion was successful, the simplified expression "X * 1/C" is
Shuxin Yang320f52a2013-01-14 22:48:41 +00001089/// returned; otherwise, NULL is returned.
1090///
1091static Instruction *CvtFDivConstToReciprocal(Value *Dividend,
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001092 Constant *Divisor,
Shuxin Yang320f52a2013-01-14 22:48:41 +00001093 bool AllowReciprocal) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001094 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001095 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001096
1097 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001098 APFloat Reciprocal(FpVal.getSemantics());
1099 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001100
Michael Gottesman3cb77ab2013-06-19 21:23:18 +00001101 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001102 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1103 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1104 Cvt = !Reciprocal.isDenormal();
1105 }
1106
1107 if (!Cvt)
Craig Topperf40110f2014-04-25 05:29:35 +00001108 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001109
1110 ConstantFP *R;
1111 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1112 return BinaryOperator::CreateFMul(Dividend, R);
1113}
1114
Frits van Bommel2a559512011-01-29 17:50:27 +00001115Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1116 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1117
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001118 if (Value *V = SimplifyVectorOp(I))
1119 return ReplaceInstUsesWith(I, V);
1120
Hal Finkel60db0582014-09-07 18:57:58 +00001121 if (Value *V = SimplifyFDivInst(Op0, Op1, DL, TLI, DT, AT))
Frits van Bommel2a559512011-01-29 17:50:27 +00001122 return ReplaceInstUsesWith(I, V);
1123
Stephen Lina9b57f62013-07-20 07:13:13 +00001124 if (isa<Constant>(Op0))
1125 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1126 if (Instruction *R = FoldOpIntoSelect(I, SI))
1127 return R;
1128
Shuxin Yang320f52a2013-01-14 22:48:41 +00001129 bool AllowReassociate = I.hasUnsafeAlgebra();
1130 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001131
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001132 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001133 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1134 if (Instruction *R = FoldOpIntoSelect(I, SI))
1135 return R;
1136
Shuxin Yang320f52a2013-01-14 22:48:41 +00001137 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +00001138 Constant *C1 = nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001139 Constant *C2 = Op1C;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001140 Value *X;
Craig Topperf40110f2014-04-25 05:29:35 +00001141 Instruction *Res = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001142
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001143 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001144 // (X*C1)/C2 => X * (C1/C2)
1145 //
1146 Constant *C = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001147 if (isNormalFp(C))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001148 Res = BinaryOperator::CreateFMul(X, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001149 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001150 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1151 //
1152 Constant *C = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001153 if (isNormalFp(C)) {
1154 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001155 if (!Res)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001156 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001157 }
1158 }
1159
1160 if (Res) {
1161 Res->setFastMathFlags(I.getFastMathFlags());
1162 return Res;
1163 }
1164 }
1165
1166 // X / C => X * 1/C
Owen Anderson4557a152014-01-16 21:07:52 +00001167 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1168 T->copyFastMathFlags(&I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001169 return T;
Owen Anderson4557a152014-01-16 21:07:52 +00001170 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001171
Craig Topperf40110f2014-04-25 05:29:35 +00001172 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001173 }
1174
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001175 if (AllowReassociate && isa<Constant>(Op0)) {
1176 Constant *C1 = cast<Constant>(Op0), *C2;
Craig Topperf40110f2014-04-25 05:29:35 +00001177 Constant *Fold = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001178 Value *X;
1179 bool CreateDiv = true;
1180
1181 // C1 / (X*C2) => (C1/C2) / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001182 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001183 Fold = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001184 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001185 // C1 / (X/C2) => (C1*C2) / X
1186 Fold = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001187 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001188 // C1 / (C2/X) => (C1/C2) * X
1189 Fold = ConstantExpr::getFDiv(C1, C2);
1190 CreateDiv = false;
1191 }
1192
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001193 if (Fold && isNormalFp(Fold)) {
1194 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1195 : BinaryOperator::CreateFMul(X, Fold);
1196 R->setFastMathFlags(I.getFastMathFlags());
1197 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001198 }
Craig Topperf40110f2014-04-25 05:29:35 +00001199 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001200 }
1201
1202 if (AllowReassociate) {
1203 Value *X, *Y;
Craig Topperf40110f2014-04-25 05:29:35 +00001204 Value *NewInst = nullptr;
1205 Instruction *SimpR = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001206
1207 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1208 // (X/Y) / Z => X / (Y*Z)
1209 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001210 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001211 NewInst = Builder->CreateFMul(Y, Op1);
Owen Anderson1664dc82014-01-20 07:44:53 +00001212 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1213 FastMathFlags Flags = I.getFastMathFlags();
1214 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1215 RI->setFastMathFlags(Flags);
1216 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001217 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1218 }
1219 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1220 // Z / (X/Y) => Z*Y / X
1221 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001222 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001223 NewInst = Builder->CreateFMul(Op0, Y);
Owen Anderson1664dc82014-01-20 07:44:53 +00001224 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1225 FastMathFlags Flags = I.getFastMathFlags();
1226 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1227 RI->setFastMathFlags(Flags);
1228 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001229 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1230 }
1231 }
1232
1233 if (NewInst) {
1234 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1235 T->setDebugLoc(I.getDebugLoc());
1236 SimpR->setFastMathFlags(I.getFastMathFlags());
1237 return SimpR;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001238 }
1239 }
1240
Craig Topperf40110f2014-04-25 05:29:35 +00001241 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001242}
1243
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001244/// This function implements the transforms common to both integer remainder
1245/// instructions (urem and srem). It is called by the visitors to those integer
1246/// remainder instructions.
1247/// @brief Common integer remainder transforms
1248Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1249 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1250
Chris Lattner7c99f192011-05-22 18:18:41 +00001251 // The RHS is known non-zero.
Hal Finkel60db0582014-09-07 18:57:58 +00001252 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +00001253 I.setOperand(1, V);
1254 return &I;
1255 }
1256
Duncan Sandsa3e36992011-05-02 16:27:02 +00001257 // Handle cases involving: rem X, (select Cond, Y, Z)
1258 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1259 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001260
Benjamin Kramer72196f32014-01-19 15:24:22 +00001261 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001262 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1263 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1264 if (Instruction *R = FoldOpIntoSelect(I, SI))
1265 return R;
1266 } else if (isa<PHINode>(Op0I)) {
1267 if (Instruction *NV = FoldOpIntoPhi(I))
1268 return NV;
1269 }
1270
1271 // See if we can fold away this rem instruction.
1272 if (SimplifyDemandedInstructionBits(I))
1273 return &I;
1274 }
1275 }
1276
Craig Topperf40110f2014-04-25 05:29:35 +00001277 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001278}
1279
1280Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1281 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1282
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001283 if (Value *V = SimplifyVectorOp(I))
1284 return ReplaceInstUsesWith(I, V);
1285
Hal Finkel60db0582014-09-07 18:57:58 +00001286 if (Value *V = SimplifyURemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001287 return ReplaceInstUsesWith(I, V);
1288
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001289 if (Instruction *common = commonIRemTransforms(I))
1290 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001291
David Majnemer6c30f492013-05-12 00:07:05 +00001292 // (zext A) urem (zext B) --> zext (A urem B)
1293 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1294 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1295 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1296 I.getType());
1297
David Majnemer470b0772013-05-11 09:01:28 +00001298 // X urem Y -> X and Y-1, where Y is a power of 2,
Hal Finkel60db0582014-09-07 18:57:58 +00001299 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, AT, &I, DT)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001300 Constant *N1 = Constant::getAllOnesValue(I.getType());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001301 Value *Add = Builder->CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001302 return BinaryOperator::CreateAnd(Op0, Add);
1303 }
1304
Nick Lewycky7459be62013-07-13 01:16:47 +00001305 // 1 urem X -> zext(X != 1)
1306 if (match(Op0, m_One())) {
1307 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1308 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1309 return ReplaceInstUsesWith(I, Ext);
1310 }
1311
Craig Topperf40110f2014-04-25 05:29:35 +00001312 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001313}
1314
1315Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1316 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1317
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001318 if (Value *V = SimplifyVectorOp(I))
1319 return ReplaceInstUsesWith(I, V);
1320
Hal Finkel60db0582014-09-07 18:57:58 +00001321 if (Value *V = SimplifySRemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001322 return ReplaceInstUsesWith(I, V);
1323
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001324 // Handle the integer rem common cases
1325 if (Instruction *Common = commonIRemTransforms(I))
1326 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001327
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001328 if (Value *RHSNeg = dyn_castNegVal(Op1))
1329 if (!isa<Constant>(RHSNeg) ||
1330 (isa<ConstantInt>(RHSNeg) &&
1331 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
1332 // X % -Y -> X % Y
1333 Worklist.AddValue(I.getOperand(1));
1334 I.setOperand(1, RHSNeg);
1335 return &I;
1336 }
1337
1338 // If the sign bits of both operands are zero (i.e. we can prove they are
1339 // unsigned inputs), turn this into a urem.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001340 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001341 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001342 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1343 MaskedValueIsZero(Op0, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001344 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001345 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1346 }
1347 }
1348
1349 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001350 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1351 Constant *C = cast<Constant>(Op1);
1352 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001353
1354 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001355 bool hasMissing = false;
1356 for (unsigned i = 0; i != VWidth; ++i) {
1357 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001358 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001359 hasMissing = true;
1360 break;
1361 }
1362
1363 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001364 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001365 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001366 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001367
Chris Lattner0256be92012-01-27 03:08:05 +00001368 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001369 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001370 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001371 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001372 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001373 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001374 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001375 }
1376 }
1377
1378 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001379 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001380 Worklist.AddValue(I.getOperand(1));
1381 I.setOperand(1, NewRHSV);
1382 return &I;
1383 }
1384 }
1385 }
1386
Craig Topperf40110f2014-04-25 05:29:35 +00001387 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001388}
1389
1390Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001391 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001392
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001393 if (Value *V = SimplifyVectorOp(I))
1394 return ReplaceInstUsesWith(I, V);
1395
Hal Finkel60db0582014-09-07 18:57:58 +00001396 if (Value *V = SimplifyFRemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001397 return ReplaceInstUsesWith(I, V);
1398
1399 // Handle cases involving: rem X, (select Cond, Y, Z)
1400 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1401 return &I;
1402
Craig Topperf40110f2014-04-25 05:29:35 +00001403 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001404}