blob: d444d33ca8a00701ed663189ceb23505a6fbaeca [file] [log] [blame]
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001//===- InstCombineMulDivRem.cpp -------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visit functions for mul, fmul, sdiv, udiv, fdiv,
11// srem, urem, frem.
12//
13//===----------------------------------------------------------------------===//
14
15#include "InstCombine.h"
Duncan Sandsd0eb6d32010-12-21 14:00:22 +000016#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000018#include "llvm/IR/PatternMatch.h"
Chris Lattnerdc054bf2010-01-05 06:09:35 +000019using namespace llvm;
20using namespace PatternMatch;
21
Chandler Carruth964daaa2014-04-22 02:55:47 +000022#define DEBUG_TYPE "instcombine"
23
Chris Lattner7c99f192011-05-22 18:18:41 +000024
25/// simplifyValueKnownNonZero - The specific integer value is used in a context
26/// where it is known to be non-zero. If this allows us to simplify the
27/// computation, do so and return the new operand, otherwise return null.
Hal Finkel60db0582014-09-07 18:57:58 +000028static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC,
29 Instruction *CxtI) {
Chris Lattner7c99f192011-05-22 18:18:41 +000030 // If V has multiple uses, then we would have to do more analysis to determine
31 // if this is safe. For example, the use could be in dynamically unreached
32 // code.
Craig Topperf40110f2014-04-25 05:29:35 +000033 if (!V->hasOneUse()) return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000034
Chris Lattner388cb8a2011-05-23 00:32:19 +000035 bool MadeChange = false;
36
Chris Lattner7c99f192011-05-22 18:18:41 +000037 // ((1 << A) >>u B) --> (1 << (A-B))
38 // Because V cannot be zero, we know that B is less than A.
David Majnemerdad21032014-10-14 20:28:40 +000039 Value *A = nullptr, *B = nullptr, *One = nullptr;
40 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(One), m_Value(A))), m_Value(B))) &&
41 match(One, m_One())) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +000042 A = IC.Builder->CreateSub(A, B);
David Majnemerdad21032014-10-14 20:28:40 +000043 return IC.Builder->CreateShl(One, A);
Chris Lattner7c99f192011-05-22 18:18:41 +000044 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000045
Chris Lattner388cb8a2011-05-23 00:32:19 +000046 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
47 // inexact. Similarly for <<.
48 if (BinaryOperator *I = dyn_cast<BinaryOperator>(V))
Hal Finkel60db0582014-09-07 18:57:58 +000049 if (I->isLogicalShift() && isKnownToBeAPowerOfTwo(I->getOperand(0), false,
50 0, IC.getAssumptionTracker(),
51 CxtI,
52 IC.getDominatorTree())) {
Chris Lattner388cb8a2011-05-23 00:32:19 +000053 // We know that this is an exact/nuw shift and that the input is a
54 // non-zero context as well.
Hal Finkel60db0582014-09-07 18:57:58 +000055 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
Chris Lattner388cb8a2011-05-23 00:32:19 +000056 I->setOperand(0, V2);
57 MadeChange = true;
58 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000059
Chris Lattner388cb8a2011-05-23 00:32:19 +000060 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
61 I->setIsExact();
62 MadeChange = true;
63 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000064
Chris Lattner388cb8a2011-05-23 00:32:19 +000065 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
66 I->setHasNoUnsignedWrap();
67 MadeChange = true;
68 }
69 }
70
Chris Lattner162dfc32011-05-22 18:26:48 +000071 // TODO: Lots more we could do here:
Chris Lattner162dfc32011-05-22 18:26:48 +000072 // If V is a phi node, we can call this on each of its operands.
73 // "select cond, X, 0" can simplify to "X".
Jim Grosbachbdbd7342013-04-05 21:20:12 +000074
Craig Topperf40110f2014-04-25 05:29:35 +000075 return MadeChange ? V : nullptr;
Chris Lattner7c99f192011-05-22 18:18:41 +000076}
77
78
Chris Lattnerdc054bf2010-01-05 06:09:35 +000079/// MultiplyOverflows - True if the multiply can not be expressed in an int
80/// this size.
David Majnemer27adb122014-10-12 08:34:24 +000081static bool MultiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
82 bool IsSigned) {
83 bool Overflow;
84 if (IsSigned)
85 Product = C1.smul_ov(C2, Overflow);
86 else
87 Product = C1.umul_ov(C2, Overflow);
Jim Grosbachbdbd7342013-04-05 21:20:12 +000088
David Majnemer27adb122014-10-12 08:34:24 +000089 return Overflow;
Chris Lattnerdc054bf2010-01-05 06:09:35 +000090}
91
David Majnemerf9a095d2014-08-16 08:55:06 +000092/// \brief True if C2 is a multiple of C1. Quotient contains C2/C1.
93static bool IsMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
94 bool IsSigned) {
95 assert(C1.getBitWidth() == C2.getBitWidth() &&
96 "Inconsistent width of constants!");
97
98 APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
99 if (IsSigned)
100 APInt::sdivrem(C1, C2, Quotient, Remainder);
101 else
102 APInt::udivrem(C1, C2, Quotient, Remainder);
103
104 return Remainder.isMinValue();
105}
106
Rafael Espindola65281bf2013-05-31 14:27:15 +0000107/// \brief A helper routine of InstCombiner::visitMul().
108///
109/// If C is a vector of known powers of 2, then this function returns
110/// a new vector obtained from C replacing each element with its logBase2.
111/// Return a null pointer otherwise.
112static Constant *getLogBase2Vector(ConstantDataVector *CV) {
113 const APInt *IVal;
114 SmallVector<Constant *, 4> Elts;
115
116 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
117 Constant *Elt = CV->getElementAsConstant(I);
118 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
Craig Topperf40110f2014-04-25 05:29:35 +0000119 return nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000120 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
121 }
122
123 return ConstantVector::get(Elts);
124}
125
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,
129 Instruction *CxtI) {
130 // 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.
140 unsigned SignBits = ComputeNumSignBits(LHS, 0, CxtI) +
141 ComputeNumSignBits(RHS, 0, CxtI);
142
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;
160 ComputeSignBit(LHS, LHSNonNegative, LHSNegative, /*Depth=*/0, CxtI);
161 ComputeSignBit(RHS, RHSNonNegative, RHSNegative, /*Depth=*/0, CxtI);
162 if (LHSNonNegative || RHSNonNegative)
163 return true;
164 }
165 return false;
166}
167
David Majnemerb1296ec2014-12-26 09:50:35 +0000168/// \brief Return true if we can prove that:
169/// (mul LHS, RHS) === (mul nuw LHS, RHS)
170bool InstCombiner::WillNotOverflowUnsignedMul(Value *LHS, Value *RHS,
171 Instruction *CxtI) {
172 // Multiplying n * m significant bits yields a result of n + m significant
173 // bits. If the total number of significant bits does not exceed the
174 // result bit width (minus 1), there is no overflow.
175 // This means if we have enough leading zero bits in the operands
176 // we can guarantee that the result does not overflow.
177 // Ref: "Hacker's Delight" by Henry Warren
178 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
179 APInt LHSKnownZero(BitWidth, 0);
180 APInt RHSKnownZero(BitWidth, 0);
181 APInt TmpKnownOne(BitWidth, 0);
182 computeKnownBits(LHS, LHSKnownZero, TmpKnownOne, 0, CxtI);
183 computeKnownBits(RHS, RHSKnownZero, TmpKnownOne, 0, CxtI);
184 // Note that underestimating the number of zero bits gives a more
185 // conservative answer.
186 unsigned ZeroBits = LHSKnownZero.countLeadingOnes() +
187 RHSKnownZero.countLeadingOnes();
188 // First handle the easy case: if we have enough zero bits there's
189 // definitely no overflow.
190 if (ZeroBits >= BitWidth)
191 return true;
192
193 // There is an ambiguous cases where there can be no overflow:
194 // ZeroBits == BitWidth - 1
195 // However, determining overflow requires calculating the sign bit of
196 // LHS * RHS/2.
197
198 return false;
199}
200
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000201Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000202 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000203 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
204
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000205 if (Value *V = SimplifyVectorOp(I))
206 return ReplaceInstUsesWith(I, V);
207
Hal Finkel60db0582014-09-07 18:57:58 +0000208 if (Value *V = SimplifyMulInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000209 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000210
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000211 if (Value *V = SimplifyUsingDistributiveLaws(I))
212 return ReplaceInstUsesWith(I, V);
213
David Majnemer027bc802014-11-22 04:52:38 +0000214 // X * -1 == 0 - X
215 if (match(Op1, m_AllOnes())) {
216 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
217 if (I.hasNoSignedWrap())
218 BO->setHasNoSignedWrap();
219 return BO;
220 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000221
Rafael Espindola65281bf2013-05-31 14:27:15 +0000222 // Also allow combining multiply instructions on vectors.
223 {
224 Value *NewOp;
225 Constant *C1, *C2;
226 const APInt *IVal;
227 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
228 m_Constant(C1))) &&
David Majnemerfd4a6d22014-11-22 04:52:52 +0000229 match(C1, m_APInt(IVal))) {
230 // ((X << C2)*C1) == (X * (C1 << C2))
231 Constant *Shl = ConstantExpr::getShl(C1, C2);
232 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
233 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
234 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
235 BO->setHasNoUnsignedWrap();
236 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
237 Shl->isNotMinSignedValue())
238 BO->setHasNoSignedWrap();
239 return BO;
240 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000241
Rafael Espindola65281bf2013-05-31 14:27:15 +0000242 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000243 Constant *NewCst = nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000244 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
245 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
246 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
247 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
248 // Replace X*(2^C) with X << C, where C is a vector of known
249 // constant powers of 2.
250 NewCst = getLogBase2Vector(CV);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000251
Rafael Espindola65281bf2013-05-31 14:27:15 +0000252 if (NewCst) {
253 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000254
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000255 if (I.hasNoUnsignedWrap())
256 Shl->setHasNoUnsignedWrap();
David Majnemer80c8f622014-11-22 04:52:55 +0000257 if (I.hasNoSignedWrap() && NewCst->isNotMinSignedValue())
258 Shl->setHasNoSignedWrap();
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000259
Rafael Espindola65281bf2013-05-31 14:27:15 +0000260 return Shl;
261 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000262 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000263 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000264
Rafael Espindola65281bf2013-05-31 14:27:15 +0000265 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Stuart Hastings23804832011-06-01 16:42:47 +0000266 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
267 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
268 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000269 {
270 const APInt & Val = CI->getValue();
271 const APInt &PosVal = Val.abs();
272 if (Val.isNegative() && PosVal.isPowerOf2()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000273 Value *X = nullptr, *Y = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000274 if (Op0->hasOneUse()) {
275 ConstantInt *C1;
Craig Topperf40110f2014-04-25 05:29:35 +0000276 Value *Sub = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000277 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
278 Sub = Builder->CreateSub(X, Y, "suba");
279 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
280 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
281 if (Sub)
282 return
283 BinaryOperator::CreateMul(Sub,
284 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000285 }
286 }
287 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000288 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000289
Chris Lattner6b657ae2011-02-10 05:36:31 +0000290 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000291 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000292 // Try to fold constant mul into select arguments.
293 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
294 if (Instruction *R = FoldOpIntoSelect(I, SI))
295 return R;
296
297 if (isa<PHINode>(Op0))
298 if (Instruction *NV = FoldOpIntoPhi(I))
299 return NV;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000300
301 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
302 {
303 Value *X;
304 Constant *C1;
305 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
David Majnemer6cf6c052014-06-19 07:14:33 +0000306 Value *Mul = Builder->CreateMul(C1, Op1);
307 // Only go forward with the transform if C1*CI simplifies to a tidier
308 // constant.
309 if (!match(Mul, m_Mul(m_Value(), m_Value())))
310 return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
Benjamin Kramer72196f32014-01-19 15:24:22 +0000311 }
312 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000313 }
314
David Majnemer8279a7502014-11-22 07:25:19 +0000315 if (Value *Op0v = dyn_castNegVal(Op0)) { // -X * -Y = X*Y
316 if (Value *Op1v = dyn_castNegVal(Op1)) {
317 BinaryOperator *BO = BinaryOperator::CreateMul(Op0v, Op1v);
318 if (I.hasNoSignedWrap() &&
319 match(Op0, m_NSWSub(m_Value(), m_Value())) &&
320 match(Op1, m_NSWSub(m_Value(), m_Value())))
321 BO->setHasNoSignedWrap();
322 return BO;
323 }
324 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000325
326 // (X / Y) * Y = X - (X % Y)
327 // (X / Y) * -Y = (X % Y) - X
328 {
329 Value *Op1C = Op1;
330 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
331 if (!BO ||
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000332 (BO->getOpcode() != Instruction::UDiv &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000333 BO->getOpcode() != Instruction::SDiv)) {
334 Op1C = Op0;
335 BO = dyn_cast<BinaryOperator>(Op1);
336 }
337 Value *Neg = dyn_castNegVal(Op1C);
338 if (BO && BO->hasOneUse() &&
339 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
340 (BO->getOpcode() == Instruction::UDiv ||
341 BO->getOpcode() == Instruction::SDiv)) {
342 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
343
Chris Lattner35315d02011-02-06 21:44:57 +0000344 // If the division is exact, X % Y is zero, so we end up with X or -X.
345 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000346 if (SDiv->isExact()) {
347 if (Op1BO == Op1C)
348 return ReplaceInstUsesWith(I, Op0BO);
349 return BinaryOperator::CreateNeg(Op0BO);
350 }
351
352 Value *Rem;
353 if (BO->getOpcode() == Instruction::UDiv)
354 Rem = Builder->CreateURem(Op0BO, Op1BO);
355 else
356 Rem = Builder->CreateSRem(Op0BO, Op1BO);
357 Rem->takeName(BO);
358
359 if (Op1BO == Op1C)
360 return BinaryOperator::CreateSub(Op0BO, Rem);
361 return BinaryOperator::CreateSub(Rem, Op0BO);
362 }
363 }
364
365 /// i1 mul -> i1 and.
Benjamin Kramer72196f32014-01-19 15:24:22 +0000366 if (I.getType()->getScalarType()->isIntegerTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000367 return BinaryOperator::CreateAnd(Op0, Op1);
368
369 // X*(1 << Y) --> X << Y
370 // (1 << Y)*X --> X << Y
371 {
372 Value *Y;
David Majnemer546f8102014-11-22 08:57:02 +0000373 BinaryOperator *BO = nullptr;
374 bool ShlNSW = false;
375 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
376 BO = BinaryOperator::CreateShl(Op1, Y);
377 ShlNSW = cast<BinaryOperator>(Op0)->hasNoSignedWrap();
David Majnemer8e6f6a92014-11-24 16:41:13 +0000378 } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
David Majnemer546f8102014-11-22 08:57:02 +0000379 BO = BinaryOperator::CreateShl(Op0, Y);
380 ShlNSW = cast<BinaryOperator>(Op1)->hasNoSignedWrap();
381 }
382 if (BO) {
383 if (I.hasNoUnsignedWrap())
384 BO->setHasNoUnsignedWrap();
385 if (I.hasNoSignedWrap() && ShlNSW)
386 BO->setHasNoSignedWrap();
387 return BO;
388 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000389 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000390
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000391 // If one of the operands of the multiply is a cast from a boolean value, then
392 // we know the bool is either zero or one, so this is a 'masking' multiply.
393 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands19d0b472010-02-16 11:11:14 +0000394 if (!I.getType()->isVectorTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000395 // -2 is "-1 << 1" so it is all bits set except the low one.
396 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000397
Craig Topperf40110f2014-04-25 05:29:35 +0000398 Value *BoolCast = nullptr, *OtherOp = nullptr;
Hal Finkel60db0582014-09-07 18:57:58 +0000399 if (MaskedValueIsZero(Op0, Negative2, 0, &I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000400 BoolCast = Op0, OtherOp = Op1;
Hal Finkel60db0582014-09-07 18:57:58 +0000401 else if (MaskedValueIsZero(Op1, Negative2, 0, &I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000402 BoolCast = Op1, OtherOp = Op0;
403
404 if (BoolCast) {
405 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000406 BoolCast);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000407 return BinaryOperator::CreateAnd(V, OtherOp);
408 }
409 }
410
David Majnemer54c2ca22014-12-26 09:10:14 +0000411 if (!I.hasNoSignedWrap() && WillNotOverflowSignedMul(Op0, Op1, &I)) {
412 Changed = true;
413 I.setHasNoSignedWrap(true);
414 }
415
David Majnemerb1296ec2014-12-26 09:50:35 +0000416 if (!I.hasNoUnsignedWrap() && WillNotOverflowUnsignedMul(Op0, Op1, &I)) {
417 Changed = true;
418 I.setHasNoUnsignedWrap(true);
419 }
420
Craig Topperf40110f2014-04-25 05:29:35 +0000421 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000422}
423
Sanjay Patel17045f72014-10-14 00:33:23 +0000424/// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
Pedro Artigas993acd02012-11-30 22:07:05 +0000425static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Sanjay Patel17045f72014-10-14 00:33:23 +0000426 if (!Op->hasOneUse())
427 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000428
Sanjay Patel17045f72014-10-14 00:33:23 +0000429 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
430 if (!II)
431 return;
432 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
433 return;
434 Log2 = II;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000435
Sanjay Patel17045f72014-10-14 00:33:23 +0000436 Value *OpLog2Of = II->getArgOperand(0);
437 if (!OpLog2Of->hasOneUse())
438 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000439
Sanjay Patel17045f72014-10-14 00:33:23 +0000440 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
441 if (!I)
442 return;
443 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
444 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000445
Sanjay Patel17045f72014-10-14 00:33:23 +0000446 if (match(I->getOperand(0), m_SpecificFP(0.5)))
447 Y = I->getOperand(1);
448 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
449 Y = I->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000450}
Pedro Artigas993acd02012-11-30 22:07:05 +0000451
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000452static bool isFiniteNonZeroFp(Constant *C) {
453 if (C->getType()->isVectorTy()) {
454 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
455 ++I) {
456 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
457 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
458 return false;
459 }
460 return true;
461 }
462
463 return isa<ConstantFP>(C) &&
464 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
465}
466
467static bool isNormalFp(Constant *C) {
468 if (C->getType()->isVectorTy()) {
469 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
470 ++I) {
471 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
472 if (!CFP || !CFP->getValueAPF().isNormal())
473 return false;
474 }
475 return true;
476 }
477
478 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
479}
480
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000481/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
482/// true iff the given value is FMul or FDiv with one and only one operand
483/// being a normal constant (i.e. not Zero/NaN/Infinity).
484static bool isFMulOrFDivWithConstant(Value *V) {
485 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000486 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yang80138662013-01-07 22:41:28 +0000487 I->getOpcode() != Instruction::FDiv))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000488 return false;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000489
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000490 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
491 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000492
493 if (C0 && C1)
494 return false;
495
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000496 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000497}
498
499/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
500/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
501/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000502/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000503/// resulting expression. Note that this function could return NULL in
504/// case the constants cannot be folded into a normal floating-point.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000505///
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000506Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yang80138662013-01-07 22:41:28 +0000507 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000508 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
509
510 Value *Opnd0 = FMulOrDiv->getOperand(0);
511 Value *Opnd1 = FMulOrDiv->getOperand(1);
512
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000513 Constant *C0 = dyn_cast<Constant>(Opnd0);
514 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000515
Craig Topperf40110f2014-04-25 05:29:35 +0000516 BinaryOperator *R = nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000517
518 // (X * C0) * C => X * (C0*C)
519 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
520 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000521 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000522 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
523 } else {
524 if (C0) {
525 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000526 if (FMulOrDiv->hasOneUse()) {
527 // It would otherwise introduce another div.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000528 Constant *F = ConstantExpr::getFMul(C0, C);
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000529 if (isNormalFp(F))
530 R = BinaryOperator::CreateFDiv(F, Opnd1);
531 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000532 } else {
533 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000534 Constant *F = ConstantExpr::getFDiv(C, C1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000535 if (isNormalFp(F)) {
536 R = BinaryOperator::CreateFMul(Opnd0, F);
537 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000538 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000539 Constant *F = ConstantExpr::getFDiv(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000540 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000541 R = BinaryOperator::CreateFDiv(Opnd0, F);
542 }
543 }
544 }
545
546 if (R) {
547 R->setHasUnsafeAlgebra(true);
548 InsertNewInstWith(R, *InsertBefore);
549 }
550
551 return R;
552}
553
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000554Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000555 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000556 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
557
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000558 if (Value *V = SimplifyVectorOp(I))
559 return ReplaceInstUsesWith(I, V);
560
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000561 if (isa<Constant>(Op0))
562 std::swap(Op0, Op1);
563
Hal Finkel60db0582014-09-07 18:57:58 +0000564 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL, TLI,
565 DT, AT))
Michael Ilsemand5787be2012-12-12 00:28:32 +0000566 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000567
Shuxin Yange8227452013-01-15 21:09:32 +0000568 bool AllowReassociate = I.hasUnsafeAlgebra();
569
Michael Ilsemand5787be2012-12-12 00:28:32 +0000570 // Simplify mul instructions with a constant RHS.
571 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000572 // Try to fold constant mul into select arguments.
573 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
574 if (Instruction *R = FoldOpIntoSelect(I, SI))
575 return R;
576
577 if (isa<PHINode>(Op0))
578 if (Instruction *NV = FoldOpIntoPhi(I))
579 return NV;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000580
Owen Andersonf74cfe02014-01-16 20:36:42 +0000581 // (fmul X, -1.0) --> (fsub -0.0, X)
Benjamin Kramerfea9ac92014-01-18 16:43:14 +0000582 if (match(Op1, m_SpecificFP(-1.0))) {
583 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
584 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000585 RI->copyFastMathFlags(&I);
586 return RI;
587 }
588
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000589 Constant *C = cast<Constant>(Op1);
590 if (AllowReassociate && isFiniteNonZeroFp(C)) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000591 // Let MDC denote an expression in one of these forms:
592 // X * C, C/X, X/C, where C is a constant.
593 //
594 // Try to simplify "MDC * Constant"
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000595 if (isFMulOrFDivWithConstant(Op0))
596 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000597 return ReplaceInstUsesWith(I, V);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000598
Quentin Colombete684a6d2013-02-28 21:12:40 +0000599 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000600 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
601 if (FAddSub &&
602 (FAddSub->getOpcode() == Instruction::FAdd ||
603 FAddSub->getOpcode() == Instruction::FSub)) {
604 Value *Opnd0 = FAddSub->getOperand(0);
605 Value *Opnd1 = FAddSub->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000606 Constant *C0 = dyn_cast<Constant>(Opnd0);
607 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000608 bool Swap = false;
609 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000610 std::swap(C0, C1);
611 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000612 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000613 }
614
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000615 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000616 Value *M1 = ConstantExpr::getFMul(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000617 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000618 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
Craig Topperf40110f2014-04-25 05:29:35 +0000619 nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000620 if (M0 && M1) {
621 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
622 std::swap(M0, M1);
623
Benjamin Kramer67485762013-09-30 15:39:59 +0000624 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
625 ? BinaryOperator::CreateFAdd(M0, M1)
626 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000627 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000628 return RI;
629 }
630 }
631 }
632 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000633 }
634
Sanjay Patel12d1ce52014-10-02 21:10:54 +0000635 // sqrt(X) * sqrt(X) -> X
636 if (AllowReassociate && (Op0 == Op1))
637 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0))
638 if (II->getIntrinsicID() == Intrinsic::sqrt)
639 return ReplaceInstUsesWith(I, II->getOperand(0));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000640
Pedro Artigasd8795042012-11-30 19:09:41 +0000641 // Under unsafe algebra do:
642 // X * log2(0.5*Y) = X*log2(Y) - X
Sanjay Patelb41d4612014-10-02 15:20:45 +0000643 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +0000644 Value *OpX = nullptr;
645 Value *OpY = nullptr;
Pedro Artigasd8795042012-11-30 19:09:41 +0000646 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000647 detectLog2OfHalf(Op0, OpY, Log2);
648 if (OpY) {
649 OpX = Op1;
650 } else {
651 detectLog2OfHalf(Op1, OpY, Log2);
652 if (OpY) {
653 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000654 }
655 }
656 // if pattern detected emit alternate sequence
657 if (OpX && OpY) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000658 BuilderTy::FastMathFlagGuard Guard(*Builder);
659 Builder->SetFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000660 Log2->setArgOperand(0, OpY);
661 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
Benjamin Kramer67485762013-09-30 15:39:59 +0000662 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
663 FSub->takeName(&I);
664 return ReplaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000665 }
666 }
667
Shuxin Yange8227452013-01-15 21:09:32 +0000668 // Handle symmetric situation in a 2-iteration loop
669 Value *Opnd0 = Op0;
670 Value *Opnd1 = Op1;
671 for (int i = 0; i < 2; i++) {
672 bool IgnoreZeroSign = I.hasNoSignedZeros();
673 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000674 BuilderTy::FastMathFlagGuard Guard(*Builder);
675 Builder->SetFastMathFlags(I.getFastMathFlags());
676
Shuxin Yange8227452013-01-15 21:09:32 +0000677 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
678 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000679
Shuxin Yange8227452013-01-15 21:09:32 +0000680 // -X * -Y => X*Y
Owen Andersone8537fc2014-01-16 20:59:41 +0000681 if (N1) {
682 Value *FMul = Builder->CreateFMul(N0, N1);
683 FMul->takeName(&I);
684 return ReplaceInstUsesWith(I, FMul);
685 }
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000686
Shuxin Yange8227452013-01-15 21:09:32 +0000687 if (Opnd0->hasOneUse()) {
688 // -X * Y => -(X*Y) (Promote negation as high as possible)
689 Value *T = Builder->CreateFMul(N0, Opnd1);
Benjamin Kramer67485762013-09-30 15:39:59 +0000690 Value *Neg = Builder->CreateFNeg(T);
691 Neg->takeName(&I);
692 return ReplaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000693 }
694 }
Shuxin Yange8227452013-01-15 21:09:32 +0000695
696 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000697 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000698 // 1) to form a power expression (of X).
699 // 2) potentially shorten the critical path: After transformation, the
700 // latency of the instruction Y is amortized by the expression of X*X,
701 // and therefore Y is in a "less critical" position compared to what it
702 // was before the transformation.
703 //
704 if (AllowReassociate) {
705 Value *Opnd0_0, *Opnd0_1;
706 if (Opnd0->hasOneUse() &&
707 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000708 Value *Y = nullptr;
Shuxin Yange8227452013-01-15 21:09:32 +0000709 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
710 Y = Opnd0_1;
711 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
712 Y = Opnd0_0;
713
714 if (Y) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000715 BuilderTy::FastMathFlagGuard Guard(*Builder);
716 Builder->SetFastMathFlags(I.getFastMathFlags());
717 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
Shuxin Yange8227452013-01-15 21:09:32 +0000718
Benjamin Kramer67485762013-09-30 15:39:59 +0000719 Value *R = Builder->CreateFMul(T, Y);
720 R->takeName(&I);
721 return ReplaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000722 }
723 }
724 }
725
726 if (!isa<Constant>(Op1))
727 std::swap(Opnd0, Opnd1);
728 else
729 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000730 }
731
Craig Topperf40110f2014-04-25 05:29:35 +0000732 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000733}
734
735/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
736/// instruction.
737bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
738 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000739
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000740 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
741 int NonNullOperand = -1;
742 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
743 if (ST->isNullValue())
744 NonNullOperand = 2;
745 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
746 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
747 if (ST->isNullValue())
748 NonNullOperand = 1;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000749
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000750 if (NonNullOperand == -1)
751 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000752
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000753 Value *SelectCond = SI->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000754
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000755 // Change the div/rem to use 'Y' instead of the select.
756 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000757
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000758 // Okay, we know we replace the operand of the div/rem with 'Y' with no
759 // problem. However, the select, or the condition of the select may have
760 // multiple uses. Based on our knowledge that the operand must be non-zero,
761 // propagate the known value for the select into other uses of it, and
762 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000763
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000764 // If the select and condition only have a single use, don't bother with this,
765 // early exit.
766 if (SI->use_empty() && SelectCond->hasOneUse())
767 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000768
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000769 // Scan the current block backward, looking for other uses of SI.
770 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000771
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000772 while (BBI != BBFront) {
773 --BBI;
774 // If we found a call to a function, we can't assume it will return, so
775 // information from below it cannot be propagated above it.
776 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
777 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000778
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000779 // Replace uses of the select or its condition with the known values.
780 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
781 I != E; ++I) {
782 if (*I == SI) {
783 *I = SI->getOperand(NonNullOperand);
784 Worklist.Add(BBI);
785 } else if (*I == SelectCond) {
Jakub Staszak96ff4d62013-06-06 23:34:59 +0000786 *I = Builder->getInt1(NonNullOperand == 1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000787 Worklist.Add(BBI);
788 }
789 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000790
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000791 // If we past the instruction, quit looking for it.
792 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000793 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000794 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000795 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000796
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000797 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000798 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000799 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000800
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000801 }
802 return true;
803}
804
805
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000806/// This function implements the transforms common to both integer division
807/// instructions (udiv and sdiv). It is called by the visitors to those integer
808/// division instructions.
809/// @brief Common integer divide transforms
810Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
811 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
812
Chris Lattner7c99f192011-05-22 18:18:41 +0000813 // The RHS is known non-zero.
Hal Finkel60db0582014-09-07 18:57:58 +0000814 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +0000815 I.setOperand(1, V);
816 return &I;
817 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000818
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000819 // Handle cases involving: [su]div X, (select Cond, Y, Z)
820 // This does not apply for fdiv.
821 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
822 return &I;
823
David Majnemer27adb122014-10-12 08:34:24 +0000824 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
825 const APInt *C2;
826 if (match(Op1, m_APInt(C2))) {
David Majnemerf9a095d2014-08-16 08:55:06 +0000827 Value *X;
David Majnemer27adb122014-10-12 08:34:24 +0000828 const APInt *C1;
829 bool IsSigned = I.getOpcode() == Instruction::SDiv;
David Majnemerf9a095d2014-08-16 08:55:06 +0000830
David Majnemer27adb122014-10-12 08:34:24 +0000831 // (X / C1) / C2 -> X / (C1*C2)
832 if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
833 (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
834 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
835 if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
836 return BinaryOperator::Create(I.getOpcode(), X,
837 ConstantInt::get(I.getType(), Product));
838 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000839
David Majnemer27adb122014-10-12 08:34:24 +0000840 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
841 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
842 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
843
844 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
845 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
846 BinaryOperator *BO = BinaryOperator::Create(
847 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
848 BO->setIsExact(I.isExact());
849 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000850 }
851
David Majnemer27adb122014-10-12 08:34:24 +0000852 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
853 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
854 BinaryOperator *BO = BinaryOperator::Create(
855 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
856 BO->setHasNoUnsignedWrap(
857 !IsSigned &&
858 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
859 BO->setHasNoSignedWrap(
860 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
861 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000862 }
863 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000864
David Majnemer27adb122014-10-12 08:34:24 +0000865 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
866 *C1 != C1->getBitWidth() - 1) ||
867 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
868 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
869 APInt C1Shifted = APInt::getOneBitSet(
870 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
871
872 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
873 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
874 BinaryOperator *BO = BinaryOperator::Create(
875 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
876 BO->setIsExact(I.isExact());
877 return BO;
878 }
879
880 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
881 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
882 BinaryOperator *BO = BinaryOperator::Create(
883 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
884 BO->setHasNoUnsignedWrap(
885 !IsSigned &&
886 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
887 BO->setHasNoSignedWrap(
888 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
889 return BO;
890 }
891 }
892
893 if (*C2 != 0) { // avoid X udiv 0
894 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
895 if (Instruction *R = FoldOpIntoSelect(I, SI))
896 return R;
897 if (isa<PHINode>(Op0))
898 if (Instruction *NV = FoldOpIntoPhi(I))
899 return NV;
900 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000901 }
902 }
903
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000904 if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
905 if (One->isOne() && !I.getType()->isIntegerTy(1)) {
906 bool isSigned = I.getOpcode() == Instruction::SDiv;
907 if (isSigned) {
908 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
909 // result is one, if Op1 is -1 then the result is minus one, otherwise
910 // it's zero.
911 Value *Inc = Builder->CreateAdd(Op1, One);
912 Value *Cmp = Builder->CreateICmpULT(
913 Inc, ConstantInt::get(I.getType(), 3));
914 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
915 } else {
916 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
917 // result is one, otherwise it's zero.
918 return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
919 }
920 }
921 }
922
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000923 // See if we can fold away this div instruction.
924 if (SimplifyDemandedInstructionBits(I))
925 return &I;
926
Duncan Sands771e82a2011-01-28 16:51:11 +0000927 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Craig Topperf40110f2014-04-25 05:29:35 +0000928 Value *X = nullptr, *Z = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +0000929 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
930 bool isSigned = I.getOpcode() == Instruction::SDiv;
931 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
932 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
933 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000934 }
935
Craig Topperf40110f2014-04-25 05:29:35 +0000936 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000937}
938
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000939/// dyn_castZExtVal - Checks if V is a zext or constant that can
940/// be truncated to Ty without losing bits.
Chris Lattner229907c2011-07-18 04:54:35 +0000941static Value *dyn_castZExtVal(Value *V, Type *Ty) {
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000942 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
943 if (Z->getSrcTy() == Ty)
944 return Z->getOperand(0);
945 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
946 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
947 return ConstantExpr::getTrunc(C, Ty);
948 }
Craig Topperf40110f2014-04-25 05:29:35 +0000949 return nullptr;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000950}
951
David Majnemer37f8f442013-07-04 21:17:49 +0000952namespace {
953const unsigned MaxDepth = 6;
954typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
955 const BinaryOperator &I,
956 InstCombiner &IC);
957
958/// \brief Used to maintain state for visitUDivOperand().
959struct UDivFoldAction {
960 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
961 ///< operand. This can be zero if this action
962 ///< joins two actions together.
963
964 Value *OperandToFold; ///< Which operand to fold.
965 union {
966 Instruction *FoldResult; ///< The instruction returned when FoldAction is
967 ///< invoked.
968
969 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
970 ///< joins two actions together.
971 };
972
973 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +0000974 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +0000975 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
976 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
977};
978}
979
980// X udiv 2^C -> X >> C
981static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
982 const BinaryOperator &I, InstCombiner &IC) {
983 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
984 BinaryOperator *LShr = BinaryOperator::CreateLShr(
985 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000986 if (I.isExact())
987 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000988 return LShr;
989}
990
991// X udiv C, where C >= signbit
992static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
993 const BinaryOperator &I, InstCombiner &IC) {
994 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
995
996 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
997 ConstantInt::get(I.getType(), 1));
998}
999
1000// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
1001static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
1002 InstCombiner &IC) {
1003 Instruction *ShiftLeft = cast<Instruction>(Op1);
1004 if (isa<ZExtInst>(ShiftLeft))
1005 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
1006
1007 const APInt &CI =
1008 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
1009 Value *N = ShiftLeft->getOperand(1);
1010 if (CI != 1)
1011 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
1012 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
1013 N = IC.Builder->CreateZExt(N, Z->getDestTy());
1014 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
Suyog Sarda65f5ae92014-10-07 12:04:07 +00001015 if (I.isExact())
1016 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +00001017 return LShr;
1018}
1019
1020// \brief Recursively visits the possible right hand operands of a udiv
1021// instruction, seeing through select instructions, to determine if we can
1022// replace the udiv with something simpler. If we find that an operand is not
1023// able to simplify the udiv, we abort the entire transformation.
1024static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
1025 SmallVectorImpl<UDivFoldAction> &Actions,
1026 unsigned Depth = 0) {
1027 // Check to see if this is an unsigned division with an exact power of 2,
1028 // if so, convert to a right shift.
1029 if (match(Op1, m_Power2())) {
1030 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
1031 return Actions.size();
1032 }
1033
1034 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
1035 // X udiv C, where C >= signbit
1036 if (C->getValue().isNegative()) {
1037 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
1038 return Actions.size();
1039 }
1040
1041 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
1042 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
1043 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
1044 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
1045 return Actions.size();
1046 }
1047
1048 // The remaining tests are all recursive, so bail out if we hit the limit.
1049 if (Depth++ == MaxDepth)
1050 return 0;
1051
1052 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
David Majnemer492e6122014-08-30 09:19:05 +00001053 if (size_t LHSIdx =
1054 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
1055 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
1056 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
David Majnemer37f8f442013-07-04 21:17:49 +00001057 return Actions.size();
1058 }
1059
1060 return 0;
1061}
1062
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001063Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
1064 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1065
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001066 if (Value *V = SimplifyVectorOp(I))
1067 return ReplaceInstUsesWith(I, V);
1068
Hal Finkel60db0582014-09-07 18:57:58 +00001069 if (Value *V = SimplifyUDivInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sands771e82a2011-01-28 16:51:11 +00001070 return ReplaceInstUsesWith(I, V);
1071
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001072 // Handle the integer div common cases
1073 if (Instruction *Common = commonIDivTransforms(I))
1074 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001075
Benjamin Kramerd4a64712012-08-30 15:07:40 +00001076 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
David Majnemera2521382014-10-13 21:48:30 +00001077 {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +00001078 Value *X;
David Majnemera2521382014-10-13 21:48:30 +00001079 const APInt *C1, *C2;
1080 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
1081 match(Op1, m_APInt(C2))) {
1082 bool Overflow;
1083 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
David Majnemera3aeb152014-11-22 18:16:54 +00001084 if (!Overflow) {
1085 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1086 BinaryOperator *BO = BinaryOperator::CreateUDiv(
David Majnemera2521382014-10-13 21:48:30 +00001087 X, ConstantInt::get(X->getType(), C2ShlC1));
David Majnemera3aeb152014-11-22 18:16:54 +00001088 if (IsExact)
1089 BO->setIsExact();
1090 return BO;
1091 }
David Majnemera2521382014-10-13 21:48:30 +00001092 }
Nadav Rotem11935b22012-08-28 10:01:43 +00001093 }
1094
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001095 // (zext A) udiv (zext B) --> zext (A udiv B)
1096 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1097 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
Suyog Sardaea205512014-10-07 11:56:06 +00001098 return new ZExtInst(
1099 Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", I.isExact()),
1100 I.getType());
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001101
David Majnemer37f8f442013-07-04 21:17:49 +00001102 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1103 SmallVector<UDivFoldAction, 6> UDivActions;
1104 if (visitUDivOperand(Op0, Op1, I, UDivActions))
1105 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1106 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1107 Value *ActionOp1 = UDivActions[i].OperandToFold;
1108 Instruction *Inst;
1109 if (Action)
1110 Inst = Action(Op0, ActionOp1, I, *this);
1111 else {
1112 // This action joins two actions together. The RHS of this action is
1113 // simply the last action we processed, we saved the LHS action index in
1114 // the joining action.
1115 size_t SelectRHSIdx = i - 1;
1116 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1117 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1118 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1119 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1120 SelectLHS, SelectRHS);
1121 }
1122
1123 // If this is the last action to process, return it to the InstCombiner.
1124 // Otherwise, we insert it before the UDiv and record it so that we may
1125 // use it as part of a joining action (i.e., a SelectInst).
1126 if (e - i != 1) {
1127 Inst->insertBefore(&I);
1128 UDivActions[i].FoldResult = Inst;
1129 } else
1130 return Inst;
1131 }
1132
Craig Topperf40110f2014-04-25 05:29:35 +00001133 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001134}
1135
1136Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1137 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1138
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001139 if (Value *V = SimplifyVectorOp(I))
1140 return ReplaceInstUsesWith(I, V);
1141
Hal Finkel60db0582014-09-07 18:57:58 +00001142 if (Value *V = SimplifySDivInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sands771e82a2011-01-28 16:51:11 +00001143 return ReplaceInstUsesWith(I, V);
1144
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001145 // Handle the integer div common cases
1146 if (Instruction *Common = commonIDivTransforms(I))
1147 return Common;
1148
Benjamin Kramer72196f32014-01-19 15:24:22 +00001149 // sdiv X, -1 == -X
1150 if (match(Op1, m_AllOnes()))
1151 return BinaryOperator::CreateNeg(Op0);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001152
Benjamin Kramer72196f32014-01-19 15:24:22 +00001153 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001154 // sdiv X, C --> ashr exact X, log2(C)
1155 if (I.isExact() && RHS->getValue().isNonNegative() &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001156 RHS->getValue().isPowerOf2()) {
1157 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1158 RHS->getValue().exactLogBase2());
Chris Lattner6b657ae2011-02-10 05:36:31 +00001159 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001160 }
Benjamin Kramer72196f32014-01-19 15:24:22 +00001161 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001162
Benjamin Kramer72196f32014-01-19 15:24:22 +00001163 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
David Majnemerf28e2a42014-07-02 06:42:13 +00001164 // X/INT_MIN -> X == INT_MIN
1165 if (RHS->isMinSignedValue())
1166 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1167
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001168 // -X/C --> X/-C provided the negation doesn't overflow.
David Majnemerfa4699e2014-11-22 20:00:34 +00001169 Value *X;
1170 if (match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1171 auto *BO = BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(RHS));
1172 BO->setIsExact(I.isExact());
1173 return BO;
1174 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001175 }
1176
1177 // If the sign bits of both operands are zero (i.e. we can prove they are
1178 // unsigned inputs), turn this into a udiv.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001179 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001180 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001181 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1182 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001183 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
David Majnemerec6e4812014-11-22 20:00:38 +00001184 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1185 BO->setIsExact(I.isExact());
1186 return BO;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001187 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001188
David Majnemerfb380552014-11-22 20:00:41 +00001189 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, AT, &I, DT)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001190 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1191 // Safe because the only negative value (1 << Y) can take on is
1192 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1193 // the sign bit set.
David Majnemerfb380552014-11-22 20:00:41 +00001194 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1195 BO->setIsExact(I.isExact());
1196 return BO;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001197 }
1198 }
1199 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001200
Craig Topperf40110f2014-04-25 05:29:35 +00001201 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001202}
1203
Shuxin Yang320f52a2013-01-14 22:48:41 +00001204/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1205/// FP value and:
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001206/// 1) 1/C is exact, or
Shuxin Yang320f52a2013-01-14 22:48:41 +00001207/// 2) reciprocal is allowed.
Sylvestre Ledru149e2812013-05-14 23:36:24 +00001208/// If the conversion was successful, the simplified expression "X * 1/C" is
Shuxin Yang320f52a2013-01-14 22:48:41 +00001209/// returned; otherwise, NULL is returned.
1210///
Suyog Sardaea205512014-10-07 11:56:06 +00001211static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
Shuxin Yang320f52a2013-01-14 22:48:41 +00001212 bool AllowReciprocal) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001213 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001214 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001215
1216 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001217 APFloat Reciprocal(FpVal.getSemantics());
1218 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001219
Michael Gottesman3cb77ab2013-06-19 21:23:18 +00001220 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001221 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1222 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1223 Cvt = !Reciprocal.isDenormal();
1224 }
1225
1226 if (!Cvt)
Craig Topperf40110f2014-04-25 05:29:35 +00001227 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001228
1229 ConstantFP *R;
1230 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1231 return BinaryOperator::CreateFMul(Dividend, R);
1232}
1233
Frits van Bommel2a559512011-01-29 17:50:27 +00001234Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1235 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1236
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001237 if (Value *V = SimplifyVectorOp(I))
1238 return ReplaceInstUsesWith(I, V);
1239
Hal Finkel60db0582014-09-07 18:57:58 +00001240 if (Value *V = SimplifyFDivInst(Op0, Op1, DL, TLI, DT, AT))
Frits van Bommel2a559512011-01-29 17:50:27 +00001241 return ReplaceInstUsesWith(I, V);
1242
Stephen Lina9b57f62013-07-20 07:13:13 +00001243 if (isa<Constant>(Op0))
1244 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1245 if (Instruction *R = FoldOpIntoSelect(I, SI))
1246 return R;
1247
Shuxin Yang320f52a2013-01-14 22:48:41 +00001248 bool AllowReassociate = I.hasUnsafeAlgebra();
1249 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001250
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001251 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001252 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1253 if (Instruction *R = FoldOpIntoSelect(I, SI))
1254 return R;
1255
Shuxin Yang320f52a2013-01-14 22:48:41 +00001256 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +00001257 Constant *C1 = nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001258 Constant *C2 = Op1C;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001259 Value *X;
Craig Topperf40110f2014-04-25 05:29:35 +00001260 Instruction *Res = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001261
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001262 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001263 // (X*C1)/C2 => X * (C1/C2)
1264 //
1265 Constant *C = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001266 if (isNormalFp(C))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001267 Res = BinaryOperator::CreateFMul(X, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001268 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001269 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1270 //
1271 Constant *C = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001272 if (isNormalFp(C)) {
1273 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001274 if (!Res)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001275 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001276 }
1277 }
1278
1279 if (Res) {
1280 Res->setFastMathFlags(I.getFastMathFlags());
1281 return Res;
1282 }
1283 }
1284
1285 // X / C => X * 1/C
Owen Anderson4557a152014-01-16 21:07:52 +00001286 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1287 T->copyFastMathFlags(&I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001288 return T;
Owen Anderson4557a152014-01-16 21:07:52 +00001289 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001290
Craig Topperf40110f2014-04-25 05:29:35 +00001291 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001292 }
1293
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001294 if (AllowReassociate && isa<Constant>(Op0)) {
1295 Constant *C1 = cast<Constant>(Op0), *C2;
Craig Topperf40110f2014-04-25 05:29:35 +00001296 Constant *Fold = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001297 Value *X;
1298 bool CreateDiv = true;
1299
1300 // C1 / (X*C2) => (C1/C2) / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001301 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001302 Fold = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001303 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001304 // C1 / (X/C2) => (C1*C2) / X
1305 Fold = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001306 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001307 // C1 / (C2/X) => (C1/C2) * X
1308 Fold = ConstantExpr::getFDiv(C1, C2);
1309 CreateDiv = false;
1310 }
1311
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001312 if (Fold && isNormalFp(Fold)) {
1313 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1314 : BinaryOperator::CreateFMul(X, Fold);
1315 R->setFastMathFlags(I.getFastMathFlags());
1316 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001317 }
Craig Topperf40110f2014-04-25 05:29:35 +00001318 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001319 }
1320
1321 if (AllowReassociate) {
1322 Value *X, *Y;
Craig Topperf40110f2014-04-25 05:29:35 +00001323 Value *NewInst = nullptr;
1324 Instruction *SimpR = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001325
1326 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1327 // (X/Y) / Z => X / (Y*Z)
1328 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001329 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001330 NewInst = Builder->CreateFMul(Y, Op1);
Owen Anderson1664dc82014-01-20 07:44:53 +00001331 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1332 FastMathFlags Flags = I.getFastMathFlags();
1333 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1334 RI->setFastMathFlags(Flags);
1335 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001336 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1337 }
1338 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1339 // Z / (X/Y) => Z*Y / X
1340 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001341 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001342 NewInst = Builder->CreateFMul(Op0, Y);
Owen Anderson1664dc82014-01-20 07:44:53 +00001343 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1344 FastMathFlags Flags = I.getFastMathFlags();
1345 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1346 RI->setFastMathFlags(Flags);
1347 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001348 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1349 }
1350 }
1351
1352 if (NewInst) {
1353 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1354 T->setDebugLoc(I.getDebugLoc());
1355 SimpR->setFastMathFlags(I.getFastMathFlags());
1356 return SimpR;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001357 }
1358 }
1359
Craig Topperf40110f2014-04-25 05:29:35 +00001360 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001361}
1362
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001363/// This function implements the transforms common to both integer remainder
1364/// instructions (urem and srem). It is called by the visitors to those integer
1365/// remainder instructions.
1366/// @brief Common integer remainder transforms
1367Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1368 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1369
Chris Lattner7c99f192011-05-22 18:18:41 +00001370 // The RHS is known non-zero.
Hal Finkel60db0582014-09-07 18:57:58 +00001371 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, &I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +00001372 I.setOperand(1, V);
1373 return &I;
1374 }
1375
Duncan Sandsa3e36992011-05-02 16:27:02 +00001376 // Handle cases involving: rem X, (select Cond, Y, Z)
1377 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1378 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001379
Benjamin Kramer72196f32014-01-19 15:24:22 +00001380 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001381 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1382 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1383 if (Instruction *R = FoldOpIntoSelect(I, SI))
1384 return R;
1385 } else if (isa<PHINode>(Op0I)) {
1386 if (Instruction *NV = FoldOpIntoPhi(I))
1387 return NV;
1388 }
1389
1390 // See if we can fold away this rem instruction.
1391 if (SimplifyDemandedInstructionBits(I))
1392 return &I;
1393 }
1394 }
1395
Craig Topperf40110f2014-04-25 05:29:35 +00001396 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001397}
1398
1399Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1400 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1401
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001402 if (Value *V = SimplifyVectorOp(I))
1403 return ReplaceInstUsesWith(I, V);
1404
Hal Finkel60db0582014-09-07 18:57:58 +00001405 if (Value *V = SimplifyURemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001406 return ReplaceInstUsesWith(I, V);
1407
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001408 if (Instruction *common = commonIRemTransforms(I))
1409 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001410
David Majnemer6c30f492013-05-12 00:07:05 +00001411 // (zext A) urem (zext B) --> zext (A urem B)
1412 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1413 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1414 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1415 I.getType());
1416
David Majnemer470b0772013-05-11 09:01:28 +00001417 // X urem Y -> X and Y-1, where Y is a power of 2,
Hal Finkel60db0582014-09-07 18:57:58 +00001418 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, AT, &I, DT)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001419 Constant *N1 = Constant::getAllOnesValue(I.getType());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001420 Value *Add = Builder->CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001421 return BinaryOperator::CreateAnd(Op0, Add);
1422 }
1423
Nick Lewycky7459be62013-07-13 01:16:47 +00001424 // 1 urem X -> zext(X != 1)
1425 if (match(Op0, m_One())) {
1426 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1427 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1428 return ReplaceInstUsesWith(I, Ext);
1429 }
1430
Craig Topperf40110f2014-04-25 05:29:35 +00001431 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001432}
1433
1434Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1435 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1436
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001437 if (Value *V = SimplifyVectorOp(I))
1438 return ReplaceInstUsesWith(I, V);
1439
Hal Finkel60db0582014-09-07 18:57:58 +00001440 if (Value *V = SimplifySRemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001441 return ReplaceInstUsesWith(I, V);
1442
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001443 // Handle the integer rem common cases
1444 if (Instruction *Common = commonIRemTransforms(I))
1445 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001446
David Majnemerdb077302014-10-13 22:37:51 +00001447 {
1448 const APInt *Y;
1449 // X % -Y -> X % Y
1450 if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001451 Worklist.AddValue(I.getOperand(1));
David Majnemerdb077302014-10-13 22:37:51 +00001452 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001453 return &I;
1454 }
David Majnemerdb077302014-10-13 22:37:51 +00001455 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001456
1457 // If the sign bits of both operands are zero (i.e. we can prove they are
1458 // unsigned inputs), turn this into a urem.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001459 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001460 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001461 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1462 MaskedValueIsZero(Op0, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001463 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001464 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1465 }
1466 }
1467
1468 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001469 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1470 Constant *C = cast<Constant>(Op1);
1471 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001472
1473 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001474 bool hasMissing = false;
1475 for (unsigned i = 0; i != VWidth; ++i) {
1476 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001477 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001478 hasMissing = true;
1479 break;
1480 }
1481
1482 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001483 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001484 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001485 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001486
Chris Lattner0256be92012-01-27 03:08:05 +00001487 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001488 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001489 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001490 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001491 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001492 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001493 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001494 }
1495 }
1496
1497 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001498 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001499 Worklist.AddValue(I.getOperand(1));
1500 I.setOperand(1, NewRHSV);
1501 return &I;
1502 }
1503 }
1504 }
1505
Craig Topperf40110f2014-04-25 05:29:35 +00001506 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001507}
1508
1509Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001510 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001511
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001512 if (Value *V = SimplifyVectorOp(I))
1513 return ReplaceInstUsesWith(I, V);
1514
Hal Finkel60db0582014-09-07 18:57:58 +00001515 if (Value *V = SimplifyFRemInst(Op0, Op1, DL, TLI, DT, AT))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001516 return ReplaceInstUsesWith(I, V);
1517
1518 // Handle cases involving: rem X, (select Cond, Y, Z)
1519 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1520 return &I;
1521
Craig Topperf40110f2014-04-25 05:29:35 +00001522 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001523}