blob: e6c04f51dad6087e9246658234bcb97bebd1ebdf [file] [log] [blame]
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001//===- InstCombineMulDivRem.cpp -------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visit functions for mul, fmul, sdiv, udiv, fdiv,
11// srem, urem, frem.
12//
13//===----------------------------------------------------------------------===//
14
15#include "InstCombine.h"
Duncan Sandsd0eb6d32010-12-21 14:00:22 +000016#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/IntrinsicInst.h"
Chris Lattnerdc054bf2010-01-05 06:09:35 +000018#include "llvm/Support/PatternMatch.h"
19using namespace llvm;
20using namespace PatternMatch;
21
Chris Lattner7c99f192011-05-22 18:18:41 +000022
23/// simplifyValueKnownNonZero - The specific integer value is used in a context
24/// where it is known to be non-zero. If this allows us to simplify the
25/// computation, do so and return the new operand, otherwise return null.
26static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC) {
27 // If V has multiple uses, then we would have to do more analysis to determine
28 // if this is safe. For example, the use could be in dynamically unreached
29 // code.
30 if (!V->hasOneUse()) return 0;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000031
Chris Lattner388cb8a2011-05-23 00:32:19 +000032 bool MadeChange = false;
33
Chris Lattner7c99f192011-05-22 18:18:41 +000034 // ((1 << A) >>u B) --> (1 << (A-B))
35 // Because V cannot be zero, we know that B is less than A.
Chris Lattner321c58f2011-05-23 00:09:55 +000036 Value *A = 0, *B = 0, *PowerOf2 = 0;
37 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(PowerOf2), m_Value(A))),
Chris Lattner7c99f192011-05-22 18:18:41 +000038 m_Value(B))) &&
39 // The "1" can be any value known to be a power of 2.
Rafael Espindola319f74c2012-12-13 03:37:24 +000040 isKnownToBeAPowerOfTwo(PowerOf2)) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +000041 A = IC.Builder->CreateSub(A, B);
Chris Lattner321c58f2011-05-23 00:09:55 +000042 return IC.Builder->CreateShl(PowerOf2, A);
Chris Lattner7c99f192011-05-22 18:18:41 +000043 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000044
Chris Lattner388cb8a2011-05-23 00:32:19 +000045 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
46 // inexact. Similarly for <<.
47 if (BinaryOperator *I = dyn_cast<BinaryOperator>(V))
Rafael Espindola319f74c2012-12-13 03:37:24 +000048 if (I->isLogicalShift() && isKnownToBeAPowerOfTwo(I->getOperand(0))) {
Chris Lattner388cb8a2011-05-23 00:32:19 +000049 // We know that this is an exact/nuw shift and that the input is a
50 // non-zero context as well.
51 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC)) {
52 I->setOperand(0, V2);
53 MadeChange = true;
54 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000055
Chris Lattner388cb8a2011-05-23 00:32:19 +000056 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
57 I->setIsExact();
58 MadeChange = true;
59 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000060
Chris Lattner388cb8a2011-05-23 00:32:19 +000061 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
62 I->setHasNoUnsignedWrap();
63 MadeChange = true;
64 }
65 }
66
Chris Lattner162dfc32011-05-22 18:26:48 +000067 // TODO: Lots more we could do here:
Chris Lattner162dfc32011-05-22 18:26:48 +000068 // If V is a phi node, we can call this on each of its operands.
69 // "select cond, X, 0" can simplify to "X".
Jim Grosbachbdbd7342013-04-05 21:20:12 +000070
Chris Lattner388cb8a2011-05-23 00:32:19 +000071 return MadeChange ? V : 0;
Chris Lattner7c99f192011-05-22 18:18:41 +000072}
73
74
Chris Lattnerdc054bf2010-01-05 06:09:35 +000075/// MultiplyOverflows - True if the multiply can not be expressed in an int
76/// this size.
77static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
78 uint32_t W = C1->getBitWidth();
79 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
80 if (sign) {
Jay Foad583abbc2010-12-07 08:25:19 +000081 LHSExt = LHSExt.sext(W * 2);
82 RHSExt = RHSExt.sext(W * 2);
Chris Lattnerdc054bf2010-01-05 06:09:35 +000083 } else {
Jay Foad583abbc2010-12-07 08:25:19 +000084 LHSExt = LHSExt.zext(W * 2);
85 RHSExt = RHSExt.zext(W * 2);
Chris Lattnerdc054bf2010-01-05 06:09:35 +000086 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000087
Chris Lattnerdc054bf2010-01-05 06:09:35 +000088 APInt MulExt = LHSExt * RHSExt;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000089
Chris Lattnerdc054bf2010-01-05 06:09:35 +000090 if (!sign)
91 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
Jim Grosbachbdbd7342013-04-05 21:20:12 +000092
Chris Lattnerdc054bf2010-01-05 06:09:35 +000093 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
94 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
95 return MulExt.slt(Min) || MulExt.sgt(Max);
96}
97
Rafael Espindola65281bf2013-05-31 14:27:15 +000098/// \brief A helper routine of InstCombiner::visitMul().
99///
100/// If C is a vector of known powers of 2, then this function returns
101/// a new vector obtained from C replacing each element with its logBase2.
102/// Return a null pointer otherwise.
103static Constant *getLogBase2Vector(ConstantDataVector *CV) {
104 const APInt *IVal;
105 SmallVector<Constant *, 4> Elts;
106
107 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
108 Constant *Elt = CV->getElementAsConstant(I);
109 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
110 return 0;
111 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
112 }
113
114 return ConstantVector::get(Elts);
115}
116
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000117Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000118 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000119 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
120
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000121 if (Value *V = SimplifyMulInst(Op0, Op1, TD))
122 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000123
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000124 if (Value *V = SimplifyUsingDistributiveLaws(I))
125 return ReplaceInstUsesWith(I, V);
126
Chris Lattner6b657ae2011-02-10 05:36:31 +0000127 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X
128 return BinaryOperator::CreateNeg(Op0, I.getName());
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000129
Rafael Espindola65281bf2013-05-31 14:27:15 +0000130 // Also allow combining multiply instructions on vectors.
131 {
132 Value *NewOp;
133 Constant *C1, *C2;
134 const APInt *IVal;
135 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
136 m_Constant(C1))) &&
137 match(C1, m_APInt(IVal)))
138 // ((X << C1)*C2) == (X * (C2 << C1))
139 return BinaryOperator::CreateMul(NewOp, ConstantExpr::getShl(C1, C2));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000140
Rafael Espindola65281bf2013-05-31 14:27:15 +0000141 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
142 Constant *NewCst = 0;
143 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
144 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
145 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
146 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
147 // Replace X*(2^C) with X << C, where C is a vector of known
148 // constant powers of 2.
149 NewCst = getLogBase2Vector(CV);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000150
Rafael Espindola65281bf2013-05-31 14:27:15 +0000151 if (NewCst) {
152 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
153 if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap();
154 if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap();
155 return Shl;
156 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000157 }
Rafael Espindola65281bf2013-05-31 14:27:15 +0000158 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000159
Rafael Espindola65281bf2013-05-31 14:27:15 +0000160 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +0000161 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
162 { Value *X; ConstantInt *C1;
163 if (Op0->hasOneUse() &&
164 match(Op0, m_Add(m_Value(X), m_ConstantInt(C1)))) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000165 Value *Add = Builder->CreateMul(X, CI);
Chris Lattner6b657ae2011-02-10 05:36:31 +0000166 return BinaryOperator::CreateAdd(Add, Builder->CreateMul(C1, CI));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000167 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000168 }
Stuart Hastings82843742011-05-30 20:00:33 +0000169
Stuart Hastings23804832011-06-01 16:42:47 +0000170 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
171 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
172 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastings82843742011-05-30 20:00:33 +0000173 {
174 const APInt & Val = CI->getValue();
175 const APInt &PosVal = Val.abs();
176 if (Val.isNegative() && PosVal.isPowerOf2()) {
Stuart Hastings23804832011-06-01 16:42:47 +0000177 Value *X = 0, *Y = 0;
178 if (Op0->hasOneUse()) {
179 ConstantInt *C1;
180 Value *Sub = 0;
181 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
182 Sub = Builder->CreateSub(X, Y, "suba");
183 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
184 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
185 if (Sub)
186 return
187 BinaryOperator::CreateMul(Sub,
188 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastings82843742011-05-30 20:00:33 +0000189 }
190 }
191 }
Chris Lattner6b657ae2011-02-10 05:36:31 +0000192 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000193
Chris Lattner6b657ae2011-02-10 05:36:31 +0000194 // Simplify mul instructions with a constant RHS.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000195 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000196 // Try to fold constant mul into select arguments.
197 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
198 if (Instruction *R = FoldOpIntoSelect(I, SI))
199 return R;
200
201 if (isa<PHINode>(Op0))
202 if (Instruction *NV = FoldOpIntoPhi(I))
203 return NV;
204 }
205
206 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
207 if (Value *Op1v = dyn_castNegVal(Op1))
208 return BinaryOperator::CreateMul(Op0v, Op1v);
209
210 // (X / Y) * Y = X - (X % Y)
211 // (X / Y) * -Y = (X % Y) - X
212 {
213 Value *Op1C = Op1;
214 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
215 if (!BO ||
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000216 (BO->getOpcode() != Instruction::UDiv &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000217 BO->getOpcode() != Instruction::SDiv)) {
218 Op1C = Op0;
219 BO = dyn_cast<BinaryOperator>(Op1);
220 }
221 Value *Neg = dyn_castNegVal(Op1C);
222 if (BO && BO->hasOneUse() &&
223 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
224 (BO->getOpcode() == Instruction::UDiv ||
225 BO->getOpcode() == Instruction::SDiv)) {
226 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
227
Chris Lattner35315d02011-02-06 21:44:57 +0000228 // If the division is exact, X % Y is zero, so we end up with X or -X.
229 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000230 if (SDiv->isExact()) {
231 if (Op1BO == Op1C)
232 return ReplaceInstUsesWith(I, Op0BO);
233 return BinaryOperator::CreateNeg(Op0BO);
234 }
235
236 Value *Rem;
237 if (BO->getOpcode() == Instruction::UDiv)
238 Rem = Builder->CreateURem(Op0BO, Op1BO);
239 else
240 Rem = Builder->CreateSRem(Op0BO, Op1BO);
241 Rem->takeName(BO);
242
243 if (Op1BO == Op1C)
244 return BinaryOperator::CreateSub(Op0BO, Rem);
245 return BinaryOperator::CreateSub(Rem, Op0BO);
246 }
247 }
248
249 /// i1 mul -> i1 and.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000250 if (I.getType()->isIntegerTy(1))
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000251 return BinaryOperator::CreateAnd(Op0, Op1);
252
253 // X*(1 << Y) --> X << Y
254 // (1 << Y)*X --> X << Y
255 {
256 Value *Y;
257 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
258 return BinaryOperator::CreateShl(Op1, Y);
259 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
260 return BinaryOperator::CreateShl(Op0, Y);
261 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000262
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000263 // If one of the operands of the multiply is a cast from a boolean value, then
264 // we know the bool is either zero or one, so this is a 'masking' multiply.
265 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands19d0b472010-02-16 11:11:14 +0000266 if (!I.getType()->isVectorTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000267 // -2 is "-1 << 1" so it is all bits set except the low one.
268 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000269
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000270 Value *BoolCast = 0, *OtherOp = 0;
271 if (MaskedValueIsZero(Op0, Negative2))
272 BoolCast = Op0, OtherOp = Op1;
273 else if (MaskedValueIsZero(Op1, Negative2))
274 BoolCast = Op1, OtherOp = Op0;
275
276 if (BoolCast) {
277 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000278 BoolCast);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000279 return BinaryOperator::CreateAnd(V, OtherOp);
280 }
281 }
282
283 return Changed ? &I : 0;
284}
285
Pedro Artigas993acd02012-11-30 22:07:05 +0000286//
287// Detect pattern:
288//
289// log2(Y*0.5)
290//
291// And check for corresponding fast math flags
292//
293
294static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Pedro Artigas00b83c92012-11-30 22:47:15 +0000295
296 if (!Op->hasOneUse())
297 return;
298
299 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
300 if (!II)
301 return;
302 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
303 return;
304 Log2 = II;
305
306 Value *OpLog2Of = II->getArgOperand(0);
307 if (!OpLog2Of->hasOneUse())
308 return;
309
310 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
311 if (!I)
312 return;
313 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
314 return;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000315
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000316 if (match(I->getOperand(0), m_SpecificFP(0.5)))
Pedro Artigas00b83c92012-11-30 22:47:15 +0000317 Y = I->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000318 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
Pedro Artigas00b83c92012-11-30 22:47:15 +0000319 Y = I->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000320}
Pedro Artigas993acd02012-11-30 22:07:05 +0000321
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000322static bool isFiniteNonZeroFp(Constant *C) {
323 if (C->getType()->isVectorTy()) {
324 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
325 ++I) {
326 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
327 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
328 return false;
329 }
330 return true;
331 }
332
333 return isa<ConstantFP>(C) &&
334 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
335}
336
337static bool isNormalFp(Constant *C) {
338 if (C->getType()->isVectorTy()) {
339 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
340 ++I) {
341 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
342 if (!CFP || !CFP->getValueAPF().isNormal())
343 return false;
344 }
345 return true;
346 }
347
348 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
349}
350
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000351/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
352/// true iff the given value is FMul or FDiv with one and only one operand
353/// being a normal constant (i.e. not Zero/NaN/Infinity).
354static bool isFMulOrFDivWithConstant(Value *V) {
355 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000356 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yang80138662013-01-07 22:41:28 +0000357 I->getOpcode() != Instruction::FDiv))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000358 return false;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000359
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000360 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
361 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000362
363 if (C0 && C1)
364 return false;
365
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000366 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000367}
368
369/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
370/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
371/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000372/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000373/// resulting expression. Note that this function could return NULL in
374/// case the constants cannot be folded into a normal floating-point.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000375///
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000376Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yang80138662013-01-07 22:41:28 +0000377 Instruction *InsertBefore) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000378 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
379
380 Value *Opnd0 = FMulOrDiv->getOperand(0);
381 Value *Opnd1 = FMulOrDiv->getOperand(1);
382
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000383 Constant *C0 = dyn_cast<Constant>(Opnd0);
384 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000385
386 BinaryOperator *R = 0;
387
388 // (X * C0) * C => X * (C0*C)
389 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
390 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000391 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000392 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
393 } else {
394 if (C0) {
395 // (C0 / X) * C => (C0 * C) / X
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000396 if (FMulOrDiv->hasOneUse()) {
397 // It would otherwise introduce another div.
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000398 Constant *F = ConstantExpr::getFMul(C0, C);
Shuxin Yang3a7ca6e2013-09-19 21:13:46 +0000399 if (isNormalFp(F))
400 R = BinaryOperator::CreateFDiv(F, Opnd1);
401 }
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000402 } else {
403 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000404 Constant *F = ConstantExpr::getFDiv(C, C1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000405 if (isNormalFp(F)) {
406 R = BinaryOperator::CreateFMul(Opnd0, F);
407 } else {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000408 // (X / C1) * C => X / (C1/C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000409 Constant *F = ConstantExpr::getFDiv(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000410 if (isNormalFp(F))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000411 R = BinaryOperator::CreateFDiv(Opnd0, F);
412 }
413 }
414 }
415
416 if (R) {
417 R->setHasUnsafeAlgebra(true);
418 InsertNewInstWith(R, *InsertBefore);
419 }
420
421 return R;
422}
423
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000424Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +0000425 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000426 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
427
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000428 if (isa<Constant>(Op0))
429 std::swap(Op0, Op1);
430
Michael Ilsemand5787be2012-12-12 00:28:32 +0000431 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), TD))
432 return ReplaceInstUsesWith(I, V);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000433
Shuxin Yange8227452013-01-15 21:09:32 +0000434 bool AllowReassociate = I.hasUnsafeAlgebra();
435
Michael Ilsemand5787be2012-12-12 00:28:32 +0000436 // Simplify mul instructions with a constant RHS.
437 if (isa<Constant>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000438 // Try to fold constant mul into select arguments.
439 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
440 if (Instruction *R = FoldOpIntoSelect(I, SI))
441 return R;
442
443 if (isa<PHINode>(Op0))
444 if (Instruction *NV = FoldOpIntoPhi(I))
445 return NV;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000446
Owen Andersonf74cfe02014-01-16 20:36:42 +0000447 // (fmul X, -1.0) --> (fsub -0.0, X)
Benjamin Kramerfea9ac92014-01-18 16:43:14 +0000448 if (match(Op1, m_SpecificFP(-1.0))) {
449 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
450 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
Owen Andersonf74cfe02014-01-16 20:36:42 +0000451 RI->copyFastMathFlags(&I);
452 return RI;
453 }
454
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000455 Constant *C = cast<Constant>(Op1);
456 if (AllowReassociate && isFiniteNonZeroFp(C)) {
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000457 // Let MDC denote an expression in one of these forms:
458 // X * C, C/X, X/C, where C is a constant.
459 //
460 // Try to simplify "MDC * Constant"
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000461 if (isFMulOrFDivWithConstant(Op0))
462 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000463 return ReplaceInstUsesWith(I, V);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000464
Quentin Colombete684a6d2013-02-28 21:12:40 +0000465 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000466 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
467 if (FAddSub &&
468 (FAddSub->getOpcode() == Instruction::FAdd ||
469 FAddSub->getOpcode() == Instruction::FSub)) {
470 Value *Opnd0 = FAddSub->getOperand(0);
471 Value *Opnd1 = FAddSub->getOperand(1);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000472 Constant *C0 = dyn_cast<Constant>(Opnd0);
473 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000474 bool Swap = false;
475 if (C0) {
Shuxin Yang80138662013-01-07 22:41:28 +0000476 std::swap(C0, C1);
477 std::swap(Opnd0, Opnd1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000478 Swap = true;
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000479 }
480
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000481 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombete684a6d2013-02-28 21:12:40 +0000482 Value *M1 = ConstantExpr::getFMul(C1, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000483 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000484 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
485 0;
486 if (M0 && M1) {
487 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
488 std::swap(M0, M1);
489
Benjamin Kramer67485762013-09-30 15:39:59 +0000490 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
491 ? BinaryOperator::CreateFAdd(M0, M1)
492 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yange8227452013-01-15 21:09:32 +0000493 RI->copyFastMathFlags(&I);
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000494 return RI;
495 }
496 }
497 }
498 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000499 }
500
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000501
Pedro Artigasd8795042012-11-30 19:09:41 +0000502 // Under unsafe algebra do:
503 // X * log2(0.5*Y) = X*log2(Y) - X
504 if (I.hasUnsafeAlgebra()) {
505 Value *OpX = NULL;
506 Value *OpY = NULL;
507 IntrinsicInst *Log2;
Pedro Artigas993acd02012-11-30 22:07:05 +0000508 detectLog2OfHalf(Op0, OpY, Log2);
509 if (OpY) {
510 OpX = Op1;
511 } else {
512 detectLog2OfHalf(Op1, OpY, Log2);
513 if (OpY) {
514 OpX = Op0;
Pedro Artigasd8795042012-11-30 19:09:41 +0000515 }
516 }
517 // if pattern detected emit alternate sequence
518 if (OpX && OpY) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000519 BuilderTy::FastMathFlagGuard Guard(*Builder);
520 Builder->SetFastMathFlags(Log2->getFastMathFlags());
Pedro Artigasd8795042012-11-30 19:09:41 +0000521 Log2->setArgOperand(0, OpY);
522 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
Benjamin Kramer67485762013-09-30 15:39:59 +0000523 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
524 FSub->takeName(&I);
525 return ReplaceInstUsesWith(I, FSub);
Pedro Artigasd8795042012-11-30 19:09:41 +0000526 }
527 }
528
Shuxin Yange8227452013-01-15 21:09:32 +0000529 // Handle symmetric situation in a 2-iteration loop
530 Value *Opnd0 = Op0;
531 Value *Opnd1 = Op1;
532 for (int i = 0; i < 2; i++) {
533 bool IgnoreZeroSign = I.hasNoSignedZeros();
534 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000535 BuilderTy::FastMathFlagGuard Guard(*Builder);
536 Builder->SetFastMathFlags(I.getFastMathFlags());
537
Shuxin Yange8227452013-01-15 21:09:32 +0000538 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
539 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000540
Shuxin Yange8227452013-01-15 21:09:32 +0000541 // -X * -Y => X*Y
Owen Andersone8537fc2014-01-16 20:59:41 +0000542 if (N1) {
543 Value *FMul = Builder->CreateFMul(N0, N1);
544 FMul->takeName(&I);
545 return ReplaceInstUsesWith(I, FMul);
546 }
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000547
Shuxin Yange8227452013-01-15 21:09:32 +0000548 if (Opnd0->hasOneUse()) {
549 // -X * Y => -(X*Y) (Promote negation as high as possible)
550 Value *T = Builder->CreateFMul(N0, Opnd1);
Benjamin Kramer67485762013-09-30 15:39:59 +0000551 Value *Neg = Builder->CreateFNeg(T);
552 Neg->takeName(&I);
553 return ReplaceInstUsesWith(I, Neg);
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000554 }
555 }
Shuxin Yange8227452013-01-15 21:09:32 +0000556
557 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000558 // The purpose is two-fold:
Shuxin Yange8227452013-01-15 21:09:32 +0000559 // 1) to form a power expression (of X).
560 // 2) potentially shorten the critical path: After transformation, the
561 // latency of the instruction Y is amortized by the expression of X*X,
562 // and therefore Y is in a "less critical" position compared to what it
563 // was before the transformation.
564 //
565 if (AllowReassociate) {
566 Value *Opnd0_0, *Opnd0_1;
567 if (Opnd0->hasOneUse() &&
568 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
569 Value *Y = 0;
570 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
571 Y = Opnd0_1;
572 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
573 Y = Opnd0_0;
574
575 if (Y) {
Benjamin Kramer67485762013-09-30 15:39:59 +0000576 BuilderTy::FastMathFlagGuard Guard(*Builder);
577 Builder->SetFastMathFlags(I.getFastMathFlags());
578 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
Shuxin Yange8227452013-01-15 21:09:32 +0000579
Benjamin Kramer67485762013-09-30 15:39:59 +0000580 Value *R = Builder->CreateFMul(T, Y);
581 R->takeName(&I);
582 return ReplaceInstUsesWith(I, R);
Shuxin Yange8227452013-01-15 21:09:32 +0000583 }
584 }
585 }
586
Stephen Lin03f9fbb2013-07-17 20:06:03 +0000587 // B * (uitofp i1 C) -> select C, B, 0
588 if (I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) {
589 Value *LHS = Op0, *RHS = Op1;
590 Value *B, *C;
Stephen Lin4ef13872013-07-26 17:55:00 +0000591 if (!match(RHS, m_UIToFP(m_Value(C))))
Stephen Lin03f9fbb2013-07-17 20:06:03 +0000592 std::swap(LHS, RHS);
593
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000594 if (match(RHS, m_UIToFP(m_Value(C))) &&
595 C->getType()->getScalarType()->isIntegerTy(1)) {
Stephen Lin03f9fbb2013-07-17 20:06:03 +0000596 B = LHS;
597 Value *Zero = ConstantFP::getNegativeZero(B->getType());
598 return SelectInst::Create(C, B, Zero);
599 }
600 }
601
602 // A * (1 - uitofp i1 C) -> select C, 0, A
603 if (I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) {
604 Value *LHS = Op0, *RHS = Op1;
605 Value *A, *C;
Stephen Lin4ef13872013-07-26 17:55:00 +0000606 if (!match(RHS, m_FSub(m_FPOne(), m_UIToFP(m_Value(C)))))
Stephen Lin03f9fbb2013-07-17 20:06:03 +0000607 std::swap(LHS, RHS);
608
Stephen Lin4ef13872013-07-26 17:55:00 +0000609 if (match(RHS, m_FSub(m_FPOne(), m_UIToFP(m_Value(C)))) &&
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000610 C->getType()->getScalarType()->isIntegerTy(1)) {
Stephen Lin03f9fbb2013-07-17 20:06:03 +0000611 A = LHS;
612 Value *Zero = ConstantFP::getNegativeZero(A->getType());
613 return SelectInst::Create(C, Zero, A);
614 }
615 }
616
Shuxin Yange8227452013-01-15 21:09:32 +0000617 if (!isa<Constant>(Op1))
618 std::swap(Opnd0, Opnd1);
619 else
620 break;
Shuxin Yangf8e9a5a2012-12-14 18:46:06 +0000621 }
622
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000623 return Changed ? &I : 0;
624}
625
626/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
627/// instruction.
628bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
629 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000630
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000631 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
632 int NonNullOperand = -1;
633 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
634 if (ST->isNullValue())
635 NonNullOperand = 2;
636 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
637 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
638 if (ST->isNullValue())
639 NonNullOperand = 1;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000640
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000641 if (NonNullOperand == -1)
642 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000643
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000644 Value *SelectCond = SI->getOperand(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000645
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000646 // Change the div/rem to use 'Y' instead of the select.
647 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000648
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000649 // Okay, we know we replace the operand of the div/rem with 'Y' with no
650 // problem. However, the select, or the condition of the select may have
651 // multiple uses. Based on our knowledge that the operand must be non-zero,
652 // propagate the known value for the select into other uses of it, and
653 // propagate a known value of the condition into its other users.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000654
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000655 // If the select and condition only have a single use, don't bother with this,
656 // early exit.
657 if (SI->use_empty() && SelectCond->hasOneUse())
658 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000659
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000660 // Scan the current block backward, looking for other uses of SI.
661 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000662
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000663 while (BBI != BBFront) {
664 --BBI;
665 // If we found a call to a function, we can't assume it will return, so
666 // information from below it cannot be propagated above it.
667 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
668 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000669
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000670 // Replace uses of the select or its condition with the known values.
671 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
672 I != E; ++I) {
673 if (*I == SI) {
674 *I = SI->getOperand(NonNullOperand);
675 Worklist.Add(BBI);
676 } else if (*I == SelectCond) {
Jakub Staszak96ff4d62013-06-06 23:34:59 +0000677 *I = Builder->getInt1(NonNullOperand == 1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000678 Worklist.Add(BBI);
679 }
680 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000681
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000682 // If we past the instruction, quit looking for it.
683 if (&*BBI == SI)
684 SI = 0;
685 if (&*BBI == SelectCond)
686 SelectCond = 0;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000687
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000688 // If we ran out of things to eliminate, break out of the loop.
689 if (SelectCond == 0 && SI == 0)
690 break;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000691
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000692 }
693 return true;
694}
695
696
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000697/// This function implements the transforms common to both integer division
698/// instructions (udiv and sdiv). It is called by the visitors to those integer
699/// division instructions.
700/// @brief Common integer divide transforms
701Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
702 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
703
Chris Lattner7c99f192011-05-22 18:18:41 +0000704 // The RHS is known non-zero.
705 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
706 I.setOperand(1, V);
707 return &I;
708 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000709
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000710 // Handle cases involving: [su]div X, (select Cond, Y, Z)
711 // This does not apply for fdiv.
712 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
713 return &I;
714
715 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000716 // (X / C1) / C2 -> X / (C1*C2)
717 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
718 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
719 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
720 if (MultiplyOverflows(RHS, LHSRHS,
721 I.getOpcode()==Instruction::SDiv))
722 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner6b657ae2011-02-10 05:36:31 +0000723 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
724 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000725 }
726
727 if (!RHS->isZero()) { // avoid X udiv 0
728 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
729 if (Instruction *R = FoldOpIntoSelect(I, SI))
730 return R;
731 if (isa<PHINode>(Op0))
732 if (Instruction *NV = FoldOpIntoPhi(I))
733 return NV;
734 }
735 }
736
Benjamin Kramer57b3df52011-04-30 18:16:00 +0000737 // See if we can fold away this div instruction.
738 if (SimplifyDemandedInstructionBits(I))
739 return &I;
740
Duncan Sands771e82a2011-01-28 16:51:11 +0000741 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
742 Value *X = 0, *Z = 0;
743 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
744 bool isSigned = I.getOpcode() == Instruction::SDiv;
745 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
746 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
747 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000748 }
749
750 return 0;
751}
752
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000753/// dyn_castZExtVal - Checks if V is a zext or constant that can
754/// be truncated to Ty without losing bits.
Chris Lattner229907c2011-07-18 04:54:35 +0000755static Value *dyn_castZExtVal(Value *V, Type *Ty) {
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000756 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
757 if (Z->getSrcTy() == Ty)
758 return Z->getOperand(0);
759 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
760 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
761 return ConstantExpr::getTrunc(C, Ty);
762 }
763 return 0;
764}
765
David Majnemer37f8f442013-07-04 21:17:49 +0000766namespace {
767const unsigned MaxDepth = 6;
768typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
769 const BinaryOperator &I,
770 InstCombiner &IC);
771
772/// \brief Used to maintain state for visitUDivOperand().
773struct UDivFoldAction {
774 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
775 ///< operand. This can be zero if this action
776 ///< joins two actions together.
777
778 Value *OperandToFold; ///< Which operand to fold.
779 union {
780 Instruction *FoldResult; ///< The instruction returned when FoldAction is
781 ///< invoked.
782
783 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
784 ///< joins two actions together.
785 };
786
787 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
788 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(0) {}
789 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
790 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
791};
792}
793
794// X udiv 2^C -> X >> C
795static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
796 const BinaryOperator &I, InstCombiner &IC) {
797 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
798 BinaryOperator *LShr = BinaryOperator::CreateLShr(
799 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
800 if (I.isExact()) LShr->setIsExact();
801 return LShr;
802}
803
804// X udiv C, where C >= signbit
805static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
806 const BinaryOperator &I, InstCombiner &IC) {
807 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
808
809 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
810 ConstantInt::get(I.getType(), 1));
811}
812
813// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
814static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
815 InstCombiner &IC) {
816 Instruction *ShiftLeft = cast<Instruction>(Op1);
817 if (isa<ZExtInst>(ShiftLeft))
818 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
819
820 const APInt &CI =
821 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
822 Value *N = ShiftLeft->getOperand(1);
823 if (CI != 1)
824 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
825 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
826 N = IC.Builder->CreateZExt(N, Z->getDestTy());
827 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
828 if (I.isExact()) LShr->setIsExact();
829 return LShr;
830}
831
832// \brief Recursively visits the possible right hand operands of a udiv
833// instruction, seeing through select instructions, to determine if we can
834// replace the udiv with something simpler. If we find that an operand is not
835// able to simplify the udiv, we abort the entire transformation.
836static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
837 SmallVectorImpl<UDivFoldAction> &Actions,
838 unsigned Depth = 0) {
839 // Check to see if this is an unsigned division with an exact power of 2,
840 // if so, convert to a right shift.
841 if (match(Op1, m_Power2())) {
842 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
843 return Actions.size();
844 }
845
846 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
847 // X udiv C, where C >= signbit
848 if (C->getValue().isNegative()) {
849 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
850 return Actions.size();
851 }
852
853 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
854 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
855 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
856 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
857 return Actions.size();
858 }
859
860 // The remaining tests are all recursive, so bail out if we hit the limit.
861 if (Depth++ == MaxDepth)
862 return 0;
863
864 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
865 if (size_t LHSIdx = visitUDivOperand(Op0, SI->getOperand(1), I, Actions))
866 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions)) {
867 Actions.push_back(UDivFoldAction((FoldUDivOperandCb)0, Op1, LHSIdx-1));
868 return Actions.size();
869 }
870
871 return 0;
872}
873
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000874Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
875 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
876
Duncan Sands771e82a2011-01-28 16:51:11 +0000877 if (Value *V = SimplifyUDivInst(Op0, Op1, TD))
878 return ReplaceInstUsesWith(I, V);
879
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000880 // Handle the integer div common cases
881 if (Instruction *Common = commonIDivTransforms(I))
882 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000883
Benjamin Kramerd4a64712012-08-30 15:07:40 +0000884 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
Nadav Rotemd4577872012-08-28 12:23:22 +0000885 if (ConstantInt *C2 = dyn_cast<ConstantInt>(Op1)) {
Benjamin Kramer9c0a8072012-08-28 13:08:13 +0000886 Value *X;
887 ConstantInt *C1;
888 if (match(Op0, m_LShr(m_Value(X), m_ConstantInt(C1)))) {
Benjamin Kramer1e1a1de2012-08-28 13:59:23 +0000889 APInt NC = C2->getValue().shl(C1->getLimitedValue(C1->getBitWidth()-1));
Benjamin Kramer9c0a8072012-08-28 13:08:13 +0000890 return BinaryOperator::CreateUDiv(X, Builder->getInt(NC));
Nadav Rotem11935b22012-08-28 10:01:43 +0000891 }
892 }
893
Benjamin Kramer9aa91b12011-04-30 18:16:07 +0000894 // (zext A) udiv (zext B) --> zext (A udiv B)
895 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
896 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
897 return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
898 I.isExact()),
899 I.getType());
900
David Majnemer37f8f442013-07-04 21:17:49 +0000901 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
902 SmallVector<UDivFoldAction, 6> UDivActions;
903 if (visitUDivOperand(Op0, Op1, I, UDivActions))
904 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
905 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
906 Value *ActionOp1 = UDivActions[i].OperandToFold;
907 Instruction *Inst;
908 if (Action)
909 Inst = Action(Op0, ActionOp1, I, *this);
910 else {
911 // This action joins two actions together. The RHS of this action is
912 // simply the last action we processed, we saved the LHS action index in
913 // the joining action.
914 size_t SelectRHSIdx = i - 1;
915 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
916 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
917 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
918 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
919 SelectLHS, SelectRHS);
920 }
921
922 // If this is the last action to process, return it to the InstCombiner.
923 // Otherwise, we insert it before the UDiv and record it so that we may
924 // use it as part of a joining action (i.e., a SelectInst).
925 if (e - i != 1) {
926 Inst->insertBefore(&I);
927 UDivActions[i].FoldResult = Inst;
928 } else
929 return Inst;
930 }
931
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000932 return 0;
933}
934
935Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
936 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
937
Duncan Sands771e82a2011-01-28 16:51:11 +0000938 if (Value *V = SimplifySDivInst(Op0, Op1, TD))
939 return ReplaceInstUsesWith(I, V);
940
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000941 // Handle the integer div common cases
942 if (Instruction *Common = commonIDivTransforms(I))
943 return Common;
944
945 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
946 // sdiv X, -1 == -X
947 if (RHS->isAllOnesValue())
948 return BinaryOperator::CreateNeg(Op0);
949
Chris Lattner6b657ae2011-02-10 05:36:31 +0000950 // sdiv X, C --> ashr exact X, log2(C)
951 if (I.isExact() && RHS->getValue().isNonNegative() &&
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000952 RHS->getValue().isPowerOf2()) {
953 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
954 RHS->getValue().exactLogBase2());
Chris Lattner6b657ae2011-02-10 05:36:31 +0000955 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000956 }
957
958 // -X/C --> X/-C provided the negation doesn't overflow.
959 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
Chris Lattner6b657ae2011-02-10 05:36:31 +0000960 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000961 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
962 ConstantExpr::getNeg(RHS));
963 }
964
965 // If the sign bits of both operands are zero (i.e. we can prove they are
966 // unsigned inputs), turn this into a udiv.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000967 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000968 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
969 if (MaskedValueIsZero(Op0, Mask)) {
970 if (MaskedValueIsZero(Op1, Mask)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000971 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000972 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
973 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000974
Chris Lattner6b657ae2011-02-10 05:36:31 +0000975 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000976 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
977 // Safe because the only negative value (1 << Y) can take on is
978 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
979 // the sign bit set.
980 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
981 }
982 }
983 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000984
Chris Lattnerdc054bf2010-01-05 06:09:35 +0000985 return 0;
986}
987
Shuxin Yang320f52a2013-01-14 22:48:41 +0000988/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
989/// FP value and:
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000990/// 1) 1/C is exact, or
Shuxin Yang320f52a2013-01-14 22:48:41 +0000991/// 2) reciprocal is allowed.
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000992/// If the conversion was successful, the simplified expression "X * 1/C" is
Shuxin Yang320f52a2013-01-14 22:48:41 +0000993/// returned; otherwise, NULL is returned.
994///
995static Instruction *CvtFDivConstToReciprocal(Value *Dividend,
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000996 Constant *Divisor,
Shuxin Yang320f52a2013-01-14 22:48:41 +0000997 bool AllowReciprocal) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000998 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
999 return 0;
1000
1001 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
Shuxin Yang320f52a2013-01-14 22:48:41 +00001002 APFloat Reciprocal(FpVal.getSemantics());
1003 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001004
Michael Gottesman3cb77ab2013-06-19 21:23:18 +00001005 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001006 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1007 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1008 Cvt = !Reciprocal.isDenormal();
1009 }
1010
1011 if (!Cvt)
1012 return 0;
1013
1014 ConstantFP *R;
1015 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1016 return BinaryOperator::CreateFMul(Dividend, R);
1017}
1018
Frits van Bommel2a559512011-01-29 17:50:27 +00001019Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1020 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1021
1022 if (Value *V = SimplifyFDivInst(Op0, Op1, TD))
1023 return ReplaceInstUsesWith(I, V);
1024
Stephen Lina9b57f62013-07-20 07:13:13 +00001025 if (isa<Constant>(Op0))
1026 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1027 if (Instruction *R = FoldOpIntoSelect(I, SI))
1028 return R;
1029
Shuxin Yang320f52a2013-01-14 22:48:41 +00001030 bool AllowReassociate = I.hasUnsafeAlgebra();
1031 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001032
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001033 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina9b57f62013-07-20 07:13:13 +00001034 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1035 if (Instruction *R = FoldOpIntoSelect(I, SI))
1036 return R;
1037
Shuxin Yang320f52a2013-01-14 22:48:41 +00001038 if (AllowReassociate) {
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001039 Constant *C1 = 0;
1040 Constant *C2 = Op1C;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001041 Value *X;
1042 Instruction *Res = 0;
1043
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001044 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001045 // (X*C1)/C2 => X * (C1/C2)
1046 //
1047 Constant *C = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001048 if (isNormalFp(C))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001049 Res = BinaryOperator::CreateFMul(X, C);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001050 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001051 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1052 //
1053 Constant *C = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001054 if (isNormalFp(C)) {
1055 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001056 if (!Res)
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001057 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001058 }
1059 }
1060
1061 if (Res) {
1062 Res->setFastMathFlags(I.getFastMathFlags());
1063 return Res;
1064 }
1065 }
1066
1067 // X / C => X * 1/C
Owen Anderson4557a152014-01-16 21:07:52 +00001068 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1069 T->copyFastMathFlags(&I);
Shuxin Yang320f52a2013-01-14 22:48:41 +00001070 return T;
Owen Anderson4557a152014-01-16 21:07:52 +00001071 }
Shuxin Yang320f52a2013-01-14 22:48:41 +00001072
1073 return 0;
1074 }
1075
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001076 if (AllowReassociate && isa<Constant>(Op0)) {
1077 Constant *C1 = cast<Constant>(Op0), *C2;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001078 Constant *Fold = 0;
1079 Value *X;
1080 bool CreateDiv = true;
1081
1082 // C1 / (X*C2) => (C1/C2) / X
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001083 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang320f52a2013-01-14 22:48:41 +00001084 Fold = ConstantExpr::getFDiv(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001085 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001086 // C1 / (X/C2) => (C1*C2) / X
1087 Fold = ConstantExpr::getFMul(C1, C2);
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001088 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001089 // C1 / (C2/X) => (C1/C2) * X
1090 Fold = ConstantExpr::getFDiv(C1, C2);
1091 CreateDiv = false;
1092 }
1093
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001094 if (Fold && isNormalFp(Fold)) {
1095 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1096 : BinaryOperator::CreateFMul(X, Fold);
1097 R->setFastMathFlags(I.getFastMathFlags());
1098 return R;
Shuxin Yang320f52a2013-01-14 22:48:41 +00001099 }
1100 return 0;
1101 }
1102
1103 if (AllowReassociate) {
1104 Value *X, *Y;
1105 Value *NewInst = 0;
1106 Instruction *SimpR = 0;
1107
1108 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1109 // (X/Y) / Z => X / (Y*Z)
1110 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001111 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001112 NewInst = Builder->CreateFMul(Y, Op1);
1113 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1114 }
1115 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1116 // Z / (X/Y) => Z*Y / X
1117 //
Benjamin Kramer76b15d02014-01-19 13:36:27 +00001118 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
Shuxin Yang320f52a2013-01-14 22:48:41 +00001119 NewInst = Builder->CreateFMul(Op0, Y);
1120 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1121 }
1122 }
1123
1124 if (NewInst) {
1125 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1126 T->setDebugLoc(I.getDebugLoc());
1127 SimpR->setFastMathFlags(I.getFastMathFlags());
1128 return SimpR;
Benjamin Kramer8564e0d2011-03-30 15:42:35 +00001129 }
1130 }
1131
Frits van Bommel2a559512011-01-29 17:50:27 +00001132 return 0;
1133}
1134
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001135/// This function implements the transforms common to both integer remainder
1136/// instructions (urem and srem). It is called by the visitors to those integer
1137/// remainder instructions.
1138/// @brief Common integer remainder transforms
1139Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1140 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1141
Chris Lattner7c99f192011-05-22 18:18:41 +00001142 // The RHS is known non-zero.
1143 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
1144 I.setOperand(1, V);
1145 return &I;
1146 }
1147
Duncan Sandsa3e36992011-05-02 16:27:02 +00001148 // Handle cases involving: rem X, (select Cond, Y, Z)
1149 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1150 return &I;
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001151
Duncan Sands6b699f82011-05-02 18:41:29 +00001152 if (isa<ConstantInt>(Op1)) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001153 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1154 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1155 if (Instruction *R = FoldOpIntoSelect(I, SI))
1156 return R;
1157 } else if (isa<PHINode>(Op0I)) {
1158 if (Instruction *NV = FoldOpIntoPhi(I))
1159 return NV;
1160 }
1161
1162 // See if we can fold away this rem instruction.
1163 if (SimplifyDemandedInstructionBits(I))
1164 return &I;
1165 }
1166 }
1167
1168 return 0;
1169}
1170
1171Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1172 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1173
Duncan Sandsa3e36992011-05-02 16:27:02 +00001174 if (Value *V = SimplifyURemInst(Op0, Op1, TD))
1175 return ReplaceInstUsesWith(I, V);
1176
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001177 if (Instruction *common = commonIRemTransforms(I))
1178 return common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001179
David Majnemer6c30f492013-05-12 00:07:05 +00001180 // (zext A) urem (zext B) --> zext (A urem B)
1181 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1182 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1183 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1184 I.getType());
1185
David Majnemer470b0772013-05-11 09:01:28 +00001186 // X urem Y -> X and Y-1, where Y is a power of 2,
1187 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true)) {
Chris Lattner6b657ae2011-02-10 05:36:31 +00001188 Constant *N1 = Constant::getAllOnesValue(I.getType());
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001189 Value *Add = Builder->CreateAdd(Op1, N1);
Chris Lattner6b657ae2011-02-10 05:36:31 +00001190 return BinaryOperator::CreateAnd(Op0, Add);
1191 }
1192
Nick Lewycky7459be62013-07-13 01:16:47 +00001193 // 1 urem X -> zext(X != 1)
1194 if (match(Op0, m_One())) {
1195 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1196 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1197 return ReplaceInstUsesWith(I, Ext);
1198 }
1199
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001200 return 0;
1201}
1202
1203Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1204 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1205
Duncan Sandsa3e36992011-05-02 16:27:02 +00001206 if (Value *V = SimplifySRemInst(Op0, Op1, TD))
1207 return ReplaceInstUsesWith(I, V);
1208
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001209 // Handle the integer rem common cases
1210 if (Instruction *Common = commonIRemTransforms(I))
1211 return Common;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001212
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001213 if (Value *RHSNeg = dyn_castNegVal(Op1))
1214 if (!isa<Constant>(RHSNeg) ||
1215 (isa<ConstantInt>(RHSNeg) &&
1216 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
1217 // X % -Y -> X % Y
1218 Worklist.AddValue(I.getOperand(1));
1219 I.setOperand(1, RHSNeg);
1220 return &I;
1221 }
1222
1223 // If the sign bits of both operands are zero (i.e. we can prove they are
1224 // unsigned inputs), turn this into a urem.
Duncan Sands9dff9be2010-02-15 16:12:20 +00001225 if (I.getType()->isIntegerTy()) {
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001226 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1227 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001228 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001229 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1230 }
1231 }
1232
1233 // If it's a constant vector, flip any negative values positive.
Chris Lattner0256be92012-01-27 03:08:05 +00001234 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1235 Constant *C = cast<Constant>(Op1);
1236 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001237
1238 bool hasNegative = false;
Chris Lattner0256be92012-01-27 03:08:05 +00001239 bool hasMissing = false;
1240 for (unsigned i = 0; i != VWidth; ++i) {
1241 Constant *Elt = C->getAggregateElement(i);
1242 if (Elt == 0) {
1243 hasMissing = true;
1244 break;
1245 }
1246
1247 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerb1a15122011-07-15 06:08:15 +00001248 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001249 hasNegative = true;
Chris Lattner0256be92012-01-27 03:08:05 +00001250 }
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001251
Chris Lattner0256be92012-01-27 03:08:05 +00001252 if (hasNegative && !hasMissing) {
Chris Lattner47a86bd2012-01-25 06:02:56 +00001253 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001254 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +00001255 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattner0256be92012-01-27 03:08:05 +00001256 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerb1a15122011-07-15 06:08:15 +00001257 if (RHS->isNegative())
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001258 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001259 }
1260 }
1261
1262 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattner0256be92012-01-27 03:08:05 +00001263 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001264 Worklist.AddValue(I.getOperand(1));
1265 I.setOperand(1, NewRHSV);
1266 return &I;
1267 }
1268 }
1269 }
1270
1271 return 0;
1272}
1273
1274Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001275 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdc054bf2010-01-05 06:09:35 +00001276
Duncan Sandsa3e36992011-05-02 16:27:02 +00001277 if (Value *V = SimplifyFRemInst(Op0, Op1, TD))
1278 return ReplaceInstUsesWith(I, V);
1279
1280 // Handle cases involving: rem X, (select Cond, Y, Z)
1281 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1282 return &I;
1283
1284 return 0;
1285}