blob: 6c6e7d8151634b37bbce43ff4ec7977a0ef67ec0 [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.
28static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC) {
29 // If V has multiple uses, then we would have to do more analysis to determine
30 // if this is safe. For example, the use could be in dynamically unreached
31 // code.
Craig Topperf40110f2014-04-25 05:29:35 +000032 if (!V->hasOneUse()) return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000033
Chris Lattner388cb8a2011-05-23 00:32:19 +000034 bool MadeChange = false;
35
Chris Lattner7c99f192011-05-22 18:18:41 +000036 // ((1 << A) >>u B) --> (1 << (A-B))
37 // Because V cannot be zero, we know that B is less than A.
Craig Topperf40110f2014-04-25 05:29:35 +000038 Value *A = nullptr, *B = nullptr, *PowerOf2 = nullptr;
Chris Lattner321c58f2011-05-23 00:09:55 +000039 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(PowerOf2), m_Value(A))),
Chris Lattner7c99f192011-05-22 18:18:41 +000040 m_Value(B))) &&
41 // The "1" can be any value known to be a power of 2.
Rafael Espindola319f74c2012-12-13 03:37:24 +000042 isKnownToBeAPowerOfTwo(PowerOf2)) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +000043 A = IC.Builder->CreateSub(A, B);
Chris Lattner321c58f2011-05-23 00:09:55 +000044 return IC.Builder->CreateShl(PowerOf2, A);
Chris Lattner7c99f192011-05-22 18:18:41 +000045 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000046
Chris Lattner388cb8a2011-05-23 00:32:19 +000047 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
48 // inexact. Similarly for <<.
49 if (BinaryOperator *I = dyn_cast<BinaryOperator>(V))
Rafael Espindola319f74c2012-12-13 03:37:24 +000050 if (I->isLogicalShift() && isKnownToBeAPowerOfTwo(I->getOperand(0))) {
Chris Lattner388cb8a2011-05-23 00:32:19 +000051 // We know that this is an exact/nuw shift and that the input is a
52 // non-zero context as well.
53 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC)) {
54 I->setOperand(0, V2);
55 MadeChange = true;
56 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000057
Chris Lattner388cb8a2011-05-23 00:32:19 +000058 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
59 I->setIsExact();
60 MadeChange = true;
61 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000062
Chris Lattner388cb8a2011-05-23 00:32:19 +000063 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
64 I->setHasNoUnsignedWrap();
65 MadeChange = true;
66 }
67 }
68
Chris Lattner162dfc32011-05-22 18:26:48 +000069 // TODO: Lots more we could do here:
Chris Lattner162dfc32011-05-22 18:26:48 +000070 // If V is a phi node, we can call this on each of its operands.
71 // "select cond, X, 0" can simplify to "X".
Jim Grosbachbdbd7342013-04-05 21:20:12 +000072
Craig Topperf40110f2014-04-25 05:29:35 +000073 return MadeChange ? V : nullptr;
Chris Lattner7c99f192011-05-22 18:18:41 +000074}
75
76
Chris Lattnerdc054bf2010-01-05 06:09:35 +000077/// MultiplyOverflows - True if the multiply can not be expressed in an int
78/// this size.
79static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
80 uint32_t W = C1->getBitWidth();
81 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
82 if (sign) {
Jay Foad583abbc2010-12-07 08:25:19 +000083 LHSExt = LHSExt.sext(W * 2);
84 RHSExt = RHSExt.sext(W * 2);
Chris Lattnerdc054bf2010-01-05 06:09:35 +000085 } else {
Jay Foad583abbc2010-12-07 08:25:19 +000086 LHSExt = LHSExt.zext(W * 2);
87 RHSExt = RHSExt.zext(W * 2);
Chris Lattnerdc054bf2010-01-05 06:09:35 +000088 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000089
Chris Lattnerdc054bf2010-01-05 06:09:35 +000090 APInt MulExt = LHSExt * RHSExt;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000091
Chris Lattnerdc054bf2010-01-05 06:09:35 +000092 if (!sign)
93 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
Jim Grosbachbdbd7342013-04-05 21:20:12 +000094
Chris Lattnerdc054bf2010-01-05 06:09:35 +000095 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
96 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
97 return MulExt.slt(Min) || MulExt.sgt(Max);
98}
99
Rafael Espindola65281bf2013-05-31 14:27:15 +0000100/// \brief A helper routine of InstCombiner::visitMul().
101///
102/// If C is a vector of known powers of 2, then this function returns
103/// a new vector obtained from C replacing each element with its logBase2.
104/// Return a null pointer otherwise.
105static Constant *getLogBase2Vector(ConstantDataVector *CV) {
106 const APInt *IVal;
107 SmallVector<Constant *, 4> Elts;
108
109 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
110 Constant *Elt = CV->getElementAsConstant(I);
111 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
Craig Topperf40110f2014-04-25 05:29:35 +0000112 return nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000113 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
114 }
115
116 return ConstantVector::get(Elts);
117}
118
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000119Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000120 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000121 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
122
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000123 if (Value *V = SimplifyVectorOp(I))
124 return ReplaceInstUsesWith(I, V);
125
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000126 if (Value *V = SimplifyMulInst(Op0, Op1, DL))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000127 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000128
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000129 if (Value *V = SimplifyUsingDistributiveLaws(I))
130 return ReplaceInstUsesWith(I, V);
131
Chris Lattner6b657ae2011-02-10 05:36:31 +0000132 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X
133 return BinaryOperator::CreateNeg(Op0, I.getName());
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000134
Rafael Espindola65281bf2013-05-31 14:27:15 +0000135 // Also allow combining multiply instructions on vectors.
136 {
137 Value *NewOp;
138 Constant *C1, *C2;
139 const APInt *IVal;
140 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
141 m_Constant(C1))) &&
142 match(C1, m_APInt(IVal)))
143 // ((X << C1)*C2) == (X * (C2 << C1))
144 return BinaryOperator::CreateMul(NewOp, ConstantExpr::getShl(C1, C2));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000145
Rafael Espindola65281bf2013-05-31 14:27:15 +0000146 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000147 Constant *NewCst = nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000148 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
149 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
150 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
151 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
152 // Replace X*(2^C) with X << C, where C is a vector of known
153 // constant powers of 2.
154 NewCst = getLogBase2Vector(CV);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000155
Rafael Espindola65281bf2013-05-31 14:27:15 +0000156 if (NewCst) {
157 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
158 if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap();
159 if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap();
160 return Shl;
161 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000162 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000163 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000164
Rafael Espindola65281bf2013-05-31 14:27:15 +0000165 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Stuart Hastings23804832011-06-01 16:42:47 +0000166 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
167 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
168 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000169 {
170 const APInt & Val = CI->getValue();
171 const APInt &PosVal = Val.abs();
172 if (Val.isNegative() && PosVal.isPowerOf2()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000173 Value *X = nullptr, *Y = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000174 if (Op0->hasOneUse()) {
175 ConstantInt *C1;
Craig Topperf40110f2014-04-25 05:29:35 +0000176 Value *Sub = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000177 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
178 Sub = Builder->CreateSub(X, Y, "suba");
179 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
180 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
181 if (Sub)
182 return
183 BinaryOperator::CreateMul(Sub,
184 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000185 }
186 }
187 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000188 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000189
Chris Lattner6b657ae2011-02-10 05:36:31 +0000190 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000191 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000192 // Try to fold constant mul into select arguments.
193 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
194 if (Instruction *R = FoldOpIntoSelect(I, SI))
195 return R;
196
197 if (isa<PHINode>(Op0))
198 if (Instruction *NV = FoldOpIntoPhi(I))
199 return NV;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000200
201 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
202 {
203 Value *X;
204 Constant *C1;
205 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
David Majnemer6cf6c052014-06-19 07:14:33 +0000206 Value *Mul = Builder->CreateMul(C1, Op1);
207 // Only go forward with the transform if C1*CI simplifies to a tidier
208 // constant.
209 if (!match(Mul, m_Mul(m_Value(), m_Value())))
210 return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
Benjamin Kramer72196f32014-01-19 15:24:22 +0000211 }
212 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000213 }
214
215 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
216 if (Value *Op1v = dyn_castNegVal(Op1))
217 return BinaryOperator::CreateMul(Op0v, Op1v);
218
219 // (X / Y) * Y = X - (X % Y)
220 // (X / Y) * -Y = (X % Y) - X
221 {
222 Value *Op1C = Op1;
223 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
224 if (!BO ||
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000225 (BO->getOpcode() != Instruction::UDiv &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000226 BO->getOpcode() != Instruction::SDiv)) {
227 Op1C = Op0;
228 BO = dyn_cast<BinaryOperator>(Op1);
229 }
230 Value *Neg = dyn_castNegVal(Op1C);
231 if (BO && BO->hasOneUse() &&
232 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
233 (BO->getOpcode() == Instruction::UDiv ||
234 BO->getOpcode() == Instruction::SDiv)) {
235 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
236
Chris Lattner35315d02011-02-06 21:44:57 +0000237 // If the division is exact, X % Y is zero, so we end up with X or -X.
238 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000239 if (SDiv->isExact()) {
240 if (Op1BO == Op1C)
241 return ReplaceInstUsesWith(I, Op0BO);
242 return BinaryOperator::CreateNeg(Op0BO);
243 }
244
245 Value *Rem;
246 if (BO->getOpcode() == Instruction::UDiv)
247 Rem = Builder->CreateURem(Op0BO, Op1BO);
248 else
249 Rem = Builder->CreateSRem(Op0BO, Op1BO);
250 Rem->takeName(BO);
251
252 if (Op1BO == Op1C)
253 return BinaryOperator::CreateSub(Op0BO, Rem);
254 return BinaryOperator::CreateSub(Rem, Op0BO);
255 }
256 }
257
258 /// i1 mul -> i1 and.
Benjamin Kramer72196f32014-01-19 15:24:22 +0000259 if (I.getType()->getScalarType()->isIntegerTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000260 return BinaryOperator::CreateAnd(Op0, Op1);
261
262 // X*(1 << Y) --> X << Y
263 // (1 << Y)*X --> X << Y
264 {
265 Value *Y;
266 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
267 return BinaryOperator::CreateShl(Op1, Y);
268 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
269 return BinaryOperator::CreateShl(Op0, Y);
270 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000271
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000272 // If one of the operands of the multiply is a cast from a boolean value, then
273 // we know the bool is either zero or one, so this is a 'masking' multiply.
274 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands19d0b472010-02-16 11:11:14 +0000275 if (!I.getType()->isVectorTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000276 // -2 is "-1 << 1" so it is all bits set except the low one.
277 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000278
Craig Topperf40110f2014-04-25 05:29:35 +0000279 Value *BoolCast = nullptr, *OtherOp = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000280 if (MaskedValueIsZero(Op0, Negative2))
281 BoolCast = Op0, OtherOp = Op1;
282 else if (MaskedValueIsZero(Op1, Negative2))
283 BoolCast = Op1, OtherOp = Op0;
284
285 if (BoolCast) {
286 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000287 BoolCast);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000288 return BinaryOperator::CreateAnd(V, OtherOp);
289 }
290 }
291
Craig Topperf40110f2014-04-25 05:29:35 +0000292 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000293}
294
Pedro Artigas993acd02012-11-30 22:07:05 +0000295//
296// Detect pattern:
297//
298// log2(Y*0.5)
299//
300// And check for corresponding fast math flags
301//
302
303static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Pedro Artigas00b83c92012-11-30 22:47:15 +0000304
305 if (!Op->hasOneUse())
306 return;
307
308 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
309 if (!II)
310 return;
311 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
312 return;
313 Log2 = II;
314
315 Value *OpLog2Of = II->getArgOperand(0);
316 if (!OpLog2Of->hasOneUse())
317 return;
318
319 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
320 if (!I)
321 return;
322 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
323 return;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000324
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000325 if (match(I->getOperand(0), m_SpecificFP(0.5)))
Pedro Artigas00b83c92012-11-30 22:47:15 +0000326 Y = I->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000327 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
Pedro Artigas00b83c92012-11-30 22:47:15 +0000328 Y = I->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000329}
Pedro Artigas993acd02012-11-30 22:07:05 +0000330
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000331static bool isFiniteNonZeroFp(Constant *C) {
332 if (C->getType()->isVectorTy()) {
333 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
334 ++I) {
335 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
336 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
337 return false;
338 }
339 return true;
340 }
341
342 return isa<ConstantFP>(C) &&
343 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
344}
345
346static bool isNormalFp(Constant *C) {
347 if (C->getType()->isVectorTy()) {
348 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
349 ++I) {
350 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
351 if (!CFP || !CFP->getValueAPF().isNormal())
352 return false;
353 }
354 return true;
355 }
356
357 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
358}
359
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000360/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
361/// true iff the given value is FMul or FDiv with one and only one operand
362/// being a normal constant (i.e. not Zero/NaN/Infinity).
363static bool isFMulOrFDivWithConstant(Value *V) {
364 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000365 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yang80138662013-01-07 22:41:28 +0000366 I->getOpcode() != Instruction::FDiv))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000367 return false;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000368
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000369 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
370 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000371
372 if (C0 && C1)
373 return false;
374
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000375 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000376}
377
378/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
379/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
380/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000381/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000382/// resulting expression. Note that this function could return NULL in
383/// case the constants cannot be folded into a normal floating-point.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000384///
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000385Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yang80138662013-01-07 22:41:28 +0000386 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000387 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
388
389 Value *Opnd0 = FMulOrDiv->getOperand(0);
390 Value *Opnd1 = FMulOrDiv->getOperand(1);
391
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000392 Constant *C0 = dyn_cast<Constant>(Opnd0);
393 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000394
Craig Topperf40110f2014-04-25 05:29:35 +0000395 BinaryOperator *R = nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000396
397 // (X * C0) * C => X * (C0*C)
398 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
399 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000400 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000401 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
402 } else {
403 if (C0) {
404 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000405 if (FMulOrDiv->hasOneUse()) {
406 // It would otherwise introduce another div.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000407 Constant *F = ConstantExpr::getFMul(C0, C);
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000408 if (isNormalFp(F))
409 R = BinaryOperator::CreateFDiv(F, Opnd1);
410 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000411 } else {
412 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000413 Constant *F = ConstantExpr::getFDiv(C, C1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000414 if (isNormalFp(F)) {
415 R = BinaryOperator::CreateFMul(Opnd0, F);
416 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000417 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000418 Constant *F = ConstantExpr::getFDiv(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000419 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000420 R = BinaryOperator::CreateFDiv(Opnd0, F);
421 }
422 }
423 }
424
425 if (R) {
426 R->setHasUnsafeAlgebra(true);
427 InsertNewInstWith(R, *InsertBefore);
428 }
429
430 return R;
431}
432
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000433Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000434 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000435 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
436
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000437 if (Value *V = SimplifyVectorOp(I))
438 return ReplaceInstUsesWith(I, V);
439
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000440 if (isa<Constant>(Op0))
441 std::swap(Op0, Op1);
442
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000443 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL))
Michael Ilsemand5787be2012-12-12 00:28:32 +0000444 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000445
Shuxin Yange8227452013-01-15 21:09:32 +0000446 bool AllowReassociate = I.hasUnsafeAlgebra();
447
Michael Ilsemand5787be2012-12-12 00:28:32 +0000448 // Simplify mul instructions with a constant RHS.
449 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000450 // Try to fold constant mul into select arguments.
451 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
452 if (Instruction *R = FoldOpIntoSelect(I, SI))
453 return R;
454
455 if (isa<PHINode>(Op0))
456 if (Instruction *NV = FoldOpIntoPhi(I))
457 return NV;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000458
Owen Andersonf74cfe02014-01-16 20:36:42 +0000459 // (fmul X, -1.0) --> (fsub -0.0, X)
Benjamin Kramerfea9ac92014-01-18 16:43:14 +0000460 if (match(Op1, m_SpecificFP(-1.0))) {
461 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
462 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000463 RI->copyFastMathFlags(&I);
464 return RI;
465 }
466
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000467 Constant *C = cast<Constant>(Op1);
468 if (AllowReassociate && isFiniteNonZeroFp(C)) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000469 // Let MDC denote an expression in one of these forms:
470 // X * C, C/X, X/C, where C is a constant.
471 //
472 // Try to simplify "MDC * Constant"
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000473 if (isFMulOrFDivWithConstant(Op0))
474 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000475 return ReplaceInstUsesWith(I, V);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000476
Quentin Colombete684a6d2013-02-28 21:12:40 +0000477 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000478 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
479 if (FAddSub &&
480 (FAddSub->getOpcode() == Instruction::FAdd ||
481 FAddSub->getOpcode() == Instruction::FSub)) {
482 Value *Opnd0 = FAddSub->getOperand(0);
483 Value *Opnd1 = FAddSub->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000484 Constant *C0 = dyn_cast<Constant>(Opnd0);
485 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000486 bool Swap = false;
487 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000488 std::swap(C0, C1);
489 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000490 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000491 }
492
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000493 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000494 Value *M1 = ConstantExpr::getFMul(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000495 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000496 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
Craig Topperf40110f2014-04-25 05:29:35 +0000497 nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000498 if (M0 && M1) {
499 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
500 std::swap(M0, M1);
501
Benjamin Kramer67485762013-09-30 15:39:59 +0000502 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
503 ? BinaryOperator::CreateFAdd(M0, M1)
504 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000505 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000506 return RI;
507 }
508 }
509 }
510 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000511 }
512
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000513
Pedro Artigasd8795042012-11-30 19:09:41 +0000514 // Under unsafe algebra do:
515 // X * log2(0.5*Y) = X*log2(Y) - X
516 if (I.hasUnsafeAlgebra()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000517 Value *OpX = nullptr;
518 Value *OpY = nullptr;
Pedro Artigasd8795042012-11-30 19:09:41 +0000519 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000520 detectLog2OfHalf(Op0, OpY, Log2);
521 if (OpY) {
522 OpX = Op1;
523 } else {
524 detectLog2OfHalf(Op1, OpY, Log2);
525 if (OpY) {
526 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000527 }
528 }
529 // if pattern detected emit alternate sequence
530 if (OpX && OpY) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000531 BuilderTy::FastMathFlagGuard Guard(*Builder);
532 Builder->SetFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000533 Log2->setArgOperand(0, OpY);
534 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
Benjamin Kramer67485762013-09-30 15:39:59 +0000535 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
536 FSub->takeName(&I);
537 return ReplaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000538 }
539 }
540
Shuxin Yange8227452013-01-15 21:09:32 +0000541 // Handle symmetric situation in a 2-iteration loop
542 Value *Opnd0 = Op0;
543 Value *Opnd1 = Op1;
544 for (int i = 0; i < 2; i++) {
545 bool IgnoreZeroSign = I.hasNoSignedZeros();
546 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000547 BuilderTy::FastMathFlagGuard Guard(*Builder);
548 Builder->SetFastMathFlags(I.getFastMathFlags());
549
Shuxin Yange8227452013-01-15 21:09:32 +0000550 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
551 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000552
Shuxin Yange8227452013-01-15 21:09:32 +0000553 // -X * -Y => X*Y
Owen Andersone8537fc2014-01-16 20:59:41 +0000554 if (N1) {
555 Value *FMul = Builder->CreateFMul(N0, N1);
556 FMul->takeName(&I);
557 return ReplaceInstUsesWith(I, FMul);
558 }
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000559
Shuxin Yange8227452013-01-15 21:09:32 +0000560 if (Opnd0->hasOneUse()) {
561 // -X * Y => -(X*Y) (Promote negation as high as possible)
562 Value *T = Builder->CreateFMul(N0, Opnd1);
Benjamin Kramer67485762013-09-30 15:39:59 +0000563 Value *Neg = Builder->CreateFNeg(T);
564 Neg->takeName(&I);
565 return ReplaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000566 }
567 }
Shuxin Yange8227452013-01-15 21:09:32 +0000568
569 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000570 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000571 // 1) to form a power expression (of X).
572 // 2) potentially shorten the critical path: After transformation, the
573 // latency of the instruction Y is amortized by the expression of X*X,
574 // and therefore Y is in a "less critical" position compared to what it
575 // was before the transformation.
576 //
577 if (AllowReassociate) {
578 Value *Opnd0_0, *Opnd0_1;
579 if (Opnd0->hasOneUse() &&
580 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000581 Value *Y = nullptr;
Shuxin Yange8227452013-01-15 21:09:32 +0000582 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
583 Y = Opnd0_1;
584 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
585 Y = Opnd0_0;
586
587 if (Y) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000588 BuilderTy::FastMathFlagGuard Guard(*Builder);
589 Builder->SetFastMathFlags(I.getFastMathFlags());
590 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
Shuxin Yange8227452013-01-15 21:09:32 +0000591
Benjamin Kramer67485762013-09-30 15:39:59 +0000592 Value *R = Builder->CreateFMul(T, Y);
593 R->takeName(&I);
594 return ReplaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000595 }
596 }
597 }
598
Stephen Lin03f9fbb2013-07-17 20:06:03 +0000599 // B * (uitofp i1 C) -> select C, B, 0
600 if (I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) {
601 Value *LHS = Op0, *RHS = Op1;
602 Value *B, *C;
Stephen Lin4ef13872013-07-26 17:55:00 +0000603 if (!match(RHS, m_UIToFP(m_Value(C))))
Stephen Lin03f9fbb2013-07-17 20:06:03 +0000604 std::swap(LHS, RHS);
605
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000606 if (match(RHS, m_UIToFP(m_Value(C))) &&
607 C->getType()->getScalarType()->isIntegerTy(1)) {
Stephen Lin03f9fbb2013-07-17 20:06:03 +0000608 B = LHS;
609 Value *Zero = ConstantFP::getNegativeZero(B->getType());
610 return SelectInst::Create(C, B, Zero);
611 }
612 }
613
614 // A * (1 - uitofp i1 C) -> select C, 0, A
615 if (I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) {
616 Value *LHS = Op0, *RHS = Op1;
617 Value *A, *C;
Stephen Lin4ef13872013-07-26 17:55:00 +0000618 if (!match(RHS, m_FSub(m_FPOne(), m_UIToFP(m_Value(C)))))
Stephen Lin03f9fbb2013-07-17 20:06:03 +0000619 std::swap(LHS, RHS);
620
Stephen Lin4ef13872013-07-26 17:55:00 +0000621 if (match(RHS, m_FSub(m_FPOne(), m_UIToFP(m_Value(C)))) &&
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000622 C->getType()->getScalarType()->isIntegerTy(1)) {
Stephen Lin03f9fbb2013-07-17 20:06:03 +0000623 A = LHS;
624 Value *Zero = ConstantFP::getNegativeZero(A->getType());
625 return SelectInst::Create(C, Zero, A);
626 }
627 }
628
Shuxin Yange8227452013-01-15 21:09:32 +0000629 if (!isa<Constant>(Op1))
630 std::swap(Opnd0, Opnd1);
631 else
632 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000633 }
634
Craig Topperf40110f2014-04-25 05:29:35 +0000635 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000636}
637
638/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
639/// instruction.
640bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
641 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000642
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000643 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
644 int NonNullOperand = -1;
645 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
646 if (ST->isNullValue())
647 NonNullOperand = 2;
648 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
649 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
650 if (ST->isNullValue())
651 NonNullOperand = 1;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000652
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000653 if (NonNullOperand == -1)
654 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000655
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000656 Value *SelectCond = SI->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000657
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000658 // Change the div/rem to use 'Y' instead of the select.
659 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000660
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000661 // Okay, we know we replace the operand of the div/rem with 'Y' with no
662 // problem. However, the select, or the condition of the select may have
663 // multiple uses. Based on our knowledge that the operand must be non-zero,
664 // propagate the known value for the select into other uses of it, and
665 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000666
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000667 // If the select and condition only have a single use, don't bother with this,
668 // early exit.
669 if (SI->use_empty() && SelectCond->hasOneUse())
670 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000671
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000672 // Scan the current block backward, looking for other uses of SI.
673 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000674
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000675 while (BBI != BBFront) {
676 --BBI;
677 // If we found a call to a function, we can't assume it will return, so
678 // information from below it cannot be propagated above it.
679 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
680 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000681
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000682 // Replace uses of the select or its condition with the known values.
683 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
684 I != E; ++I) {
685 if (*I == SI) {
686 *I = SI->getOperand(NonNullOperand);
687 Worklist.Add(BBI);
688 } else if (*I == SelectCond) {
Jakub Staszak96ff4d62013-06-06 23:34:59 +0000689 *I = Builder->getInt1(NonNullOperand == 1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000690 Worklist.Add(BBI);
691 }
692 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000693
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000694 // If we past the instruction, quit looking for it.
695 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000696 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000697 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000698 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000699
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000700 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000701 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000702 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000703
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000704 }
705 return true;
706}
707
708
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000709/// This function implements the transforms common to both integer division
710/// instructions (udiv and sdiv). It is called by the visitors to those integer
711/// division instructions.
712/// @brief Common integer divide transforms
713Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
714 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
715
Chris Lattner7c99f192011-05-22 18:18:41 +0000716 // The RHS is known non-zero.
717 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
718 I.setOperand(1, V);
719 return &I;
720 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000721
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000722 // Handle cases involving: [su]div X, (select Cond, Y, Z)
723 // This does not apply for fdiv.
724 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
725 return &I;
726
727 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000728 // (X / C1) / C2 -> X / (C1*C2)
729 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
730 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
731 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
732 if (MultiplyOverflows(RHS, LHSRHS,
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000733 I.getOpcode() == Instruction::SDiv))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000734 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner6b657ae2011-02-10 05:36:31 +0000735 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
736 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000737 }
738
739 if (!RHS->isZero()) { // avoid X udiv 0
740 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
741 if (Instruction *R = FoldOpIntoSelect(I, SI))
742 return R;
743 if (isa<PHINode>(Op0))
744 if (Instruction *NV = FoldOpIntoPhi(I))
745 return NV;
746 }
747 }
748
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000749 if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
750 if (One->isOne() && !I.getType()->isIntegerTy(1)) {
751 bool isSigned = I.getOpcode() == Instruction::SDiv;
752 if (isSigned) {
753 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
754 // result is one, if Op1 is -1 then the result is minus one, otherwise
755 // it's zero.
756 Value *Inc = Builder->CreateAdd(Op1, One);
757 Value *Cmp = Builder->CreateICmpULT(
758 Inc, ConstantInt::get(I.getType(), 3));
759 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
760 } else {
761 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
762 // result is one, otherwise it's zero.
763 return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
764 }
765 }
766 }
767
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000768 // See if we can fold away this div instruction.
769 if (SimplifyDemandedInstructionBits(I))
770 return &I;
771
Duncan Sands771e82a2011-01-28 16:51:11 +0000772 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Craig Topperf40110f2014-04-25 05:29:35 +0000773 Value *X = nullptr, *Z = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +0000774 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
775 bool isSigned = I.getOpcode() == Instruction::SDiv;
776 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
777 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
778 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000779 }
780
Craig Topperf40110f2014-04-25 05:29:35 +0000781 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000782}
783
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000784/// dyn_castZExtVal - Checks if V is a zext or constant that can
785/// be truncated to Ty without losing bits.
Chris Lattner229907c2011-07-18 04:54:35 +0000786static Value *dyn_castZExtVal(Value *V, Type *Ty) {
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000787 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
788 if (Z->getSrcTy() == Ty)
789 return Z->getOperand(0);
790 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
791 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
792 return ConstantExpr::getTrunc(C, Ty);
793 }
Craig Topperf40110f2014-04-25 05:29:35 +0000794 return nullptr;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000795}
796
David Majnemer37f8f442013-07-04 21:17:49 +0000797namespace {
798const unsigned MaxDepth = 6;
799typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
800 const BinaryOperator &I,
801 InstCombiner &IC);
802
803/// \brief Used to maintain state for visitUDivOperand().
804struct UDivFoldAction {
805 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
806 ///< operand. This can be zero if this action
807 ///< joins two actions together.
808
809 Value *OperandToFold; ///< Which operand to fold.
810 union {
811 Instruction *FoldResult; ///< The instruction returned when FoldAction is
812 ///< invoked.
813
814 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
815 ///< joins two actions together.
816 };
817
818 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +0000819 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +0000820 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
821 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
822};
823}
824
825// X udiv 2^C -> X >> C
826static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
827 const BinaryOperator &I, InstCombiner &IC) {
828 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
829 BinaryOperator *LShr = BinaryOperator::CreateLShr(
830 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
831 if (I.isExact()) LShr->setIsExact();
832 return LShr;
833}
834
835// X udiv C, where C >= signbit
836static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
837 const BinaryOperator &I, InstCombiner &IC) {
838 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
839
840 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
841 ConstantInt::get(I.getType(), 1));
842}
843
844// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
845static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
846 InstCombiner &IC) {
847 Instruction *ShiftLeft = cast<Instruction>(Op1);
848 if (isa<ZExtInst>(ShiftLeft))
849 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
850
851 const APInt &CI =
852 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
853 Value *N = ShiftLeft->getOperand(1);
854 if (CI != 1)
855 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
856 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
857 N = IC.Builder->CreateZExt(N, Z->getDestTy());
858 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
859 if (I.isExact()) LShr->setIsExact();
860 return LShr;
861}
862
863// \brief Recursively visits the possible right hand operands of a udiv
864// instruction, seeing through select instructions, to determine if we can
865// replace the udiv with something simpler. If we find that an operand is not
866// able to simplify the udiv, we abort the entire transformation.
867static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
868 SmallVectorImpl<UDivFoldAction> &Actions,
869 unsigned Depth = 0) {
870 // Check to see if this is an unsigned division with an exact power of 2,
871 // if so, convert to a right shift.
872 if (match(Op1, m_Power2())) {
873 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
874 return Actions.size();
875 }
876
877 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
878 // X udiv C, where C >= signbit
879 if (C->getValue().isNegative()) {
880 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
881 return Actions.size();
882 }
883
884 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
885 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
886 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
887 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
888 return Actions.size();
889 }
890
891 // The remaining tests are all recursive, so bail out if we hit the limit.
892 if (Depth++ == MaxDepth)
893 return 0;
894
895 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
896 if (size_t LHSIdx = visitUDivOperand(Op0, SI->getOperand(1), I, Actions))
897 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000898 Actions.push_back(UDivFoldAction((FoldUDivOperandCb)nullptr, Op1,
899 LHSIdx-1));
David Majnemer37f8f442013-07-04 21:17:49 +0000900 return Actions.size();
901 }
902
903 return 0;
904}
905
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000906Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
907 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
908
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000909 if (Value *V = SimplifyVectorOp(I))
910 return ReplaceInstUsesWith(I, V);
911
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000912 if (Value *V = SimplifyUDivInst(Op0, Op1, DL))
Duncan Sands771e82a2011-01-28 16:51:11 +0000913 return ReplaceInstUsesWith(I, V);
914
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000915 // Handle the integer div common cases
916 if (Instruction *Common = commonIDivTransforms(I))
917 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000918
Benjamin Kramerd4a64712012-08-30 15:07:40 +0000919 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
Benjamin Kramer72196f32014-01-19 15:24:22 +0000920 if (Constant *C2 = dyn_cast<Constant>(Op1)) {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +0000921 Value *X;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000922 Constant *C1;
923 if (match(Op0, m_LShr(m_Value(X), m_Constant(C1))))
924 return BinaryOperator::CreateUDiv(X, ConstantExpr::getShl(C2, C1));
Nadav Rotem11935b22012-08-28 10:01:43 +0000925 }
926
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000927 // (zext A) udiv (zext B) --> zext (A udiv B)
928 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
929 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
930 return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
931 I.isExact()),
932 I.getType());
933
David Majnemer37f8f442013-07-04 21:17:49 +0000934 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
935 SmallVector<UDivFoldAction, 6> UDivActions;
936 if (visitUDivOperand(Op0, Op1, I, UDivActions))
937 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
938 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
939 Value *ActionOp1 = UDivActions[i].OperandToFold;
940 Instruction *Inst;
941 if (Action)
942 Inst = Action(Op0, ActionOp1, I, *this);
943 else {
944 // This action joins two actions together. The RHS of this action is
945 // simply the last action we processed, we saved the LHS action index in
946 // the joining action.
947 size_t SelectRHSIdx = i - 1;
948 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
949 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
950 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
951 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
952 SelectLHS, SelectRHS);
953 }
954
955 // If this is the last action to process, return it to the InstCombiner.
956 // Otherwise, we insert it before the UDiv and record it so that we may
957 // use it as part of a joining action (i.e., a SelectInst).
958 if (e - i != 1) {
959 Inst->insertBefore(&I);
960 UDivActions[i].FoldResult = Inst;
961 } else
962 return Inst;
963 }
964
Craig Topperf40110f2014-04-25 05:29:35 +0000965 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000966}
967
968Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
969 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
970
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000971 if (Value *V = SimplifyVectorOp(I))
972 return ReplaceInstUsesWith(I, V);
973
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000974 if (Value *V = SimplifySDivInst(Op0, Op1, DL))
Duncan Sands771e82a2011-01-28 16:51:11 +0000975 return ReplaceInstUsesWith(I, V);
976
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000977 // Handle the integer div common cases
978 if (Instruction *Common = commonIDivTransforms(I))
979 return Common;
980
Benjamin Kramer72196f32014-01-19 15:24:22 +0000981 // sdiv X, -1 == -X
982 if (match(Op1, m_AllOnes()))
983 return BinaryOperator::CreateNeg(Op0);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000984
Benjamin Kramer72196f32014-01-19 15:24:22 +0000985 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +0000986 // sdiv X, C --> ashr exact X, log2(C)
987 if (I.isExact() && RHS->getValue().isNonNegative() &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000988 RHS->getValue().isPowerOf2()) {
989 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
990 RHS->getValue().exactLogBase2());
Chris Lattner6b657ae2011-02-10 05:36:31 +0000991 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000992 }
Benjamin Kramer72196f32014-01-19 15:24:22 +0000993 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000994
Benjamin Kramer72196f32014-01-19 15:24:22 +0000995 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
David Majnemerf28e2a42014-07-02 06:42:13 +0000996 // X/INT_MIN -> X == INT_MIN
997 if (RHS->isMinSignedValue())
998 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
999
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001000 // -X/C --> X/-C provided the negation doesn't overflow.
1001 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
Chris Lattner6b657ae2011-02-10 05:36:31 +00001002 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001003 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
1004 ConstantExpr::getNeg(RHS));
1005 }
1006
1007 // If the sign bits of both operands are zero (i.e. we can prove they are
1008 // unsigned inputs), turn this into a udiv.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001009 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001010 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1011 if (MaskedValueIsZero(Op0, Mask)) {
1012 if (MaskedValueIsZero(Op1, Mask)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001013 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001014 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1015 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001016
Chris Lattner6b657ae2011-02-10 05:36:31 +00001017 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001018 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1019 // Safe because the only negative value (1 << Y) can take on is
1020 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1021 // the sign bit set.
1022 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1023 }
1024 }
1025 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001026
Craig Topperf40110f2014-04-25 05:29:35 +00001027 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001028}
1029
Shuxin Yang320f52a2013-01-14 22:48:41 +00001030/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1031/// FP value and:
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001032/// 1) 1/C is exact, or
Shuxin Yang320f52a2013-01-14 22:48:41 +00001033/// 2) reciprocal is allowed.
Sylvestre Ledru149e2812013-05-14 23:36:24 +00001034/// If the conversion was successful, the simplified expression "X * 1/C" is
Shuxin Yang320f52a2013-01-14 22:48:41 +00001035/// returned; otherwise, NULL is returned.
1036///
1037static Instruction *CvtFDivConstToReciprocal(Value *Dividend,
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001038 Constant *Divisor,
Shuxin Yang320f52a2013-01-14 22:48:41 +00001039 bool AllowReciprocal) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001040 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001041 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001042
1043 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001044 APFloat Reciprocal(FpVal.getSemantics());
1045 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001046
Michael Gottesman3cb77ab2013-06-19 21:23:18 +00001047 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001048 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1049 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1050 Cvt = !Reciprocal.isDenormal();
1051 }
1052
1053 if (!Cvt)
Craig Topperf40110f2014-04-25 05:29:35 +00001054 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001055
1056 ConstantFP *R;
1057 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1058 return BinaryOperator::CreateFMul(Dividend, R);
1059}
1060
Frits van Bommel2a559512011-01-29 17:50:27 +00001061Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1062 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1063
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001064 if (Value *V = SimplifyVectorOp(I))
1065 return ReplaceInstUsesWith(I, V);
1066
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001067 if (Value *V = SimplifyFDivInst(Op0, Op1, DL))
Frits van Bommel2a559512011-01-29 17:50:27 +00001068 return ReplaceInstUsesWith(I, V);
1069
Stephen Lina9b57f62013-07-20 07:13:13 +00001070 if (isa<Constant>(Op0))
1071 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1072 if (Instruction *R = FoldOpIntoSelect(I, SI))
1073 return R;
1074
Shuxin Yang320f52a2013-01-14 22:48:41 +00001075 bool AllowReassociate = I.hasUnsafeAlgebra();
1076 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001077
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001078 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001079 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1080 if (Instruction *R = FoldOpIntoSelect(I, SI))
1081 return R;
1082
Shuxin Yang320f52a2013-01-14 22:48:41 +00001083 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +00001084 Constant *C1 = nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001085 Constant *C2 = Op1C;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001086 Value *X;
Craig Topperf40110f2014-04-25 05:29:35 +00001087 Instruction *Res = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001088
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001089 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001090 // (X*C1)/C2 => X * (C1/C2)
1091 //
1092 Constant *C = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001093 if (isNormalFp(C))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001094 Res = BinaryOperator::CreateFMul(X, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001095 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001096 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1097 //
1098 Constant *C = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001099 if (isNormalFp(C)) {
1100 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001101 if (!Res)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001102 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001103 }
1104 }
1105
1106 if (Res) {
1107 Res->setFastMathFlags(I.getFastMathFlags());
1108 return Res;
1109 }
1110 }
1111
1112 // X / C => X * 1/C
Owen Anderson4557a152014-01-16 21:07:52 +00001113 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1114 T->copyFastMathFlags(&I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001115 return T;
Owen Anderson4557a152014-01-16 21:07:52 +00001116 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001117
Craig Topperf40110f2014-04-25 05:29:35 +00001118 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001119 }
1120
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001121 if (AllowReassociate && isa<Constant>(Op0)) {
1122 Constant *C1 = cast<Constant>(Op0), *C2;
Craig Topperf40110f2014-04-25 05:29:35 +00001123 Constant *Fold = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001124 Value *X;
1125 bool CreateDiv = true;
1126
1127 // C1 / (X*C2) => (C1/C2) / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001128 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001129 Fold = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001130 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001131 // C1 / (X/C2) => (C1*C2) / X
1132 Fold = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001133 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001134 // C1 / (C2/X) => (C1/C2) * X
1135 Fold = ConstantExpr::getFDiv(C1, C2);
1136 CreateDiv = false;
1137 }
1138
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001139 if (Fold && isNormalFp(Fold)) {
1140 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1141 : BinaryOperator::CreateFMul(X, Fold);
1142 R->setFastMathFlags(I.getFastMathFlags());
1143 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001144 }
Craig Topperf40110f2014-04-25 05:29:35 +00001145 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001146 }
1147
1148 if (AllowReassociate) {
1149 Value *X, *Y;
Craig Topperf40110f2014-04-25 05:29:35 +00001150 Value *NewInst = nullptr;
1151 Instruction *SimpR = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001152
1153 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1154 // (X/Y) / Z => X / (Y*Z)
1155 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001156 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001157 NewInst = Builder->CreateFMul(Y, Op1);
Owen Anderson1664dc82014-01-20 07:44:53 +00001158 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1159 FastMathFlags Flags = I.getFastMathFlags();
1160 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1161 RI->setFastMathFlags(Flags);
1162 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001163 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1164 }
1165 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1166 // Z / (X/Y) => Z*Y / X
1167 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001168 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001169 NewInst = Builder->CreateFMul(Op0, Y);
Owen Anderson1664dc82014-01-20 07:44:53 +00001170 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1171 FastMathFlags Flags = I.getFastMathFlags();
1172 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1173 RI->setFastMathFlags(Flags);
1174 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001175 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1176 }
1177 }
1178
1179 if (NewInst) {
1180 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1181 T->setDebugLoc(I.getDebugLoc());
1182 SimpR->setFastMathFlags(I.getFastMathFlags());
1183 return SimpR;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001184 }
1185 }
1186
Craig Topperf40110f2014-04-25 05:29:35 +00001187 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001188}
1189
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001190/// This function implements the transforms common to both integer remainder
1191/// instructions (urem and srem). It is called by the visitors to those integer
1192/// remainder instructions.
1193/// @brief Common integer remainder transforms
1194Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1195 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1196
Chris Lattner7c99f192011-05-22 18:18:41 +00001197 // The RHS is known non-zero.
1198 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
1199 I.setOperand(1, V);
1200 return &I;
1201 }
1202
Duncan Sandsa3e36992011-05-02 16:27:02 +00001203 // Handle cases involving: rem X, (select Cond, Y, Z)
1204 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1205 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001206
Benjamin Kramer72196f32014-01-19 15:24:22 +00001207 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001208 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1209 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1210 if (Instruction *R = FoldOpIntoSelect(I, SI))
1211 return R;
1212 } else if (isa<PHINode>(Op0I)) {
1213 if (Instruction *NV = FoldOpIntoPhi(I))
1214 return NV;
1215 }
1216
1217 // See if we can fold away this rem instruction.
1218 if (SimplifyDemandedInstructionBits(I))
1219 return &I;
1220 }
1221 }
1222
Craig Topperf40110f2014-04-25 05:29:35 +00001223 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001224}
1225
1226Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1227 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1228
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001229 if (Value *V = SimplifyVectorOp(I))
1230 return ReplaceInstUsesWith(I, V);
1231
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001232 if (Value *V = SimplifyURemInst(Op0, Op1, DL))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001233 return ReplaceInstUsesWith(I, V);
1234
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001235 if (Instruction *common = commonIRemTransforms(I))
1236 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001237
David Majnemer6c30f492013-05-12 00:07:05 +00001238 // (zext A) urem (zext B) --> zext (A urem B)
1239 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1240 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1241 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1242 I.getType());
1243
David Majnemer470b0772013-05-11 09:01:28 +00001244 // X urem Y -> X and Y-1, where Y is a power of 2,
1245 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001246 Constant *N1 = Constant::getAllOnesValue(I.getType());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001247 Value *Add = Builder->CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001248 return BinaryOperator::CreateAnd(Op0, Add);
1249 }
1250
Nick Lewycky7459be62013-07-13 01:16:47 +00001251 // 1 urem X -> zext(X != 1)
1252 if (match(Op0, m_One())) {
1253 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1254 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1255 return ReplaceInstUsesWith(I, Ext);
1256 }
1257
Craig Topperf40110f2014-04-25 05:29:35 +00001258 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001259}
1260
1261Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1262 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1263
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001264 if (Value *V = SimplifyVectorOp(I))
1265 return ReplaceInstUsesWith(I, V);
1266
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001267 if (Value *V = SimplifySRemInst(Op0, Op1, DL))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001268 return ReplaceInstUsesWith(I, V);
1269
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001270 // Handle the integer rem common cases
1271 if (Instruction *Common = commonIRemTransforms(I))
1272 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001273
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001274 if (Value *RHSNeg = dyn_castNegVal(Op1))
1275 if (!isa<Constant>(RHSNeg) ||
1276 (isa<ConstantInt>(RHSNeg) &&
1277 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
1278 // X % -Y -> X % Y
1279 Worklist.AddValue(I.getOperand(1));
1280 I.setOperand(1, RHSNeg);
1281 return &I;
1282 }
1283
1284 // If the sign bits of both operands are zero (i.e. we can prove they are
1285 // unsigned inputs), turn this into a urem.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001286 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001287 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1288 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001289 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001290 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1291 }
1292 }
1293
1294 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001295 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1296 Constant *C = cast<Constant>(Op1);
1297 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001298
1299 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001300 bool hasMissing = false;
1301 for (unsigned i = 0; i != VWidth; ++i) {
1302 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001303 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001304 hasMissing = true;
1305 break;
1306 }
1307
1308 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001309 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001310 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001311 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001312
Chris Lattner0256be92012-01-27 03:08:05 +00001313 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001314 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001315 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001316 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001317 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001318 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001319 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001320 }
1321 }
1322
1323 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001324 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001325 Worklist.AddValue(I.getOperand(1));
1326 I.setOperand(1, NewRHSV);
1327 return &I;
1328 }
1329 }
1330 }
1331
Craig Topperf40110f2014-04-25 05:29:35 +00001332 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001333}
1334
1335Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001336 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001337
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001338 if (Value *V = SimplifyVectorOp(I))
1339 return ReplaceInstUsesWith(I, V);
1340
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001341 if (Value *V = SimplifyFRemInst(Op0, Op1, DL))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001342 return ReplaceInstUsesWith(I, V);
1343
1344 // Handle cases involving: rem X, (select Cond, Y, Z)
1345 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1346 return &I;
1347
Craig Topperf40110f2014-04-25 05:29:35 +00001348 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001349}