blob: a9b60d373c37b1ca2c7bff08f331149adb376fd6 [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
Chris Lattner613f1a32011-05-23 00:32:19 +000032 bool MadeChange = false;
33
Chris Lattner1add46d2011-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 Lattner6083bb92011-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 Lattner1add46d2011-05-22 18:18:41 +000038 m_Value(B))) &&
39 // The "1" can be any value known to be a power of 2.
Chris Lattner6083bb92011-05-23 00:09:55 +000040 isPowerOfTwo(PowerOf2, IC.getTargetData())) {
Chris Lattner1add46d2011-05-22 18:18:41 +000041 A = IC.Builder->CreateSub(A, B, "tmp");
Chris Lattner6083bb92011-05-23 00:09:55 +000042 return IC.Builder->CreateShl(PowerOf2, A);
Chris Lattner1add46d2011-05-22 18:18:41 +000043 }
44
Chris Lattner613f1a32011-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))
48 if (I->isLogicalShift() &&
49 isPowerOfTwo(I->getOperand(0), IC.getTargetData())) {
50 // We know that this is an exact/nuw shift and that the input is a
51 // non-zero context as well.
52 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC)) {
53 I->setOperand(0, V2);
54 MadeChange = true;
55 }
56
57 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
58 I->setIsExact();
59 MadeChange = true;
60 }
61
62 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
63 I->setHasNoUnsignedWrap();
64 MadeChange = true;
65 }
66 }
67
Chris Lattner6c9b8d32011-05-22 18:26:48 +000068 // TODO: Lots more we could do here:
Chris Lattner6c9b8d32011-05-22 18:26:48 +000069 // If V is a phi node, we can call this on each of its operands.
70 // "select cond, X, 0" can simplify to "X".
71
Chris Lattner613f1a32011-05-23 00:32:19 +000072 return MadeChange ? V : 0;
Chris Lattner1add46d2011-05-22 18:18:41 +000073}
74
75
Chris Lattnerd12c27c2010-01-05 06:09:35 +000076/// MultiplyOverflows - True if the multiply can not be expressed in an int
77/// this size.
78static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
79 uint32_t W = C1->getBitWidth();
80 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
81 if (sign) {
Jay Foad40f8f622010-12-07 08:25:19 +000082 LHSExt = LHSExt.sext(W * 2);
83 RHSExt = RHSExt.sext(W * 2);
Chris Lattnerd12c27c2010-01-05 06:09:35 +000084 } else {
Jay Foad40f8f622010-12-07 08:25:19 +000085 LHSExt = LHSExt.zext(W * 2);
86 RHSExt = RHSExt.zext(W * 2);
Chris Lattnerd12c27c2010-01-05 06:09:35 +000087 }
88
89 APInt MulExt = LHSExt * RHSExt;
90
91 if (!sign)
92 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
93
94 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
95 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
96 return MulExt.slt(Min) || MulExt.sgt(Max);
97}
98
99Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands096aa792010-11-13 15:10:37 +0000100 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000101 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
102
Duncan Sands82fdab32010-12-21 14:00:22 +0000103 if (Value *V = SimplifyMulInst(Op0, Op1, TD))
104 return ReplaceInstUsesWith(I, V);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000105
Duncan Sands37bf92b2010-12-22 13:36:08 +0000106 if (Value *V = SimplifyUsingDistributiveLaws(I))
107 return ReplaceInstUsesWith(I, V);
108
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000109 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X
110 return BinaryOperator::CreateNeg(Op0, I.getName());
111
112 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
113
114 // ((X << C1)*C2) == (X * (C2 << C1))
115 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
116 if (SI->getOpcode() == Instruction::Shl)
117 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
118 return BinaryOperator::CreateMul(SI->getOperand(0),
119 ConstantExpr::getShl(CI, ShOp));
120
121 const APInt &Val = CI->getValue();
122 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
123 Constant *NewCst = ConstantInt::get(Op0->getType(), Val.logBase2());
124 BinaryOperator *Shl = BinaryOperator::CreateShl(Op0, NewCst);
125 if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap();
126 if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap();
127 return Shl;
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000128 }
129
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000130 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
131 { Value *X; ConstantInt *C1;
132 if (Op0->hasOneUse() &&
133 match(Op0, m_Add(m_Value(X), m_ConstantInt(C1)))) {
134 Value *Add = Builder->CreateMul(X, CI, "tmp");
135 return BinaryOperator::CreateAdd(Add, Builder->CreateMul(C1, CI));
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000136 }
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000137 }
138 }
139
140 // Simplify mul instructions with a constant RHS.
141 if (isa<Constant>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000142 // Try to fold constant mul into select arguments.
143 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
144 if (Instruction *R = FoldOpIntoSelect(I, SI))
145 return R;
146
147 if (isa<PHINode>(Op0))
148 if (Instruction *NV = FoldOpIntoPhi(I))
149 return NV;
150 }
151
152 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
153 if (Value *Op1v = dyn_castNegVal(Op1))
154 return BinaryOperator::CreateMul(Op0v, Op1v);
155
156 // (X / Y) * Y = X - (X % Y)
157 // (X / Y) * -Y = (X % Y) - X
158 {
159 Value *Op1C = Op1;
160 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
161 if (!BO ||
162 (BO->getOpcode() != Instruction::UDiv &&
163 BO->getOpcode() != Instruction::SDiv)) {
164 Op1C = Op0;
165 BO = dyn_cast<BinaryOperator>(Op1);
166 }
167 Value *Neg = dyn_castNegVal(Op1C);
168 if (BO && BO->hasOneUse() &&
169 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
170 (BO->getOpcode() == Instruction::UDiv ||
171 BO->getOpcode() == Instruction::SDiv)) {
172 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
173
Chris Lattner35bda892011-02-06 21:44:57 +0000174 // If the division is exact, X % Y is zero, so we end up with X or -X.
175 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000176 if (SDiv->isExact()) {
177 if (Op1BO == Op1C)
178 return ReplaceInstUsesWith(I, Op0BO);
179 return BinaryOperator::CreateNeg(Op0BO);
180 }
181
182 Value *Rem;
183 if (BO->getOpcode() == Instruction::UDiv)
184 Rem = Builder->CreateURem(Op0BO, Op1BO);
185 else
186 Rem = Builder->CreateSRem(Op0BO, Op1BO);
187 Rem->takeName(BO);
188
189 if (Op1BO == Op1C)
190 return BinaryOperator::CreateSub(Op0BO, Rem);
191 return BinaryOperator::CreateSub(Rem, Op0BO);
192 }
193 }
194
195 /// i1 mul -> i1 and.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000196 if (I.getType()->isIntegerTy(1))
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000197 return BinaryOperator::CreateAnd(Op0, Op1);
198
199 // X*(1 << Y) --> X << Y
200 // (1 << Y)*X --> X << Y
201 {
202 Value *Y;
203 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
204 return BinaryOperator::CreateShl(Op1, Y);
205 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
206 return BinaryOperator::CreateShl(Op0, Y);
207 }
208
209 // If one of the operands of the multiply is a cast from a boolean value, then
210 // we know the bool is either zero or one, so this is a 'masking' multiply.
211 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands1df98592010-02-16 11:11:14 +0000212 if (!I.getType()->isVectorTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000213 // -2 is "-1 << 1" so it is all bits set except the low one.
214 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
215
216 Value *BoolCast = 0, *OtherOp = 0;
217 if (MaskedValueIsZero(Op0, Negative2))
218 BoolCast = Op0, OtherOp = Op1;
219 else if (MaskedValueIsZero(Op1, Negative2))
220 BoolCast = Op1, OtherOp = Op0;
221
222 if (BoolCast) {
223 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
224 BoolCast, "tmp");
225 return BinaryOperator::CreateAnd(V, OtherOp);
226 }
227 }
228
229 return Changed ? &I : 0;
230}
231
232Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands096aa792010-11-13 15:10:37 +0000233 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000234 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
235
236 // Simplify mul instructions with a constant RHS...
237 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
238 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
239 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
240 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
241 if (Op1F->isExactlyValue(1.0))
Dan Gohmana9445e12010-03-02 01:11:08 +0000242 return ReplaceInstUsesWith(I, Op0); // Eliminate 'fmul double %X, 1.0'
Duncan Sands1df98592010-02-16 11:11:14 +0000243 } else if (Op1C->getType()->isVectorTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000244 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
245 // As above, vector X*splat(1.0) -> X in all defined cases.
246 if (Constant *Splat = Op1V->getSplatValue()) {
247 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
248 if (F->isExactlyValue(1.0))
249 return ReplaceInstUsesWith(I, Op0);
250 }
251 }
252 }
253
254 // Try to fold constant mul into select arguments.
255 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
256 if (Instruction *R = FoldOpIntoSelect(I, SI))
257 return R;
258
259 if (isa<PHINode>(Op0))
260 if (Instruction *NV = FoldOpIntoPhi(I))
261 return NV;
262 }
263
264 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
265 if (Value *Op1v = dyn_castFNegVal(Op1))
266 return BinaryOperator::CreateFMul(Op0v, Op1v);
267
268 return Changed ? &I : 0;
269}
270
271/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
272/// instruction.
273bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
274 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
275
276 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
277 int NonNullOperand = -1;
278 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
279 if (ST->isNullValue())
280 NonNullOperand = 2;
281 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
282 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
283 if (ST->isNullValue())
284 NonNullOperand = 1;
285
286 if (NonNullOperand == -1)
287 return false;
288
289 Value *SelectCond = SI->getOperand(0);
290
291 // Change the div/rem to use 'Y' instead of the select.
292 I.setOperand(1, SI->getOperand(NonNullOperand));
293
294 // Okay, we know we replace the operand of the div/rem with 'Y' with no
295 // problem. However, the select, or the condition of the select may have
296 // multiple uses. Based on our knowledge that the operand must be non-zero,
297 // propagate the known value for the select into other uses of it, and
298 // propagate a known value of the condition into its other users.
299
300 // If the select and condition only have a single use, don't bother with this,
301 // early exit.
302 if (SI->use_empty() && SelectCond->hasOneUse())
303 return true;
304
305 // Scan the current block backward, looking for other uses of SI.
306 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
307
308 while (BBI != BBFront) {
309 --BBI;
310 // If we found a call to a function, we can't assume it will return, so
311 // information from below it cannot be propagated above it.
312 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
313 break;
314
315 // Replace uses of the select or its condition with the known values.
316 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
317 I != E; ++I) {
318 if (*I == SI) {
319 *I = SI->getOperand(NonNullOperand);
320 Worklist.Add(BBI);
321 } else if (*I == SelectCond) {
322 *I = NonNullOperand == 1 ? ConstantInt::getTrue(BBI->getContext()) :
323 ConstantInt::getFalse(BBI->getContext());
324 Worklist.Add(BBI);
325 }
326 }
327
328 // If we past the instruction, quit looking for it.
329 if (&*BBI == SI)
330 SI = 0;
331 if (&*BBI == SelectCond)
332 SelectCond = 0;
333
334 // If we ran out of things to eliminate, break out of the loop.
335 if (SelectCond == 0 && SI == 0)
336 break;
337
338 }
339 return true;
340}
341
342
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000343/// This function implements the transforms common to both integer division
344/// instructions (udiv and sdiv). It is called by the visitors to those integer
345/// division instructions.
346/// @brief Common integer divide transforms
347Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
348 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
349
Chris Lattner1add46d2011-05-22 18:18:41 +0000350 // The RHS is known non-zero.
351 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
352 I.setOperand(1, V);
353 return &I;
354 }
355
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000356 // Handle cases involving: [su]div X, (select Cond, Y, Z)
357 // This does not apply for fdiv.
358 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
359 return &I;
360
361 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000362 // (X / C1) / C2 -> X / (C1*C2)
363 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
364 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
365 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
366 if (MultiplyOverflows(RHS, LHSRHS,
367 I.getOpcode()==Instruction::SDiv))
368 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000369 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
370 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000371 }
372
373 if (!RHS->isZero()) { // avoid X udiv 0
374 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
375 if (Instruction *R = FoldOpIntoSelect(I, SI))
376 return R;
377 if (isa<PHINode>(Op0))
378 if (Instruction *NV = FoldOpIntoPhi(I))
379 return NV;
380 }
381 }
382
Benjamin Kramer23b02cd2011-04-30 18:16:00 +0000383 // See if we can fold away this div instruction.
384 if (SimplifyDemandedInstructionBits(I))
385 return &I;
386
Duncan Sands593faa52011-01-28 16:51:11 +0000387 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
388 Value *X = 0, *Z = 0;
389 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
390 bool isSigned = I.getOpcode() == Instruction::SDiv;
391 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
392 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
393 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000394 }
395
396 return 0;
397}
398
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +0000399/// dyn_castZExtVal - Checks if V is a zext or constant that can
400/// be truncated to Ty without losing bits.
401static Value *dyn_castZExtVal(Value *V, const Type *Ty) {
402 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
403 if (Z->getSrcTy() == Ty)
404 return Z->getOperand(0);
405 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
406 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
407 return ConstantExpr::getTrunc(C, Ty);
408 }
409 return 0;
410}
411
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000412Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
413 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
414
Duncan Sands593faa52011-01-28 16:51:11 +0000415 if (Value *V = SimplifyUDivInst(Op0, Op1, TD))
416 return ReplaceInstUsesWith(I, V);
417
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000418 // Handle the integer div common cases
419 if (Instruction *Common = commonIDivTransforms(I))
420 return Common;
421
422 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson5b396202010-01-17 06:49:03 +0000423 // X udiv 2^C -> X >> C
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000424 // Check to see if this is an unsigned division with an exact power of 2,
425 // if so, convert to a right shift.
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000426 if (C->getValue().isPowerOf2()) { // 0 not included in isPowerOf2
427 BinaryOperator *LShr =
428 BinaryOperator::CreateLShr(Op0,
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000429 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000430 if (I.isExact()) LShr->setIsExact();
431 return LShr;
432 }
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000433
434 // X udiv C, where C >= signbit
435 if (C->getValue().isNegative()) {
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000436 Value *IC = Builder->CreateICmpULT(Op0, C);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000437 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
438 ConstantInt::get(I.getType(), 1));
439 }
440 }
441
442 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000443 { const APInt *CI; Value *N;
444 if (match(Op1, m_Shl(m_Power2(CI), m_Value(N)))) {
445 if (*CI != 1)
446 N = Builder->CreateAdd(N, ConstantInt::get(I.getType(), CI->logBase2()),
447 "tmp");
448 if (I.isExact())
449 return BinaryOperator::CreateExactLShr(Op0, N);
450 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000451 }
452 }
453
454 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
455 // where C1&C2 are powers of two.
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000456 { Value *Cond; const APInt *C1, *C2;
457 if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) {
458 // Construct the "on true" case of the select
459 Value *TSI = Builder->CreateLShr(Op0, C1->logBase2(), Op1->getName()+".t",
460 I.isExact());
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000461
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000462 // Construct the "on false" case of the select
463 Value *FSI = Builder->CreateLShr(Op0, C2->logBase2(), Op1->getName()+".f",
464 I.isExact());
465
466 // construct the select instruction and return it.
467 return SelectInst::Create(Cond, TSI, FSI);
468 }
469 }
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +0000470
471 // (zext A) udiv (zext B) --> zext (A udiv B)
472 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
473 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
474 return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
475 I.isExact()),
476 I.getType());
477
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000478 return 0;
479}
480
481Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
482 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
483
Duncan Sands593faa52011-01-28 16:51:11 +0000484 if (Value *V = SimplifySDivInst(Op0, Op1, TD))
485 return ReplaceInstUsesWith(I, V);
486
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000487 // Handle the integer div common cases
488 if (Instruction *Common = commonIDivTransforms(I))
489 return Common;
490
491 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
492 // sdiv X, -1 == -X
493 if (RHS->isAllOnesValue())
494 return BinaryOperator::CreateNeg(Op0);
495
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000496 // sdiv X, C --> ashr exact X, log2(C)
497 if (I.isExact() && RHS->getValue().isNonNegative() &&
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000498 RHS->getValue().isPowerOf2()) {
499 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
500 RHS->getValue().exactLogBase2());
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000501 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000502 }
503
504 // -X/C --> X/-C provided the negation doesn't overflow.
505 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000506 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000507 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
508 ConstantExpr::getNeg(RHS));
509 }
510
511 // If the sign bits of both operands are zero (i.e. we can prove they are
512 // unsigned inputs), turn this into a udiv.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000513 if (I.getType()->isIntegerTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000514 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
515 if (MaskedValueIsZero(Op0, Mask)) {
516 if (MaskedValueIsZero(Op1, Mask)) {
517 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
518 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
519 }
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000520
521 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000522 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
523 // Safe because the only negative value (1 << Y) can take on is
524 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
525 // the sign bit set.
526 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
527 }
528 }
529 }
530
531 return 0;
532}
533
Frits van Bommel31726c12011-01-29 17:50:27 +0000534Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
535 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
536
537 if (Value *V = SimplifyFDivInst(Op0, Op1, TD))
538 return ReplaceInstUsesWith(I, V);
539
Benjamin Kramer54673962011-03-30 15:42:35 +0000540 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
541 const APFloat &Op1F = Op1C->getValueAPF();
542
543 // If the divisor has an exact multiplicative inverse we can turn the fdiv
544 // into a cheaper fmul.
545 APFloat Reciprocal(Op1F.getSemantics());
546 if (Op1F.getExactInverse(&Reciprocal)) {
547 ConstantFP *RFP = ConstantFP::get(Builder->getContext(), Reciprocal);
548 return BinaryOperator::CreateFMul(Op0, RFP);
549 }
550 }
551
Frits van Bommel31726c12011-01-29 17:50:27 +0000552 return 0;
553}
554
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000555/// This function implements the transforms common to both integer remainder
556/// instructions (urem and srem). It is called by the visitors to those integer
557/// remainder instructions.
558/// @brief Common integer remainder transforms
559Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
560 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
561
Chris Lattner1add46d2011-05-22 18:18:41 +0000562 // The RHS is known non-zero.
563 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
564 I.setOperand(1, V);
565 return &I;
566 }
567
Duncan Sandsf24ed772011-05-02 16:27:02 +0000568 // Handle cases involving: rem X, (select Cond, Y, Z)
569 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
570 return &I;
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000571
Duncan Sands00676a62011-05-02 18:41:29 +0000572 if (isa<ConstantInt>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000573 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
574 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
575 if (Instruction *R = FoldOpIntoSelect(I, SI))
576 return R;
577 } else if (isa<PHINode>(Op0I)) {
578 if (Instruction *NV = FoldOpIntoPhi(I))
579 return NV;
580 }
581
582 // See if we can fold away this rem instruction.
583 if (SimplifyDemandedInstructionBits(I))
584 return &I;
585 }
586 }
587
588 return 0;
589}
590
591Instruction *InstCombiner::visitURem(BinaryOperator &I) {
592 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
593
Duncan Sandsf24ed772011-05-02 16:27:02 +0000594 if (Value *V = SimplifyURemInst(Op0, Op1, TD))
595 return ReplaceInstUsesWith(I, V);
596
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000597 if (Instruction *common = commonIRemTransforms(I))
598 return common;
599
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000600 // X urem C^2 -> X and C-1
601 { const APInt *C;
602 if (match(Op1, m_Power2(C)))
603 return BinaryOperator::CreateAnd(Op0,
604 ConstantInt::get(I.getType(), *C-1));
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000605 }
606
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000607 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
608 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
609 Constant *N1 = Constant::getAllOnesValue(I.getType());
610 Value *Add = Builder->CreateAdd(Op1, N1, "tmp");
611 return BinaryOperator::CreateAnd(Op0, Add);
612 }
613
614 // urem X, (select Cond, 2^C1, 2^C2) -->
615 // select Cond, (and X, C1-1), (and X, C2-1)
616 // when C1&C2 are powers of two.
617 { Value *Cond; const APInt *C1, *C2;
618 if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) {
619 Value *TrueAnd = Builder->CreateAnd(Op0, *C1-1, Op1->getName()+".t");
620 Value *FalseAnd = Builder->CreateAnd(Op0, *C2-1, Op1->getName()+".f");
621 return SelectInst::Create(Cond, TrueAnd, FalseAnd);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000622 }
623 }
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +0000624
625 // (zext A) urem (zext B) --> zext (A urem B)
626 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
627 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
628 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
629 I.getType());
630
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000631 return 0;
632}
633
634Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
635 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
636
Duncan Sandsf24ed772011-05-02 16:27:02 +0000637 if (Value *V = SimplifySRemInst(Op0, Op1, TD))
638 return ReplaceInstUsesWith(I, V);
639
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000640 // Handle the integer rem common cases
641 if (Instruction *Common = commonIRemTransforms(I))
642 return Common;
643
644 if (Value *RHSNeg = dyn_castNegVal(Op1))
645 if (!isa<Constant>(RHSNeg) ||
646 (isa<ConstantInt>(RHSNeg) &&
647 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
648 // X % -Y -> X % Y
649 Worklist.AddValue(I.getOperand(1));
650 I.setOperand(1, RHSNeg);
651 return &I;
652 }
653
654 // If the sign bits of both operands are zero (i.e. we can prove they are
655 // unsigned inputs), turn this into a urem.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000656 if (I.getType()->isIntegerTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000657 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
658 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
659 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
660 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
661 }
662 }
663
664 // If it's a constant vector, flip any negative values positive.
665 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
666 unsigned VWidth = RHSV->getNumOperands();
667
668 bool hasNegative = false;
669 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
670 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
671 if (RHS->getValue().isNegative())
672 hasNegative = true;
673
674 if (hasNegative) {
675 std::vector<Constant *> Elts(VWidth);
676 for (unsigned i = 0; i != VWidth; ++i) {
677 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
678 if (RHS->getValue().isNegative())
679 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
680 else
681 Elts[i] = RHS;
682 }
683 }
684
685 Constant *NewRHSV = ConstantVector::get(Elts);
686 if (NewRHSV != RHSV) {
687 Worklist.AddValue(I.getOperand(1));
688 I.setOperand(1, NewRHSV);
689 return &I;
690 }
691 }
692 }
693
694 return 0;
695}
696
697Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsf24ed772011-05-02 16:27:02 +0000698 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000699
Duncan Sandsf24ed772011-05-02 16:27:02 +0000700 if (Value *V = SimplifyFRemInst(Op0, Op1, TD))
701 return ReplaceInstUsesWith(I, V);
702
703 // Handle cases involving: rem X, (select Cond, Y, Z)
704 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
705 return &I;
706
707 return 0;
708}