blob: fdec6407b800a2893bcb481f9d3e571fbdb67f12 [file] [log] [blame]
Chris Lattnerd12c27c2010-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"
16#include "llvm/IntrinsicInst.h"
Duncan Sands82fdab32010-12-21 14:00:22 +000017#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattnerd12c27c2010-01-05 06:09:35 +000018#include "llvm/Support/PatternMatch.h"
19using namespace llvm;
20using namespace PatternMatch;
21
Chris Lattner1add46d2011-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;
31
32 // ((1 << A) >>u B) --> (1 << (A-B))
33 // Because V cannot be zero, we know that B is less than A.
Chris Lattner6083bb92011-05-23 00:09:55 +000034 Value *A = 0, *B = 0, *PowerOf2 = 0;
35 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(PowerOf2), m_Value(A))),
Chris Lattner1add46d2011-05-22 18:18:41 +000036 m_Value(B))) &&
37 // The "1" can be any value known to be a power of 2.
Chris Lattner6083bb92011-05-23 00:09:55 +000038 isPowerOfTwo(PowerOf2, IC.getTargetData())) {
Chris Lattner1add46d2011-05-22 18:18:41 +000039 A = IC.Builder->CreateSub(A, B, "tmp");
Chris Lattner6083bb92011-05-23 00:09:55 +000040 return IC.Builder->CreateShl(PowerOf2, A);
Chris Lattner1add46d2011-05-22 18:18:41 +000041 }
42
Chris Lattner6c9b8d32011-05-22 18:26:48 +000043 // TODO: Lots more we could do here:
44 // "1 >> X" could get an "isexact" bit.
45 // If V is a phi node, we can call this on each of its operands.
46 // "select cond, X, 0" can simplify to "X".
47
Chris Lattner1add46d2011-05-22 18:18:41 +000048 return 0;
49}
50
51
Chris Lattnerd12c27c2010-01-05 06:09:35 +000052/// MultiplyOverflows - True if the multiply can not be expressed in an int
53/// this size.
54static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
55 uint32_t W = C1->getBitWidth();
56 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
57 if (sign) {
Jay Foad40f8f622010-12-07 08:25:19 +000058 LHSExt = LHSExt.sext(W * 2);
59 RHSExt = RHSExt.sext(W * 2);
Chris Lattnerd12c27c2010-01-05 06:09:35 +000060 } else {
Jay Foad40f8f622010-12-07 08:25:19 +000061 LHSExt = LHSExt.zext(W * 2);
62 RHSExt = RHSExt.zext(W * 2);
Chris Lattnerd12c27c2010-01-05 06:09:35 +000063 }
64
65 APInt MulExt = LHSExt * RHSExt;
66
67 if (!sign)
68 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
69
70 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
71 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
72 return MulExt.slt(Min) || MulExt.sgt(Max);
73}
74
75Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands096aa792010-11-13 15:10:37 +000076 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerd12c27c2010-01-05 06:09:35 +000077 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
78
Duncan Sands82fdab32010-12-21 14:00:22 +000079 if (Value *V = SimplifyMulInst(Op0, Op1, TD))
80 return ReplaceInstUsesWith(I, V);
Chris Lattnerd12c27c2010-01-05 06:09:35 +000081
Duncan Sands37bf92b2010-12-22 13:36:08 +000082 if (Value *V = SimplifyUsingDistributiveLaws(I))
83 return ReplaceInstUsesWith(I, V);
84
Chris Lattner7a6aa1a2011-02-10 05:36:31 +000085 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X
86 return BinaryOperator::CreateNeg(Op0, I.getName());
87
88 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
89
90 // ((X << C1)*C2) == (X * (C2 << C1))
91 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
92 if (SI->getOpcode() == Instruction::Shl)
93 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
94 return BinaryOperator::CreateMul(SI->getOperand(0),
95 ConstantExpr::getShl(CI, ShOp));
96
97 const APInt &Val = CI->getValue();
98 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
99 Constant *NewCst = ConstantInt::get(Op0->getType(), Val.logBase2());
100 BinaryOperator *Shl = BinaryOperator::CreateShl(Op0, NewCst);
101 if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap();
102 if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap();
103 return Shl;
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000104 }
105
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000106 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
107 { Value *X; ConstantInt *C1;
108 if (Op0->hasOneUse() &&
109 match(Op0, m_Add(m_Value(X), m_ConstantInt(C1)))) {
110 Value *Add = Builder->CreateMul(X, CI, "tmp");
111 return BinaryOperator::CreateAdd(Add, Builder->CreateMul(C1, CI));
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000112 }
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000113 }
114 }
115
116 // Simplify mul instructions with a constant RHS.
117 if (isa<Constant>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000118 // Try to fold constant mul into select arguments.
119 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
120 if (Instruction *R = FoldOpIntoSelect(I, SI))
121 return R;
122
123 if (isa<PHINode>(Op0))
124 if (Instruction *NV = FoldOpIntoPhi(I))
125 return NV;
126 }
127
128 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
129 if (Value *Op1v = dyn_castNegVal(Op1))
130 return BinaryOperator::CreateMul(Op0v, Op1v);
131
132 // (X / Y) * Y = X - (X % Y)
133 // (X / Y) * -Y = (X % Y) - X
134 {
135 Value *Op1C = Op1;
136 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
137 if (!BO ||
138 (BO->getOpcode() != Instruction::UDiv &&
139 BO->getOpcode() != Instruction::SDiv)) {
140 Op1C = Op0;
141 BO = dyn_cast<BinaryOperator>(Op1);
142 }
143 Value *Neg = dyn_castNegVal(Op1C);
144 if (BO && BO->hasOneUse() &&
145 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
146 (BO->getOpcode() == Instruction::UDiv ||
147 BO->getOpcode() == Instruction::SDiv)) {
148 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
149
Chris Lattner35bda892011-02-06 21:44:57 +0000150 // If the division is exact, X % Y is zero, so we end up with X or -X.
151 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000152 if (SDiv->isExact()) {
153 if (Op1BO == Op1C)
154 return ReplaceInstUsesWith(I, Op0BO);
155 return BinaryOperator::CreateNeg(Op0BO);
156 }
157
158 Value *Rem;
159 if (BO->getOpcode() == Instruction::UDiv)
160 Rem = Builder->CreateURem(Op0BO, Op1BO);
161 else
162 Rem = Builder->CreateSRem(Op0BO, Op1BO);
163 Rem->takeName(BO);
164
165 if (Op1BO == Op1C)
166 return BinaryOperator::CreateSub(Op0BO, Rem);
167 return BinaryOperator::CreateSub(Rem, Op0BO);
168 }
169 }
170
171 /// i1 mul -> i1 and.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000172 if (I.getType()->isIntegerTy(1))
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000173 return BinaryOperator::CreateAnd(Op0, Op1);
174
175 // X*(1 << Y) --> X << Y
176 // (1 << Y)*X --> X << Y
177 {
178 Value *Y;
179 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
180 return BinaryOperator::CreateShl(Op1, Y);
181 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
182 return BinaryOperator::CreateShl(Op0, Y);
183 }
184
185 // If one of the operands of the multiply is a cast from a boolean value, then
186 // we know the bool is either zero or one, so this is a 'masking' multiply.
187 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands1df98592010-02-16 11:11:14 +0000188 if (!I.getType()->isVectorTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000189 // -2 is "-1 << 1" so it is all bits set except the low one.
190 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
191
192 Value *BoolCast = 0, *OtherOp = 0;
193 if (MaskedValueIsZero(Op0, Negative2))
194 BoolCast = Op0, OtherOp = Op1;
195 else if (MaskedValueIsZero(Op1, Negative2))
196 BoolCast = Op1, OtherOp = Op0;
197
198 if (BoolCast) {
199 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
200 BoolCast, "tmp");
201 return BinaryOperator::CreateAnd(V, OtherOp);
202 }
203 }
204
205 return Changed ? &I : 0;
206}
207
208Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands096aa792010-11-13 15:10:37 +0000209 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000210 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
211
212 // Simplify mul instructions with a constant RHS...
213 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
214 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
215 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
216 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
217 if (Op1F->isExactlyValue(1.0))
Dan Gohmana9445e12010-03-02 01:11:08 +0000218 return ReplaceInstUsesWith(I, Op0); // Eliminate 'fmul double %X, 1.0'
Duncan Sands1df98592010-02-16 11:11:14 +0000219 } else if (Op1C->getType()->isVectorTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000220 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
221 // As above, vector X*splat(1.0) -> X in all defined cases.
222 if (Constant *Splat = Op1V->getSplatValue()) {
223 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
224 if (F->isExactlyValue(1.0))
225 return ReplaceInstUsesWith(I, Op0);
226 }
227 }
228 }
229
230 // Try to fold constant mul into select arguments.
231 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
232 if (Instruction *R = FoldOpIntoSelect(I, SI))
233 return R;
234
235 if (isa<PHINode>(Op0))
236 if (Instruction *NV = FoldOpIntoPhi(I))
237 return NV;
238 }
239
240 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
241 if (Value *Op1v = dyn_castFNegVal(Op1))
242 return BinaryOperator::CreateFMul(Op0v, Op1v);
243
244 return Changed ? &I : 0;
245}
246
247/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
248/// instruction.
249bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
250 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
251
252 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
253 int NonNullOperand = -1;
254 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
255 if (ST->isNullValue())
256 NonNullOperand = 2;
257 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
258 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
259 if (ST->isNullValue())
260 NonNullOperand = 1;
261
262 if (NonNullOperand == -1)
263 return false;
264
265 Value *SelectCond = SI->getOperand(0);
266
267 // Change the div/rem to use 'Y' instead of the select.
268 I.setOperand(1, SI->getOperand(NonNullOperand));
269
270 // Okay, we know we replace the operand of the div/rem with 'Y' with no
271 // problem. However, the select, or the condition of the select may have
272 // multiple uses. Based on our knowledge that the operand must be non-zero,
273 // propagate the known value for the select into other uses of it, and
274 // propagate a known value of the condition into its other users.
275
276 // If the select and condition only have a single use, don't bother with this,
277 // early exit.
278 if (SI->use_empty() && SelectCond->hasOneUse())
279 return true;
280
281 // Scan the current block backward, looking for other uses of SI.
282 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
283
284 while (BBI != BBFront) {
285 --BBI;
286 // If we found a call to a function, we can't assume it will return, so
287 // information from below it cannot be propagated above it.
288 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
289 break;
290
291 // Replace uses of the select or its condition with the known values.
292 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
293 I != E; ++I) {
294 if (*I == SI) {
295 *I = SI->getOperand(NonNullOperand);
296 Worklist.Add(BBI);
297 } else if (*I == SelectCond) {
298 *I = NonNullOperand == 1 ? ConstantInt::getTrue(BBI->getContext()) :
299 ConstantInt::getFalse(BBI->getContext());
300 Worklist.Add(BBI);
301 }
302 }
303
304 // If we past the instruction, quit looking for it.
305 if (&*BBI == SI)
306 SI = 0;
307 if (&*BBI == SelectCond)
308 SelectCond = 0;
309
310 // If we ran out of things to eliminate, break out of the loop.
311 if (SelectCond == 0 && SI == 0)
312 break;
313
314 }
315 return true;
316}
317
318
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000319/// This function implements the transforms common to both integer division
320/// instructions (udiv and sdiv). It is called by the visitors to those integer
321/// division instructions.
322/// @brief Common integer divide transforms
323Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
324 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
325
Chris Lattner1add46d2011-05-22 18:18:41 +0000326 // The RHS is known non-zero.
327 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
328 I.setOperand(1, V);
329 return &I;
330 }
331
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000332 // Handle cases involving: [su]div X, (select Cond, Y, Z)
333 // This does not apply for fdiv.
334 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
335 return &I;
336
337 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000338 // (X / C1) / C2 -> X / (C1*C2)
339 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
340 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
341 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
342 if (MultiplyOverflows(RHS, LHSRHS,
343 I.getOpcode()==Instruction::SDiv))
344 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000345 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
346 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000347 }
348
349 if (!RHS->isZero()) { // avoid X udiv 0
350 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
351 if (Instruction *R = FoldOpIntoSelect(I, SI))
352 return R;
353 if (isa<PHINode>(Op0))
354 if (Instruction *NV = FoldOpIntoPhi(I))
355 return NV;
356 }
357 }
358
Benjamin Kramer23b02cd2011-04-30 18:16:00 +0000359 // See if we can fold away this div instruction.
360 if (SimplifyDemandedInstructionBits(I))
361 return &I;
362
Duncan Sands593faa52011-01-28 16:51:11 +0000363 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
364 Value *X = 0, *Z = 0;
365 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
366 bool isSigned = I.getOpcode() == Instruction::SDiv;
367 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
368 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
369 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000370 }
371
372 return 0;
373}
374
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +0000375/// dyn_castZExtVal - Checks if V is a zext or constant that can
376/// be truncated to Ty without losing bits.
377static Value *dyn_castZExtVal(Value *V, const Type *Ty) {
378 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
379 if (Z->getSrcTy() == Ty)
380 return Z->getOperand(0);
381 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
382 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
383 return ConstantExpr::getTrunc(C, Ty);
384 }
385 return 0;
386}
387
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000388Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
389 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
390
Duncan Sands593faa52011-01-28 16:51:11 +0000391 if (Value *V = SimplifyUDivInst(Op0, Op1, TD))
392 return ReplaceInstUsesWith(I, V);
393
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000394 // Handle the integer div common cases
395 if (Instruction *Common = commonIDivTransforms(I))
396 return Common;
397
398 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson5b396202010-01-17 06:49:03 +0000399 // X udiv 2^C -> X >> C
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000400 // Check to see if this is an unsigned division with an exact power of 2,
401 // if so, convert to a right shift.
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000402 if (C->getValue().isPowerOf2()) { // 0 not included in isPowerOf2
403 BinaryOperator *LShr =
404 BinaryOperator::CreateLShr(Op0,
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000405 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000406 if (I.isExact()) LShr->setIsExact();
407 return LShr;
408 }
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000409
410 // X udiv C, where C >= signbit
411 if (C->getValue().isNegative()) {
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000412 Value *IC = Builder->CreateICmpULT(Op0, C);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000413 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
414 ConstantInt::get(I.getType(), 1));
415 }
416 }
417
418 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000419 { const APInt *CI; Value *N;
420 if (match(Op1, m_Shl(m_Power2(CI), m_Value(N)))) {
421 if (*CI != 1)
422 N = Builder->CreateAdd(N, ConstantInt::get(I.getType(), CI->logBase2()),
423 "tmp");
424 if (I.isExact())
425 return BinaryOperator::CreateExactLShr(Op0, N);
426 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000427 }
428 }
429
430 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
431 // where C1&C2 are powers of two.
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000432 { Value *Cond; const APInt *C1, *C2;
433 if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) {
434 // Construct the "on true" case of the select
435 Value *TSI = Builder->CreateLShr(Op0, C1->logBase2(), Op1->getName()+".t",
436 I.isExact());
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000437
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000438 // Construct the "on false" case of the select
439 Value *FSI = Builder->CreateLShr(Op0, C2->logBase2(), Op1->getName()+".f",
440 I.isExact());
441
442 // construct the select instruction and return it.
443 return SelectInst::Create(Cond, TSI, FSI);
444 }
445 }
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +0000446
447 // (zext A) udiv (zext B) --> zext (A udiv B)
448 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
449 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
450 return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
451 I.isExact()),
452 I.getType());
453
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000454 return 0;
455}
456
457Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
458 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
459
Duncan Sands593faa52011-01-28 16:51:11 +0000460 if (Value *V = SimplifySDivInst(Op0, Op1, TD))
461 return ReplaceInstUsesWith(I, V);
462
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000463 // Handle the integer div common cases
464 if (Instruction *Common = commonIDivTransforms(I))
465 return Common;
466
467 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
468 // sdiv X, -1 == -X
469 if (RHS->isAllOnesValue())
470 return BinaryOperator::CreateNeg(Op0);
471
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000472 // sdiv X, C --> ashr exact X, log2(C)
473 if (I.isExact() && RHS->getValue().isNonNegative() &&
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000474 RHS->getValue().isPowerOf2()) {
475 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
476 RHS->getValue().exactLogBase2());
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000477 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000478 }
479
480 // -X/C --> X/-C provided the negation doesn't overflow.
481 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000482 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000483 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
484 ConstantExpr::getNeg(RHS));
485 }
486
487 // If the sign bits of both operands are zero (i.e. we can prove they are
488 // unsigned inputs), turn this into a udiv.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000489 if (I.getType()->isIntegerTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000490 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
491 if (MaskedValueIsZero(Op0, Mask)) {
492 if (MaskedValueIsZero(Op1, Mask)) {
493 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
494 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
495 }
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000496
497 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000498 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
499 // Safe because the only negative value (1 << Y) can take on is
500 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
501 // the sign bit set.
502 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
503 }
504 }
505 }
506
507 return 0;
508}
509
Frits van Bommel31726c12011-01-29 17:50:27 +0000510Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
511 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
512
513 if (Value *V = SimplifyFDivInst(Op0, Op1, TD))
514 return ReplaceInstUsesWith(I, V);
515
Benjamin Kramer54673962011-03-30 15:42:35 +0000516 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
517 const APFloat &Op1F = Op1C->getValueAPF();
518
519 // If the divisor has an exact multiplicative inverse we can turn the fdiv
520 // into a cheaper fmul.
521 APFloat Reciprocal(Op1F.getSemantics());
522 if (Op1F.getExactInverse(&Reciprocal)) {
523 ConstantFP *RFP = ConstantFP::get(Builder->getContext(), Reciprocal);
524 return BinaryOperator::CreateFMul(Op0, RFP);
525 }
526 }
527
Frits van Bommel31726c12011-01-29 17:50:27 +0000528 return 0;
529}
530
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000531/// This function implements the transforms common to both integer remainder
532/// instructions (urem and srem). It is called by the visitors to those integer
533/// remainder instructions.
534/// @brief Common integer remainder transforms
535Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
536 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
537
Chris Lattner1add46d2011-05-22 18:18:41 +0000538 // The RHS is known non-zero.
539 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
540 I.setOperand(1, V);
541 return &I;
542 }
543
Duncan Sandsf24ed772011-05-02 16:27:02 +0000544 // Handle cases involving: rem X, (select Cond, Y, Z)
545 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
546 return &I;
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000547
Duncan Sands00676a62011-05-02 18:41:29 +0000548 if (isa<ConstantInt>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000549 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
550 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
551 if (Instruction *R = FoldOpIntoSelect(I, SI))
552 return R;
553 } else if (isa<PHINode>(Op0I)) {
554 if (Instruction *NV = FoldOpIntoPhi(I))
555 return NV;
556 }
557
558 // See if we can fold away this rem instruction.
559 if (SimplifyDemandedInstructionBits(I))
560 return &I;
561 }
562 }
563
564 return 0;
565}
566
567Instruction *InstCombiner::visitURem(BinaryOperator &I) {
568 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
569
Duncan Sandsf24ed772011-05-02 16:27:02 +0000570 if (Value *V = SimplifyURemInst(Op0, Op1, TD))
571 return ReplaceInstUsesWith(I, V);
572
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000573 if (Instruction *common = commonIRemTransforms(I))
574 return common;
575
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000576 // X urem C^2 -> X and C-1
577 { const APInt *C;
578 if (match(Op1, m_Power2(C)))
579 return BinaryOperator::CreateAnd(Op0,
580 ConstantInt::get(I.getType(), *C-1));
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000581 }
582
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000583 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
584 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
585 Constant *N1 = Constant::getAllOnesValue(I.getType());
586 Value *Add = Builder->CreateAdd(Op1, N1, "tmp");
587 return BinaryOperator::CreateAnd(Op0, Add);
588 }
589
590 // urem X, (select Cond, 2^C1, 2^C2) -->
591 // select Cond, (and X, C1-1), (and X, C2-1)
592 // when C1&C2 are powers of two.
593 { Value *Cond; const APInt *C1, *C2;
594 if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) {
595 Value *TrueAnd = Builder->CreateAnd(Op0, *C1-1, Op1->getName()+".t");
596 Value *FalseAnd = Builder->CreateAnd(Op0, *C2-1, Op1->getName()+".f");
597 return SelectInst::Create(Cond, TrueAnd, FalseAnd);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000598 }
599 }
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +0000600
601 // (zext A) urem (zext B) --> zext (A urem B)
602 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
603 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
604 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
605 I.getType());
606
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000607 return 0;
608}
609
610Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
611 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
612
Duncan Sandsf24ed772011-05-02 16:27:02 +0000613 if (Value *V = SimplifySRemInst(Op0, Op1, TD))
614 return ReplaceInstUsesWith(I, V);
615
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000616 // Handle the integer rem common cases
617 if (Instruction *Common = commonIRemTransforms(I))
618 return Common;
619
620 if (Value *RHSNeg = dyn_castNegVal(Op1))
621 if (!isa<Constant>(RHSNeg) ||
622 (isa<ConstantInt>(RHSNeg) &&
623 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
624 // X % -Y -> X % Y
625 Worklist.AddValue(I.getOperand(1));
626 I.setOperand(1, RHSNeg);
627 return &I;
628 }
629
630 // If the sign bits of both operands are zero (i.e. we can prove they are
631 // unsigned inputs), turn this into a urem.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000632 if (I.getType()->isIntegerTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000633 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
634 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
635 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
636 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
637 }
638 }
639
640 // If it's a constant vector, flip any negative values positive.
641 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
642 unsigned VWidth = RHSV->getNumOperands();
643
644 bool hasNegative = false;
645 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
646 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
647 if (RHS->getValue().isNegative())
648 hasNegative = true;
649
650 if (hasNegative) {
651 std::vector<Constant *> Elts(VWidth);
652 for (unsigned i = 0; i != VWidth; ++i) {
653 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
654 if (RHS->getValue().isNegative())
655 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
656 else
657 Elts[i] = RHS;
658 }
659 }
660
661 Constant *NewRHSV = ConstantVector::get(Elts);
662 if (NewRHSV != RHSV) {
663 Worklist.AddValue(I.getOperand(1));
664 I.setOperand(1, NewRHSV);
665 return &I;
666 }
667 }
668 }
669
670 return 0;
671}
672
673Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsf24ed772011-05-02 16:27:02 +0000674 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000675
Duncan Sandsf24ed772011-05-02 16:27:02 +0000676 if (Value *V = SimplifyFRemInst(Op0, Op1, TD))
677 return ReplaceInstUsesWith(I, V);
678
679 // Handle cases involving: rem X, (select Cond, Y, Z)
680 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
681 return &I;
682
683 return 0;
684}