blob: a554e9f628e073630908a4a899ad4703fd735122 [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
Chandler Carrutha9174582015-01-22 05:25:13 +000015#include "InstCombineInternal.h"
Duncan Sandsd0eb6d32010-12-21 14:00:22 +000016#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000018#include "llvm/IR/PatternMatch.h"
Chris Lattnerdc054bf2010-01-05 06:09:35 +000019using namespace llvm;
20using namespace PatternMatch;
21
Chandler Carruth964daaa2014-04-22 02:55:47 +000022#define DEBUG_TYPE "instcombine"
23
Chris Lattner7c99f192011-05-22 18:18:41 +000024
25/// simplifyValueKnownNonZero - The specific integer value is used in a context
26/// where it is known to be non-zero. If this allows us to simplify the
27/// computation, do so and return the new operand, otherwise return null.
Hal Finkel60db0582014-09-07 18:57:58 +000028static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC,
Mehdi Aminia28d91d2015-03-10 02:37:25 +000029 Instruction &CxtI) {
Chris Lattner7c99f192011-05-22 18:18:41 +000030 // If V has multiple uses, then we would have to do more analysis to determine
31 // if this is safe. For example, the use could be in dynamically unreached
32 // code.
Craig Topperf40110f2014-04-25 05:29:35 +000033 if (!V->hasOneUse()) return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000034
Chris Lattner388cb8a2011-05-23 00:32:19 +000035 bool MadeChange = false;
36
Chris Lattner7c99f192011-05-22 18:18:41 +000037 // ((1 << A) >>u B) --> (1 << (A-B))
38 // Because V cannot be zero, we know that B is less than A.
David Majnemerdad21032014-10-14 20:28:40 +000039 Value *A = nullptr, *B = nullptr, *One = nullptr;
40 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) &&
41 match(One, m_One())) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +000042 A = IC.Builder->CreateSub(A, B);
David Majnemerdad21032014-10-14 20:28:40 +000043 return IC.Builder->CreateShl(One, A);
Chris Lattner7c99f192011-05-22 18:18:41 +000044 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000045
Chris Lattner388cb8a2011-05-23 00:32:19 +000046 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
47 // inexact. Similarly for <<.
48 if (BinaryOperator *I = dyn_cast<BinaryOperator>(V))
Chandler Carruth66b31302015-01-04 12:03:27 +000049 if (I->isLogicalShift() &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +000050 isKnownToBeAPowerOfTwo(I->getOperand(0), IC.getDataLayout(), false, 0,
51 IC.getAssumptionCache(), &CxtI,
Chandler Carruth66b31302015-01-04 12:03:27 +000052 IC.getDominatorTree())) {
Chris Lattner388cb8a2011-05-23 00:32:19 +000053 // We know that this is an exact/nuw shift and that the input is a
54 // non-zero context as well.
Hal Finkel60db0582014-09-07 18:57:58 +000055 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
Chris Lattner388cb8a2011-05-23 00:32:19 +000056 I->setOperand(0, V2);
57 MadeChange = true;
58 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000059
Chris Lattner388cb8a2011-05-23 00:32:19 +000060 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
61 I->setIsExact();
62 MadeChange = true;
63 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000064
Chris Lattner388cb8a2011-05-23 00:32:19 +000065 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
66 I->setHasNoUnsignedWrap();
67 MadeChange = true;
68 }
69 }
70
Chris Lattner162dfc32011-05-22 18:26:48 +000071 // TODO: Lots more we could do here:
Chris Lattner162dfc32011-05-22 18:26:48 +000072 // If V is a phi node, we can call this on each of its operands.
73 // "select cond, X, 0" can simplify to "X".
Jim Grosbachbdbd7342013-04-05 21:20:12 +000074
Craig Topperf40110f2014-04-25 05:29:35 +000075 return MadeChange ? V : nullptr;
Chris Lattner7c99f192011-05-22 18:18:41 +000076}
77
78
Chris Lattnerdc054bf2010-01-05 06:09:35 +000079/// MultiplyOverflows - True if the multiply can not be expressed in an int
80/// this size.
David Majnemer27adb122014-10-12 08:34:24 +000081static bool MultiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
82 bool IsSigned) {
83 bool Overflow;
84 if (IsSigned)
85 Product = C1.smul_ov(C2, Overflow);
86 else
87 Product = C1.umul_ov(C2, Overflow);
Jim Grosbachbdbd7342013-04-05 21:20:12 +000088
David Majnemer27adb122014-10-12 08:34:24 +000089 return Overflow;
Chris Lattnerdc054bf2010-01-05 06:09:35 +000090}
91
David Majnemerf9a095d2014-08-16 08:55:06 +000092/// \brief True if C2 is a multiple of C1. Quotient contains C2/C1.
93static bool IsMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
94 bool IsSigned) {
95 assert(C1.getBitWidth() == C2.getBitWidth() &&
96 "Inconsistent width of constants!");
97
98 APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
99 if (IsSigned)
100 APInt::sdivrem(C1, C2, Quotient, Remainder);
101 else
102 APInt::udivrem(C1, C2, Quotient, Remainder);
103
104 return Remainder.isMinValue();
105}
106
Rafael Espindola65281bf2013-05-31 14:27:15 +0000107/// \brief A helper routine of InstCombiner::visitMul().
108///
109/// If C is a vector of known powers of 2, then this function returns
110/// a new vector obtained from C replacing each element with its logBase2.
111/// Return a null pointer otherwise.
112static Constant *getLogBase2Vector(ConstantDataVector *CV) {
113 const APInt *IVal;
114 SmallVector<Constant *, 4> Elts;
115
116 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
117 Constant *Elt = CV->getElementAsConstant(I);
118 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
Craig Topperf40110f2014-04-25 05:29:35 +0000119 return nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000120 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
121 }
122
123 return ConstantVector::get(Elts);
124}
125
David Majnemer54c2ca22014-12-26 09:10:14 +0000126/// \brief Return true if we can prove that:
127/// (mul LHS, RHS) === (mul nsw LHS, RHS)
128bool InstCombiner::WillNotOverflowSignedMul(Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000129 Instruction &CxtI) {
David Majnemer54c2ca22014-12-26 09:10:14 +0000130 // Multiplying n * m significant bits yields a result of n + m significant
131 // bits. If the total number of significant bits does not exceed the
132 // result bit width (minus 1), there is no overflow.
133 // This means if we have enough leading sign bits in the operands
134 // we can guarantee that the result does not overflow.
135 // Ref: "Hacker's Delight" by Henry Warren
136 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
137
138 // Note that underestimating the number of sign bits gives a more
139 // conservative answer.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000140 unsigned SignBits =
141 ComputeNumSignBits(LHS, 0, &CxtI) + ComputeNumSignBits(RHS, 0, &CxtI);
David Majnemer54c2ca22014-12-26 09:10:14 +0000142
143 // First handle the easy case: if we have enough sign bits there's
144 // definitely no overflow.
145 if (SignBits > BitWidth + 1)
146 return true;
147
148 // There are two ambiguous cases where there can be no overflow:
149 // SignBits == BitWidth + 1 and
150 // SignBits == BitWidth
151 // The second case is difficult to check, therefore we only handle the
152 // first case.
153 if (SignBits == BitWidth + 1) {
154 // It overflows only when both arguments are negative and the true
155 // product is exactly the minimum negative number.
156 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
157 // For simplicity we just check if at least one side is not negative.
158 bool LHSNonNegative, LHSNegative;
159 bool RHSNonNegative, RHSNegative;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000160 ComputeSignBit(LHS, LHSNonNegative, LHSNegative, /*Depth=*/0, &CxtI);
161 ComputeSignBit(RHS, RHSNonNegative, RHSNegative, /*Depth=*/0, &CxtI);
David Majnemer54c2ca22014-12-26 09:10:14 +0000162 if (LHSNonNegative || RHSNonNegative)
163 return true;
164 }
165 return false;
166}
167
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000168Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000169 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000170 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
171
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000172 if (Value *V = SimplifyVectorOp(I))
173 return ReplaceInstUsesWith(I, V);
174
Chandler Carruth66b31302015-01-04 12:03:27 +0000175 if (Value *V = SimplifyMulInst(Op0, Op1, DL, TLI, DT, AC))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000176 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000177
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000178 if (Value *V = SimplifyUsingDistributiveLaws(I))
179 return ReplaceInstUsesWith(I, V);
180
David Majnemer027bc802014-11-22 04:52:38 +0000181 // X * -1 == 0 - X
182 if (match(Op1, m_AllOnes())) {
183 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
184 if (I.hasNoSignedWrap())
185 BO->setHasNoSignedWrap();
186 return BO;
187 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000188
Rafael Espindola65281bf2013-05-31 14:27:15 +0000189 // Also allow combining multiply instructions on vectors.
190 {
191 Value *NewOp;
192 Constant *C1, *C2;
193 const APInt *IVal;
194 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
195 m_Constant(C1))) &&
David Majnemerfd4a6d22014-11-22 04:52:52 +0000196 match(C1, m_APInt(IVal))) {
197 // ((X << C2)*C1) == (X * (C1 << C2))
198 Constant *Shl = ConstantExpr::getShl(C1, C2);
199 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
200 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
201 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
202 BO->setHasNoUnsignedWrap();
203 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
204 Shl->isNotMinSignedValue())
205 BO->setHasNoSignedWrap();
206 return BO;
207 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000208
Rafael Espindola65281bf2013-05-31 14:27:15 +0000209 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000210 Constant *NewCst = nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000211 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
212 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
213 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
214 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
215 // Replace X*(2^C) with X << C, where C is a vector of known
216 // constant powers of 2.
217 NewCst = getLogBase2Vector(CV);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000218
Rafael Espindola65281bf2013-05-31 14:27:15 +0000219 if (NewCst) {
David Majnemer45951a62015-04-18 04:41:30 +0000220 unsigned Width = NewCst->getType()->getPrimitiveSizeInBits();
Rafael Espindola65281bf2013-05-31 14:27:15 +0000221 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000222
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000223 if (I.hasNoUnsignedWrap())
224 Shl->setHasNoUnsignedWrap();
David Majnemer45951a62015-04-18 04:41:30 +0000225 if (I.hasNoSignedWrap()) {
226 uint64_t V;
227 if (match(NewCst, m_ConstantInt(V)) && V != Width - 1)
228 Shl->setHasNoSignedWrap();
229 }
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000230
Rafael Espindola65281bf2013-05-31 14:27:15 +0000231 return Shl;
232 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000233 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000234 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000235
Rafael Espindola65281bf2013-05-31 14:27:15 +0000236 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Stuart Hastings23804832011-06-01 16:42:47 +0000237 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
238 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
239 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000240 {
241 const APInt & Val = CI->getValue();
242 const APInt &PosVal = Val.abs();
243 if (Val.isNegative() && PosVal.isPowerOf2()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000244 Value *X = nullptr, *Y = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000245 if (Op0->hasOneUse()) {
246 ConstantInt *C1;
Craig Topperf40110f2014-04-25 05:29:35 +0000247 Value *Sub = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000248 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
249 Sub = Builder->CreateSub(X, Y, "suba");
250 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
251 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
252 if (Sub)
253 return
254 BinaryOperator::CreateMul(Sub,
255 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000256 }
257 }
258 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000259 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000260
Chris Lattner6b657ae2011-02-10 05:36:31 +0000261 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000262 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000263 // Try to fold constant mul into select arguments.
264 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
265 if (Instruction *R = FoldOpIntoSelect(I, SI))
266 return R;
267
268 if (isa<PHINode>(Op0))
269 if (Instruction *NV = FoldOpIntoPhi(I))
270 return NV;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000271
272 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
273 {
274 Value *X;
275 Constant *C1;
276 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
David Majnemer6cf6c052014-06-19 07:14:33 +0000277 Value *Mul = Builder->CreateMul(C1, Op1);
278 // Only go forward with the transform if C1*CI simplifies to a tidier
279 // constant.
280 if (!match(Mul, m_Mul(m_Value(), m_Value())))
281 return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
Benjamin Kramer72196f32014-01-19 15:24:22 +0000282 }
283 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000284 }
285
David Majnemer8279a7502014-11-22 07:25:19 +0000286 if (Value *Op0v = dyn_castNegVal(Op0)) { // -X * -Y = X*Y
287 if (Value *Op1v = dyn_castNegVal(Op1)) {
288 BinaryOperator *BO = BinaryOperator::CreateMul(Op0v, Op1v);
289 if (I.hasNoSignedWrap() &&
290 match(Op0, m_NSWSub(m_Value(), m_Value())) &&
291 match(Op1, m_NSWSub(m_Value(), m_Value())))
292 BO->setHasNoSignedWrap();
293 return BO;
294 }
295 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000296
297 // (X / Y) * Y = X - (X % Y)
298 // (X / Y) * -Y = (X % Y) - X
299 {
300 Value *Op1C = Op1;
301 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
302 if (!BO ||
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000303 (BO->getOpcode() != Instruction::UDiv &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000304 BO->getOpcode() != Instruction::SDiv)) {
305 Op1C = Op0;
306 BO = dyn_cast<BinaryOperator>(Op1);
307 }
308 Value *Neg = dyn_castNegVal(Op1C);
309 if (BO && BO->hasOneUse() &&
310 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
311 (BO->getOpcode() == Instruction::UDiv ||
312 BO->getOpcode() == Instruction::SDiv)) {
313 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
314
Chris Lattner35315d02011-02-06 21:44:57 +0000315 // If the division is exact, X % Y is zero, so we end up with X or -X.
316 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000317 if (SDiv->isExact()) {
318 if (Op1BO == Op1C)
319 return ReplaceInstUsesWith(I, Op0BO);
320 return BinaryOperator::CreateNeg(Op0BO);
321 }
322
323 Value *Rem;
324 if (BO->getOpcode() == Instruction::UDiv)
325 Rem = Builder->CreateURem(Op0BO, Op1BO);
326 else
327 Rem = Builder->CreateSRem(Op0BO, Op1BO);
328 Rem->takeName(BO);
329
330 if (Op1BO == Op1C)
331 return BinaryOperator::CreateSub(Op0BO, Rem);
332 return BinaryOperator::CreateSub(Rem, Op0BO);
333 }
334 }
335
336 /// i1 mul -> i1 and.
Benjamin Kramer72196f32014-01-19 15:24:22 +0000337 if (I.getType()->getScalarType()->isIntegerTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000338 return BinaryOperator::CreateAnd(Op0, Op1);
339
340 // X*(1 << Y) --> X << Y
341 // (1 << Y)*X --> X << Y
342 {
343 Value *Y;
David Majnemer546f8102014-11-22 08:57:02 +0000344 BinaryOperator *BO = nullptr;
345 bool ShlNSW = false;
346 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
347 BO = BinaryOperator::CreateShl(Op1, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000348 ShlNSW = cast<ShlOperator>(Op0)->hasNoSignedWrap();
David Majnemer8e6f6a92014-11-24 16:41:13 +0000349 } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
David Majnemer546f8102014-11-22 08:57:02 +0000350 BO = BinaryOperator::CreateShl(Op0, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000351 ShlNSW = cast<ShlOperator>(Op1)->hasNoSignedWrap();
David Majnemer546f8102014-11-22 08:57:02 +0000352 }
353 if (BO) {
354 if (I.hasNoUnsignedWrap())
355 BO->setHasNoUnsignedWrap();
356 if (I.hasNoSignedWrap() && ShlNSW)
357 BO->setHasNoSignedWrap();
358 return BO;
359 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000360 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000361
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000362 // If one of the operands of the multiply is a cast from a boolean value, then
363 // we know the bool is either zero or one, so this is a 'masking' multiply.
364 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands19d0b472010-02-16 11:11:14 +0000365 if (!I.getType()->isVectorTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000366 // -2 is "-1 << 1" so it is all bits set except the low one.
367 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000368
Craig Topperf40110f2014-04-25 05:29:35 +0000369 Value *BoolCast = nullptr, *OtherOp = nullptr;
Hal Finkel60db0582014-09-07 18:57:58 +0000370 if (MaskedValueIsZero(Op0, Negative2, 0, &I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000371 BoolCast = Op0, OtherOp = Op1;
Hal Finkel60db0582014-09-07 18:57:58 +0000372 else if (MaskedValueIsZero(Op1, Negative2, 0, &I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000373 BoolCast = Op1, OtherOp = Op0;
374
375 if (BoolCast) {
376 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000377 BoolCast);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000378 return BinaryOperator::CreateAnd(V, OtherOp);
379 }
380 }
381
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000382 if (!I.hasNoSignedWrap() && WillNotOverflowSignedMul(Op0, Op1, I)) {
David Majnemer54c2ca22014-12-26 09:10:14 +0000383 Changed = true;
384 I.setHasNoSignedWrap(true);
385 }
386
David Majnemer491331a2015-01-02 07:29:43 +0000387 if (!I.hasNoUnsignedWrap() &&
388 computeOverflowForUnsignedMul(Op0, Op1, &I) ==
389 OverflowResult::NeverOverflows) {
David Majnemerb1296ec2014-12-26 09:50:35 +0000390 Changed = true;
391 I.setHasNoUnsignedWrap(true);
392 }
393
Craig Topperf40110f2014-04-25 05:29:35 +0000394 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000395}
396
Sanjay Patel17045f72014-10-14 00:33:23 +0000397/// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
Pedro Artigas993acd02012-11-30 22:07:05 +0000398static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Sanjay Patel17045f72014-10-14 00:33:23 +0000399 if (!Op->hasOneUse())
400 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000401
Sanjay Patel17045f72014-10-14 00:33:23 +0000402 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
403 if (!II)
404 return;
405 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
406 return;
407 Log2 = II;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000408
Sanjay Patel17045f72014-10-14 00:33:23 +0000409 Value *OpLog2Of = II->getArgOperand(0);
410 if (!OpLog2Of->hasOneUse())
411 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000412
Sanjay Patel17045f72014-10-14 00:33:23 +0000413 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
414 if (!I)
415 return;
416 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
417 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000418
Sanjay Patel17045f72014-10-14 00:33:23 +0000419 if (match(I->getOperand(0), m_SpecificFP(0.5)))
420 Y = I->getOperand(1);
421 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
422 Y = I->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000423}
Pedro Artigas993acd02012-11-30 22:07:05 +0000424
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000425static bool isFiniteNonZeroFp(Constant *C) {
426 if (C->getType()->isVectorTy()) {
427 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
428 ++I) {
Michael Kupersteinbcb26d62015-03-05 08:38:57 +0000429 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000430 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
431 return false;
432 }
433 return true;
434 }
435
436 return isa<ConstantFP>(C) &&
437 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
438}
439
440static bool isNormalFp(Constant *C) {
441 if (C->getType()->isVectorTy()) {
442 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
443 ++I) {
Michael Kupersteinbcb26d62015-03-05 08:38:57 +0000444 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000445 if (!CFP || !CFP->getValueAPF().isNormal())
446 return false;
447 }
448 return true;
449 }
450
451 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
452}
453
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000454/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
455/// true iff the given value is FMul or FDiv with one and only one operand
456/// being a normal constant (i.e. not Zero/NaN/Infinity).
457static bool isFMulOrFDivWithConstant(Value *V) {
458 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000459 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yang80138662013-01-07 22:41:28 +0000460 I->getOpcode() != Instruction::FDiv))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000461 return false;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000462
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000463 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
464 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000465
466 if (C0 && C1)
467 return false;
468
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000469 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000470}
471
472/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
473/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
474/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000475/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000476/// resulting expression. Note that this function could return NULL in
477/// case the constants cannot be folded into a normal floating-point.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000478///
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000479Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yang80138662013-01-07 22:41:28 +0000480 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000481 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
482
483 Value *Opnd0 = FMulOrDiv->getOperand(0);
484 Value *Opnd1 = FMulOrDiv->getOperand(1);
485
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000486 Constant *C0 = dyn_cast<Constant>(Opnd0);
487 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000488
Craig Topperf40110f2014-04-25 05:29:35 +0000489 BinaryOperator *R = nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000490
491 // (X * C0) * C => X * (C0*C)
492 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
493 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000494 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000495 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
496 } else {
497 if (C0) {
498 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000499 if (FMulOrDiv->hasOneUse()) {
500 // It would otherwise introduce another div.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000501 Constant *F = ConstantExpr::getFMul(C0, C);
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000502 if (isNormalFp(F))
503 R = BinaryOperator::CreateFDiv(F, Opnd1);
504 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000505 } else {
506 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000507 Constant *F = ConstantExpr::getFDiv(C, C1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000508 if (isNormalFp(F)) {
509 R = BinaryOperator::CreateFMul(Opnd0, F);
510 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000511 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000512 Constant *F = ConstantExpr::getFDiv(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000513 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000514 R = BinaryOperator::CreateFDiv(Opnd0, F);
515 }
516 }
517 }
518
519 if (R) {
520 R->setHasUnsafeAlgebra(true);
521 InsertNewInstWith(R, *InsertBefore);
522 }
523
524 return R;
525}
526
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000527Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000528 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000529 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
530
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000531 if (Value *V = SimplifyVectorOp(I))
532 return ReplaceInstUsesWith(I, V);
533
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000534 if (isa<Constant>(Op0))
535 std::swap(Op0, Op1);
536
Chandler Carruth66b31302015-01-04 12:03:27 +0000537 if (Value *V =
538 SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL, TLI, DT, AC))
Michael Ilsemand5787be2012-12-12 00:28:32 +0000539 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000540
Shuxin Yange8227452013-01-15 21:09:32 +0000541 bool AllowReassociate = I.hasUnsafeAlgebra();
542
Michael Ilsemand5787be2012-12-12 00:28:32 +0000543 // Simplify mul instructions with a constant RHS.
544 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000545 // Try to fold constant mul into select arguments.
546 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
547 if (Instruction *R = FoldOpIntoSelect(I, SI))
548 return R;
549
550 if (isa<PHINode>(Op0))
551 if (Instruction *NV = FoldOpIntoPhi(I))
552 return NV;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000553
Owen Andersonf74cfe02014-01-16 20:36:42 +0000554 // (fmul X, -1.0) --> (fsub -0.0, X)
Benjamin Kramerfea9ac92014-01-18 16:43:14 +0000555 if (match(Op1, m_SpecificFP(-1.0))) {
556 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
557 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000558 RI->copyFastMathFlags(&I);
559 return RI;
560 }
561
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000562 Constant *C = cast<Constant>(Op1);
563 if (AllowReassociate && isFiniteNonZeroFp(C)) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000564 // Let MDC denote an expression in one of these forms:
565 // X * C, C/X, X/C, where C is a constant.
566 //
567 // Try to simplify "MDC * Constant"
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000568 if (isFMulOrFDivWithConstant(Op0))
569 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000570 return ReplaceInstUsesWith(I, V);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000571
Quentin Colombete684a6d2013-02-28 21:12:40 +0000572 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000573 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
574 if (FAddSub &&
575 (FAddSub->getOpcode() == Instruction::FAdd ||
576 FAddSub->getOpcode() == Instruction::FSub)) {
577 Value *Opnd0 = FAddSub->getOperand(0);
578 Value *Opnd1 = FAddSub->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000579 Constant *C0 = dyn_cast<Constant>(Opnd0);
580 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000581 bool Swap = false;
582 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000583 std::swap(C0, C1);
584 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000585 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000586 }
587
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000588 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000589 Value *M1 = ConstantExpr::getFMul(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000590 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000591 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
Craig Topperf40110f2014-04-25 05:29:35 +0000592 nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000593 if (M0 && M1) {
594 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
595 std::swap(M0, M1);
596
Benjamin Kramer67485762013-09-30 15:39:59 +0000597 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
598 ? BinaryOperator::CreateFAdd(M0, M1)
599 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000600 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000601 return RI;
602 }
603 }
604 }
605 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000606 }
607
Sanjay Patel12d1ce52014-10-02 21:10:54 +0000608 // sqrt(X) * sqrt(X) -> X
609 if (AllowReassociate && (Op0 == Op1))
610 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0))
611 if (II->getIntrinsicID() == Intrinsic::sqrt)
612 return ReplaceInstUsesWith(I, II->getOperand(0));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000613
Pedro Artigasd8795042012-11-30 19:09:41 +0000614 // Under unsafe algebra do:
615 // X * log2(0.5*Y) = X*log2(Y) - X
Sanjay Patelb41d4612014-10-02 15:20:45 +0000616 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +0000617 Value *OpX = nullptr;
618 Value *OpY = nullptr;
Pedro Artigasd8795042012-11-30 19:09:41 +0000619 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000620 detectLog2OfHalf(Op0, OpY, Log2);
621 if (OpY) {
622 OpX = Op1;
623 } else {
624 detectLog2OfHalf(Op1, OpY, Log2);
625 if (OpY) {
626 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000627 }
628 }
629 // if pattern detected emit alternate sequence
630 if (OpX && OpY) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000631 BuilderTy::FastMathFlagGuard Guard(*Builder);
632 Builder->SetFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000633 Log2->setArgOperand(0, OpY);
634 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
Benjamin Kramer67485762013-09-30 15:39:59 +0000635 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
636 FSub->takeName(&I);
637 return ReplaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000638 }
639 }
640
Shuxin Yange8227452013-01-15 21:09:32 +0000641 // Handle symmetric situation in a 2-iteration loop
642 Value *Opnd0 = Op0;
643 Value *Opnd1 = Op1;
644 for (int i = 0; i < 2; i++) {
645 bool IgnoreZeroSign = I.hasNoSignedZeros();
646 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000647 BuilderTy::FastMathFlagGuard Guard(*Builder);
648 Builder->SetFastMathFlags(I.getFastMathFlags());
649
Shuxin Yange8227452013-01-15 21:09:32 +0000650 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
651 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000652
Shuxin Yange8227452013-01-15 21:09:32 +0000653 // -X * -Y => X*Y
Owen Andersone8537fc2014-01-16 20:59:41 +0000654 if (N1) {
655 Value *FMul = Builder->CreateFMul(N0, N1);
656 FMul->takeName(&I);
657 return ReplaceInstUsesWith(I, FMul);
658 }
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000659
Shuxin Yange8227452013-01-15 21:09:32 +0000660 if (Opnd0->hasOneUse()) {
661 // -X * Y => -(X*Y) (Promote negation as high as possible)
662 Value *T = Builder->CreateFMul(N0, Opnd1);
Benjamin Kramer67485762013-09-30 15:39:59 +0000663 Value *Neg = Builder->CreateFNeg(T);
664 Neg->takeName(&I);
665 return ReplaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000666 }
667 }
Shuxin Yange8227452013-01-15 21:09:32 +0000668
669 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000670 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000671 // 1) to form a power expression (of X).
672 // 2) potentially shorten the critical path: After transformation, the
673 // latency of the instruction Y is amortized by the expression of X*X,
674 // and therefore Y is in a "less critical" position compared to what it
675 // was before the transformation.
676 //
677 if (AllowReassociate) {
678 Value *Opnd0_0, *Opnd0_1;
679 if (Opnd0->hasOneUse() &&
680 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000681 Value *Y = nullptr;
Shuxin Yange8227452013-01-15 21:09:32 +0000682 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
683 Y = Opnd0_1;
684 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
685 Y = Opnd0_0;
686
687 if (Y) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000688 BuilderTy::FastMathFlagGuard Guard(*Builder);
689 Builder->SetFastMathFlags(I.getFastMathFlags());
690 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
Shuxin Yange8227452013-01-15 21:09:32 +0000691
Benjamin Kramer67485762013-09-30 15:39:59 +0000692 Value *R = Builder->CreateFMul(T, Y);
693 R->takeName(&I);
694 return ReplaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000695 }
696 }
697 }
698
699 if (!isa<Constant>(Op1))
700 std::swap(Opnd0, Opnd1);
701 else
702 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000703 }
704
Craig Topperf40110f2014-04-25 05:29:35 +0000705 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000706}
707
708/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
709/// instruction.
710bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
711 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000712
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000713 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
714 int NonNullOperand = -1;
715 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
716 if (ST->isNullValue())
717 NonNullOperand = 2;
718 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
719 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
720 if (ST->isNullValue())
721 NonNullOperand = 1;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000722
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000723 if (NonNullOperand == -1)
724 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000725
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000726 Value *SelectCond = SI->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000727
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000728 // Change the div/rem to use 'Y' instead of the select.
729 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000730
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000731 // Okay, we know we replace the operand of the div/rem with 'Y' with no
732 // problem. However, the select, or the condition of the select may have
733 // multiple uses. Based on our knowledge that the operand must be non-zero,
734 // propagate the known value for the select into other uses of it, and
735 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000736
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000737 // If the select and condition only have a single use, don't bother with this,
738 // early exit.
739 if (SI->use_empty() && SelectCond->hasOneUse())
740 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000741
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000742 // Scan the current block backward, looking for other uses of SI.
743 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000744
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000745 while (BBI != BBFront) {
746 --BBI;
747 // If we found a call to a function, we can't assume it will return, so
748 // information from below it cannot be propagated above it.
749 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
750 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000751
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000752 // Replace uses of the select or its condition with the known values.
753 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
754 I != E; ++I) {
755 if (*I == SI) {
756 *I = SI->getOperand(NonNullOperand);
757 Worklist.Add(BBI);
758 } else if (*I == SelectCond) {
Jakub Staszak96ff4d62013-06-06 23:34:59 +0000759 *I = Builder->getInt1(NonNullOperand == 1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000760 Worklist.Add(BBI);
761 }
762 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000763
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000764 // If we past the instruction, quit looking for it.
765 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000766 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000767 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000768 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000769
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000770 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000771 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000772 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000773
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000774 }
775 return true;
776}
777
778
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000779/// This function implements the transforms common to both integer division
780/// instructions (udiv and sdiv). It is called by the visitors to those integer
781/// division instructions.
782/// @brief Common integer divide transforms
783Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
784 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
785
Chris Lattner7c99f192011-05-22 18:18:41 +0000786 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000787 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +0000788 I.setOperand(1, V);
789 return &I;
790 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000791
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000792 // Handle cases involving: [su]div X, (select Cond, Y, Z)
793 // This does not apply for fdiv.
794 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
795 return &I;
796
David Majnemer27adb122014-10-12 08:34:24 +0000797 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
798 const APInt *C2;
799 if (match(Op1, m_APInt(C2))) {
David Majnemerf9a095d2014-08-16 08:55:06 +0000800 Value *X;
David Majnemer27adb122014-10-12 08:34:24 +0000801 const APInt *C1;
802 bool IsSigned = I.getOpcode() == Instruction::SDiv;
David Majnemerf9a095d2014-08-16 08:55:06 +0000803
David Majnemer27adb122014-10-12 08:34:24 +0000804 // (X / C1) / C2 -> X / (C1*C2)
805 if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
806 (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
807 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
808 if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
809 return BinaryOperator::Create(I.getOpcode(), X,
810 ConstantInt::get(I.getType(), Product));
811 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000812
David Majnemer27adb122014-10-12 08:34:24 +0000813 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
814 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
815 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
816
817 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
818 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
819 BinaryOperator *BO = BinaryOperator::Create(
820 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
821 BO->setIsExact(I.isExact());
822 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000823 }
824
David Majnemer27adb122014-10-12 08:34:24 +0000825 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
826 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
827 BinaryOperator *BO = BinaryOperator::Create(
828 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
829 BO->setHasNoUnsignedWrap(
830 !IsSigned &&
831 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
832 BO->setHasNoSignedWrap(
833 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
834 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000835 }
836 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000837
David Majnemer27adb122014-10-12 08:34:24 +0000838 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
839 *C1 != C1->getBitWidth() - 1) ||
840 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
841 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
842 APInt C1Shifted = APInt::getOneBitSet(
843 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
844
845 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
846 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
847 BinaryOperator *BO = BinaryOperator::Create(
848 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
849 BO->setIsExact(I.isExact());
850 return BO;
851 }
852
853 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
854 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
855 BinaryOperator *BO = BinaryOperator::Create(
856 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
857 BO->setHasNoUnsignedWrap(
858 !IsSigned &&
859 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
860 BO->setHasNoSignedWrap(
861 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
862 return BO;
863 }
864 }
865
866 if (*C2 != 0) { // avoid X udiv 0
867 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
868 if (Instruction *R = FoldOpIntoSelect(I, SI))
869 return R;
870 if (isa<PHINode>(Op0))
871 if (Instruction *NV = FoldOpIntoPhi(I))
872 return NV;
873 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000874 }
875 }
876
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000877 if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
878 if (One->isOne() && !I.getType()->isIntegerTy(1)) {
879 bool isSigned = I.getOpcode() == Instruction::SDiv;
880 if (isSigned) {
881 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
882 // result is one, if Op1 is -1 then the result is minus one, otherwise
883 // it's zero.
884 Value *Inc = Builder->CreateAdd(Op1, One);
885 Value *Cmp = Builder->CreateICmpULT(
886 Inc, ConstantInt::get(I.getType(), 3));
887 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
888 } else {
889 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
890 // result is one, otherwise it's zero.
891 return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
892 }
893 }
894 }
895
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000896 // See if we can fold away this div instruction.
897 if (SimplifyDemandedInstructionBits(I))
898 return &I;
899
Duncan Sands771e82a2011-01-28 16:51:11 +0000900 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Craig Topperf40110f2014-04-25 05:29:35 +0000901 Value *X = nullptr, *Z = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +0000902 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
903 bool isSigned = I.getOpcode() == Instruction::SDiv;
904 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
905 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
906 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000907 }
908
Craig Topperf40110f2014-04-25 05:29:35 +0000909 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000910}
911
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000912/// dyn_castZExtVal - Checks if V is a zext or constant that can
913/// be truncated to Ty without losing bits.
Chris Lattner229907c2011-07-18 04:54:35 +0000914static Value *dyn_castZExtVal(Value *V, Type *Ty) {
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000915 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
916 if (Z->getSrcTy() == Ty)
917 return Z->getOperand(0);
918 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
919 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
920 return ConstantExpr::getTrunc(C, Ty);
921 }
Craig Topperf40110f2014-04-25 05:29:35 +0000922 return nullptr;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000923}
924
David Majnemer37f8f442013-07-04 21:17:49 +0000925namespace {
926const unsigned MaxDepth = 6;
927typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
928 const BinaryOperator &I,
929 InstCombiner &IC);
930
931/// \brief Used to maintain state for visitUDivOperand().
932struct UDivFoldAction {
933 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
934 ///< operand. This can be zero if this action
935 ///< joins two actions together.
936
937 Value *OperandToFold; ///< Which operand to fold.
938 union {
939 Instruction *FoldResult; ///< The instruction returned when FoldAction is
940 ///< invoked.
941
942 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
943 ///< joins two actions together.
944 };
945
946 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +0000947 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +0000948 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
949 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
950};
951}
952
953// X udiv 2^C -> X >> C
954static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
955 const BinaryOperator &I, InstCombiner &IC) {
956 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
957 BinaryOperator *LShr = BinaryOperator::CreateLShr(
958 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000959 if (I.isExact())
960 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000961 return LShr;
962}
963
964// X udiv C, where C >= signbit
965static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
966 const BinaryOperator &I, InstCombiner &IC) {
967 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
968
969 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
970 ConstantInt::get(I.getType(), 1));
971}
972
973// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
974static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
975 InstCombiner &IC) {
976 Instruction *ShiftLeft = cast<Instruction>(Op1);
977 if (isa<ZExtInst>(ShiftLeft))
978 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
979
980 const APInt &CI =
981 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
982 Value *N = ShiftLeft->getOperand(1);
983 if (CI != 1)
984 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
985 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
986 N = IC.Builder->CreateZExt(N, Z->getDestTy());
987 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000988 if (I.isExact())
989 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000990 return LShr;
991}
992
993// \brief Recursively visits the possible right hand operands of a udiv
994// instruction, seeing through select instructions, to determine if we can
995// replace the udiv with something simpler. If we find that an operand is not
996// able to simplify the udiv, we abort the entire transformation.
997static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
998 SmallVectorImpl<UDivFoldAction> &Actions,
999 unsigned Depth = 0) {
1000 // Check to see if this is an unsigned division with an exact power of 2,
1001 // if so, convert to a right shift.
1002 if (match(Op1, m_Power2())) {
1003 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
1004 return Actions.size();
1005 }
1006
1007 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
1008 // X udiv C, where C >= signbit
1009 if (C->getValue().isNegative()) {
1010 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
1011 return Actions.size();
1012 }
1013
1014 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
1015 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
1016 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
1017 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
1018 return Actions.size();
1019 }
1020
1021 // The remaining tests are all recursive, so bail out if we hit the limit.
1022 if (Depth++ == MaxDepth)
1023 return 0;
1024
1025 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
David Majnemer492e6122014-08-30 09:19:05 +00001026 if (size_t LHSIdx =
1027 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
1028 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
1029 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
David Majnemer37f8f442013-07-04 21:17:49 +00001030 return Actions.size();
1031 }
1032
1033 return 0;
1034}
1035
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001036Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
1037 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1038
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001039 if (Value *V = SimplifyVectorOp(I))
1040 return ReplaceInstUsesWith(I, V);
1041
Chandler Carruth66b31302015-01-04 12:03:27 +00001042 if (Value *V = SimplifyUDivInst(Op0, Op1, DL, TLI, DT, AC))
Duncan Sands771e82a2011-01-28 16:51:11 +00001043 return ReplaceInstUsesWith(I, V);
1044
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001045 // Handle the integer div common cases
1046 if (Instruction *Common = commonIDivTransforms(I))
1047 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001048
Benjamin Kramerd4a64712012-08-30 15:07:40 +00001049 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
David Majnemera2521382014-10-13 21:48:30 +00001050 {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +00001051 Value *X;
David Majnemera2521382014-10-13 21:48:30 +00001052 const APInt *C1, *C2;
1053 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
1054 match(Op1, m_APInt(C2))) {
1055 bool Overflow;
1056 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
David Majnemera3aeb152014-11-22 18:16:54 +00001057 if (!Overflow) {
1058 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1059 BinaryOperator *BO = BinaryOperator::CreateUDiv(
David Majnemera2521382014-10-13 21:48:30 +00001060 X, ConstantInt::get(X->getType(), C2ShlC1));
David Majnemera3aeb152014-11-22 18:16:54 +00001061 if (IsExact)
1062 BO->setIsExact();
1063 return BO;
1064 }
David Majnemera2521382014-10-13 21:48:30 +00001065 }
Nadav Rotem11935b22012-08-28 10:01:43 +00001066 }
1067
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001068 // (zext A) udiv (zext B) --> zext (A udiv B)
1069 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1070 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
Suyog Sardaea205512014-10-07 11:56:06 +00001071 return new ZExtInst(
1072 Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", I.isExact()),
1073 I.getType());
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001074
David Majnemer37f8f442013-07-04 21:17:49 +00001075 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1076 SmallVector<UDivFoldAction, 6> UDivActions;
1077 if (visitUDivOperand(Op0, Op1, I, UDivActions))
1078 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1079 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1080 Value *ActionOp1 = UDivActions[i].OperandToFold;
1081 Instruction *Inst;
1082 if (Action)
1083 Inst = Action(Op0, ActionOp1, I, *this);
1084 else {
1085 // This action joins two actions together. The RHS of this action is
1086 // simply the last action we processed, we saved the LHS action index in
1087 // the joining action.
1088 size_t SelectRHSIdx = i - 1;
1089 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1090 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1091 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1092 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1093 SelectLHS, SelectRHS);
1094 }
1095
1096 // If this is the last action to process, return it to the InstCombiner.
1097 // Otherwise, we insert it before the UDiv and record it so that we may
1098 // use it as part of a joining action (i.e., a SelectInst).
1099 if (e - i != 1) {
1100 Inst->insertBefore(&I);
1101 UDivActions[i].FoldResult = Inst;
1102 } else
1103 return Inst;
1104 }
1105
Craig Topperf40110f2014-04-25 05:29:35 +00001106 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001107}
1108
1109Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1110 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1111
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001112 if (Value *V = SimplifyVectorOp(I))
1113 return ReplaceInstUsesWith(I, V);
1114
Chandler Carruth66b31302015-01-04 12:03:27 +00001115 if (Value *V = SimplifySDivInst(Op0, Op1, DL, TLI, DT, AC))
Duncan Sands771e82a2011-01-28 16:51:11 +00001116 return ReplaceInstUsesWith(I, V);
1117
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001118 // Handle the integer div common cases
1119 if (Instruction *Common = commonIDivTransforms(I))
1120 return Common;
1121
Benjamin Kramer72196f32014-01-19 15:24:22 +00001122 // sdiv X, -1 == -X
1123 if (match(Op1, m_AllOnes()))
1124 return BinaryOperator::CreateNeg(Op0);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001125
Benjamin Kramer72196f32014-01-19 15:24:22 +00001126 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001127 // sdiv X, C --> ashr exact X, log2(C)
1128 if (I.isExact() && RHS->getValue().isNonNegative() &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001129 RHS->getValue().isPowerOf2()) {
1130 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1131 RHS->getValue().exactLogBase2());
Chris Lattner6b657ae2011-02-10 05:36:31 +00001132 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001133 }
Benjamin Kramer72196f32014-01-19 15:24:22 +00001134 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001135
Benjamin Kramer72196f32014-01-19 15:24:22 +00001136 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
David Majnemerf28e2a42014-07-02 06:42:13 +00001137 // X/INT_MIN -> X == INT_MIN
1138 if (RHS->isMinSignedValue())
1139 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1140
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001141 // -X/C --> X/-C provided the negation doesn't overflow.
David Majnemerfa4699e2014-11-22 20:00:34 +00001142 Value *X;
1143 if (match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1144 auto *BO = BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(RHS));
1145 BO->setIsExact(I.isExact());
1146 return BO;
1147 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001148 }
1149
1150 // If the sign bits of both operands are zero (i.e. we can prove they are
1151 // unsigned inputs), turn this into a udiv.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001152 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001153 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001154 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1155 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001156 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
David Majnemerec6e4812014-11-22 20:00:38 +00001157 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1158 BO->setIsExact(I.isExact());
1159 return BO;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001160 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001161
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001162 if (isKnownToBeAPowerOfTwo(Op1, DL, /*OrZero*/ true, 0, AC, &I, DT)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001163 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1164 // Safe because the only negative value (1 << Y) can take on is
1165 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1166 // the sign bit set.
David Majnemerfb380552014-11-22 20:00:41 +00001167 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1168 BO->setIsExact(I.isExact());
1169 return BO;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001170 }
1171 }
1172 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001173
Craig Topperf40110f2014-04-25 05:29:35 +00001174 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001175}
1176
Shuxin Yang320f52a2013-01-14 22:48:41 +00001177/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1178/// FP value and:
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001179/// 1) 1/C is exact, or
Shuxin Yang320f52a2013-01-14 22:48:41 +00001180/// 2) reciprocal is allowed.
Sylvestre Ledru149e2812013-05-14 23:36:24 +00001181/// If the conversion was successful, the simplified expression "X * 1/C" is
Shuxin Yang320f52a2013-01-14 22:48:41 +00001182/// returned; otherwise, NULL is returned.
1183///
Suyog Sardaea205512014-10-07 11:56:06 +00001184static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
Shuxin Yang320f52a2013-01-14 22:48:41 +00001185 bool AllowReciprocal) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001186 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001187 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001188
1189 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001190 APFloat Reciprocal(FpVal.getSemantics());
1191 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001192
Michael Gottesman3cb77ab2013-06-19 21:23:18 +00001193 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001194 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1195 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1196 Cvt = !Reciprocal.isDenormal();
1197 }
1198
1199 if (!Cvt)
Craig Topperf40110f2014-04-25 05:29:35 +00001200 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001201
1202 ConstantFP *R;
1203 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1204 return BinaryOperator::CreateFMul(Dividend, R);
1205}
1206
Frits van Bommel2a559512011-01-29 17:50:27 +00001207Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1208 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1209
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001210 if (Value *V = SimplifyVectorOp(I))
1211 return ReplaceInstUsesWith(I, V);
1212
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001213 if (Value *V = SimplifyFDivInst(Op0, Op1, I.getFastMathFlags(),
1214 DL, TLI, DT, AC))
Frits van Bommel2a559512011-01-29 17:50:27 +00001215 return ReplaceInstUsesWith(I, V);
1216
Stephen Lina9b57f62013-07-20 07:13:13 +00001217 if (isa<Constant>(Op0))
1218 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1219 if (Instruction *R = FoldOpIntoSelect(I, SI))
1220 return R;
1221
Shuxin Yang320f52a2013-01-14 22:48:41 +00001222 bool AllowReassociate = I.hasUnsafeAlgebra();
1223 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001224
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001225 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001226 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1227 if (Instruction *R = FoldOpIntoSelect(I, SI))
1228 return R;
1229
Shuxin Yang320f52a2013-01-14 22:48:41 +00001230 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +00001231 Constant *C1 = nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001232 Constant *C2 = Op1C;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001233 Value *X;
Craig Topperf40110f2014-04-25 05:29:35 +00001234 Instruction *Res = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001235
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001236 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001237 // (X*C1)/C2 => X * (C1/C2)
1238 //
1239 Constant *C = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001240 if (isNormalFp(C))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001241 Res = BinaryOperator::CreateFMul(X, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001242 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001243 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1244 //
1245 Constant *C = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001246 if (isNormalFp(C)) {
1247 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001248 if (!Res)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001249 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001250 }
1251 }
1252
1253 if (Res) {
1254 Res->setFastMathFlags(I.getFastMathFlags());
1255 return Res;
1256 }
1257 }
1258
1259 // X / C => X * 1/C
Owen Anderson4557a152014-01-16 21:07:52 +00001260 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1261 T->copyFastMathFlags(&I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001262 return T;
Owen Anderson4557a152014-01-16 21:07:52 +00001263 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001264
Craig Topperf40110f2014-04-25 05:29:35 +00001265 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001266 }
1267
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001268 if (AllowReassociate && isa<Constant>(Op0)) {
1269 Constant *C1 = cast<Constant>(Op0), *C2;
Craig Topperf40110f2014-04-25 05:29:35 +00001270 Constant *Fold = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001271 Value *X;
1272 bool CreateDiv = true;
1273
1274 // C1 / (X*C2) => (C1/C2) / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001275 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001276 Fold = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001277 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001278 // C1 / (X/C2) => (C1*C2) / X
1279 Fold = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001280 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001281 // C1 / (C2/X) => (C1/C2) * X
1282 Fold = ConstantExpr::getFDiv(C1, C2);
1283 CreateDiv = false;
1284 }
1285
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001286 if (Fold && isNormalFp(Fold)) {
1287 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1288 : BinaryOperator::CreateFMul(X, Fold);
1289 R->setFastMathFlags(I.getFastMathFlags());
1290 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001291 }
Craig Topperf40110f2014-04-25 05:29:35 +00001292 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001293 }
1294
1295 if (AllowReassociate) {
1296 Value *X, *Y;
Craig Topperf40110f2014-04-25 05:29:35 +00001297 Value *NewInst = nullptr;
1298 Instruction *SimpR = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001299
1300 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1301 // (X/Y) / Z => X / (Y*Z)
1302 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001303 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001304 NewInst = Builder->CreateFMul(Y, Op1);
Owen Anderson1664dc82014-01-20 07:44:53 +00001305 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1306 FastMathFlags Flags = I.getFastMathFlags();
1307 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1308 RI->setFastMathFlags(Flags);
1309 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001310 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1311 }
1312 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1313 // Z / (X/Y) => Z*Y / X
1314 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001315 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001316 NewInst = Builder->CreateFMul(Op0, Y);
Owen Anderson1664dc82014-01-20 07:44:53 +00001317 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1318 FastMathFlags Flags = I.getFastMathFlags();
1319 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1320 RI->setFastMathFlags(Flags);
1321 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001322 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1323 }
1324 }
1325
1326 if (NewInst) {
1327 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1328 T->setDebugLoc(I.getDebugLoc());
1329 SimpR->setFastMathFlags(I.getFastMathFlags());
1330 return SimpR;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001331 }
1332 }
1333
Craig Topperf40110f2014-04-25 05:29:35 +00001334 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001335}
1336
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001337/// This function implements the transforms common to both integer remainder
1338/// instructions (urem and srem). It is called by the visitors to those integer
1339/// remainder instructions.
1340/// @brief Common integer remainder transforms
1341Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1342 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1343
Chris Lattner7c99f192011-05-22 18:18:41 +00001344 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001345 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +00001346 I.setOperand(1, V);
1347 return &I;
1348 }
1349
Duncan Sandsa3e36992011-05-02 16:27:02 +00001350 // Handle cases involving: rem X, (select Cond, Y, Z)
1351 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1352 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001353
Benjamin Kramer72196f32014-01-19 15:24:22 +00001354 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001355 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1356 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1357 if (Instruction *R = FoldOpIntoSelect(I, SI))
1358 return R;
1359 } else if (isa<PHINode>(Op0I)) {
1360 if (Instruction *NV = FoldOpIntoPhi(I))
1361 return NV;
1362 }
1363
1364 // See if we can fold away this rem instruction.
1365 if (SimplifyDemandedInstructionBits(I))
1366 return &I;
1367 }
1368 }
1369
Craig Topperf40110f2014-04-25 05:29:35 +00001370 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001371}
1372
1373Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1374 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1375
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001376 if (Value *V = SimplifyVectorOp(I))
1377 return ReplaceInstUsesWith(I, V);
1378
Chandler Carruth66b31302015-01-04 12:03:27 +00001379 if (Value *V = SimplifyURemInst(Op0, Op1, DL, TLI, DT, AC))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001380 return ReplaceInstUsesWith(I, V);
1381
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001382 if (Instruction *common = commonIRemTransforms(I))
1383 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001384
David Majnemer6c30f492013-05-12 00:07:05 +00001385 // (zext A) urem (zext B) --> zext (A urem B)
1386 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1387 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1388 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1389 I.getType());
1390
David Majnemer470b0772013-05-11 09:01:28 +00001391 // X urem Y -> X and Y-1, where Y is a power of 2,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001392 if (isKnownToBeAPowerOfTwo(Op1, DL, /*OrZero*/ true, 0, AC, &I, DT)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001393 Constant *N1 = Constant::getAllOnesValue(I.getType());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001394 Value *Add = Builder->CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001395 return BinaryOperator::CreateAnd(Op0, Add);
1396 }
1397
Nick Lewycky7459be62013-07-13 01:16:47 +00001398 // 1 urem X -> zext(X != 1)
1399 if (match(Op0, m_One())) {
1400 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1401 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1402 return ReplaceInstUsesWith(I, Ext);
1403 }
1404
Craig Topperf40110f2014-04-25 05:29:35 +00001405 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001406}
1407
1408Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1409 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1410
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001411 if (Value *V = SimplifyVectorOp(I))
1412 return ReplaceInstUsesWith(I, V);
1413
Chandler Carruth66b31302015-01-04 12:03:27 +00001414 if (Value *V = SimplifySRemInst(Op0, Op1, DL, TLI, DT, AC))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001415 return ReplaceInstUsesWith(I, V);
1416
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001417 // Handle the integer rem common cases
1418 if (Instruction *Common = commonIRemTransforms(I))
1419 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001420
David Majnemerdb077302014-10-13 22:37:51 +00001421 {
1422 const APInt *Y;
1423 // X % -Y -> X % Y
1424 if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001425 Worklist.AddValue(I.getOperand(1));
David Majnemerdb077302014-10-13 22:37:51 +00001426 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001427 return &I;
1428 }
David Majnemerdb077302014-10-13 22:37:51 +00001429 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001430
1431 // If the sign bits of both operands are zero (i.e. we can prove they are
1432 // unsigned inputs), turn this into a urem.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001433 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001434 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001435 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1436 MaskedValueIsZero(Op0, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001437 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001438 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1439 }
1440 }
1441
1442 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001443 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1444 Constant *C = cast<Constant>(Op1);
1445 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001446
1447 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001448 bool hasMissing = false;
1449 for (unsigned i = 0; i != VWidth; ++i) {
1450 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001451 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001452 hasMissing = true;
1453 break;
1454 }
1455
1456 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001457 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001458 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001459 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001460
Chris Lattner0256be92012-01-27 03:08:05 +00001461 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001462 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001463 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001464 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001465 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001466 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001467 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001468 }
1469 }
1470
1471 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001472 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001473 Worklist.AddValue(I.getOperand(1));
1474 I.setOperand(1, NewRHSV);
1475 return &I;
1476 }
1477 }
1478 }
1479
Craig Topperf40110f2014-04-25 05:29:35 +00001480 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001481}
1482
1483Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001484 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001485
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001486 if (Value *V = SimplifyVectorOp(I))
1487 return ReplaceInstUsesWith(I, V);
1488
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001489 if (Value *V = SimplifyFRemInst(Op0, Op1, I.getFastMathFlags(),
1490 DL, TLI, DT, AC))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001491 return ReplaceInstUsesWith(I, V);
1492
1493 // Handle cases involving: rem X, (select Cond, Y, Z)
1494 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1495 return &I;
1496
Craig Topperf40110f2014-04-25 05:29:35 +00001497 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001498}