blob: 3f86ddfd104e01a1e505eeb170ab4fa4a90c7ab7 [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
David Majnemerf9a095d2014-08-16 08:55:06 +0000100/// \brief True if C2 is a multiple of C1. Quotient contains C2/C1.
101static bool IsMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
102 bool IsSigned) {
103 assert(C1.getBitWidth() == C2.getBitWidth() &&
104 "Inconsistent width of constants!");
105
106 APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
107 if (IsSigned)
108 APInt::sdivrem(C1, C2, Quotient, Remainder);
109 else
110 APInt::udivrem(C1, C2, Quotient, Remainder);
111
112 return Remainder.isMinValue();
113}
114
Rafael Espindola65281bf2013-05-31 14:27:15 +0000115/// \brief A helper routine of InstCombiner::visitMul().
116///
117/// If C is a vector of known powers of 2, then this function returns
118/// a new vector obtained from C replacing each element with its logBase2.
119/// Return a null pointer otherwise.
120static Constant *getLogBase2Vector(ConstantDataVector *CV) {
121 const APInt *IVal;
122 SmallVector<Constant *, 4> Elts;
123
124 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
125 Constant *Elt = CV->getElementAsConstant(I);
126 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
Craig Topperf40110f2014-04-25 05:29:35 +0000127 return nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000128 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
129 }
130
131 return ConstantVector::get(Elts);
132}
133
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000134Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000135 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000136 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
137
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000138 if (Value *V = SimplifyVectorOp(I))
139 return ReplaceInstUsesWith(I, V);
140
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000141 if (Value *V = SimplifyMulInst(Op0, Op1, DL))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000142 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000143
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000144 if (Value *V = SimplifyUsingDistributiveLaws(I))
145 return ReplaceInstUsesWith(I, V);
146
Chris Lattner6b657ae2011-02-10 05:36:31 +0000147 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X
148 return BinaryOperator::CreateNeg(Op0, I.getName());
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000149
Rafael Espindola65281bf2013-05-31 14:27:15 +0000150 // Also allow combining multiply instructions on vectors.
151 {
152 Value *NewOp;
153 Constant *C1, *C2;
154 const APInt *IVal;
155 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
156 m_Constant(C1))) &&
157 match(C1, m_APInt(IVal)))
158 // ((X << C1)*C2) == (X * (C2 << C1))
159 return BinaryOperator::CreateMul(NewOp, ConstantExpr::getShl(C1, C2));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000160
Rafael Espindola65281bf2013-05-31 14:27:15 +0000161 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000162 Constant *NewCst = nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000163 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
164 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
165 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
166 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
167 // Replace X*(2^C) with X << C, where C is a vector of known
168 // constant powers of 2.
169 NewCst = getLogBase2Vector(CV);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000170
Rafael Espindola65281bf2013-05-31 14:27:15 +0000171 if (NewCst) {
172 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
173 if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap();
174 if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap();
175 return Shl;
176 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000177 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000178 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000179
Rafael Espindola65281bf2013-05-31 14:27:15 +0000180 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Stuart Hastings23804832011-06-01 16:42:47 +0000181 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
182 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
183 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000184 {
185 const APInt & Val = CI->getValue();
186 const APInt &PosVal = Val.abs();
187 if (Val.isNegative() && PosVal.isPowerOf2()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000188 Value *X = nullptr, *Y = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000189 if (Op0->hasOneUse()) {
190 ConstantInt *C1;
Craig Topperf40110f2014-04-25 05:29:35 +0000191 Value *Sub = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000192 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
193 Sub = Builder->CreateSub(X, Y, "suba");
194 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
195 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
196 if (Sub)
197 return
198 BinaryOperator::CreateMul(Sub,
199 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000200 }
201 }
202 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000203 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000204
Chris Lattner6b657ae2011-02-10 05:36:31 +0000205 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000206 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000207 // Try to fold constant mul into select arguments.
208 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
209 if (Instruction *R = FoldOpIntoSelect(I, SI))
210 return R;
211
212 if (isa<PHINode>(Op0))
213 if (Instruction *NV = FoldOpIntoPhi(I))
214 return NV;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000215
216 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
217 {
218 Value *X;
219 Constant *C1;
220 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
David Majnemer6cf6c052014-06-19 07:14:33 +0000221 Value *Mul = Builder->CreateMul(C1, Op1);
222 // Only go forward with the transform if C1*CI simplifies to a tidier
223 // constant.
224 if (!match(Mul, m_Mul(m_Value(), m_Value())))
225 return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
Benjamin Kramer72196f32014-01-19 15:24:22 +0000226 }
227 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000228 }
229
230 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
231 if (Value *Op1v = dyn_castNegVal(Op1))
232 return BinaryOperator::CreateMul(Op0v, Op1v);
233
234 // (X / Y) * Y = X - (X % Y)
235 // (X / Y) * -Y = (X % Y) - X
236 {
237 Value *Op1C = Op1;
238 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
239 if (!BO ||
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000240 (BO->getOpcode() != Instruction::UDiv &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000241 BO->getOpcode() != Instruction::SDiv)) {
242 Op1C = Op0;
243 BO = dyn_cast<BinaryOperator>(Op1);
244 }
245 Value *Neg = dyn_castNegVal(Op1C);
246 if (BO && BO->hasOneUse() &&
247 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
248 (BO->getOpcode() == Instruction::UDiv ||
249 BO->getOpcode() == Instruction::SDiv)) {
250 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
251
Chris Lattner35315d02011-02-06 21:44:57 +0000252 // If the division is exact, X % Y is zero, so we end up with X or -X.
253 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000254 if (SDiv->isExact()) {
255 if (Op1BO == Op1C)
256 return ReplaceInstUsesWith(I, Op0BO);
257 return BinaryOperator::CreateNeg(Op0BO);
258 }
259
260 Value *Rem;
261 if (BO->getOpcode() == Instruction::UDiv)
262 Rem = Builder->CreateURem(Op0BO, Op1BO);
263 else
264 Rem = Builder->CreateSRem(Op0BO, Op1BO);
265 Rem->takeName(BO);
266
267 if (Op1BO == Op1C)
268 return BinaryOperator::CreateSub(Op0BO, Rem);
269 return BinaryOperator::CreateSub(Rem, Op0BO);
270 }
271 }
272
273 /// i1 mul -> i1 and.
Benjamin Kramer72196f32014-01-19 15:24:22 +0000274 if (I.getType()->getScalarType()->isIntegerTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000275 return BinaryOperator::CreateAnd(Op0, Op1);
276
277 // X*(1 << Y) --> X << Y
278 // (1 << Y)*X --> X << Y
279 {
280 Value *Y;
281 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
282 return BinaryOperator::CreateShl(Op1, Y);
283 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
284 return BinaryOperator::CreateShl(Op0, Y);
285 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000286
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000287 // If one of the operands of the multiply is a cast from a boolean value, then
288 // we know the bool is either zero or one, so this is a 'masking' multiply.
289 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands19d0b472010-02-16 11:11:14 +0000290 if (!I.getType()->isVectorTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000291 // -2 is "-1 << 1" so it is all bits set except the low one.
292 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000293
Craig Topperf40110f2014-04-25 05:29:35 +0000294 Value *BoolCast = nullptr, *OtherOp = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000295 if (MaskedValueIsZero(Op0, Negative2))
296 BoolCast = Op0, OtherOp = Op1;
297 else if (MaskedValueIsZero(Op1, Negative2))
298 BoolCast = Op1, OtherOp = Op0;
299
300 if (BoolCast) {
301 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000302 BoolCast);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000303 return BinaryOperator::CreateAnd(V, OtherOp);
304 }
305 }
306
Craig Topperf40110f2014-04-25 05:29:35 +0000307 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000308}
309
Pedro Artigas993acd02012-11-30 22:07:05 +0000310//
311// Detect pattern:
312//
313// log2(Y*0.5)
314//
315// And check for corresponding fast math flags
316//
317
318static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Pedro Artigas00b83c92012-11-30 22:47:15 +0000319
320 if (!Op->hasOneUse())
321 return;
322
323 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
324 if (!II)
325 return;
326 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
327 return;
328 Log2 = II;
329
330 Value *OpLog2Of = II->getArgOperand(0);
331 if (!OpLog2Of->hasOneUse())
332 return;
333
334 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
335 if (!I)
336 return;
337 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
338 return;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000339
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000340 if (match(I->getOperand(0), m_SpecificFP(0.5)))
Pedro Artigas00b83c92012-11-30 22:47:15 +0000341 Y = I->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000342 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
Pedro Artigas00b83c92012-11-30 22:47:15 +0000343 Y = I->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000344}
Pedro Artigas993acd02012-11-30 22:07:05 +0000345
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000346static bool isFiniteNonZeroFp(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().isFiniteNonZero())
352 return false;
353 }
354 return true;
355 }
356
357 return isa<ConstantFP>(C) &&
358 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
359}
360
361static bool isNormalFp(Constant *C) {
362 if (C->getType()->isVectorTy()) {
363 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
364 ++I) {
365 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
366 if (!CFP || !CFP->getValueAPF().isNormal())
367 return false;
368 }
369 return true;
370 }
371
372 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
373}
374
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000375/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
376/// true iff the given value is FMul or FDiv with one and only one operand
377/// being a normal constant (i.e. not Zero/NaN/Infinity).
378static bool isFMulOrFDivWithConstant(Value *V) {
379 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000380 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yang80138662013-01-07 22:41:28 +0000381 I->getOpcode() != Instruction::FDiv))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000382 return false;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000383
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000384 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
385 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000386
387 if (C0 && C1)
388 return false;
389
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000390 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000391}
392
393/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
394/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
395/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000396/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000397/// resulting expression. Note that this function could return NULL in
398/// case the constants cannot be folded into a normal floating-point.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000399///
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000400Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yang80138662013-01-07 22:41:28 +0000401 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000402 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
403
404 Value *Opnd0 = FMulOrDiv->getOperand(0);
405 Value *Opnd1 = FMulOrDiv->getOperand(1);
406
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000407 Constant *C0 = dyn_cast<Constant>(Opnd0);
408 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000409
Craig Topperf40110f2014-04-25 05:29:35 +0000410 BinaryOperator *R = nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000411
412 // (X * C0) * C => X * (C0*C)
413 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
414 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000415 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000416 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
417 } else {
418 if (C0) {
419 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000420 if (FMulOrDiv->hasOneUse()) {
421 // It would otherwise introduce another div.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000422 Constant *F = ConstantExpr::getFMul(C0, C);
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000423 if (isNormalFp(F))
424 R = BinaryOperator::CreateFDiv(F, Opnd1);
425 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000426 } else {
427 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000428 Constant *F = ConstantExpr::getFDiv(C, C1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000429 if (isNormalFp(F)) {
430 R = BinaryOperator::CreateFMul(Opnd0, F);
431 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000432 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000433 Constant *F = ConstantExpr::getFDiv(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000434 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000435 R = BinaryOperator::CreateFDiv(Opnd0, F);
436 }
437 }
438 }
439
440 if (R) {
441 R->setHasUnsafeAlgebra(true);
442 InsertNewInstWith(R, *InsertBefore);
443 }
444
445 return R;
446}
447
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000448Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000449 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000450 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
451
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000452 if (Value *V = SimplifyVectorOp(I))
453 return ReplaceInstUsesWith(I, V);
454
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000455 if (isa<Constant>(Op0))
456 std::swap(Op0, Op1);
457
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000458 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL))
Michael Ilsemand5787be2012-12-12 00:28:32 +0000459 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000460
Shuxin Yange8227452013-01-15 21:09:32 +0000461 bool AllowReassociate = I.hasUnsafeAlgebra();
462
Michael Ilsemand5787be2012-12-12 00:28:32 +0000463 // Simplify mul instructions with a constant RHS.
464 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000465 // Try to fold constant mul into select arguments.
466 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
467 if (Instruction *R = FoldOpIntoSelect(I, SI))
468 return R;
469
470 if (isa<PHINode>(Op0))
471 if (Instruction *NV = FoldOpIntoPhi(I))
472 return NV;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000473
Owen Andersonf74cfe02014-01-16 20:36:42 +0000474 // (fmul X, -1.0) --> (fsub -0.0, X)
Benjamin Kramerfea9ac92014-01-18 16:43:14 +0000475 if (match(Op1, m_SpecificFP(-1.0))) {
476 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
477 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000478 RI->copyFastMathFlags(&I);
479 return RI;
480 }
481
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000482 Constant *C = cast<Constant>(Op1);
483 if (AllowReassociate && isFiniteNonZeroFp(C)) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000484 // Let MDC denote an expression in one of these forms:
485 // X * C, C/X, X/C, where C is a constant.
486 //
487 // Try to simplify "MDC * Constant"
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000488 if (isFMulOrFDivWithConstant(Op0))
489 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000490 return ReplaceInstUsesWith(I, V);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000491
Quentin Colombete684a6d2013-02-28 21:12:40 +0000492 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000493 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
494 if (FAddSub &&
495 (FAddSub->getOpcode() == Instruction::FAdd ||
496 FAddSub->getOpcode() == Instruction::FSub)) {
497 Value *Opnd0 = FAddSub->getOperand(0);
498 Value *Opnd1 = FAddSub->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000499 Constant *C0 = dyn_cast<Constant>(Opnd0);
500 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000501 bool Swap = false;
502 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000503 std::swap(C0, C1);
504 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000505 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000506 }
507
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000508 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000509 Value *M1 = ConstantExpr::getFMul(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000510 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000511 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
Craig Topperf40110f2014-04-25 05:29:35 +0000512 nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000513 if (M0 && M1) {
514 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
515 std::swap(M0, M1);
516
Benjamin Kramer67485762013-09-30 15:39:59 +0000517 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
518 ? BinaryOperator::CreateFAdd(M0, M1)
519 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000520 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000521 return RI;
522 }
523 }
524 }
525 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000526 }
527
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000528
Pedro Artigasd8795042012-11-30 19:09:41 +0000529 // Under unsafe algebra do:
530 // X * log2(0.5*Y) = X*log2(Y) - X
531 if (I.hasUnsafeAlgebra()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000532 Value *OpX = nullptr;
533 Value *OpY = nullptr;
Pedro Artigasd8795042012-11-30 19:09:41 +0000534 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000535 detectLog2OfHalf(Op0, OpY, Log2);
536 if (OpY) {
537 OpX = Op1;
538 } else {
539 detectLog2OfHalf(Op1, OpY, Log2);
540 if (OpY) {
541 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000542 }
543 }
544 // if pattern detected emit alternate sequence
545 if (OpX && OpY) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000546 BuilderTy::FastMathFlagGuard Guard(*Builder);
547 Builder->SetFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000548 Log2->setArgOperand(0, OpY);
549 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
Benjamin Kramer67485762013-09-30 15:39:59 +0000550 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
551 FSub->takeName(&I);
552 return ReplaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000553 }
554 }
555
Shuxin Yange8227452013-01-15 21:09:32 +0000556 // Handle symmetric situation in a 2-iteration loop
557 Value *Opnd0 = Op0;
558 Value *Opnd1 = Op1;
559 for (int i = 0; i < 2; i++) {
560 bool IgnoreZeroSign = I.hasNoSignedZeros();
561 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000562 BuilderTy::FastMathFlagGuard Guard(*Builder);
563 Builder->SetFastMathFlags(I.getFastMathFlags());
564
Shuxin Yange8227452013-01-15 21:09:32 +0000565 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
566 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000567
Shuxin Yange8227452013-01-15 21:09:32 +0000568 // -X * -Y => X*Y
Owen Andersone8537fc2014-01-16 20:59:41 +0000569 if (N1) {
570 Value *FMul = Builder->CreateFMul(N0, N1);
571 FMul->takeName(&I);
572 return ReplaceInstUsesWith(I, FMul);
573 }
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000574
Shuxin Yange8227452013-01-15 21:09:32 +0000575 if (Opnd0->hasOneUse()) {
576 // -X * Y => -(X*Y) (Promote negation as high as possible)
577 Value *T = Builder->CreateFMul(N0, Opnd1);
Benjamin Kramer67485762013-09-30 15:39:59 +0000578 Value *Neg = Builder->CreateFNeg(T);
579 Neg->takeName(&I);
580 return ReplaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000581 }
582 }
Shuxin Yange8227452013-01-15 21:09:32 +0000583
584 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000585 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000586 // 1) to form a power expression (of X).
587 // 2) potentially shorten the critical path: After transformation, the
588 // latency of the instruction Y is amortized by the expression of X*X,
589 // and therefore Y is in a "less critical" position compared to what it
590 // was before the transformation.
591 //
592 if (AllowReassociate) {
593 Value *Opnd0_0, *Opnd0_1;
594 if (Opnd0->hasOneUse() &&
595 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000596 Value *Y = nullptr;
Shuxin Yange8227452013-01-15 21:09:32 +0000597 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
598 Y = Opnd0_1;
599 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
600 Y = Opnd0_0;
601
602 if (Y) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000603 BuilderTy::FastMathFlagGuard Guard(*Builder);
604 Builder->SetFastMathFlags(I.getFastMathFlags());
605 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
Shuxin Yange8227452013-01-15 21:09:32 +0000606
Benjamin Kramer67485762013-09-30 15:39:59 +0000607 Value *R = Builder->CreateFMul(T, Y);
608 R->takeName(&I);
609 return ReplaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000610 }
611 }
612 }
613
614 if (!isa<Constant>(Op1))
615 std::swap(Opnd0, Opnd1);
616 else
617 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000618 }
619
Craig Topperf40110f2014-04-25 05:29:35 +0000620 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000621}
622
623/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
624/// instruction.
625bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
626 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000627
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000628 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
629 int NonNullOperand = -1;
630 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
631 if (ST->isNullValue())
632 NonNullOperand = 2;
633 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
634 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
635 if (ST->isNullValue())
636 NonNullOperand = 1;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000637
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000638 if (NonNullOperand == -1)
639 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000640
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000641 Value *SelectCond = SI->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000642
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000643 // Change the div/rem to use 'Y' instead of the select.
644 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000645
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000646 // Okay, we know we replace the operand of the div/rem with 'Y' with no
647 // problem. However, the select, or the condition of the select may have
648 // multiple uses. Based on our knowledge that the operand must be non-zero,
649 // propagate the known value for the select into other uses of it, and
650 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000651
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000652 // If the select and condition only have a single use, don't bother with this,
653 // early exit.
654 if (SI->use_empty() && SelectCond->hasOneUse())
655 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000656
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000657 // Scan the current block backward, looking for other uses of SI.
658 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000659
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000660 while (BBI != BBFront) {
661 --BBI;
662 // If we found a call to a function, we can't assume it will return, so
663 // information from below it cannot be propagated above it.
664 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
665 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000666
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000667 // Replace uses of the select or its condition with the known values.
668 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
669 I != E; ++I) {
670 if (*I == SI) {
671 *I = SI->getOperand(NonNullOperand);
672 Worklist.Add(BBI);
673 } else if (*I == SelectCond) {
Jakub Staszak96ff4d62013-06-06 23:34:59 +0000674 *I = Builder->getInt1(NonNullOperand == 1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000675 Worklist.Add(BBI);
676 }
677 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000678
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000679 // If we past the instruction, quit looking for it.
680 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000681 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000682 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000683 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000684
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000685 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000686 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000687 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000688
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000689 }
690 return true;
691}
692
693
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000694/// This function implements the transforms common to both integer division
695/// instructions (udiv and sdiv). It is called by the visitors to those integer
696/// division instructions.
697/// @brief Common integer divide transforms
698Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
699 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
700
Chris Lattner7c99f192011-05-22 18:18:41 +0000701 // The RHS is known non-zero.
702 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
703 I.setOperand(1, V);
704 return &I;
705 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000706
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000707 // Handle cases involving: [su]div X, (select Cond, Y, Z)
708 // This does not apply for fdiv.
709 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
710 return &I;
711
712 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
David Majnemerf9a095d2014-08-16 08:55:06 +0000713 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
714 // (X / C1) / C2 -> X / (C1*C2)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000715 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
716 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
717 if (MultiplyOverflows(RHS, LHSRHS,
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000718 I.getOpcode() == Instruction::SDiv))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000719 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner6b657ae2011-02-10 05:36:31 +0000720 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
721 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000722 }
723
David Majnemerf9a095d2014-08-16 08:55:06 +0000724 Value *X;
725 const APInt *C1, *C2;
726 if (match(RHS, m_APInt(C2))) {
727 bool IsSigned = I.getOpcode() == Instruction::SDiv;
728 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
729 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
730 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
731
732 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
733 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
734 BinaryOperator *BO = BinaryOperator::Create(
735 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
736 BO->setIsExact(I.isExact());
737 return BO;
738 }
739
740 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
741 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
742 BinaryOperator *BO = BinaryOperator::Create(
743 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
744 BO->setHasNoUnsignedWrap(
745 !IsSigned &&
746 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
747 BO->setHasNoSignedWrap(
748 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
749 return BO;
750 }
751 }
752
753 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1)))) ||
754 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
755 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
756 APInt C1Shifted = APInt::getOneBitSet(
757 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
758
759 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
760 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
761 BinaryOperator *BO = BinaryOperator::Create(
762 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
763 BO->setIsExact(I.isExact());
764 return BO;
765 }
766
767 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
768 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
769 BinaryOperator *BO = BinaryOperator::Create(
770 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
771 BO->setHasNoUnsignedWrap(
772 !IsSigned &&
773 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
774 BO->setHasNoSignedWrap(
775 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
776 return BO;
777 }
778 }
779 }
780 }
781
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000782 if (!RHS->isZero()) { // avoid X udiv 0
783 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
784 if (Instruction *R = FoldOpIntoSelect(I, SI))
785 return R;
786 if (isa<PHINode>(Op0))
787 if (Instruction *NV = FoldOpIntoPhi(I))
788 return NV;
789 }
790 }
791
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000792 if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
793 if (One->isOne() && !I.getType()->isIntegerTy(1)) {
794 bool isSigned = I.getOpcode() == Instruction::SDiv;
795 if (isSigned) {
796 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
797 // result is one, if Op1 is -1 then the result is minus one, otherwise
798 // it's zero.
799 Value *Inc = Builder->CreateAdd(Op1, One);
800 Value *Cmp = Builder->CreateICmpULT(
801 Inc, ConstantInt::get(I.getType(), 3));
802 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
803 } else {
804 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
805 // result is one, otherwise it's zero.
806 return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
807 }
808 }
809 }
810
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000811 // See if we can fold away this div instruction.
812 if (SimplifyDemandedInstructionBits(I))
813 return &I;
814
Duncan Sands771e82a2011-01-28 16:51:11 +0000815 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Craig Topperf40110f2014-04-25 05:29:35 +0000816 Value *X = nullptr, *Z = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +0000817 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
818 bool isSigned = I.getOpcode() == Instruction::SDiv;
819 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
820 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
821 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000822 }
823
Craig Topperf40110f2014-04-25 05:29:35 +0000824 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000825}
826
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000827/// dyn_castZExtVal - Checks if V is a zext or constant that can
828/// be truncated to Ty without losing bits.
Chris Lattner229907c2011-07-18 04:54:35 +0000829static Value *dyn_castZExtVal(Value *V, Type *Ty) {
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000830 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
831 if (Z->getSrcTy() == Ty)
832 return Z->getOperand(0);
833 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
834 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
835 return ConstantExpr::getTrunc(C, Ty);
836 }
Craig Topperf40110f2014-04-25 05:29:35 +0000837 return nullptr;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000838}
839
David Majnemer37f8f442013-07-04 21:17:49 +0000840namespace {
841const unsigned MaxDepth = 6;
842typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
843 const BinaryOperator &I,
844 InstCombiner &IC);
845
846/// \brief Used to maintain state for visitUDivOperand().
847struct UDivFoldAction {
848 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
849 ///< operand. This can be zero if this action
850 ///< joins two actions together.
851
852 Value *OperandToFold; ///< Which operand to fold.
853 union {
854 Instruction *FoldResult; ///< The instruction returned when FoldAction is
855 ///< invoked.
856
857 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
858 ///< joins two actions together.
859 };
860
861 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +0000862 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +0000863 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
864 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
865};
866}
867
868// X udiv 2^C -> X >> C
869static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
870 const BinaryOperator &I, InstCombiner &IC) {
871 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
872 BinaryOperator *LShr = BinaryOperator::CreateLShr(
873 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
874 if (I.isExact()) LShr->setIsExact();
875 return LShr;
876}
877
878// X udiv C, where C >= signbit
879static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
880 const BinaryOperator &I, InstCombiner &IC) {
881 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
882
883 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
884 ConstantInt::get(I.getType(), 1));
885}
886
887// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
888static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
889 InstCombiner &IC) {
890 Instruction *ShiftLeft = cast<Instruction>(Op1);
891 if (isa<ZExtInst>(ShiftLeft))
892 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
893
894 const APInt &CI =
895 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
896 Value *N = ShiftLeft->getOperand(1);
897 if (CI != 1)
898 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
899 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
900 N = IC.Builder->CreateZExt(N, Z->getDestTy());
901 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
902 if (I.isExact()) LShr->setIsExact();
903 return LShr;
904}
905
906// \brief Recursively visits the possible right hand operands of a udiv
907// instruction, seeing through select instructions, to determine if we can
908// replace the udiv with something simpler. If we find that an operand is not
909// able to simplify the udiv, we abort the entire transformation.
910static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
911 SmallVectorImpl<UDivFoldAction> &Actions,
912 unsigned Depth = 0) {
913 // Check to see if this is an unsigned division with an exact power of 2,
914 // if so, convert to a right shift.
915 if (match(Op1, m_Power2())) {
916 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
917 return Actions.size();
918 }
919
920 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
921 // X udiv C, where C >= signbit
922 if (C->getValue().isNegative()) {
923 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
924 return Actions.size();
925 }
926
927 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
928 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
929 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
930 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
931 return Actions.size();
932 }
933
934 // The remaining tests are all recursive, so bail out if we hit the limit.
935 if (Depth++ == MaxDepth)
936 return 0;
937
938 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
David Majnemer492e6122014-08-30 09:19:05 +0000939 if (size_t LHSIdx =
940 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
941 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
942 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
David Majnemer37f8f442013-07-04 21:17:49 +0000943 return Actions.size();
944 }
945
946 return 0;
947}
948
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000949Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
950 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
951
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000952 if (Value *V = SimplifyVectorOp(I))
953 return ReplaceInstUsesWith(I, V);
954
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000955 if (Value *V = SimplifyUDivInst(Op0, Op1, DL))
Duncan Sands771e82a2011-01-28 16:51:11 +0000956 return ReplaceInstUsesWith(I, V);
957
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000958 // Handle the integer div common cases
959 if (Instruction *Common = commonIDivTransforms(I))
960 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000961
Benjamin Kramerd4a64712012-08-30 15:07:40 +0000962 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
Benjamin Kramer72196f32014-01-19 15:24:22 +0000963 if (Constant *C2 = dyn_cast<Constant>(Op1)) {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +0000964 Value *X;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000965 Constant *C1;
966 if (match(Op0, m_LShr(m_Value(X), m_Constant(C1))))
967 return BinaryOperator::CreateUDiv(X, ConstantExpr::getShl(C2, C1));
Nadav Rotem11935b22012-08-28 10:01:43 +0000968 }
969
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000970 // (zext A) udiv (zext B) --> zext (A udiv B)
971 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
972 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
973 return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
974 I.isExact()),
975 I.getType());
976
David Majnemer37f8f442013-07-04 21:17:49 +0000977 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
978 SmallVector<UDivFoldAction, 6> UDivActions;
979 if (visitUDivOperand(Op0, Op1, I, UDivActions))
980 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
981 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
982 Value *ActionOp1 = UDivActions[i].OperandToFold;
983 Instruction *Inst;
984 if (Action)
985 Inst = Action(Op0, ActionOp1, I, *this);
986 else {
987 // This action joins two actions together. The RHS of this action is
988 // simply the last action we processed, we saved the LHS action index in
989 // the joining action.
990 size_t SelectRHSIdx = i - 1;
991 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
992 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
993 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
994 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
995 SelectLHS, SelectRHS);
996 }
997
998 // If this is the last action to process, return it to the InstCombiner.
999 // Otherwise, we insert it before the UDiv and record it so that we may
1000 // use it as part of a joining action (i.e., a SelectInst).
1001 if (e - i != 1) {
1002 Inst->insertBefore(&I);
1003 UDivActions[i].FoldResult = Inst;
1004 } else
1005 return Inst;
1006 }
1007
Craig Topperf40110f2014-04-25 05:29:35 +00001008 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001009}
1010
1011Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1012 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1013
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001014 if (Value *V = SimplifyVectorOp(I))
1015 return ReplaceInstUsesWith(I, V);
1016
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001017 if (Value *V = SimplifySDivInst(Op0, Op1, DL))
Duncan Sands771e82a2011-01-28 16:51:11 +00001018 return ReplaceInstUsesWith(I, V);
1019
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001020 // Handle the integer div common cases
1021 if (Instruction *Common = commonIDivTransforms(I))
1022 return Common;
1023
Benjamin Kramer72196f32014-01-19 15:24:22 +00001024 // sdiv X, -1 == -X
1025 if (match(Op1, m_AllOnes()))
1026 return BinaryOperator::CreateNeg(Op0);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001027
Benjamin Kramer72196f32014-01-19 15:24:22 +00001028 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001029 // sdiv X, C --> ashr exact X, log2(C)
1030 if (I.isExact() && RHS->getValue().isNonNegative() &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001031 RHS->getValue().isPowerOf2()) {
1032 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1033 RHS->getValue().exactLogBase2());
Chris Lattner6b657ae2011-02-10 05:36:31 +00001034 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001035 }
Benjamin Kramer72196f32014-01-19 15:24:22 +00001036 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001037
Benjamin Kramer72196f32014-01-19 15:24:22 +00001038 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
David Majnemerf28e2a42014-07-02 06:42:13 +00001039 // X/INT_MIN -> X == INT_MIN
1040 if (RHS->isMinSignedValue())
1041 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1042
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001043 // -X/C --> X/-C provided the negation doesn't overflow.
1044 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
Chris Lattner6b657ae2011-02-10 05:36:31 +00001045 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001046 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
1047 ConstantExpr::getNeg(RHS));
1048 }
1049
1050 // If the sign bits of both operands are zero (i.e. we can prove they are
1051 // unsigned inputs), turn this into a udiv.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001052 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001053 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1054 if (MaskedValueIsZero(Op0, Mask)) {
1055 if (MaskedValueIsZero(Op1, Mask)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001056 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001057 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1058 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001059
Chris Lattner6b657ae2011-02-10 05:36:31 +00001060 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001061 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1062 // Safe because the only negative value (1 << Y) can take on is
1063 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1064 // the sign bit set.
1065 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1066 }
1067 }
1068 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001069
Craig Topperf40110f2014-04-25 05:29:35 +00001070 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001071}
1072
Shuxin Yang320f52a2013-01-14 22:48:41 +00001073/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1074/// FP value and:
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001075/// 1) 1/C is exact, or
Shuxin Yang320f52a2013-01-14 22:48:41 +00001076/// 2) reciprocal is allowed.
Sylvestre Ledru149e2812013-05-14 23:36:24 +00001077/// If the conversion was successful, the simplified expression "X * 1/C" is
Shuxin Yang320f52a2013-01-14 22:48:41 +00001078/// returned; otherwise, NULL is returned.
1079///
1080static Instruction *CvtFDivConstToReciprocal(Value *Dividend,
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001081 Constant *Divisor,
Shuxin Yang320f52a2013-01-14 22:48:41 +00001082 bool AllowReciprocal) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001083 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001084 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001085
1086 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001087 APFloat Reciprocal(FpVal.getSemantics());
1088 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001089
Michael Gottesman3cb77ab2013-06-19 21:23:18 +00001090 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001091 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1092 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1093 Cvt = !Reciprocal.isDenormal();
1094 }
1095
1096 if (!Cvt)
Craig Topperf40110f2014-04-25 05:29:35 +00001097 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001098
1099 ConstantFP *R;
1100 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1101 return BinaryOperator::CreateFMul(Dividend, R);
1102}
1103
Frits van Bommel2a559512011-01-29 17:50:27 +00001104Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1105 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1106
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001107 if (Value *V = SimplifyVectorOp(I))
1108 return ReplaceInstUsesWith(I, V);
1109
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001110 if (Value *V = SimplifyFDivInst(Op0, Op1, DL))
Frits van Bommel2a559512011-01-29 17:50:27 +00001111 return ReplaceInstUsesWith(I, V);
1112
Stephen Lina9b57f62013-07-20 07:13:13 +00001113 if (isa<Constant>(Op0))
1114 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1115 if (Instruction *R = FoldOpIntoSelect(I, SI))
1116 return R;
1117
Shuxin Yang320f52a2013-01-14 22:48:41 +00001118 bool AllowReassociate = I.hasUnsafeAlgebra();
1119 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001120
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001121 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001122 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1123 if (Instruction *R = FoldOpIntoSelect(I, SI))
1124 return R;
1125
Shuxin Yang320f52a2013-01-14 22:48:41 +00001126 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +00001127 Constant *C1 = nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001128 Constant *C2 = Op1C;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001129 Value *X;
Craig Topperf40110f2014-04-25 05:29:35 +00001130 Instruction *Res = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001131
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001132 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001133 // (X*C1)/C2 => X * (C1/C2)
1134 //
1135 Constant *C = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001136 if (isNormalFp(C))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001137 Res = BinaryOperator::CreateFMul(X, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001138 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001139 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1140 //
1141 Constant *C = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001142 if (isNormalFp(C)) {
1143 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001144 if (!Res)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001145 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001146 }
1147 }
1148
1149 if (Res) {
1150 Res->setFastMathFlags(I.getFastMathFlags());
1151 return Res;
1152 }
1153 }
1154
1155 // X / C => X * 1/C
Owen Anderson4557a152014-01-16 21:07:52 +00001156 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1157 T->copyFastMathFlags(&I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001158 return T;
Owen Anderson4557a152014-01-16 21:07:52 +00001159 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001160
Craig Topperf40110f2014-04-25 05:29:35 +00001161 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001162 }
1163
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001164 if (AllowReassociate && isa<Constant>(Op0)) {
1165 Constant *C1 = cast<Constant>(Op0), *C2;
Craig Topperf40110f2014-04-25 05:29:35 +00001166 Constant *Fold = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001167 Value *X;
1168 bool CreateDiv = true;
1169
1170 // C1 / (X*C2) => (C1/C2) / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001171 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001172 Fold = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001173 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001174 // C1 / (X/C2) => (C1*C2) / X
1175 Fold = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001176 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001177 // C1 / (C2/X) => (C1/C2) * X
1178 Fold = ConstantExpr::getFDiv(C1, C2);
1179 CreateDiv = false;
1180 }
1181
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001182 if (Fold && isNormalFp(Fold)) {
1183 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1184 : BinaryOperator::CreateFMul(X, Fold);
1185 R->setFastMathFlags(I.getFastMathFlags());
1186 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001187 }
Craig Topperf40110f2014-04-25 05:29:35 +00001188 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001189 }
1190
1191 if (AllowReassociate) {
1192 Value *X, *Y;
Craig Topperf40110f2014-04-25 05:29:35 +00001193 Value *NewInst = nullptr;
1194 Instruction *SimpR = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001195
1196 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1197 // (X/Y) / Z => X / (Y*Z)
1198 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001199 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001200 NewInst = Builder->CreateFMul(Y, Op1);
Owen Anderson1664dc82014-01-20 07:44:53 +00001201 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1202 FastMathFlags Flags = I.getFastMathFlags();
1203 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1204 RI->setFastMathFlags(Flags);
1205 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001206 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1207 }
1208 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1209 // Z / (X/Y) => Z*Y / X
1210 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001211 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001212 NewInst = Builder->CreateFMul(Op0, Y);
Owen Anderson1664dc82014-01-20 07:44:53 +00001213 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1214 FastMathFlags Flags = I.getFastMathFlags();
1215 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1216 RI->setFastMathFlags(Flags);
1217 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001218 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1219 }
1220 }
1221
1222 if (NewInst) {
1223 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1224 T->setDebugLoc(I.getDebugLoc());
1225 SimpR->setFastMathFlags(I.getFastMathFlags());
1226 return SimpR;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001227 }
1228 }
1229
Craig Topperf40110f2014-04-25 05:29:35 +00001230 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001231}
1232
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001233/// This function implements the transforms common to both integer remainder
1234/// instructions (urem and srem). It is called by the visitors to those integer
1235/// remainder instructions.
1236/// @brief Common integer remainder transforms
1237Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1238 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1239
Chris Lattner7c99f192011-05-22 18:18:41 +00001240 // The RHS is known non-zero.
1241 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
1242 I.setOperand(1, V);
1243 return &I;
1244 }
1245
Duncan Sandsa3e36992011-05-02 16:27:02 +00001246 // Handle cases involving: rem X, (select Cond, Y, Z)
1247 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1248 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001249
Benjamin Kramer72196f32014-01-19 15:24:22 +00001250 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001251 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1252 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1253 if (Instruction *R = FoldOpIntoSelect(I, SI))
1254 return R;
1255 } else if (isa<PHINode>(Op0I)) {
1256 if (Instruction *NV = FoldOpIntoPhi(I))
1257 return NV;
1258 }
1259
1260 // See if we can fold away this rem instruction.
1261 if (SimplifyDemandedInstructionBits(I))
1262 return &I;
1263 }
1264 }
1265
Craig Topperf40110f2014-04-25 05:29:35 +00001266 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001267}
1268
1269Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1270 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1271
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001272 if (Value *V = SimplifyVectorOp(I))
1273 return ReplaceInstUsesWith(I, V);
1274
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001275 if (Value *V = SimplifyURemInst(Op0, Op1, DL))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001276 return ReplaceInstUsesWith(I, V);
1277
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001278 if (Instruction *common = commonIRemTransforms(I))
1279 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001280
David Majnemer6c30f492013-05-12 00:07:05 +00001281 // (zext A) urem (zext B) --> zext (A urem B)
1282 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1283 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1284 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1285 I.getType());
1286
David Majnemer470b0772013-05-11 09:01:28 +00001287 // X urem Y -> X and Y-1, where Y is a power of 2,
1288 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001289 Constant *N1 = Constant::getAllOnesValue(I.getType());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001290 Value *Add = Builder->CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001291 return BinaryOperator::CreateAnd(Op0, Add);
1292 }
1293
Nick Lewycky7459be62013-07-13 01:16:47 +00001294 // 1 urem X -> zext(X != 1)
1295 if (match(Op0, m_One())) {
1296 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1297 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1298 return ReplaceInstUsesWith(I, Ext);
1299 }
1300
Craig Topperf40110f2014-04-25 05:29:35 +00001301 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001302}
1303
1304Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1305 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1306
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001307 if (Value *V = SimplifyVectorOp(I))
1308 return ReplaceInstUsesWith(I, V);
1309
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001310 if (Value *V = SimplifySRemInst(Op0, Op1, DL))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001311 return ReplaceInstUsesWith(I, V);
1312
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001313 // Handle the integer rem common cases
1314 if (Instruction *Common = commonIRemTransforms(I))
1315 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001316
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001317 if (Value *RHSNeg = dyn_castNegVal(Op1))
1318 if (!isa<Constant>(RHSNeg) ||
1319 (isa<ConstantInt>(RHSNeg) &&
1320 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
1321 // X % -Y -> X % Y
1322 Worklist.AddValue(I.getOperand(1));
1323 I.setOperand(1, RHSNeg);
1324 return &I;
1325 }
1326
1327 // If the sign bits of both operands are zero (i.e. we can prove they are
1328 // unsigned inputs), turn this into a urem.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001329 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001330 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1331 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001332 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001333 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1334 }
1335 }
1336
1337 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001338 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1339 Constant *C = cast<Constant>(Op1);
1340 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001341
1342 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001343 bool hasMissing = false;
1344 for (unsigned i = 0; i != VWidth; ++i) {
1345 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001346 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001347 hasMissing = true;
1348 break;
1349 }
1350
1351 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001352 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001353 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001354 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001355
Chris Lattner0256be92012-01-27 03:08:05 +00001356 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001357 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001358 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001359 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001360 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001361 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001362 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001363 }
1364 }
1365
1366 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001367 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001368 Worklist.AddValue(I.getOperand(1));
1369 I.setOperand(1, NewRHSV);
1370 return &I;
1371 }
1372 }
1373 }
1374
Craig Topperf40110f2014-04-25 05:29:35 +00001375 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001376}
1377
1378Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001379 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001380
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001381 if (Value *V = SimplifyVectorOp(I))
1382 return ReplaceInstUsesWith(I, V);
1383
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001384 if (Value *V = SimplifyFRemInst(Op0, Op1, DL))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001385 return ReplaceInstUsesWith(I, V);
1386
1387 // Handle cases involving: rem X, (select Cond, Y, Z)
1388 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1389 return &I;
1390
Craig Topperf40110f2014-04-25 05:29:35 +00001391 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001392}