blob: bb3d9281edb828cad4f962d98b7f13e3a8bbb2a9 [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
David Majnemer135ca402015-09-06 06:49:59 +000098 // Bail if we will divide by zero.
99 if (C2.isMinValue())
100 return false;
101
102 // Bail if we would divide INT_MIN by -1.
103 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnesValue())
104 return false;
105
David Majnemerf9a095d2014-08-16 08:55:06 +0000106 APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
107 if (IsSigned)
108 APInt::sdivrem(C1, C2, Quotient, Remainder);
109 else
110 APInt::udivrem(C1, C2, Quotient, Remainder);
111
112 return Remainder.isMinValue();
113}
114
Rafael Espindola65281bf2013-05-31 14:27:15 +0000115/// \brief A helper routine of InstCombiner::visitMul().
116///
117/// If C is a vector of known powers of 2, then this function returns
118/// a new vector obtained from C replacing each element with its logBase2.
119/// Return a null pointer otherwise.
120static Constant *getLogBase2Vector(ConstantDataVector *CV) {
121 const APInt *IVal;
122 SmallVector<Constant *, 4> Elts;
123
124 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
125 Constant *Elt = CV->getElementAsConstant(I);
126 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
Craig Topperf40110f2014-04-25 05:29:35 +0000127 return nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000128 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
129 }
130
131 return ConstantVector::get(Elts);
132}
133
David Majnemer54c2ca22014-12-26 09:10:14 +0000134/// \brief Return true if we can prove that:
135/// (mul LHS, RHS) === (mul nsw LHS, RHS)
136bool InstCombiner::WillNotOverflowSignedMul(Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000137 Instruction &CxtI) {
David Majnemer54c2ca22014-12-26 09:10:14 +0000138 // Multiplying n * m significant bits yields a result of n + m significant
139 // bits. If the total number of significant bits does not exceed the
140 // result bit width (minus 1), there is no overflow.
141 // This means if we have enough leading sign bits in the operands
142 // we can guarantee that the result does not overflow.
143 // Ref: "Hacker's Delight" by Henry Warren
144 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
145
146 // Note that underestimating the number of sign bits gives a more
147 // conservative answer.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000148 unsigned SignBits =
149 ComputeNumSignBits(LHS, 0, &CxtI) + ComputeNumSignBits(RHS, 0, &CxtI);
David Majnemer54c2ca22014-12-26 09:10:14 +0000150
151 // First handle the easy case: if we have enough sign bits there's
152 // definitely no overflow.
153 if (SignBits > BitWidth + 1)
154 return true;
155
156 // There are two ambiguous cases where there can be no overflow:
157 // SignBits == BitWidth + 1 and
158 // SignBits == BitWidth
159 // The second case is difficult to check, therefore we only handle the
160 // first case.
161 if (SignBits == BitWidth + 1) {
162 // It overflows only when both arguments are negative and the true
163 // product is exactly the minimum negative number.
164 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
165 // For simplicity we just check if at least one side is not negative.
166 bool LHSNonNegative, LHSNegative;
167 bool RHSNonNegative, RHSNegative;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000168 ComputeSignBit(LHS, LHSNonNegative, LHSNegative, /*Depth=*/0, &CxtI);
169 ComputeSignBit(RHS, RHSNonNegative, RHSNegative, /*Depth=*/0, &CxtI);
David Majnemer54c2ca22014-12-26 09:10:14 +0000170 if (LHSNonNegative || RHSNonNegative)
171 return true;
172 }
173 return false;
174}
175
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000176Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000177 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000178 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
179
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000180 if (Value *V = SimplifyVectorOp(I))
181 return ReplaceInstUsesWith(I, V);
182
Chandler Carruth66b31302015-01-04 12:03:27 +0000183 if (Value *V = SimplifyMulInst(Op0, Op1, DL, TLI, DT, AC))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000184 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000185
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000186 if (Value *V = SimplifyUsingDistributiveLaws(I))
187 return ReplaceInstUsesWith(I, V);
188
David Majnemer027bc802014-11-22 04:52:38 +0000189 // X * -1 == 0 - X
190 if (match(Op1, m_AllOnes())) {
191 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
192 if (I.hasNoSignedWrap())
193 BO->setHasNoSignedWrap();
194 return BO;
195 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000196
Rafael Espindola65281bf2013-05-31 14:27:15 +0000197 // Also allow combining multiply instructions on vectors.
198 {
199 Value *NewOp;
200 Constant *C1, *C2;
201 const APInt *IVal;
202 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
203 m_Constant(C1))) &&
David Majnemerfd4a6d22014-11-22 04:52:52 +0000204 match(C1, m_APInt(IVal))) {
205 // ((X << C2)*C1) == (X * (C1 << C2))
206 Constant *Shl = ConstantExpr::getShl(C1, C2);
207 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
208 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
209 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
210 BO->setHasNoUnsignedWrap();
211 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
212 Shl->isNotMinSignedValue())
213 BO->setHasNoSignedWrap();
214 return BO;
215 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000216
Rafael Espindola65281bf2013-05-31 14:27:15 +0000217 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000218 Constant *NewCst = nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000219 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
220 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
221 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
222 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
223 // Replace X*(2^C) with X << C, where C is a vector of known
224 // constant powers of 2.
225 NewCst = getLogBase2Vector(CV);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000226
Rafael Espindola65281bf2013-05-31 14:27:15 +0000227 if (NewCst) {
David Majnemer45951a62015-04-18 04:41:30 +0000228 unsigned Width = NewCst->getType()->getPrimitiveSizeInBits();
Rafael Espindola65281bf2013-05-31 14:27:15 +0000229 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000230
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000231 if (I.hasNoUnsignedWrap())
232 Shl->setHasNoUnsignedWrap();
David Majnemer45951a62015-04-18 04:41:30 +0000233 if (I.hasNoSignedWrap()) {
234 uint64_t V;
235 if (match(NewCst, m_ConstantInt(V)) && V != Width - 1)
236 Shl->setHasNoSignedWrap();
237 }
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000238
Rafael Espindola65281bf2013-05-31 14:27:15 +0000239 return Shl;
240 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000241 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000242 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000243
Rafael Espindola65281bf2013-05-31 14:27:15 +0000244 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Stuart Hastings23804832011-06-01 16:42:47 +0000245 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
246 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
247 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000248 {
249 const APInt & Val = CI->getValue();
250 const APInt &PosVal = Val.abs();
251 if (Val.isNegative() && PosVal.isPowerOf2()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000252 Value *X = nullptr, *Y = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000253 if (Op0->hasOneUse()) {
254 ConstantInt *C1;
Craig Topperf40110f2014-04-25 05:29:35 +0000255 Value *Sub = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000256 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
257 Sub = Builder->CreateSub(X, Y, "suba");
258 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
259 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
260 if (Sub)
261 return
262 BinaryOperator::CreateMul(Sub,
263 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000264 }
265 }
266 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000267 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000268
Chris Lattner6b657ae2011-02-10 05:36:31 +0000269 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000270 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000271 // Try to fold constant mul into select arguments.
272 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
273 if (Instruction *R = FoldOpIntoSelect(I, SI))
274 return R;
275
276 if (isa<PHINode>(Op0))
277 if (Instruction *NV = FoldOpIntoPhi(I))
278 return NV;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000279
280 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
281 {
282 Value *X;
283 Constant *C1;
284 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
David Majnemer6cf6c052014-06-19 07:14:33 +0000285 Value *Mul = Builder->CreateMul(C1, Op1);
286 // Only go forward with the transform if C1*CI simplifies to a tidier
287 // constant.
288 if (!match(Mul, m_Mul(m_Value(), m_Value())))
289 return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
Benjamin Kramer72196f32014-01-19 15:24:22 +0000290 }
291 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000292 }
293
David Majnemer8279a7502014-11-22 07:25:19 +0000294 if (Value *Op0v = dyn_castNegVal(Op0)) { // -X * -Y = X*Y
295 if (Value *Op1v = dyn_castNegVal(Op1)) {
296 BinaryOperator *BO = BinaryOperator::CreateMul(Op0v, Op1v);
297 if (I.hasNoSignedWrap() &&
298 match(Op0, m_NSWSub(m_Value(), m_Value())) &&
299 match(Op1, m_NSWSub(m_Value(), m_Value())))
300 BO->setHasNoSignedWrap();
301 return BO;
302 }
303 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000304
305 // (X / Y) * Y = X - (X % Y)
306 // (X / Y) * -Y = (X % Y) - X
307 {
308 Value *Op1C = Op1;
309 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
310 if (!BO ||
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000311 (BO->getOpcode() != Instruction::UDiv &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000312 BO->getOpcode() != Instruction::SDiv)) {
313 Op1C = Op0;
314 BO = dyn_cast<BinaryOperator>(Op1);
315 }
316 Value *Neg = dyn_castNegVal(Op1C);
317 if (BO && BO->hasOneUse() &&
318 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
319 (BO->getOpcode() == Instruction::UDiv ||
320 BO->getOpcode() == Instruction::SDiv)) {
321 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
322
Chris Lattner35315d02011-02-06 21:44:57 +0000323 // If the division is exact, X % Y is zero, so we end up with X or -X.
324 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000325 if (SDiv->isExact()) {
326 if (Op1BO == Op1C)
327 return ReplaceInstUsesWith(I, Op0BO);
328 return BinaryOperator::CreateNeg(Op0BO);
329 }
330
331 Value *Rem;
332 if (BO->getOpcode() == Instruction::UDiv)
333 Rem = Builder->CreateURem(Op0BO, Op1BO);
334 else
335 Rem = Builder->CreateSRem(Op0BO, Op1BO);
336 Rem->takeName(BO);
337
338 if (Op1BO == Op1C)
339 return BinaryOperator::CreateSub(Op0BO, Rem);
340 return BinaryOperator::CreateSub(Rem, Op0BO);
341 }
342 }
343
344 /// i1 mul -> i1 and.
Benjamin Kramer72196f32014-01-19 15:24:22 +0000345 if (I.getType()->getScalarType()->isIntegerTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000346 return BinaryOperator::CreateAnd(Op0, Op1);
347
348 // X*(1 << Y) --> X << Y
349 // (1 << Y)*X --> X << Y
350 {
351 Value *Y;
David Majnemer546f8102014-11-22 08:57:02 +0000352 BinaryOperator *BO = nullptr;
353 bool ShlNSW = false;
354 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
355 BO = BinaryOperator::CreateShl(Op1, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000356 ShlNSW = cast<ShlOperator>(Op0)->hasNoSignedWrap();
David Majnemer8e6f6a92014-11-24 16:41:13 +0000357 } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
David Majnemer546f8102014-11-22 08:57:02 +0000358 BO = BinaryOperator::CreateShl(Op0, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000359 ShlNSW = cast<ShlOperator>(Op1)->hasNoSignedWrap();
David Majnemer546f8102014-11-22 08:57:02 +0000360 }
361 if (BO) {
362 if (I.hasNoUnsignedWrap())
363 BO->setHasNoUnsignedWrap();
364 if (I.hasNoSignedWrap() && ShlNSW)
365 BO->setHasNoSignedWrap();
366 return BO;
367 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000368 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000369
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000370 // If one of the operands of the multiply is a cast from a boolean value, then
371 // we know the bool is either zero or one, so this is a 'masking' multiply.
372 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands19d0b472010-02-16 11:11:14 +0000373 if (!I.getType()->isVectorTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000374 // -2 is "-1 << 1" so it is all bits set except the low one.
375 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000376
Craig Topperf40110f2014-04-25 05:29:35 +0000377 Value *BoolCast = nullptr, *OtherOp = nullptr;
Hal Finkel60db0582014-09-07 18:57:58 +0000378 if (MaskedValueIsZero(Op0, Negative2, 0, &I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000379 BoolCast = Op0, OtherOp = Op1;
Hal Finkel60db0582014-09-07 18:57:58 +0000380 else if (MaskedValueIsZero(Op1, Negative2, 0, &I))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000381 BoolCast = Op1, OtherOp = Op0;
382
383 if (BoolCast) {
384 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000385 BoolCast);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000386 return BinaryOperator::CreateAnd(V, OtherOp);
387 }
388 }
389
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000390 if (!I.hasNoSignedWrap() && WillNotOverflowSignedMul(Op0, Op1, I)) {
David Majnemer54c2ca22014-12-26 09:10:14 +0000391 Changed = true;
392 I.setHasNoSignedWrap(true);
393 }
394
David Majnemer491331a2015-01-02 07:29:43 +0000395 if (!I.hasNoUnsignedWrap() &&
396 computeOverflowForUnsignedMul(Op0, Op1, &I) ==
397 OverflowResult::NeverOverflows) {
David Majnemerb1296ec2014-12-26 09:50:35 +0000398 Changed = true;
399 I.setHasNoUnsignedWrap(true);
400 }
401
Craig Topperf40110f2014-04-25 05:29:35 +0000402 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000403}
404
Sanjay Patel17045f72014-10-14 00:33:23 +0000405/// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
Pedro Artigas993acd02012-11-30 22:07:05 +0000406static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Sanjay Patel17045f72014-10-14 00:33:23 +0000407 if (!Op->hasOneUse())
408 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000409
Sanjay Patel17045f72014-10-14 00:33:23 +0000410 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
411 if (!II)
412 return;
413 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
414 return;
415 Log2 = II;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000416
Sanjay Patel17045f72014-10-14 00:33:23 +0000417 Value *OpLog2Of = II->getArgOperand(0);
418 if (!OpLog2Of->hasOneUse())
419 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000420
Sanjay Patel17045f72014-10-14 00:33:23 +0000421 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
422 if (!I)
423 return;
424 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
425 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000426
Sanjay Patel17045f72014-10-14 00:33:23 +0000427 if (match(I->getOperand(0), m_SpecificFP(0.5)))
428 Y = I->getOperand(1);
429 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
430 Y = I->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000431}
Pedro Artigas993acd02012-11-30 22:07:05 +0000432
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000433static bool isFiniteNonZeroFp(Constant *C) {
434 if (C->getType()->isVectorTy()) {
435 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
436 ++I) {
Michael Kupersteinbcb26d62015-03-05 08:38:57 +0000437 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000438 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
439 return false;
440 }
441 return true;
442 }
443
444 return isa<ConstantFP>(C) &&
445 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
446}
447
448static bool isNormalFp(Constant *C) {
449 if (C->getType()->isVectorTy()) {
450 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
451 ++I) {
Michael Kupersteinbcb26d62015-03-05 08:38:57 +0000452 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000453 if (!CFP || !CFP->getValueAPF().isNormal())
454 return false;
455 }
456 return true;
457 }
458
459 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
460}
461
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000462/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
463/// true iff the given value is FMul or FDiv with one and only one operand
464/// being a normal constant (i.e. not Zero/NaN/Infinity).
465static bool isFMulOrFDivWithConstant(Value *V) {
466 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000467 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yang80138662013-01-07 22:41:28 +0000468 I->getOpcode() != Instruction::FDiv))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000469 return false;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000470
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000471 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
472 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000473
474 if (C0 && C1)
475 return false;
476
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000477 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000478}
479
480/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
481/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
482/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000483/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000484/// resulting expression. Note that this function could return NULL in
485/// case the constants cannot be folded into a normal floating-point.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000486///
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000487Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yang80138662013-01-07 22:41:28 +0000488 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000489 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
490
491 Value *Opnd0 = FMulOrDiv->getOperand(0);
492 Value *Opnd1 = FMulOrDiv->getOperand(1);
493
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000494 Constant *C0 = dyn_cast<Constant>(Opnd0);
495 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000496
Craig Topperf40110f2014-04-25 05:29:35 +0000497 BinaryOperator *R = nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000498
499 // (X * C0) * C => X * (C0*C)
500 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
501 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000502 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000503 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
504 } else {
505 if (C0) {
506 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000507 if (FMulOrDiv->hasOneUse()) {
508 // It would otherwise introduce another div.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000509 Constant *F = ConstantExpr::getFMul(C0, C);
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000510 if (isNormalFp(F))
511 R = BinaryOperator::CreateFDiv(F, Opnd1);
512 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000513 } else {
514 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000515 Constant *F = ConstantExpr::getFDiv(C, C1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000516 if (isNormalFp(F)) {
517 R = BinaryOperator::CreateFMul(Opnd0, F);
518 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000519 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000520 Constant *F = ConstantExpr::getFDiv(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000521 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000522 R = BinaryOperator::CreateFDiv(Opnd0, F);
523 }
524 }
525 }
526
527 if (R) {
528 R->setHasUnsafeAlgebra(true);
529 InsertNewInstWith(R, *InsertBefore);
530 }
531
532 return R;
533}
534
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000535Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000536 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000537 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
538
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000539 if (Value *V = SimplifyVectorOp(I))
540 return ReplaceInstUsesWith(I, V);
541
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000542 if (isa<Constant>(Op0))
543 std::swap(Op0, Op1);
544
Chandler Carruth66b31302015-01-04 12:03:27 +0000545 if (Value *V =
546 SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL, TLI, DT, AC))
Michael Ilsemand5787be2012-12-12 00:28:32 +0000547 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000548
Shuxin Yange8227452013-01-15 21:09:32 +0000549 bool AllowReassociate = I.hasUnsafeAlgebra();
550
Michael Ilsemand5787be2012-12-12 00:28:32 +0000551 // Simplify mul instructions with a constant RHS.
552 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000553 // Try to fold constant mul into select arguments.
554 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
555 if (Instruction *R = FoldOpIntoSelect(I, SI))
556 return R;
557
558 if (isa<PHINode>(Op0))
559 if (Instruction *NV = FoldOpIntoPhi(I))
560 return NV;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000561
Owen Andersonf74cfe02014-01-16 20:36:42 +0000562 // (fmul X, -1.0) --> (fsub -0.0, X)
Benjamin Kramerfea9ac92014-01-18 16:43:14 +0000563 if (match(Op1, m_SpecificFP(-1.0))) {
564 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
565 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000566 RI->copyFastMathFlags(&I);
567 return RI;
568 }
569
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000570 Constant *C = cast<Constant>(Op1);
571 if (AllowReassociate && isFiniteNonZeroFp(C)) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000572 // Let MDC denote an expression in one of these forms:
573 // X * C, C/X, X/C, where C is a constant.
574 //
575 // Try to simplify "MDC * Constant"
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000576 if (isFMulOrFDivWithConstant(Op0))
577 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000578 return ReplaceInstUsesWith(I, V);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000579
Quentin Colombete684a6d2013-02-28 21:12:40 +0000580 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000581 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
582 if (FAddSub &&
583 (FAddSub->getOpcode() == Instruction::FAdd ||
584 FAddSub->getOpcode() == Instruction::FSub)) {
585 Value *Opnd0 = FAddSub->getOperand(0);
586 Value *Opnd1 = FAddSub->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000587 Constant *C0 = dyn_cast<Constant>(Opnd0);
588 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000589 bool Swap = false;
590 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000591 std::swap(C0, C1);
592 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000593 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000594 }
595
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000596 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000597 Value *M1 = ConstantExpr::getFMul(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000598 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000599 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
Craig Topperf40110f2014-04-25 05:29:35 +0000600 nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000601 if (M0 && M1) {
602 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
603 std::swap(M0, M1);
604
Benjamin Kramer67485762013-09-30 15:39:59 +0000605 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
606 ? BinaryOperator::CreateFAdd(M0, M1)
607 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000608 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000609 return RI;
610 }
611 }
612 }
613 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000614 }
615
Sanjay Patel12d1ce52014-10-02 21:10:54 +0000616 // sqrt(X) * sqrt(X) -> X
617 if (AllowReassociate && (Op0 == Op1))
618 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0))
619 if (II->getIntrinsicID() == Intrinsic::sqrt)
620 return ReplaceInstUsesWith(I, II->getOperand(0));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000621
Pedro Artigasd8795042012-11-30 19:09:41 +0000622 // Under unsafe algebra do:
623 // X * log2(0.5*Y) = X*log2(Y) - X
Sanjay Patelb41d4612014-10-02 15:20:45 +0000624 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +0000625 Value *OpX = nullptr;
626 Value *OpY = nullptr;
Pedro Artigasd8795042012-11-30 19:09:41 +0000627 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000628 detectLog2OfHalf(Op0, OpY, Log2);
629 if (OpY) {
630 OpX = Op1;
631 } else {
632 detectLog2OfHalf(Op1, OpY, Log2);
633 if (OpY) {
634 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000635 }
636 }
637 // if pattern detected emit alternate sequence
638 if (OpX && OpY) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000639 BuilderTy::FastMathFlagGuard Guard(*Builder);
640 Builder->SetFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000641 Log2->setArgOperand(0, OpY);
642 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
Benjamin Kramer67485762013-09-30 15:39:59 +0000643 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
644 FSub->takeName(&I);
645 return ReplaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000646 }
647 }
648
Shuxin Yange8227452013-01-15 21:09:32 +0000649 // Handle symmetric situation in a 2-iteration loop
650 Value *Opnd0 = Op0;
651 Value *Opnd1 = Op1;
652 for (int i = 0; i < 2; i++) {
653 bool IgnoreZeroSign = I.hasNoSignedZeros();
654 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000655 BuilderTy::FastMathFlagGuard Guard(*Builder);
656 Builder->SetFastMathFlags(I.getFastMathFlags());
657
Shuxin Yange8227452013-01-15 21:09:32 +0000658 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
659 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000660
Shuxin Yange8227452013-01-15 21:09:32 +0000661 // -X * -Y => X*Y
Owen Andersone8537fc2014-01-16 20:59:41 +0000662 if (N1) {
663 Value *FMul = Builder->CreateFMul(N0, N1);
664 FMul->takeName(&I);
665 return ReplaceInstUsesWith(I, FMul);
666 }
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000667
Shuxin Yange8227452013-01-15 21:09:32 +0000668 if (Opnd0->hasOneUse()) {
669 // -X * Y => -(X*Y) (Promote negation as high as possible)
670 Value *T = Builder->CreateFMul(N0, Opnd1);
Benjamin Kramer67485762013-09-30 15:39:59 +0000671 Value *Neg = Builder->CreateFNeg(T);
672 Neg->takeName(&I);
673 return ReplaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000674 }
675 }
Shuxin Yange8227452013-01-15 21:09:32 +0000676
677 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000678 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000679 // 1) to form a power expression (of X).
680 // 2) potentially shorten the critical path: After transformation, the
681 // latency of the instruction Y is amortized by the expression of X*X,
682 // and therefore Y is in a "less critical" position compared to what it
683 // was before the transformation.
684 //
685 if (AllowReassociate) {
686 Value *Opnd0_0, *Opnd0_1;
687 if (Opnd0->hasOneUse() &&
688 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000689 Value *Y = nullptr;
Shuxin Yange8227452013-01-15 21:09:32 +0000690 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
691 Y = Opnd0_1;
692 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
693 Y = Opnd0_0;
694
695 if (Y) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000696 BuilderTy::FastMathFlagGuard Guard(*Builder);
697 Builder->SetFastMathFlags(I.getFastMathFlags());
698 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
Shuxin Yange8227452013-01-15 21:09:32 +0000699
Benjamin Kramer67485762013-09-30 15:39:59 +0000700 Value *R = Builder->CreateFMul(T, Y);
701 R->takeName(&I);
702 return ReplaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000703 }
704 }
705 }
706
707 if (!isa<Constant>(Op1))
708 std::swap(Opnd0, Opnd1);
709 else
710 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000711 }
712
Craig Topperf40110f2014-04-25 05:29:35 +0000713 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000714}
715
716/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
717/// instruction.
718bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
719 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000720
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000721 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
722 int NonNullOperand = -1;
723 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
724 if (ST->isNullValue())
725 NonNullOperand = 2;
726 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
727 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
728 if (ST->isNullValue())
729 NonNullOperand = 1;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000730
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000731 if (NonNullOperand == -1)
732 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000733
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000734 Value *SelectCond = SI->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000735
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000736 // Change the div/rem to use 'Y' instead of the select.
737 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000738
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000739 // Okay, we know we replace the operand of the div/rem with 'Y' with no
740 // problem. However, the select, or the condition of the select may have
741 // multiple uses. Based on our knowledge that the operand must be non-zero,
742 // propagate the known value for the select into other uses of it, and
743 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000744
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000745 // If the select and condition only have a single use, don't bother with this,
746 // early exit.
747 if (SI->use_empty() && SelectCond->hasOneUse())
748 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000749
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000750 // Scan the current block backward, looking for other uses of SI.
751 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000752
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000753 while (BBI != BBFront) {
754 --BBI;
755 // If we found a call to a function, we can't assume it will return, so
756 // information from below it cannot be propagated above it.
757 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
758 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000759
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000760 // Replace uses of the select or its condition with the known values.
761 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
762 I != E; ++I) {
763 if (*I == SI) {
764 *I = SI->getOperand(NonNullOperand);
765 Worklist.Add(BBI);
766 } else if (*I == SelectCond) {
Jakub Staszak96ff4d62013-06-06 23:34:59 +0000767 *I = Builder->getInt1(NonNullOperand == 1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000768 Worklist.Add(BBI);
769 }
770 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000771
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000772 // If we past the instruction, quit looking for it.
773 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000774 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000775 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000776 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000777
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000778 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000779 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000780 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000781
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000782 }
783 return true;
784}
785
786
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000787/// This function implements the transforms common to both integer division
788/// instructions (udiv and sdiv). It is called by the visitors to those integer
789/// division instructions.
790/// @brief Common integer divide transforms
791Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
792 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
793
Chris Lattner7c99f192011-05-22 18:18:41 +0000794 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000795 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +0000796 I.setOperand(1, V);
797 return &I;
798 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000799
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000800 // Handle cases involving: [su]div X, (select Cond, Y, Z)
801 // This does not apply for fdiv.
802 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
803 return &I;
804
David Majnemer27adb122014-10-12 08:34:24 +0000805 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
806 const APInt *C2;
807 if (match(Op1, m_APInt(C2))) {
David Majnemerf9a095d2014-08-16 08:55:06 +0000808 Value *X;
David Majnemer27adb122014-10-12 08:34:24 +0000809 const APInt *C1;
810 bool IsSigned = I.getOpcode() == Instruction::SDiv;
David Majnemerf9a095d2014-08-16 08:55:06 +0000811
David Majnemer27adb122014-10-12 08:34:24 +0000812 // (X / C1) / C2 -> X / (C1*C2)
813 if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
814 (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
815 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
816 if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
817 return BinaryOperator::Create(I.getOpcode(), X,
818 ConstantInt::get(I.getType(), Product));
819 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000820
David Majnemer27adb122014-10-12 08:34:24 +0000821 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
822 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
823 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
824
825 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
826 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
827 BinaryOperator *BO = BinaryOperator::Create(
828 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
829 BO->setIsExact(I.isExact());
830 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000831 }
832
David Majnemer27adb122014-10-12 08:34:24 +0000833 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
834 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
835 BinaryOperator *BO = BinaryOperator::Create(
836 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
837 BO->setHasNoUnsignedWrap(
838 !IsSigned &&
839 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
840 BO->setHasNoSignedWrap(
841 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
842 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000843 }
844 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000845
David Majnemer27adb122014-10-12 08:34:24 +0000846 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
847 *C1 != C1->getBitWidth() - 1) ||
848 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
849 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
850 APInt C1Shifted = APInt::getOneBitSet(
851 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
852
853 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
854 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
855 BinaryOperator *BO = BinaryOperator::Create(
856 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
857 BO->setIsExact(I.isExact());
858 return BO;
859 }
860
861 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
862 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
863 BinaryOperator *BO = BinaryOperator::Create(
864 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
865 BO->setHasNoUnsignedWrap(
866 !IsSigned &&
867 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
868 BO->setHasNoSignedWrap(
869 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
870 return BO;
871 }
872 }
873
874 if (*C2 != 0) { // avoid X udiv 0
875 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
876 if (Instruction *R = FoldOpIntoSelect(I, SI))
877 return R;
878 if (isa<PHINode>(Op0))
879 if (Instruction *NV = FoldOpIntoPhi(I))
880 return NV;
881 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000882 }
883 }
884
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000885 if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
886 if (One->isOne() && !I.getType()->isIntegerTy(1)) {
887 bool isSigned = I.getOpcode() == Instruction::SDiv;
888 if (isSigned) {
889 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
890 // result is one, if Op1 is -1 then the result is minus one, otherwise
891 // it's zero.
892 Value *Inc = Builder->CreateAdd(Op1, One);
893 Value *Cmp = Builder->CreateICmpULT(
894 Inc, ConstantInt::get(I.getType(), 3));
895 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
896 } else {
897 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
898 // result is one, otherwise it's zero.
899 return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
900 }
901 }
902 }
903
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000904 // See if we can fold away this div instruction.
905 if (SimplifyDemandedInstructionBits(I))
906 return &I;
907
Duncan Sands771e82a2011-01-28 16:51:11 +0000908 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Craig Topperf40110f2014-04-25 05:29:35 +0000909 Value *X = nullptr, *Z = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +0000910 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
911 bool isSigned = I.getOpcode() == Instruction::SDiv;
912 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
913 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
914 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000915 }
916
Craig Topperf40110f2014-04-25 05:29:35 +0000917 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000918}
919
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000920/// dyn_castZExtVal - Checks if V is a zext or constant that can
921/// be truncated to Ty without losing bits.
Chris Lattner229907c2011-07-18 04:54:35 +0000922static Value *dyn_castZExtVal(Value *V, Type *Ty) {
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000923 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
924 if (Z->getSrcTy() == Ty)
925 return Z->getOperand(0);
926 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
927 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
928 return ConstantExpr::getTrunc(C, Ty);
929 }
Craig Topperf40110f2014-04-25 05:29:35 +0000930 return nullptr;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000931}
932
David Majnemer37f8f442013-07-04 21:17:49 +0000933namespace {
934const unsigned MaxDepth = 6;
935typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
936 const BinaryOperator &I,
937 InstCombiner &IC);
938
939/// \brief Used to maintain state for visitUDivOperand().
940struct UDivFoldAction {
941 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
942 ///< operand. This can be zero if this action
943 ///< joins two actions together.
944
945 Value *OperandToFold; ///< Which operand to fold.
946 union {
947 Instruction *FoldResult; ///< The instruction returned when FoldAction is
948 ///< invoked.
949
950 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
951 ///< joins two actions together.
952 };
953
954 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +0000955 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +0000956 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
957 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
958};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000959}
David Majnemer37f8f442013-07-04 21:17:49 +0000960
961// X udiv 2^C -> X >> C
962static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
963 const BinaryOperator &I, InstCombiner &IC) {
964 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
965 BinaryOperator *LShr = BinaryOperator::CreateLShr(
966 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000967 if (I.isExact())
968 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000969 return LShr;
970}
971
972// X udiv C, where C >= signbit
973static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
974 const BinaryOperator &I, InstCombiner &IC) {
975 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
976
977 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
978 ConstantInt::get(I.getType(), 1));
979}
980
981// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
982static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
983 InstCombiner &IC) {
984 Instruction *ShiftLeft = cast<Instruction>(Op1);
985 if (isa<ZExtInst>(ShiftLeft))
986 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
987
988 const APInt &CI =
989 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
990 Value *N = ShiftLeft->getOperand(1);
991 if (CI != 1)
992 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
993 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
994 N = IC.Builder->CreateZExt(N, Z->getDestTy());
995 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
Suyog Sarda65f5ae92014-10-07 12:04:07 +0000996 if (I.isExact())
997 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +0000998 return LShr;
999}
1000
1001// \brief Recursively visits the possible right hand operands of a udiv
1002// instruction, seeing through select instructions, to determine if we can
1003// replace the udiv with something simpler. If we find that an operand is not
1004// able to simplify the udiv, we abort the entire transformation.
1005static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
1006 SmallVectorImpl<UDivFoldAction> &Actions,
1007 unsigned Depth = 0) {
1008 // Check to see if this is an unsigned division with an exact power of 2,
1009 // if so, convert to a right shift.
1010 if (match(Op1, m_Power2())) {
1011 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
1012 return Actions.size();
1013 }
1014
1015 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
1016 // X udiv C, where C >= signbit
1017 if (C->getValue().isNegative()) {
1018 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
1019 return Actions.size();
1020 }
1021
1022 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
1023 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
1024 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
1025 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
1026 return Actions.size();
1027 }
1028
1029 // The remaining tests are all recursive, so bail out if we hit the limit.
1030 if (Depth++ == MaxDepth)
1031 return 0;
1032
1033 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
David Majnemer492e6122014-08-30 09:19:05 +00001034 if (size_t LHSIdx =
1035 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
1036 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
1037 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
David Majnemer37f8f442013-07-04 21:17:49 +00001038 return Actions.size();
1039 }
1040
1041 return 0;
1042}
1043
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001044Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
1045 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1046
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001047 if (Value *V = SimplifyVectorOp(I))
1048 return ReplaceInstUsesWith(I, V);
1049
Chandler Carruth66b31302015-01-04 12:03:27 +00001050 if (Value *V = SimplifyUDivInst(Op0, Op1, DL, TLI, DT, AC))
Duncan Sands771e82a2011-01-28 16:51:11 +00001051 return ReplaceInstUsesWith(I, V);
1052
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001053 // Handle the integer div common cases
1054 if (Instruction *Common = commonIDivTransforms(I))
1055 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001056
Benjamin Kramerd4a64712012-08-30 15:07:40 +00001057 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
David Majnemera2521382014-10-13 21:48:30 +00001058 {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +00001059 Value *X;
David Majnemera2521382014-10-13 21:48:30 +00001060 const APInt *C1, *C2;
1061 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
1062 match(Op1, m_APInt(C2))) {
1063 bool Overflow;
1064 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
David Majnemera3aeb152014-11-22 18:16:54 +00001065 if (!Overflow) {
1066 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1067 BinaryOperator *BO = BinaryOperator::CreateUDiv(
David Majnemera2521382014-10-13 21:48:30 +00001068 X, ConstantInt::get(X->getType(), C2ShlC1));
David Majnemera3aeb152014-11-22 18:16:54 +00001069 if (IsExact)
1070 BO->setIsExact();
1071 return BO;
1072 }
David Majnemera2521382014-10-13 21:48:30 +00001073 }
Nadav Rotem11935b22012-08-28 10:01:43 +00001074 }
1075
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001076 // (zext A) udiv (zext B) --> zext (A udiv B)
1077 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1078 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
Suyog Sardaea205512014-10-07 11:56:06 +00001079 return new ZExtInst(
1080 Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", I.isExact()),
1081 I.getType());
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001082
David Majnemer37f8f442013-07-04 21:17:49 +00001083 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1084 SmallVector<UDivFoldAction, 6> UDivActions;
1085 if (visitUDivOperand(Op0, Op1, I, UDivActions))
1086 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1087 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1088 Value *ActionOp1 = UDivActions[i].OperandToFold;
1089 Instruction *Inst;
1090 if (Action)
1091 Inst = Action(Op0, ActionOp1, I, *this);
1092 else {
1093 // This action joins two actions together. The RHS of this action is
1094 // simply the last action we processed, we saved the LHS action index in
1095 // the joining action.
1096 size_t SelectRHSIdx = i - 1;
1097 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1098 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1099 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1100 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1101 SelectLHS, SelectRHS);
1102 }
1103
1104 // If this is the last action to process, return it to the InstCombiner.
1105 // Otherwise, we insert it before the UDiv and record it so that we may
1106 // use it as part of a joining action (i.e., a SelectInst).
1107 if (e - i != 1) {
1108 Inst->insertBefore(&I);
1109 UDivActions[i].FoldResult = Inst;
1110 } else
1111 return Inst;
1112 }
1113
Craig Topperf40110f2014-04-25 05:29:35 +00001114 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001115}
1116
1117Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1118 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1119
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001120 if (Value *V = SimplifyVectorOp(I))
1121 return ReplaceInstUsesWith(I, V);
1122
Chandler Carruth66b31302015-01-04 12:03:27 +00001123 if (Value *V = SimplifySDivInst(Op0, Op1, DL, TLI, DT, AC))
Duncan Sands771e82a2011-01-28 16:51:11 +00001124 return ReplaceInstUsesWith(I, V);
1125
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001126 // Handle the integer div common cases
1127 if (Instruction *Common = commonIDivTransforms(I))
1128 return Common;
1129
Benjamin Kramer72196f32014-01-19 15:24:22 +00001130 // sdiv X, -1 == -X
1131 if (match(Op1, m_AllOnes()))
1132 return BinaryOperator::CreateNeg(Op0);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001133
Benjamin Kramer72196f32014-01-19 15:24:22 +00001134 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001135 // sdiv X, C --> ashr exact X, log2(C)
1136 if (I.isExact() && RHS->getValue().isNonNegative() &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001137 RHS->getValue().isPowerOf2()) {
1138 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
1139 RHS->getValue().exactLogBase2());
Chris Lattner6b657ae2011-02-10 05:36:31 +00001140 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001141 }
Benjamin Kramer72196f32014-01-19 15:24:22 +00001142 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001143
Benjamin Kramer72196f32014-01-19 15:24:22 +00001144 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
David Majnemerf28e2a42014-07-02 06:42:13 +00001145 // X/INT_MIN -> X == INT_MIN
1146 if (RHS->isMinSignedValue())
1147 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1148
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001149 // -X/C --> X/-C provided the negation doesn't overflow.
David Majnemerfa4699e2014-11-22 20:00:34 +00001150 Value *X;
1151 if (match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1152 auto *BO = BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(RHS));
1153 BO->setIsExact(I.isExact());
1154 return BO;
1155 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001156 }
1157
1158 // If the sign bits of both operands are zero (i.e. we can prove they are
1159 // unsigned inputs), turn this into a udiv.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001160 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001161 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001162 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1163 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001164 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
David Majnemerec6e4812014-11-22 20:00:38 +00001165 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1166 BO->setIsExact(I.isExact());
1167 return BO;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001168 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001169
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001170 if (isKnownToBeAPowerOfTwo(Op1, DL, /*OrZero*/ true, 0, AC, &I, DT)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001171 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1172 // Safe because the only negative value (1 << Y) can take on is
1173 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1174 // the sign bit set.
David Majnemerfb380552014-11-22 20:00:41 +00001175 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1176 BO->setIsExact(I.isExact());
1177 return BO;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001178 }
1179 }
1180 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001181
Craig Topperf40110f2014-04-25 05:29:35 +00001182 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001183}
1184
Shuxin Yang320f52a2013-01-14 22:48:41 +00001185/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1186/// FP value and:
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001187/// 1) 1/C is exact, or
Shuxin Yang320f52a2013-01-14 22:48:41 +00001188/// 2) reciprocal is allowed.
Sylvestre Ledru149e2812013-05-14 23:36:24 +00001189/// If the conversion was successful, the simplified expression "X * 1/C" is
Shuxin Yang320f52a2013-01-14 22:48:41 +00001190/// returned; otherwise, NULL is returned.
1191///
Suyog Sardaea205512014-10-07 11:56:06 +00001192static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
Shuxin Yang320f52a2013-01-14 22:48:41 +00001193 bool AllowReciprocal) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001194 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001195 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001196
1197 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001198 APFloat Reciprocal(FpVal.getSemantics());
1199 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001200
Michael Gottesman3cb77ab2013-06-19 21:23:18 +00001201 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001202 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1203 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1204 Cvt = !Reciprocal.isDenormal();
1205 }
1206
1207 if (!Cvt)
Craig Topperf40110f2014-04-25 05:29:35 +00001208 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001209
1210 ConstantFP *R;
1211 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1212 return BinaryOperator::CreateFMul(Dividend, R);
1213}
1214
Frits van Bommel2a559512011-01-29 17:50:27 +00001215Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1216 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1217
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001218 if (Value *V = SimplifyVectorOp(I))
1219 return ReplaceInstUsesWith(I, V);
1220
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001221 if (Value *V = SimplifyFDivInst(Op0, Op1, I.getFastMathFlags(),
1222 DL, TLI, DT, AC))
Frits van Bommel2a559512011-01-29 17:50:27 +00001223 return ReplaceInstUsesWith(I, V);
1224
Stephen Lina9b57f62013-07-20 07:13:13 +00001225 if (isa<Constant>(Op0))
1226 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1227 if (Instruction *R = FoldOpIntoSelect(I, SI))
1228 return R;
1229
Shuxin Yang320f52a2013-01-14 22:48:41 +00001230 bool AllowReassociate = I.hasUnsafeAlgebra();
1231 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001232
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001233 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001234 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1235 if (Instruction *R = FoldOpIntoSelect(I, SI))
1236 return R;
1237
Shuxin Yang320f52a2013-01-14 22:48:41 +00001238 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +00001239 Constant *C1 = nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001240 Constant *C2 = Op1C;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001241 Value *X;
Craig Topperf40110f2014-04-25 05:29:35 +00001242 Instruction *Res = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001243
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001244 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001245 // (X*C1)/C2 => X * (C1/C2)
1246 //
1247 Constant *C = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001248 if (isNormalFp(C))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001249 Res = BinaryOperator::CreateFMul(X, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001250 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001251 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1252 //
1253 Constant *C = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001254 if (isNormalFp(C)) {
1255 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001256 if (!Res)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001257 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001258 }
1259 }
1260
1261 if (Res) {
1262 Res->setFastMathFlags(I.getFastMathFlags());
1263 return Res;
1264 }
1265 }
1266
1267 // X / C => X * 1/C
Owen Anderson4557a152014-01-16 21:07:52 +00001268 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1269 T->copyFastMathFlags(&I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001270 return T;
Owen Anderson4557a152014-01-16 21:07:52 +00001271 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001272
Craig Topperf40110f2014-04-25 05:29:35 +00001273 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001274 }
1275
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001276 if (AllowReassociate && isa<Constant>(Op0)) {
1277 Constant *C1 = cast<Constant>(Op0), *C2;
Craig Topperf40110f2014-04-25 05:29:35 +00001278 Constant *Fold = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001279 Value *X;
1280 bool CreateDiv = true;
1281
1282 // C1 / (X*C2) => (C1/C2) / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001283 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001284 Fold = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001285 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001286 // C1 / (X/C2) => (C1*C2) / X
1287 Fold = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001288 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001289 // C1 / (C2/X) => (C1/C2) * X
1290 Fold = ConstantExpr::getFDiv(C1, C2);
1291 CreateDiv = false;
1292 }
1293
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001294 if (Fold && isNormalFp(Fold)) {
1295 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1296 : BinaryOperator::CreateFMul(X, Fold);
1297 R->setFastMathFlags(I.getFastMathFlags());
1298 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001299 }
Craig Topperf40110f2014-04-25 05:29:35 +00001300 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001301 }
1302
1303 if (AllowReassociate) {
1304 Value *X, *Y;
Craig Topperf40110f2014-04-25 05:29:35 +00001305 Value *NewInst = nullptr;
1306 Instruction *SimpR = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001307
1308 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1309 // (X/Y) / Z => X / (Y*Z)
1310 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001311 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001312 NewInst = Builder->CreateFMul(Y, Op1);
Owen Anderson1664dc82014-01-20 07:44:53 +00001313 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1314 FastMathFlags Flags = I.getFastMathFlags();
1315 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1316 RI->setFastMathFlags(Flags);
1317 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001318 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1319 }
1320 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1321 // Z / (X/Y) => Z*Y / X
1322 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001323 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001324 NewInst = Builder->CreateFMul(Op0, Y);
Owen Anderson1664dc82014-01-20 07:44:53 +00001325 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1326 FastMathFlags Flags = I.getFastMathFlags();
1327 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1328 RI->setFastMathFlags(Flags);
1329 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001330 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1331 }
1332 }
1333
1334 if (NewInst) {
1335 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1336 T->setDebugLoc(I.getDebugLoc());
1337 SimpR->setFastMathFlags(I.getFastMathFlags());
1338 return SimpR;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001339 }
1340 }
1341
Craig Topperf40110f2014-04-25 05:29:35 +00001342 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001343}
1344
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001345/// This function implements the transforms common to both integer remainder
1346/// instructions (urem and srem). It is called by the visitors to those integer
1347/// remainder instructions.
1348/// @brief Common integer remainder transforms
1349Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1350 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1351
Chris Lattner7c99f192011-05-22 18:18:41 +00001352 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001353 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +00001354 I.setOperand(1, V);
1355 return &I;
1356 }
1357
Duncan Sandsa3e36992011-05-02 16:27:02 +00001358 // Handle cases involving: rem X, (select Cond, Y, Z)
1359 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1360 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001361
Benjamin Kramer72196f32014-01-19 15:24:22 +00001362 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001363 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1364 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1365 if (Instruction *R = FoldOpIntoSelect(I, SI))
1366 return R;
1367 } else if (isa<PHINode>(Op0I)) {
1368 if (Instruction *NV = FoldOpIntoPhi(I))
1369 return NV;
1370 }
1371
1372 // See if we can fold away this rem instruction.
1373 if (SimplifyDemandedInstructionBits(I))
1374 return &I;
1375 }
1376 }
1377
Craig Topperf40110f2014-04-25 05:29:35 +00001378 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001379}
1380
1381Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1382 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1383
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001384 if (Value *V = SimplifyVectorOp(I))
1385 return ReplaceInstUsesWith(I, V);
1386
Chandler Carruth66b31302015-01-04 12:03:27 +00001387 if (Value *V = SimplifyURemInst(Op0, Op1, DL, TLI, DT, AC))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001388 return ReplaceInstUsesWith(I, V);
1389
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001390 if (Instruction *common = commonIRemTransforms(I))
1391 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001392
David Majnemer6c30f492013-05-12 00:07:05 +00001393 // (zext A) urem (zext B) --> zext (A urem B)
1394 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1395 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1396 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1397 I.getType());
1398
David Majnemer470b0772013-05-11 09:01:28 +00001399 // X urem Y -> X and Y-1, where Y is a power of 2,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001400 if (isKnownToBeAPowerOfTwo(Op1, DL, /*OrZero*/ true, 0, AC, &I, DT)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001401 Constant *N1 = Constant::getAllOnesValue(I.getType());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001402 Value *Add = Builder->CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001403 return BinaryOperator::CreateAnd(Op0, Add);
1404 }
1405
Nick Lewycky7459be62013-07-13 01:16:47 +00001406 // 1 urem X -> zext(X != 1)
1407 if (match(Op0, m_One())) {
1408 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1409 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1410 return ReplaceInstUsesWith(I, Ext);
1411 }
1412
Craig Topperf40110f2014-04-25 05:29:35 +00001413 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001414}
1415
1416Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1417 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1418
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001419 if (Value *V = SimplifyVectorOp(I))
1420 return ReplaceInstUsesWith(I, V);
1421
Chandler Carruth66b31302015-01-04 12:03:27 +00001422 if (Value *V = SimplifySRemInst(Op0, Op1, DL, TLI, DT, AC))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001423 return ReplaceInstUsesWith(I, V);
1424
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001425 // Handle the integer rem common cases
1426 if (Instruction *Common = commonIRemTransforms(I))
1427 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001428
David Majnemerdb077302014-10-13 22:37:51 +00001429 {
1430 const APInt *Y;
1431 // X % -Y -> X % Y
1432 if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001433 Worklist.AddValue(I.getOperand(1));
David Majnemerdb077302014-10-13 22:37:51 +00001434 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001435 return &I;
1436 }
David Majnemerdb077302014-10-13 22:37:51 +00001437 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001438
1439 // If the sign bits of both operands are zero (i.e. we can prove they are
1440 // unsigned inputs), turn this into a urem.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001441 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001442 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Hal Finkel60db0582014-09-07 18:57:58 +00001443 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1444 MaskedValueIsZero(Op0, Mask, 0, &I)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001445 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001446 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1447 }
1448 }
1449
1450 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001451 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1452 Constant *C = cast<Constant>(Op1);
1453 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001454
1455 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001456 bool hasMissing = false;
1457 for (unsigned i = 0; i != VWidth; ++i) {
1458 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001459 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001460 hasMissing = true;
1461 break;
1462 }
1463
1464 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001465 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001466 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001467 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001468
Chris Lattner0256be92012-01-27 03:08:05 +00001469 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001470 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001471 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001472 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001473 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001474 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001475 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001476 }
1477 }
1478
1479 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001480 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001481 Worklist.AddValue(I.getOperand(1));
1482 I.setOperand(1, NewRHSV);
1483 return &I;
1484 }
1485 }
1486 }
1487
Craig Topperf40110f2014-04-25 05:29:35 +00001488 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001489}
1490
1491Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001492 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001493
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001494 if (Value *V = SimplifyVectorOp(I))
1495 return ReplaceInstUsesWith(I, V);
1496
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001497 if (Value *V = SimplifyFRemInst(Op0, Op1, I.getFastMathFlags(),
1498 DL, TLI, DT, AC))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001499 return ReplaceInstUsesWith(I, V);
1500
1501 // Handle cases involving: rem X, (select Cond, Y, Z)
1502 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1503 return &I;
1504
Craig Topperf40110f2014-04-25 05:29:35 +00001505 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001506}