blob: b857c04bd60a987403164644b48a50bec98cc44c [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
Sanjay Patel6eccf482015-09-09 15:24:36 +000025/// The specific integer value is used in a context where it is known to be
26/// non-zero. If this allows us to simplify the computation, do so and return
27/// 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 <<.
Sanjay Patela8ef4a52016-05-22 17:08:52 +000048 BinaryOperator *I = dyn_cast<BinaryOperator>(V);
49 if (I && I->isLogicalShift() &&
50 isKnownToBeAPowerOfTwo(I->getOperand(0), IC.getDataLayout(), false, 0,
Daniel Jasperaec2fa32016-12-19 08:22:17 +000051 &IC.getAssumptionCache(), &CxtI,
52 &IC.getDominatorTree())) {
Sanjay Patela8ef4a52016-05-22 17:08:52 +000053 // We know that this is an exact/nuw shift and that the input is a
54 // non-zero context as well.
55 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC, CxtI)) {
56 I->setOperand(0, V2);
57 MadeChange = true;
Chris Lattner388cb8a2011-05-23 00:32:19 +000058 }
59
Sanjay Patela8ef4a52016-05-22 17:08:52 +000060 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
61 I->setIsExact();
62 MadeChange = true;
63 }
64
65 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
Sanjay Patel6eccf482015-09-09 15:24:36 +000079/// True if the multiply can not be expressed in an int this size.
David Majnemer27adb122014-10-12 08:34:24 +000080static bool MultiplyOverflows(const APInt &C1, const APInt &C2, APInt &Product,
81 bool IsSigned) {
82 bool Overflow;
83 if (IsSigned)
84 Product = C1.smul_ov(C2, Overflow);
85 else
86 Product = C1.umul_ov(C2, Overflow);
Jim Grosbachbdbd7342013-04-05 21:20:12 +000087
David Majnemer27adb122014-10-12 08:34:24 +000088 return Overflow;
Chris Lattnerdc054bf2010-01-05 06:09:35 +000089}
90
David Majnemerf9a095d2014-08-16 08:55:06 +000091/// \brief True if C2 is a multiple of C1. Quotient contains C2/C1.
92static bool IsMultiple(const APInt &C1, const APInt &C2, APInt &Quotient,
93 bool IsSigned) {
94 assert(C1.getBitWidth() == C2.getBitWidth() &&
95 "Inconsistent width of constants!");
96
David Majnemer135ca402015-09-06 06:49:59 +000097 // Bail if we will divide by zero.
98 if (C2.isMinValue())
99 return false;
100
101 // Bail if we would divide INT_MIN by -1.
102 if (IsSigned && C1.isMinSignedValue() && C2.isAllOnesValue())
103 return false;
104
David Majnemerf9a095d2014-08-16 08:55:06 +0000105 APInt Remainder(C1.getBitWidth(), /*Val=*/0ULL, IsSigned);
106 if (IsSigned)
107 APInt::sdivrem(C1, C2, Quotient, Remainder);
108 else
109 APInt::udivrem(C1, C2, Quotient, Remainder);
110
111 return Remainder.isMinValue();
112}
113
Rafael Espindola65281bf2013-05-31 14:27:15 +0000114/// \brief A helper routine of InstCombiner::visitMul().
115///
116/// If C is a vector of known powers of 2, then this function returns
117/// a new vector obtained from C replacing each element with its logBase2.
118/// Return a null pointer otherwise.
119static Constant *getLogBase2Vector(ConstantDataVector *CV) {
120 const APInt *IVal;
121 SmallVector<Constant *, 4> Elts;
122
123 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
124 Constant *Elt = CV->getElementAsConstant(I);
125 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
Craig Topperf40110f2014-04-25 05:29:35 +0000126 return nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000127 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
128 }
129
130 return ConstantVector::get(Elts);
131}
132
David Majnemer54c2ca22014-12-26 09:10:14 +0000133/// \brief Return true if we can prove that:
134/// (mul LHS, RHS) === (mul nsw LHS, RHS)
135bool InstCombiner::WillNotOverflowSignedMul(Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000136 Instruction &CxtI) {
David Majnemer54c2ca22014-12-26 09:10:14 +0000137 // Multiplying n * m significant bits yields a result of n + m significant
138 // bits. If the total number of significant bits does not exceed the
139 // result bit width (minus 1), there is no overflow.
140 // This means if we have enough leading sign bits in the operands
141 // we can guarantee that the result does not overflow.
142 // Ref: "Hacker's Delight" by Henry Warren
143 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
144
145 // Note that underestimating the number of sign bits gives a more
146 // conservative answer.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000147 unsigned SignBits =
148 ComputeNumSignBits(LHS, 0, &CxtI) + ComputeNumSignBits(RHS, 0, &CxtI);
David Majnemer54c2ca22014-12-26 09:10:14 +0000149
150 // First handle the easy case: if we have enough sign bits there's
151 // definitely no overflow.
152 if (SignBits > BitWidth + 1)
153 return true;
154
155 // There are two ambiguous cases where there can be no overflow:
156 // SignBits == BitWidth + 1 and
157 // SignBits == BitWidth
158 // The second case is difficult to check, therefore we only handle the
159 // first case.
160 if (SignBits == BitWidth + 1) {
161 // It overflows only when both arguments are negative and the true
162 // product is exactly the minimum negative number.
163 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
164 // For simplicity we just check if at least one side is not negative.
165 bool LHSNonNegative, LHSNegative;
166 bool RHSNonNegative, RHSNegative;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000167 ComputeSignBit(LHS, LHSNonNegative, LHSNegative, /*Depth=*/0, &CxtI);
168 ComputeSignBit(RHS, RHSNonNegative, RHSNegative, /*Depth=*/0, &CxtI);
David Majnemer54c2ca22014-12-26 09:10:14 +0000169 if (LHSNonNegative || RHSNonNegative)
170 return true;
171 }
172 return false;
173}
174
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000175Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000176 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000177 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
178
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000179 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000180 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000181
Daniel Berlin2c75c632017-04-26 20:56:07 +0000182 if (Value *V = SimplifyMulInst(Op0, Op1, SQ))
Sanjay Patel4b198802016-02-01 22:23:39 +0000183 return replaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000184
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000185 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000186 return replaceInstUsesWith(I, V);
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000187
David Majnemer027bc802014-11-22 04:52:38 +0000188 // X * -1 == 0 - X
189 if (match(Op1, m_AllOnes())) {
190 BinaryOperator *BO = BinaryOperator::CreateNeg(Op0, I.getName());
191 if (I.hasNoSignedWrap())
192 BO->setHasNoSignedWrap();
193 return BO;
194 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000195
Rafael Espindola65281bf2013-05-31 14:27:15 +0000196 // Also allow combining multiply instructions on vectors.
197 {
198 Value *NewOp;
199 Constant *C1, *C2;
200 const APInt *IVal;
201 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
202 m_Constant(C1))) &&
David Majnemerfd4a6d22014-11-22 04:52:52 +0000203 match(C1, m_APInt(IVal))) {
204 // ((X << C2)*C1) == (X * (C1 << C2))
205 Constant *Shl = ConstantExpr::getShl(C1, C2);
206 BinaryOperator *Mul = cast<BinaryOperator>(I.getOperand(0));
207 BinaryOperator *BO = BinaryOperator::CreateMul(NewOp, Shl);
208 if (I.hasNoUnsignedWrap() && Mul->hasNoUnsignedWrap())
209 BO->setHasNoUnsignedWrap();
210 if (I.hasNoSignedWrap() && Mul->hasNoSignedWrap() &&
211 Shl->isNotMinSignedValue())
212 BO->setHasNoSignedWrap();
213 return BO;
214 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000215
Rafael Espindola65281bf2013-05-31 14:27:15 +0000216 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000217 Constant *NewCst = nullptr;
Rafael Espindola65281bf2013-05-31 14:27:15 +0000218 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
219 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
220 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
221 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
222 // Replace X*(2^C) with X << C, where C is a vector of known
223 // constant powers of 2.
224 NewCst = getLogBase2Vector(CV);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000225
Rafael Espindola65281bf2013-05-31 14:27:15 +0000226 if (NewCst) {
David Majnemer45951a62015-04-18 04:41:30 +0000227 unsigned Width = NewCst->getType()->getPrimitiveSizeInBits();
Rafael Espindola65281bf2013-05-31 14:27:15 +0000228 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000229
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000230 if (I.hasNoUnsignedWrap())
231 Shl->setHasNoUnsignedWrap();
David Majnemer45951a62015-04-18 04:41:30 +0000232 if (I.hasNoSignedWrap()) {
233 uint64_t V;
234 if (match(NewCst, m_ConstantInt(V)) && V != Width - 1)
235 Shl->setHasNoSignedWrap();
236 }
Tilmann Scheller2bc5cb62014-10-07 10:19:34 +0000237
Rafael Espindola65281bf2013-05-31 14:27:15 +0000238 return Shl;
239 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000240 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000241 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000242
Rafael Espindola65281bf2013-05-31 14:27:15 +0000243 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Stuart Hastings23804832011-06-01 16:42:47 +0000244 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
245 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
246 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000247 {
248 const APInt & Val = CI->getValue();
249 const APInt &PosVal = Val.abs();
250 if (Val.isNegative() && PosVal.isPowerOf2()) {
Craig Topperf40110f2014-04-25 05:29:35 +0000251 Value *X = nullptr, *Y = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000252 if (Op0->hasOneUse()) {
253 ConstantInt *C1;
Craig Topperf40110f2014-04-25 05:29:35 +0000254 Value *Sub = nullptr;
Stuart Hastings23804832011-06-01 16:42:47 +0000255 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
256 Sub = Builder->CreateSub(X, Y, "suba");
257 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
258 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
259 if (Sub)
260 return
261 BinaryOperator::CreateMul(Sub,
262 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000263 }
264 }
265 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000266 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000267
Chris Lattner6b657ae2011-02-10 05:36:31 +0000268 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000269 if (isa<Constant>(Op1)) {
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000270 if (Instruction *FoldedMul = foldOpWithConstantIntoOperand(I))
271 return FoldedMul;
Benjamin Kramer72196f32014-01-19 15:24:22 +0000272
273 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
274 {
275 Value *X;
276 Constant *C1;
277 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
David Majnemer6cf6c052014-06-19 07:14:33 +0000278 Value *Mul = Builder->CreateMul(C1, Op1);
279 // Only go forward with the transform if C1*CI simplifies to a tidier
280 // constant.
281 if (!match(Mul, m_Mul(m_Value(), m_Value())))
282 return BinaryOperator::CreateAdd(Builder->CreateMul(X, Op1), Mul);
Benjamin Kramer72196f32014-01-19 15:24:22 +0000283 }
284 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000285 }
286
David Majnemer8279a7502014-11-22 07:25:19 +0000287 if (Value *Op0v = dyn_castNegVal(Op0)) { // -X * -Y = X*Y
288 if (Value *Op1v = dyn_castNegVal(Op1)) {
289 BinaryOperator *BO = BinaryOperator::CreateMul(Op0v, Op1v);
290 if (I.hasNoSignedWrap() &&
291 match(Op0, m_NSWSub(m_Value(), m_Value())) &&
292 match(Op1, m_NSWSub(m_Value(), m_Value())))
293 BO->setHasNoSignedWrap();
294 return BO;
295 }
296 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000297
298 // (X / Y) * Y = X - (X % Y)
299 // (X / Y) * -Y = (X % Y) - X
300 {
Sanjay Patela0a56822017-03-14 17:27:27 +0000301 Value *Y = Op1;
302 BinaryOperator *Div = dyn_cast<BinaryOperator>(Op0);
303 if (!Div || (Div->getOpcode() != Instruction::UDiv &&
304 Div->getOpcode() != Instruction::SDiv)) {
305 Y = Op0;
306 Div = dyn_cast<BinaryOperator>(Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000307 }
Sanjay Patela0a56822017-03-14 17:27:27 +0000308 Value *Neg = dyn_castNegVal(Y);
309 if (Div && Div->hasOneUse() &&
310 (Div->getOperand(1) == Y || Div->getOperand(1) == Neg) &&
311 (Div->getOpcode() == Instruction::UDiv ||
312 Div->getOpcode() == Instruction::SDiv)) {
313 Value *X = Div->getOperand(0), *DivOp1 = Div->getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000314
Chris Lattner35315d02011-02-06 21:44:57 +0000315 // If the division is exact, X % Y is zero, so we end up with X or -X.
Sanjay Patela0a56822017-03-14 17:27:27 +0000316 if (Div->isExact()) {
317 if (DivOp1 == Y)
318 return replaceInstUsesWith(I, X);
319 return BinaryOperator::CreateNeg(X);
320 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000321
Sanjay Patela0a56822017-03-14 17:27:27 +0000322 auto RemOpc = Div->getOpcode() == Instruction::UDiv ? Instruction::URem
323 : Instruction::SRem;
324 Value *Rem = Builder->CreateBinOp(RemOpc, X, DivOp1);
325 if (DivOp1 == Y)
326 return BinaryOperator::CreateSub(X, Rem);
327 return BinaryOperator::CreateSub(Rem, X);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000328 }
329 }
330
331 /// i1 mul -> i1 and.
Benjamin Kramer72196f32014-01-19 15:24:22 +0000332 if (I.getType()->getScalarType()->isIntegerTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000333 return BinaryOperator::CreateAnd(Op0, Op1);
334
335 // X*(1 << Y) --> X << Y
336 // (1 << Y)*X --> X << Y
337 {
338 Value *Y;
David Majnemer546f8102014-11-22 08:57:02 +0000339 BinaryOperator *BO = nullptr;
340 bool ShlNSW = false;
341 if (match(Op0, m_Shl(m_One(), m_Value(Y)))) {
342 BO = BinaryOperator::CreateShl(Op1, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000343 ShlNSW = cast<ShlOperator>(Op0)->hasNoSignedWrap();
David Majnemer8e6f6a92014-11-24 16:41:13 +0000344 } else if (match(Op1, m_Shl(m_One(), m_Value(Y)))) {
David Majnemer546f8102014-11-22 08:57:02 +0000345 BO = BinaryOperator::CreateShl(Op0, Y);
David Majnemer087dc8b2015-01-04 07:36:02 +0000346 ShlNSW = cast<ShlOperator>(Op1)->hasNoSignedWrap();
David Majnemer546f8102014-11-22 08:57:02 +0000347 }
348 if (BO) {
349 if (I.hasNoUnsignedWrap())
350 BO->setHasNoUnsignedWrap();
351 if (I.hasNoSignedWrap() && ShlNSW)
352 BO->setHasNoSignedWrap();
353 return BO;
354 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000355 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000356
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000357 // If one of the operands of the multiply is a cast from a boolean value, then
358 // we know the bool is either zero or one, so this is a 'masking' multiply.
359 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands19d0b472010-02-16 11:11:14 +0000360 if (!I.getType()->isVectorTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000361 // -2 is "-1 << 1" so it is all bits set except the low one.
362 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000363
Craig Topperf40110f2014-04-25 05:29:35 +0000364 Value *BoolCast = nullptr, *OtherOp = nullptr;
Richard Trieu7a083812016-02-18 22:09:30 +0000365 if (MaskedValueIsZero(Op0, Negative2, 0, &I)) {
366 BoolCast = Op0;
367 OtherOp = Op1;
368 } else if (MaskedValueIsZero(Op1, Negative2, 0, &I)) {
369 BoolCast = Op1;
370 OtherOp = Op0;
371 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000372
373 if (BoolCast) {
374 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000375 BoolCast);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000376 return BinaryOperator::CreateAnd(V, OtherOp);
377 }
378 }
379
David Majnemera1cfd7c2016-12-30 00:28:58 +0000380 // Check for (mul (sext x), y), see if we can merge this into an
381 // integer mul followed by a sext.
382 if (SExtInst *Op0Conv = dyn_cast<SExtInst>(Op0)) {
383 // (mul (sext x), cst) --> (sext (mul x, cst'))
384 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
385 if (Op0Conv->hasOneUse()) {
386 Constant *CI =
387 ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
388 if (ConstantExpr::getSExt(CI, I.getType()) == Op1C &&
389 WillNotOverflowSignedMul(Op0Conv->getOperand(0), CI, I)) {
390 // Insert the new, smaller mul.
391 Value *NewMul =
392 Builder->CreateNSWMul(Op0Conv->getOperand(0), CI, "mulconv");
393 return new SExtInst(NewMul, I.getType());
394 }
395 }
396 }
397
398 // (mul (sext x), (sext y)) --> (sext (mul int x, y))
399 if (SExtInst *Op1Conv = dyn_cast<SExtInst>(Op1)) {
400 // Only do this if x/y have the same type, if at last one of them has a
401 // single use (so we don't increase the number of sexts), and if the
402 // integer mul will not overflow.
403 if (Op0Conv->getOperand(0)->getType() ==
404 Op1Conv->getOperand(0)->getType() &&
405 (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
406 WillNotOverflowSignedMul(Op0Conv->getOperand(0),
407 Op1Conv->getOperand(0), I)) {
408 // Insert the new integer mul.
409 Value *NewMul = Builder->CreateNSWMul(
410 Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
411 return new SExtInst(NewMul, I.getType());
412 }
413 }
414 }
415
416 // Check for (mul (zext x), y), see if we can merge this into an
417 // integer mul followed by a zext.
418 if (auto *Op0Conv = dyn_cast<ZExtInst>(Op0)) {
419 // (mul (zext x), cst) --> (zext (mul x, cst'))
420 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
421 if (Op0Conv->hasOneUse()) {
422 Constant *CI =
423 ConstantExpr::getTrunc(Op1C, Op0Conv->getOperand(0)->getType());
424 if (ConstantExpr::getZExt(CI, I.getType()) == Op1C &&
Craig Topperbb973722017-05-15 02:44:08 +0000425 willNotOverflowUnsignedMul(Op0Conv->getOperand(0), CI, I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +0000426 // Insert the new, smaller mul.
427 Value *NewMul =
428 Builder->CreateNUWMul(Op0Conv->getOperand(0), CI, "mulconv");
429 return new ZExtInst(NewMul, I.getType());
430 }
431 }
432 }
433
434 // (mul (zext x), (zext y)) --> (zext (mul int x, y))
435 if (auto *Op1Conv = dyn_cast<ZExtInst>(Op1)) {
436 // Only do this if x/y have the same type, if at last one of them has a
437 // single use (so we don't increase the number of zexts), and if the
438 // integer mul will not overflow.
439 if (Op0Conv->getOperand(0)->getType() ==
440 Op1Conv->getOperand(0)->getType() &&
441 (Op0Conv->hasOneUse() || Op1Conv->hasOneUse()) &&
Craig Topperbb973722017-05-15 02:44:08 +0000442 willNotOverflowUnsignedMul(Op0Conv->getOperand(0),
443 Op1Conv->getOperand(0), I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +0000444 // Insert the new integer mul.
445 Value *NewMul = Builder->CreateNUWMul(
446 Op0Conv->getOperand(0), Op1Conv->getOperand(0), "mulconv");
447 return new ZExtInst(NewMul, I.getType());
448 }
449 }
450 }
451
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000452 if (!I.hasNoSignedWrap() && WillNotOverflowSignedMul(Op0, Op1, I)) {
David Majnemer54c2ca22014-12-26 09:10:14 +0000453 Changed = true;
454 I.setHasNoSignedWrap(true);
455 }
456
Craig Topperbb973722017-05-15 02:44:08 +0000457 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedMul(Op0, Op1, I)) {
David Majnemerb1296ec2014-12-26 09:50:35 +0000458 Changed = true;
459 I.setHasNoUnsignedWrap(true);
460 }
461
Craig Topperf40110f2014-04-25 05:29:35 +0000462 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000463}
464
Sanjay Patel17045f72014-10-14 00:33:23 +0000465/// Detect pattern log2(Y * 0.5) with corresponding fast math flags.
Pedro Artigas993acd02012-11-30 22:07:05 +0000466static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Sanjay Patel17045f72014-10-14 00:33:23 +0000467 if (!Op->hasOneUse())
468 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000469
Sanjay Patel17045f72014-10-14 00:33:23 +0000470 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
471 if (!II)
472 return;
473 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
474 return;
475 Log2 = II;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000476
Sanjay Patel17045f72014-10-14 00:33:23 +0000477 Value *OpLog2Of = II->getArgOperand(0);
478 if (!OpLog2Of->hasOneUse())
479 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000480
Sanjay Patel17045f72014-10-14 00:33:23 +0000481 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
482 if (!I)
483 return;
484 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
485 return;
Pedro Artigas00b83c92012-11-30 22:47:15 +0000486
Sanjay Patel17045f72014-10-14 00:33:23 +0000487 if (match(I->getOperand(0), m_SpecificFP(0.5)))
488 Y = I->getOperand(1);
489 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
490 Y = I->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000491}
Pedro Artigas993acd02012-11-30 22:07:05 +0000492
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000493static bool isFiniteNonZeroFp(Constant *C) {
494 if (C->getType()->isVectorTy()) {
495 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
496 ++I) {
Michael Kupersteinbcb26d62015-03-05 08:38:57 +0000497 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000498 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
499 return false;
500 }
501 return true;
502 }
503
504 return isa<ConstantFP>(C) &&
505 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
506}
507
508static bool isNormalFp(Constant *C) {
509 if (C->getType()->isVectorTy()) {
510 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
511 ++I) {
Michael Kupersteinbcb26d62015-03-05 08:38:57 +0000512 ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(C->getAggregateElement(I));
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000513 if (!CFP || !CFP->getValueAPF().isNormal())
514 return false;
515 }
516 return true;
517 }
518
519 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
520}
521
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000522/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
523/// true iff the given value is FMul or FDiv with one and only one operand
524/// being a normal constant (i.e. not Zero/NaN/Infinity).
525static bool isFMulOrFDivWithConstant(Value *V) {
526 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000527 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yang80138662013-01-07 22:41:28 +0000528 I->getOpcode() != Instruction::FDiv))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000529 return false;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000530
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000531 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
532 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000533
534 if (C0 && C1)
535 return false;
536
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000537 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000538}
539
540/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
541/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
542/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000543/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000544/// resulting expression. Note that this function could return NULL in
545/// case the constants cannot be folded into a normal floating-point.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000546///
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000547Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yang80138662013-01-07 22:41:28 +0000548 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000549 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
550
551 Value *Opnd0 = FMulOrDiv->getOperand(0);
552 Value *Opnd1 = FMulOrDiv->getOperand(1);
553
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000554 Constant *C0 = dyn_cast<Constant>(Opnd0);
555 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000556
Craig Topperf40110f2014-04-25 05:29:35 +0000557 BinaryOperator *R = nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000558
559 // (X * C0) * C => X * (C0*C)
560 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
561 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000562 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000563 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
564 } else {
565 if (C0) {
566 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000567 if (FMulOrDiv->hasOneUse()) {
568 // It would otherwise introduce another div.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000569 Constant *F = ConstantExpr::getFMul(C0, C);
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000570 if (isNormalFp(F))
571 R = BinaryOperator::CreateFDiv(F, Opnd1);
572 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000573 } else {
574 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000575 Constant *F = ConstantExpr::getFDiv(C, C1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000576 if (isNormalFp(F)) {
577 R = BinaryOperator::CreateFMul(Opnd0, F);
578 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000579 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000580 Constant *F = ConstantExpr::getFDiv(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000581 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000582 R = BinaryOperator::CreateFDiv(Opnd0, F);
583 }
584 }
585 }
586
587 if (R) {
588 R->setHasUnsafeAlgebra(true);
589 InsertNewInstWith(R, *InsertBefore);
590 }
591
592 return R;
593}
594
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000595Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000596 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000597 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
598
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000599 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000600 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000601
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000602 if (isa<Constant>(Op0))
603 std::swap(Op0, Op1);
604
Daniel Berlin2c75c632017-04-26 20:56:07 +0000605 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), SQ))
Sanjay Patel4b198802016-02-01 22:23:39 +0000606 return replaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000607
Shuxin Yange8227452013-01-15 21:09:32 +0000608 bool AllowReassociate = I.hasUnsafeAlgebra();
609
Michael Ilsemand5787be2012-12-12 00:28:32 +0000610 // Simplify mul instructions with a constant RHS.
611 if (isa<Constant>(Op1)) {
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000612 if (Instruction *FoldedMul = foldOpWithConstantIntoOperand(I))
613 return FoldedMul;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000614
Owen Andersonf74cfe02014-01-16 20:36:42 +0000615 // (fmul X, -1.0) --> (fsub -0.0, X)
Benjamin Kramerfea9ac92014-01-18 16:43:14 +0000616 if (match(Op1, m_SpecificFP(-1.0))) {
617 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
618 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000619 RI->copyFastMathFlags(&I);
620 return RI;
621 }
622
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000623 Constant *C = cast<Constant>(Op1);
624 if (AllowReassociate && isFiniteNonZeroFp(C)) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000625 // Let MDC denote an expression in one of these forms:
626 // X * C, C/X, X/C, where C is a constant.
627 //
628 // Try to simplify "MDC * Constant"
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000629 if (isFMulOrFDivWithConstant(Op0))
630 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Sanjay Patel4b198802016-02-01 22:23:39 +0000631 return replaceInstUsesWith(I, V);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000632
Quentin Colombete684a6d2013-02-28 21:12:40 +0000633 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000634 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
635 if (FAddSub &&
636 (FAddSub->getOpcode() == Instruction::FAdd ||
637 FAddSub->getOpcode() == Instruction::FSub)) {
638 Value *Opnd0 = FAddSub->getOperand(0);
639 Value *Opnd1 = FAddSub->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000640 Constant *C0 = dyn_cast<Constant>(Opnd0);
641 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000642 bool Swap = false;
643 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000644 std::swap(C0, C1);
645 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000646 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000647 }
648
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000649 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000650 Value *M1 = ConstantExpr::getFMul(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000651 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000652 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
Craig Topperf40110f2014-04-25 05:29:35 +0000653 nullptr;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000654 if (M0 && M1) {
655 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
656 std::swap(M0, M1);
657
Benjamin Kramer67485762013-09-30 15:39:59 +0000658 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
659 ? BinaryOperator::CreateFAdd(M0, M1)
660 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000661 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000662 return RI;
663 }
664 }
665 }
666 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000667 }
668
Matt Arsenault56c079f2016-01-30 05:02:00 +0000669 if (Op0 == Op1) {
670 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
671 // sqrt(X) * sqrt(X) -> X
672 if (AllowReassociate && II->getIntrinsicID() == Intrinsic::sqrt)
Sanjay Patel4b198802016-02-01 22:23:39 +0000673 return replaceInstUsesWith(I, II->getOperand(0));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000674
Matt Arsenault56c079f2016-01-30 05:02:00 +0000675 // fabs(X) * fabs(X) -> X * X
676 if (II->getIntrinsicID() == Intrinsic::fabs) {
677 Instruction *FMulVal = BinaryOperator::CreateFMul(II->getOperand(0),
678 II->getOperand(0),
679 I.getName());
680 FMulVal->copyFastMathFlags(&I);
681 return FMulVal;
682 }
683 }
684 }
685
Pedro Artigasd8795042012-11-30 19:09:41 +0000686 // Under unsafe algebra do:
687 // X * log2(0.5*Y) = X*log2(Y) - X
Sanjay Patelb41d4612014-10-02 15:20:45 +0000688 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +0000689 Value *OpX = nullptr;
690 Value *OpY = nullptr;
Pedro Artigasd8795042012-11-30 19:09:41 +0000691 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000692 detectLog2OfHalf(Op0, OpY, Log2);
693 if (OpY) {
694 OpX = Op1;
695 } else {
696 detectLog2OfHalf(Op1, OpY, Log2);
697 if (OpY) {
698 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000699 }
700 }
701 // if pattern detected emit alternate sequence
702 if (OpX && OpY) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000703 BuilderTy::FastMathFlagGuard Guard(*Builder);
Sanjay Patela2528152016-01-12 18:03:37 +0000704 Builder->setFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000705 Log2->setArgOperand(0, OpY);
706 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
Benjamin Kramer67485762013-09-30 15:39:59 +0000707 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
708 FSub->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000709 return replaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000710 }
711 }
712
Shuxin Yange8227452013-01-15 21:09:32 +0000713 // Handle symmetric situation in a 2-iteration loop
714 Value *Opnd0 = Op0;
715 Value *Opnd1 = Op1;
716 for (int i = 0; i < 2; i++) {
717 bool IgnoreZeroSign = I.hasNoSignedZeros();
718 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000719 BuilderTy::FastMathFlagGuard Guard(*Builder);
Sanjay Patela2528152016-01-12 18:03:37 +0000720 Builder->setFastMathFlags(I.getFastMathFlags());
Benjamin Kramer67485762013-09-30 15:39:59 +0000721
Shuxin Yange8227452013-01-15 21:09:32 +0000722 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
723 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000724
Shuxin Yange8227452013-01-15 21:09:32 +0000725 // -X * -Y => X*Y
Owen Andersone8537fc2014-01-16 20:59:41 +0000726 if (N1) {
727 Value *FMul = Builder->CreateFMul(N0, N1);
728 FMul->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000729 return replaceInstUsesWith(I, FMul);
Owen Andersone8537fc2014-01-16 20:59:41 +0000730 }
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000731
Shuxin Yange8227452013-01-15 21:09:32 +0000732 if (Opnd0->hasOneUse()) {
733 // -X * Y => -(X*Y) (Promote negation as high as possible)
734 Value *T = Builder->CreateFMul(N0, Opnd1);
Benjamin Kramer67485762013-09-30 15:39:59 +0000735 Value *Neg = Builder->CreateFNeg(T);
736 Neg->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000737 return replaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000738 }
739 }
Shuxin Yange8227452013-01-15 21:09:32 +0000740
741 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000742 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000743 // 1) to form a power expression (of X).
744 // 2) potentially shorten the critical path: After transformation, the
745 // latency of the instruction Y is amortized by the expression of X*X,
746 // and therefore Y is in a "less critical" position compared to what it
747 // was before the transformation.
748 //
749 if (AllowReassociate) {
750 Value *Opnd0_0, *Opnd0_1;
751 if (Opnd0->hasOneUse() &&
752 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
Craig Topperf40110f2014-04-25 05:29:35 +0000753 Value *Y = nullptr;
Shuxin Yange8227452013-01-15 21:09:32 +0000754 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
755 Y = Opnd0_1;
756 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
757 Y = Opnd0_0;
758
759 if (Y) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000760 BuilderTy::FastMathFlagGuard Guard(*Builder);
Sanjay Patela2528152016-01-12 18:03:37 +0000761 Builder->setFastMathFlags(I.getFastMathFlags());
Benjamin Kramer67485762013-09-30 15:39:59 +0000762 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
Benjamin Kramer67485762013-09-30 15:39:59 +0000763 Value *R = Builder->CreateFMul(T, Y);
764 R->takeName(&I);
Sanjay Patel4b198802016-02-01 22:23:39 +0000765 return replaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000766 }
767 }
768 }
769
770 if (!isa<Constant>(Op1))
771 std::swap(Opnd0, Opnd1);
772 else
773 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000774 }
775
Craig Topperf40110f2014-04-25 05:29:35 +0000776 return Changed ? &I : nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000777}
778
Sanjay Patel6eccf482015-09-09 15:24:36 +0000779/// Try to fold a divide or remainder of a select instruction.
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000780bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
781 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000782
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000783 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
784 int NonNullOperand = -1;
785 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
786 if (ST->isNullValue())
787 NonNullOperand = 2;
788 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
789 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
790 if (ST->isNullValue())
791 NonNullOperand = 1;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000792
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000793 if (NonNullOperand == -1)
794 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000795
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000796 Value *SelectCond = SI->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000797
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000798 // Change the div/rem to use 'Y' instead of the select.
799 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000800
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000801 // Okay, we know we replace the operand of the div/rem with 'Y' with no
802 // problem. However, the select, or the condition of the select may have
803 // multiple uses. Based on our knowledge that the operand must be non-zero,
804 // propagate the known value for the select into other uses of it, and
805 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000806
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000807 // If the select and condition only have a single use, don't bother with this,
808 // early exit.
809 if (SI->use_empty() && SelectCond->hasOneUse())
810 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000811
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000812 // Scan the current block backward, looking for other uses of SI.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000813 BasicBlock::iterator BBI = I.getIterator(), BBFront = I.getParent()->begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000814
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000815 while (BBI != BBFront) {
816 --BBI;
817 // If we found a call to a function, we can't assume it will return, so
818 // information from below it cannot be propagated above it.
819 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
820 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000821
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000822 // Replace uses of the select or its condition with the known values.
823 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
824 I != E; ++I) {
825 if (*I == SI) {
826 *I = SI->getOperand(NonNullOperand);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000827 Worklist.Add(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000828 } else if (*I == SelectCond) {
Jakub Staszak96ff4d62013-06-06 23:34:59 +0000829 *I = Builder->getInt1(NonNullOperand == 1);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000830 Worklist.Add(&*BBI);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000831 }
832 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000833
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000834 // If we past the instruction, quit looking for it.
835 if (&*BBI == SI)
Craig Topperf40110f2014-04-25 05:29:35 +0000836 SI = nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000837 if (&*BBI == SelectCond)
Craig Topperf40110f2014-04-25 05:29:35 +0000838 SelectCond = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000839
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000840 // If we ran out of things to eliminate, break out of the loop.
Craig Topperf40110f2014-04-25 05:29:35 +0000841 if (!SelectCond && !SI)
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000842 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000843
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000844 }
845 return true;
846}
847
848
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000849/// This function implements the transforms common to both integer division
850/// instructions (udiv and sdiv). It is called by the visitors to those integer
851/// division instructions.
852/// @brief Common integer divide transforms
853Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
854 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
855
Chris Lattner7c99f192011-05-22 18:18:41 +0000856 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000857 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +0000858 I.setOperand(1, V);
859 return &I;
860 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000861
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000862 // Handle cases involving: [su]div X, (select Cond, Y, Z)
863 // This does not apply for fdiv.
864 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
865 return &I;
866
David Majnemer27adb122014-10-12 08:34:24 +0000867 if (Instruction *LHS = dyn_cast<Instruction>(Op0)) {
868 const APInt *C2;
869 if (match(Op1, m_APInt(C2))) {
David Majnemerf9a095d2014-08-16 08:55:06 +0000870 Value *X;
David Majnemer27adb122014-10-12 08:34:24 +0000871 const APInt *C1;
872 bool IsSigned = I.getOpcode() == Instruction::SDiv;
David Majnemerf9a095d2014-08-16 08:55:06 +0000873
David Majnemer27adb122014-10-12 08:34:24 +0000874 // (X / C1) / C2 -> X / (C1*C2)
875 if ((IsSigned && match(LHS, m_SDiv(m_Value(X), m_APInt(C1)))) ||
876 (!IsSigned && match(LHS, m_UDiv(m_Value(X), m_APInt(C1))))) {
877 APInt Product(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
878 if (!MultiplyOverflows(*C1, *C2, Product, IsSigned))
879 return BinaryOperator::Create(I.getOpcode(), X,
880 ConstantInt::get(I.getType(), Product));
881 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000882
David Majnemer27adb122014-10-12 08:34:24 +0000883 if ((IsSigned && match(LHS, m_NSWMul(m_Value(X), m_APInt(C1)))) ||
884 (!IsSigned && match(LHS, m_NUWMul(m_Value(X), m_APInt(C1))))) {
885 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
886
887 // (X * C1) / C2 -> X / (C2 / C1) if C2 is a multiple of C1.
888 if (IsMultiple(*C2, *C1, Quotient, IsSigned)) {
889 BinaryOperator *BO = BinaryOperator::Create(
890 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
891 BO->setIsExact(I.isExact());
892 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000893 }
894
David Majnemer27adb122014-10-12 08:34:24 +0000895 // (X * C1) / C2 -> X * (C1 / C2) if C1 is a multiple of C2.
896 if (IsMultiple(*C1, *C2, Quotient, IsSigned)) {
897 BinaryOperator *BO = BinaryOperator::Create(
898 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
899 BO->setHasNoUnsignedWrap(
900 !IsSigned &&
901 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
902 BO->setHasNoSignedWrap(
903 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
904 return BO;
David Majnemerf9a095d2014-08-16 08:55:06 +0000905 }
906 }
David Majnemerf9a095d2014-08-16 08:55:06 +0000907
David Majnemer27adb122014-10-12 08:34:24 +0000908 if ((IsSigned && match(LHS, m_NSWShl(m_Value(X), m_APInt(C1))) &&
909 *C1 != C1->getBitWidth() - 1) ||
910 (!IsSigned && match(LHS, m_NUWShl(m_Value(X), m_APInt(C1))))) {
911 APInt Quotient(C1->getBitWidth(), /*Val=*/0ULL, IsSigned);
912 APInt C1Shifted = APInt::getOneBitSet(
913 C1->getBitWidth(), static_cast<unsigned>(C1->getLimitedValue()));
914
915 // (X << C1) / C2 -> X / (C2 >> C1) if C2 is a multiple of C1.
916 if (IsMultiple(*C2, C1Shifted, Quotient, IsSigned)) {
917 BinaryOperator *BO = BinaryOperator::Create(
918 I.getOpcode(), X, ConstantInt::get(X->getType(), Quotient));
919 BO->setIsExact(I.isExact());
920 return BO;
921 }
922
923 // (X << C1) / C2 -> X * (C2 >> C1) if C1 is a multiple of C2.
924 if (IsMultiple(C1Shifted, *C2, Quotient, IsSigned)) {
925 BinaryOperator *BO = BinaryOperator::Create(
926 Instruction::Mul, X, ConstantInt::get(X->getType(), Quotient));
927 BO->setHasNoUnsignedWrap(
928 !IsSigned &&
929 cast<OverflowingBinaryOperator>(LHS)->hasNoUnsignedWrap());
930 BO->setHasNoSignedWrap(
931 cast<OverflowingBinaryOperator>(LHS)->hasNoSignedWrap());
932 return BO;
933 }
934 }
935
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000936 if (*C2 != 0) // avoid X udiv 0
937 if (Instruction *FoldedDiv = foldOpWithConstantIntoOperand(I))
938 return FoldedDiv;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000939 }
940 }
941
Craig Topper218a3592017-04-17 03:41:47 +0000942 if (match(Op0, m_One())) {
943 assert(!I.getType()->getScalarType()->isIntegerTy(1) &&
944 "i1 divide not removed?");
945 if (I.getOpcode() == Instruction::SDiv) {
946 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
947 // result is one, if Op1 is -1 then the result is minus one, otherwise
948 // it's zero.
949 Value *Inc = Builder->CreateAdd(Op1, Op0);
950 Value *Cmp = Builder->CreateICmpULT(
951 Inc, ConstantInt::get(I.getType(), 3));
952 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
953 } else {
954 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
955 // result is one, otherwise it's zero.
956 return new ZExtInst(Builder->CreateICmpEQ(Op1, Op0), I.getType());
Nick Lewyckyf0cf8fa2014-05-14 03:03:05 +0000957 }
958 }
959
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000960 // See if we can fold away this div instruction.
961 if (SimplifyDemandedInstructionBits(I))
962 return &I;
963
Duncan Sands771e82a2011-01-28 16:51:11 +0000964 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Craig Topperf40110f2014-04-25 05:29:35 +0000965 Value *X = nullptr, *Z = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +0000966 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
967 bool isSigned = I.getOpcode() == Instruction::SDiv;
968 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
969 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
970 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000971 }
972
Craig Topperf40110f2014-04-25 05:29:35 +0000973 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000974}
975
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000976/// dyn_castZExtVal - Checks if V is a zext or constant that can
977/// be truncated to Ty without losing bits.
Chris Lattner229907c2011-07-18 04:54:35 +0000978static Value *dyn_castZExtVal(Value *V, Type *Ty) {
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000979 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
980 if (Z->getSrcTy() == Ty)
981 return Z->getOperand(0);
982 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
983 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
984 return ConstantExpr::getTrunc(C, Ty);
985 }
Craig Topperf40110f2014-04-25 05:29:35 +0000986 return nullptr;
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000987}
988
David Majnemer37f8f442013-07-04 21:17:49 +0000989namespace {
990const unsigned MaxDepth = 6;
991typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
992 const BinaryOperator &I,
993 InstCombiner &IC);
994
995/// \brief Used to maintain state for visitUDivOperand().
996struct UDivFoldAction {
997 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
998 ///< operand. This can be zero if this action
999 ///< joins two actions together.
1000
1001 Value *OperandToFold; ///< Which operand to fold.
1002 union {
1003 Instruction *FoldResult; ///< The instruction returned when FoldAction is
1004 ///< invoked.
1005
1006 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
1007 ///< joins two actions together.
1008 };
1009
1010 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Craig Topperf40110f2014-04-25 05:29:35 +00001011 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemer37f8f442013-07-04 21:17:49 +00001012 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
1013 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
1014};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001015}
David Majnemer37f8f442013-07-04 21:17:49 +00001016
1017// X udiv 2^C -> X >> C
1018static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
1019 const BinaryOperator &I, InstCombiner &IC) {
1020 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
1021 BinaryOperator *LShr = BinaryOperator::CreateLShr(
1022 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
Suyog Sarda65f5ae92014-10-07 12:04:07 +00001023 if (I.isExact())
1024 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +00001025 return LShr;
1026}
1027
1028// X udiv C, where C >= signbit
1029static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
1030 const BinaryOperator &I, InstCombiner &IC) {
1031 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
1032
1033 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
1034 ConstantInt::get(I.getType(), 1));
1035}
1036
1037// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001038// X udiv (zext (C1 << N)), where C1 is "1<<C2" --> X >> (N+C2)
David Majnemer37f8f442013-07-04 21:17:49 +00001039static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
1040 InstCombiner &IC) {
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001041 Value *ShiftLeft;
1042 if (!match(Op1, m_ZExt(m_Value(ShiftLeft))))
1043 ShiftLeft = Op1;
David Majnemer37f8f442013-07-04 21:17:49 +00001044
Andrea Di Biagioa82d52d2016-09-26 12:07:23 +00001045 const APInt *CI;
1046 Value *N;
1047 if (!match(ShiftLeft, m_Shl(m_APInt(CI), m_Value(N))))
1048 llvm_unreachable("match should never fail here!");
1049 if (*CI != 1)
1050 N = IC.Builder->CreateAdd(N,
1051 ConstantInt::get(N->getType(), CI->logBase2()));
1052 if (Op1 != ShiftLeft)
1053 N = IC.Builder->CreateZExt(N, Op1->getType());
David Majnemer37f8f442013-07-04 21:17:49 +00001054 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
Suyog Sarda65f5ae92014-10-07 12:04:07 +00001055 if (I.isExact())
1056 LShr->setIsExact();
David Majnemer37f8f442013-07-04 21:17:49 +00001057 return LShr;
1058}
1059
1060// \brief Recursively visits the possible right hand operands of a udiv
1061// instruction, seeing through select instructions, to determine if we can
1062// replace the udiv with something simpler. If we find that an operand is not
1063// able to simplify the udiv, we abort the entire transformation.
1064static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
1065 SmallVectorImpl<UDivFoldAction> &Actions,
1066 unsigned Depth = 0) {
1067 // Check to see if this is an unsigned division with an exact power of 2,
1068 // if so, convert to a right shift.
1069 if (match(Op1, m_Power2())) {
1070 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
1071 return Actions.size();
1072 }
1073
1074 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
1075 // X udiv C, where C >= signbit
1076 if (C->getValue().isNegative()) {
1077 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
1078 return Actions.size();
1079 }
1080
1081 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
1082 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
1083 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
1084 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
1085 return Actions.size();
1086 }
1087
1088 // The remaining tests are all recursive, so bail out if we hit the limit.
1089 if (Depth++ == MaxDepth)
1090 return 0;
1091
1092 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
David Majnemer492e6122014-08-30 09:19:05 +00001093 if (size_t LHSIdx =
1094 visitUDivOperand(Op0, SI->getOperand(1), I, Actions, Depth))
1095 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions, Depth)) {
1096 Actions.push_back(UDivFoldAction(nullptr, Op1, LHSIdx - 1));
David Majnemer37f8f442013-07-04 21:17:49 +00001097 return Actions.size();
1098 }
1099
1100 return 0;
1101}
1102
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001103Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
1104 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1105
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001106 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001107 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001108
Daniel Berlin2c75c632017-04-26 20:56:07 +00001109 if (Value *V = SimplifyUDivInst(Op0, Op1, SQ))
Sanjay Patel4b198802016-02-01 22:23:39 +00001110 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +00001111
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001112 // Handle the integer div common cases
1113 if (Instruction *Common = commonIDivTransforms(I))
1114 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001115
Benjamin Kramerd4a64712012-08-30 15:07:40 +00001116 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
David Majnemera2521382014-10-13 21:48:30 +00001117 {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +00001118 Value *X;
David Majnemera2521382014-10-13 21:48:30 +00001119 const APInt *C1, *C2;
1120 if (match(Op0, m_LShr(m_Value(X), m_APInt(C1))) &&
1121 match(Op1, m_APInt(C2))) {
1122 bool Overflow;
1123 APInt C2ShlC1 = C2->ushl_ov(*C1, Overflow);
David Majnemera3aeb152014-11-22 18:16:54 +00001124 if (!Overflow) {
1125 bool IsExact = I.isExact() && match(Op0, m_Exact(m_Value()));
1126 BinaryOperator *BO = BinaryOperator::CreateUDiv(
David Majnemera2521382014-10-13 21:48:30 +00001127 X, ConstantInt::get(X->getType(), C2ShlC1));
David Majnemera3aeb152014-11-22 18:16:54 +00001128 if (IsExact)
1129 BO->setIsExact();
1130 return BO;
1131 }
David Majnemera2521382014-10-13 21:48:30 +00001132 }
Nadav Rotem11935b22012-08-28 10:01:43 +00001133 }
1134
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001135 // (zext A) udiv (zext B) --> zext (A udiv B)
1136 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1137 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
Suyog Sardaea205512014-10-07 11:56:06 +00001138 return new ZExtInst(
1139 Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div", I.isExact()),
1140 I.getType());
Benjamin Kramer9aa91b12011-04-30 18:16:07 +00001141
David Majnemer37f8f442013-07-04 21:17:49 +00001142 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
1143 SmallVector<UDivFoldAction, 6> UDivActions;
1144 if (visitUDivOperand(Op0, Op1, I, UDivActions))
1145 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
1146 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
1147 Value *ActionOp1 = UDivActions[i].OperandToFold;
1148 Instruction *Inst;
1149 if (Action)
1150 Inst = Action(Op0, ActionOp1, I, *this);
1151 else {
1152 // This action joins two actions together. The RHS of this action is
1153 // simply the last action we processed, we saved the LHS action index in
1154 // the joining action.
1155 size_t SelectRHSIdx = i - 1;
1156 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
1157 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
1158 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
1159 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
1160 SelectLHS, SelectRHS);
1161 }
1162
1163 // If this is the last action to process, return it to the InstCombiner.
1164 // Otherwise, we insert it before the UDiv and record it so that we may
1165 // use it as part of a joining action (i.e., a SelectInst).
1166 if (e - i != 1) {
1167 Inst->insertBefore(&I);
1168 UDivActions[i].FoldResult = Inst;
1169 } else
1170 return Inst;
1171 }
1172
Craig Topperf40110f2014-04-25 05:29:35 +00001173 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001174}
1175
1176Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
1177 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1178
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001179 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001180 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001181
Daniel Berlin2c75c632017-04-26 20:56:07 +00001182 if (Value *V = SimplifySDivInst(Op0, Op1, SQ))
Sanjay Patel4b198802016-02-01 22:23:39 +00001183 return replaceInstUsesWith(I, V);
Duncan Sands771e82a2011-01-28 16:51:11 +00001184
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001185 // Handle the integer div common cases
1186 if (Instruction *Common = commonIDivTransforms(I))
1187 return Common;
1188
Sanjay Patelc6ada532016-06-27 17:25:57 +00001189 const APInt *Op1C;
Sanjay Patelbedd1f92016-06-27 18:38:40 +00001190 if (match(Op1, m_APInt(Op1C))) {
1191 // sdiv X, -1 == -X
1192 if (Op1C->isAllOnesValue())
1193 return BinaryOperator::CreateNeg(Op0);
1194
1195 // sdiv exact X, C --> ashr exact X, log2(C)
1196 if (I.isExact() && Op1C->isNonNegative() && Op1C->isPowerOf2()) {
1197 Value *ShAmt = ConstantInt::get(Op1->getType(), Op1C->exactLogBase2());
1198 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
1199 }
Sanjay Patel59ed2ff2016-06-27 22:27:11 +00001200
1201 // If the dividend is sign-extended and the constant divisor is small enough
1202 // to fit in the source type, shrink the division to the narrower type:
1203 // (sext X) sdiv C --> sext (X sdiv C)
1204 Value *Op0Src;
1205 if (match(Op0, m_OneUse(m_SExt(m_Value(Op0Src)))) &&
1206 Op0Src->getType()->getScalarSizeInBits() >= Op1C->getMinSignedBits()) {
1207
1208 // In the general case, we need to make sure that the dividend is not the
1209 // minimum signed value because dividing that by -1 is UB. But here, we
1210 // know that the -1 divisor case is already handled above.
1211
1212 Constant *NarrowDivisor =
1213 ConstantExpr::getTrunc(cast<Constant>(Op1), Op0Src->getType());
1214 Value *NarrowOp = Builder->CreateSDiv(Op0Src, NarrowDivisor);
1215 return new SExtInst(NarrowOp, Op0->getType());
1216 }
Benjamin Kramer72196f32014-01-19 15:24:22 +00001217 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001218
Benjamin Kramer72196f32014-01-19 15:24:22 +00001219 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
David Majnemerf28e2a42014-07-02 06:42:13 +00001220 // X/INT_MIN -> X == INT_MIN
1221 if (RHS->isMinSignedValue())
1222 return new ZExtInst(Builder->CreateICmpEQ(Op0, Op1), I.getType());
1223
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001224 // -X/C --> X/-C provided the negation doesn't overflow.
David Majnemerfa4699e2014-11-22 20:00:34 +00001225 Value *X;
1226 if (match(Op0, m_NSWSub(m_Zero(), m_Value(X)))) {
1227 auto *BO = BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(RHS));
1228 BO->setIsExact(I.isExact());
1229 return BO;
1230 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001231 }
1232
1233 // If the sign bits of both operands are zero (i.e. we can prove they are
1234 // unsigned inputs), turn this into a udiv.
Craig Topperbcfd2d12017-04-20 16:56:25 +00001235 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
Craig Topperf2484682017-04-17 01:51:19 +00001236 if (MaskedValueIsZero(Op0, Mask, 0, &I)) {
1237 if (MaskedValueIsZero(Op1, Mask, 0, &I)) {
1238 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
1239 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1240 BO->setIsExact(I.isExact());
1241 return BO;
1242 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001243
Craig Topperf2484682017-04-17 01:51:19 +00001244 if (isKnownToBeAPowerOfTwo(Op1, DL, /*OrZero*/ true, 0, &AC, &I, &DT)) {
1245 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1246 // Safe because the only negative value (1 << Y) can take on is
1247 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1248 // the sign bit set.
1249 auto *BO = BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1250 BO->setIsExact(I.isExact());
1251 return BO;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001252 }
1253 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001254
Craig Topperf40110f2014-04-25 05:29:35 +00001255 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001256}
1257
Shuxin Yang320f52a2013-01-14 22:48:41 +00001258/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1259/// FP value and:
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001260/// 1) 1/C is exact, or
Shuxin Yang320f52a2013-01-14 22:48:41 +00001261/// 2) reciprocal is allowed.
Sylvestre Ledru149e2812013-05-14 23:36:24 +00001262/// If the conversion was successful, the simplified expression "X * 1/C" is
Shuxin Yang320f52a2013-01-14 22:48:41 +00001263/// returned; otherwise, NULL is returned.
1264///
Suyog Sardaea205512014-10-07 11:56:06 +00001265static Instruction *CvtFDivConstToReciprocal(Value *Dividend, Constant *Divisor,
Shuxin Yang320f52a2013-01-14 22:48:41 +00001266 bool AllowReciprocal) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001267 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001268 return nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001269
1270 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001271 APFloat Reciprocal(FpVal.getSemantics());
1272 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001273
Michael Gottesman3cb77ab2013-06-19 21:23:18 +00001274 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001275 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1276 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1277 Cvt = !Reciprocal.isDenormal();
1278 }
1279
1280 if (!Cvt)
Craig Topperf40110f2014-04-25 05:29:35 +00001281 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001282
1283 ConstantFP *R;
1284 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1285 return BinaryOperator::CreateFMul(Dividend, R);
1286}
1287
Frits van Bommel2a559512011-01-29 17:50:27 +00001288Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1289 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1290
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001291 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001292 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001293
Daniel Berlin2c75c632017-04-26 20:56:07 +00001294 if (Value *V = SimplifyFDivInst(Op0, Op1, I.getFastMathFlags(), SQ))
Sanjay Patel4b198802016-02-01 22:23:39 +00001295 return replaceInstUsesWith(I, V);
Frits van Bommel2a559512011-01-29 17:50:27 +00001296
Stephen Lina9b57f62013-07-20 07:13:13 +00001297 if (isa<Constant>(Op0))
1298 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1299 if (Instruction *R = FoldOpIntoSelect(I, SI))
1300 return R;
1301
Shuxin Yang320f52a2013-01-14 22:48:41 +00001302 bool AllowReassociate = I.hasUnsafeAlgebra();
1303 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001304
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001305 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001306 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1307 if (Instruction *R = FoldOpIntoSelect(I, SI))
1308 return R;
1309
Shuxin Yang320f52a2013-01-14 22:48:41 +00001310 if (AllowReassociate) {
Craig Topperf40110f2014-04-25 05:29:35 +00001311 Constant *C1 = nullptr;
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001312 Constant *C2 = Op1C;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001313 Value *X;
Craig Topperf40110f2014-04-25 05:29:35 +00001314 Instruction *Res = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001315
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001316 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001317 // (X*C1)/C2 => X * (C1/C2)
1318 //
1319 Constant *C = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001320 if (isNormalFp(C))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001321 Res = BinaryOperator::CreateFMul(X, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001322 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001323 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1324 //
1325 Constant *C = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001326 if (isNormalFp(C)) {
1327 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001328 if (!Res)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001329 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001330 }
1331 }
1332
1333 if (Res) {
1334 Res->setFastMathFlags(I.getFastMathFlags());
1335 return Res;
1336 }
1337 }
1338
1339 // X / C => X * 1/C
Owen Anderson4557a152014-01-16 21:07:52 +00001340 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1341 T->copyFastMathFlags(&I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001342 return T;
Owen Anderson4557a152014-01-16 21:07:52 +00001343 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001344
Craig Topperf40110f2014-04-25 05:29:35 +00001345 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001346 }
1347
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001348 if (AllowReassociate && isa<Constant>(Op0)) {
1349 Constant *C1 = cast<Constant>(Op0), *C2;
Craig Topperf40110f2014-04-25 05:29:35 +00001350 Constant *Fold = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001351 Value *X;
1352 bool CreateDiv = true;
1353
1354 // C1 / (X*C2) => (C1/C2) / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001355 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001356 Fold = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001357 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001358 // C1 / (X/C2) => (C1*C2) / X
1359 Fold = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001360 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001361 // C1 / (C2/X) => (C1/C2) * X
1362 Fold = ConstantExpr::getFDiv(C1, C2);
1363 CreateDiv = false;
1364 }
1365
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001366 if (Fold && isNormalFp(Fold)) {
1367 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1368 : BinaryOperator::CreateFMul(X, Fold);
1369 R->setFastMathFlags(I.getFastMathFlags());
1370 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001371 }
Craig Topperf40110f2014-04-25 05:29:35 +00001372 return nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001373 }
1374
1375 if (AllowReassociate) {
1376 Value *X, *Y;
Craig Topperf40110f2014-04-25 05:29:35 +00001377 Value *NewInst = nullptr;
1378 Instruction *SimpR = nullptr;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001379
1380 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1381 // (X/Y) / Z => X / (Y*Z)
1382 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001383 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001384 NewInst = Builder->CreateFMul(Y, Op1);
Owen Anderson1664dc82014-01-20 07:44:53 +00001385 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1386 FastMathFlags Flags = I.getFastMathFlags();
1387 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1388 RI->setFastMathFlags(Flags);
1389 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001390 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1391 }
1392 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1393 // Z / (X/Y) => Z*Y / X
1394 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001395 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001396 NewInst = Builder->CreateFMul(Op0, Y);
Owen Anderson1664dc82014-01-20 07:44:53 +00001397 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1398 FastMathFlags Flags = I.getFastMathFlags();
1399 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1400 RI->setFastMathFlags(Flags);
1401 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001402 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1403 }
1404 }
1405
1406 if (NewInst) {
1407 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1408 T->setDebugLoc(I.getDebugLoc());
1409 SimpR->setFastMathFlags(I.getFastMathFlags());
1410 return SimpR;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001411 }
1412 }
1413
Matt Arsenaultfdb78f82017-01-10 23:08:54 +00001414 Value *LHS;
1415 Value *RHS;
1416
1417 // -x / -y -> x / y
1418 if (match(Op0, m_FNeg(m_Value(LHS))) && match(Op1, m_FNeg(m_Value(RHS)))) {
1419 I.setOperand(0, LHS);
1420 I.setOperand(1, RHS);
1421 return &I;
1422 }
1423
Craig Topperf40110f2014-04-25 05:29:35 +00001424 return nullptr;
Frits van Bommel2a559512011-01-29 17:50:27 +00001425}
1426
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001427/// This function implements the transforms common to both integer remainder
1428/// instructions (urem and srem). It is called by the visitors to those integer
1429/// remainder instructions.
1430/// @brief Common integer remainder transforms
1431Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1432 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1433
Chris Lattner7c99f192011-05-22 18:18:41 +00001434 // The RHS is known non-zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001435 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this, I)) {
Chris Lattner7c99f192011-05-22 18:18:41 +00001436 I.setOperand(1, V);
1437 return &I;
1438 }
1439
Duncan Sandsa3e36992011-05-02 16:27:02 +00001440 // Handle cases involving: rem X, (select Cond, Y, Z)
1441 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1442 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001443
Benjamin Kramer72196f32014-01-19 15:24:22 +00001444 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001445 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1446 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1447 if (Instruction *R = FoldOpIntoSelect(I, SI))
1448 return R;
Craig Topperfb71b7d2017-04-14 19:20:12 +00001449 } else if (auto *PN = dyn_cast<PHINode>(Op0I)) {
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001450 using namespace llvm::PatternMatch;
1451 const APInt *Op1Int;
1452 if (match(Op1, m_APInt(Op1Int)) && !Op1Int->isMinValue() &&
1453 (I.getOpcode() == Instruction::URem ||
1454 !Op1Int->isMinSignedValue())) {
Craig Topperfb71b7d2017-04-14 19:20:12 +00001455 // foldOpIntoPhi will speculate instructions to the end of the PHI's
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001456 // predecessor blocks, so do this only if we know the srem or urem
1457 // will not fault.
Craig Topperfb71b7d2017-04-14 19:20:12 +00001458 if (Instruction *NV = foldOpIntoPhi(I, PN))
Sanjoy Dasb7e861a2016-06-05 21:17:04 +00001459 return NV;
1460 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001461 }
1462
1463 // See if we can fold away this rem instruction.
1464 if (SimplifyDemandedInstructionBits(I))
1465 return &I;
1466 }
1467 }
1468
Craig Topperf40110f2014-04-25 05:29:35 +00001469 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001470}
1471
1472Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1473 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1474
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001475 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001476 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001477
Daniel Berlin2c75c632017-04-26 20:56:07 +00001478 if (Value *V = SimplifyURemInst(Op0, Op1, SQ))
Sanjay Patel4b198802016-02-01 22:23:39 +00001479 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001480
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001481 if (Instruction *common = commonIRemTransforms(I))
1482 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001483
David Majnemer6c30f492013-05-12 00:07:05 +00001484 // (zext A) urem (zext B) --> zext (A urem B)
1485 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1486 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1487 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1488 I.getType());
1489
David Majnemer470b0772013-05-11 09:01:28 +00001490 // X urem Y -> X and Y-1, where Y is a power of 2,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001491 if (isKnownToBeAPowerOfTwo(Op1, DL, /*OrZero*/ true, 0, &AC, &I, &DT)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001492 Constant *N1 = Constant::getAllOnesValue(I.getType());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001493 Value *Add = Builder->CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001494 return BinaryOperator::CreateAnd(Op0, Add);
1495 }
1496
Nick Lewycky7459be62013-07-13 01:16:47 +00001497 // 1 urem X -> zext(X != 1)
1498 if (match(Op0, m_One())) {
1499 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1500 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
Sanjay Patel4b198802016-02-01 22:23:39 +00001501 return replaceInstUsesWith(I, Ext);
Nick Lewycky7459be62013-07-13 01:16:47 +00001502 }
1503
Sanjay Patel30ef70b2016-09-22 22:36:26 +00001504 // X urem C -> X < C ? X : X - C, where C >= signbit.
1505 const APInt *DivisorC;
1506 if (match(Op1, m_APInt(DivisorC)) && DivisorC->isNegative()) {
1507 Value *Cmp = Builder->CreateICmpULT(Op0, Op1);
1508 Value *Sub = Builder->CreateSub(Op0, Op1);
1509 return SelectInst::Create(Cmp, Op0, Sub);
1510 }
1511
Craig Topperf40110f2014-04-25 05:29:35 +00001512 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001513}
1514
1515Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1516 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1517
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001518 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001519 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001520
Daniel Berlin2c75c632017-04-26 20:56:07 +00001521 if (Value *V = SimplifySRemInst(Op0, Op1, SQ))
Sanjay Patel4b198802016-02-01 22:23:39 +00001522 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001523
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001524 // Handle the integer rem common cases
1525 if (Instruction *Common = commonIRemTransforms(I))
1526 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001527
David Majnemerdb077302014-10-13 22:37:51 +00001528 {
1529 const APInt *Y;
1530 // X % -Y -> X % Y
1531 if (match(Op1, m_APInt(Y)) && Y->isNegative() && !Y->isMinSignedValue()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001532 Worklist.AddValue(I.getOperand(1));
David Majnemerdb077302014-10-13 22:37:51 +00001533 I.setOperand(1, ConstantInt::get(I.getType(), -*Y));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001534 return &I;
1535 }
David Majnemerdb077302014-10-13 22:37:51 +00001536 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001537
1538 // If the sign bits of both operands are zero (i.e. we can prove they are
1539 // unsigned inputs), turn this into a urem.
Craig Topperbcfd2d12017-04-20 16:56:25 +00001540 APInt Mask(APInt::getSignMask(I.getType()->getScalarSizeInBits()));
Craig Topper1a18a7c2017-04-17 01:51:24 +00001541 if (MaskedValueIsZero(Op1, Mask, 0, &I) &&
1542 MaskedValueIsZero(Op0, Mask, 0, &I)) {
1543 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
1544 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001545 }
1546
1547 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001548 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1549 Constant *C = cast<Constant>(Op1);
1550 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001551
1552 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001553 bool hasMissing = false;
1554 for (unsigned i = 0; i != VWidth; ++i) {
1555 Constant *Elt = C->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001556 if (!Elt) {
Chris Lattner0256be92012-01-27 03:08:05 +00001557 hasMissing = true;
1558 break;
1559 }
1560
1561 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001562 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001563 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001564 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001565
Chris Lattner0256be92012-01-27 03:08:05 +00001566 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001567 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001568 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001569 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001570 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001571 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001572 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001573 }
1574 }
1575
1576 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001577 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001578 Worklist.AddValue(I.getOperand(1));
1579 I.setOperand(1, NewRHSV);
1580 return &I;
1581 }
1582 }
1583 }
1584
Craig Topperf40110f2014-04-25 05:29:35 +00001585 return nullptr;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001586}
1587
1588Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001589 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001590
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001591 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001592 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001593
Daniel Berlin2c75c632017-04-26 20:56:07 +00001594 if (Value *V = SimplifyFRemInst(Op0, Op1, I.getFastMathFlags(), SQ))
Sanjay Patel4b198802016-02-01 22:23:39 +00001595 return replaceInstUsesWith(I, V);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001596
1597 // Handle cases involving: rem X, (select Cond, Y, Z)
1598 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1599 return &I;
1600
Craig Topperf40110f2014-04-25 05:29:35 +00001601 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001602}