blob: bb6bd4e9db63da5418c81fbe144de31607756b6e [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"
Duncan Sands82fdab32010-12-21 14:00:22 +000016#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000017#include "llvm/IR/IntrinsicInst.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.
Rafael Espindoladbaa2372012-12-13 03:37:24 +000040 isKnownToBeAPowerOfTwo(PowerOf2)) {
Benjamin Kramera9390a42011-09-27 20:39:19 +000041 A = IC.Builder->CreateSub(A, B);
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))
Rafael Espindoladbaa2372012-12-13 03:37:24 +000048 if (I->isLogicalShift() && isKnownToBeAPowerOfTwo(I->getOperand(0))) {
Chris Lattner613f1a32011-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 }
55
56 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
57 I->setIsExact();
58 MadeChange = true;
59 }
60
61 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
62 I->setHasNoUnsignedWrap();
63 MadeChange = true;
64 }
65 }
66
Chris Lattner6c9b8d32011-05-22 18:26:48 +000067 // TODO: Lots more we could do here:
Chris Lattner6c9b8d32011-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".
70
Chris Lattner613f1a32011-05-23 00:32:19 +000071 return MadeChange ? V : 0;
Chris Lattner1add46d2011-05-22 18:18:41 +000072}
73
74
Chris Lattnerd12c27c2010-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 Foad40f8f622010-12-07 08:25:19 +000081 LHSExt = LHSExt.sext(W * 2);
82 RHSExt = RHSExt.sext(W * 2);
Chris Lattnerd12c27c2010-01-05 06:09:35 +000083 } else {
Jay Foad40f8f622010-12-07 08:25:19 +000084 LHSExt = LHSExt.zext(W * 2);
85 RHSExt = RHSExt.zext(W * 2);
Chris Lattnerd12c27c2010-01-05 06:09:35 +000086 }
87
88 APInt MulExt = LHSExt * RHSExt;
89
90 if (!sign)
91 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
92
93 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
98Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands096aa792010-11-13 15:10:37 +000099 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000100 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
101
Duncan Sands82fdab32010-12-21 14:00:22 +0000102 if (Value *V = SimplifyMulInst(Op0, Op1, TD))
103 return ReplaceInstUsesWith(I, V);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000104
Duncan Sands37bf92b2010-12-22 13:36:08 +0000105 if (Value *V = SimplifyUsingDistributiveLaws(I))
106 return ReplaceInstUsesWith(I, V);
107
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000108 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X
109 return BinaryOperator::CreateNeg(Op0, I.getName());
110
111 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
112
113 // ((X << C1)*C2) == (X * (C2 << C1))
114 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
115 if (SI->getOpcode() == Instruction::Shl)
116 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
117 return BinaryOperator::CreateMul(SI->getOperand(0),
118 ConstantExpr::getShl(CI, ShOp));
119
120 const APInt &Val = CI->getValue();
121 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
122 Constant *NewCst = ConstantInt::get(Op0->getType(), Val.logBase2());
123 BinaryOperator *Shl = BinaryOperator::CreateShl(Op0, NewCst);
124 if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap();
125 if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap();
126 return Shl;
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000127 }
128
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000129 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
130 { Value *X; ConstantInt *C1;
131 if (Op0->hasOneUse() &&
132 match(Op0, m_Add(m_Value(X), m_ConstantInt(C1)))) {
Benjamin Kramera9390a42011-09-27 20:39:19 +0000133 Value *Add = Builder->CreateMul(X, CI);
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000134 return BinaryOperator::CreateAdd(Add, Builder->CreateMul(C1, CI));
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000135 }
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000136 }
Stuart Hastingsacbf1072011-05-30 20:00:33 +0000137
Stuart Hastingsf1002822011-06-01 16:42:47 +0000138 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
139 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
140 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastingsacbf1072011-05-30 20:00:33 +0000141 {
142 const APInt & Val = CI->getValue();
143 const APInt &PosVal = Val.abs();
144 if (Val.isNegative() && PosVal.isPowerOf2()) {
Stuart Hastingsf1002822011-06-01 16:42:47 +0000145 Value *X = 0, *Y = 0;
146 if (Op0->hasOneUse()) {
147 ConstantInt *C1;
148 Value *Sub = 0;
149 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
150 Sub = Builder->CreateSub(X, Y, "suba");
151 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
152 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
153 if (Sub)
154 return
155 BinaryOperator::CreateMul(Sub,
156 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastingsacbf1072011-05-30 20:00:33 +0000157 }
158 }
159 }
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000160 }
161
162 // Simplify mul instructions with a constant RHS.
163 if (isa<Constant>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000164 // Try to fold constant mul into select arguments.
165 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
166 if (Instruction *R = FoldOpIntoSelect(I, SI))
167 return R;
168
169 if (isa<PHINode>(Op0))
170 if (Instruction *NV = FoldOpIntoPhi(I))
171 return NV;
172 }
173
174 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
175 if (Value *Op1v = dyn_castNegVal(Op1))
176 return BinaryOperator::CreateMul(Op0v, Op1v);
177
178 // (X / Y) * Y = X - (X % Y)
179 // (X / Y) * -Y = (X % Y) - X
180 {
181 Value *Op1C = Op1;
182 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
183 if (!BO ||
184 (BO->getOpcode() != Instruction::UDiv &&
185 BO->getOpcode() != Instruction::SDiv)) {
186 Op1C = Op0;
187 BO = dyn_cast<BinaryOperator>(Op1);
188 }
189 Value *Neg = dyn_castNegVal(Op1C);
190 if (BO && BO->hasOneUse() &&
191 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
192 (BO->getOpcode() == Instruction::UDiv ||
193 BO->getOpcode() == Instruction::SDiv)) {
194 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
195
Chris Lattner35bda892011-02-06 21:44:57 +0000196 // If the division is exact, X % Y is zero, so we end up with X or -X.
197 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000198 if (SDiv->isExact()) {
199 if (Op1BO == Op1C)
200 return ReplaceInstUsesWith(I, Op0BO);
201 return BinaryOperator::CreateNeg(Op0BO);
202 }
203
204 Value *Rem;
205 if (BO->getOpcode() == Instruction::UDiv)
206 Rem = Builder->CreateURem(Op0BO, Op1BO);
207 else
208 Rem = Builder->CreateSRem(Op0BO, Op1BO);
209 Rem->takeName(BO);
210
211 if (Op1BO == Op1C)
212 return BinaryOperator::CreateSub(Op0BO, Rem);
213 return BinaryOperator::CreateSub(Rem, Op0BO);
214 }
215 }
216
217 /// i1 mul -> i1 and.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000218 if (I.getType()->isIntegerTy(1))
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000219 return BinaryOperator::CreateAnd(Op0, Op1);
220
221 // X*(1 << Y) --> X << Y
222 // (1 << Y)*X --> X << Y
223 {
224 Value *Y;
225 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
226 return BinaryOperator::CreateShl(Op1, Y);
227 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
228 return BinaryOperator::CreateShl(Op0, Y);
229 }
230
231 // If one of the operands of the multiply is a cast from a boolean value, then
232 // we know the bool is either zero or one, so this is a 'masking' multiply.
233 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands1df98592010-02-16 11:11:14 +0000234 if (!I.getType()->isVectorTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000235 // -2 is "-1 << 1" so it is all bits set except the low one.
236 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
237
238 Value *BoolCast = 0, *OtherOp = 0;
239 if (MaskedValueIsZero(Op0, Negative2))
240 BoolCast = Op0, OtherOp = Op1;
241 else if (MaskedValueIsZero(Op1, Negative2))
242 BoolCast = Op1, OtherOp = Op0;
243
244 if (BoolCast) {
245 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramera9390a42011-09-27 20:39:19 +0000246 BoolCast);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000247 return BinaryOperator::CreateAnd(V, OtherOp);
248 }
249 }
250
251 return Changed ? &I : 0;
252}
253
Pedro Artigasc2a08d22012-11-30 22:07:05 +0000254//
255// Detect pattern:
256//
257// log2(Y*0.5)
258//
259// And check for corresponding fast math flags
260//
261
262static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Pedro Artigasef2ef3e2012-11-30 22:47:15 +0000263
264 if (!Op->hasOneUse())
265 return;
266
267 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
268 if (!II)
269 return;
270 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
271 return;
272 Log2 = II;
273
274 Value *OpLog2Of = II->getArgOperand(0);
275 if (!OpLog2Of->hasOneUse())
276 return;
277
278 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
279 if (!I)
280 return;
281 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
282 return;
283
284 ConstantFP *CFP = dyn_cast<ConstantFP>(I->getOperand(0));
285 if (CFP && CFP->isExactlyValue(0.5)) {
286 Y = I->getOperand(1);
287 return;
288 }
289 CFP = dyn_cast<ConstantFP>(I->getOperand(1));
290 if (CFP && CFP->isExactlyValue(0.5))
291 Y = I->getOperand(0);
Pedro Artigasc2a08d22012-11-30 22:07:05 +0000292}
293
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000294Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands096aa792010-11-13 15:10:37 +0000295 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000296 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
297
Michael Ilsemanc244f382012-12-12 00:28:32 +0000298 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), TD))
299 return ReplaceInstUsesWith(I, V);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000300
Michael Ilsemanc244f382012-12-12 00:28:32 +0000301 // Simplify mul instructions with a constant RHS.
302 if (isa<Constant>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000303 // Try to fold constant mul into select arguments.
304 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
305 if (Instruction *R = FoldOpIntoSelect(I, SI))
306 return R;
307
308 if (isa<PHINode>(Op0))
309 if (Instruction *NV = FoldOpIntoPhi(I))
310 return NV;
311 }
312
313 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
314 if (Value *Op1v = dyn_castFNegVal(Op1))
315 return BinaryOperator::CreateFMul(Op0v, Op1v);
316
Pedro Artigas84030dc2012-11-30 19:09:41 +0000317 // Under unsafe algebra do:
318 // X * log2(0.5*Y) = X*log2(Y) - X
319 if (I.hasUnsafeAlgebra()) {
320 Value *OpX = NULL;
321 Value *OpY = NULL;
322 IntrinsicInst *Log2;
Pedro Artigasc2a08d22012-11-30 22:07:05 +0000323 detectLog2OfHalf(Op0, OpY, Log2);
324 if (OpY) {
325 OpX = Op1;
326 } else {
327 detectLog2OfHalf(Op1, OpY, Log2);
328 if (OpY) {
329 OpX = Op0;
Pedro Artigas84030dc2012-11-30 19:09:41 +0000330 }
331 }
332 // if pattern detected emit alternate sequence
333 if (OpX && OpY) {
334 Log2->setArgOperand(0, OpY);
335 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
Pedro Artigasc2a08d22012-11-30 22:07:05 +0000336 Instruction *FMul = cast<Instruction>(FMulVal);
Pedro Artigas84030dc2012-11-30 19:09:41 +0000337 FMul->copyFastMathFlags(Log2);
338 Instruction *FSub = BinaryOperator::CreateFSub(FMulVal, OpX);
339 FSub->copyFastMathFlags(Log2);
340 return FSub;
341 }
342 }
343
Shuxin Yanga5ed0312012-12-14 18:46:06 +0000344 // X * cond ? 1.0 : 0.0 => cond ? X : 0.0
345 if (I.hasNoNaNs() && I.hasNoSignedZeros()) {
346 Value *V0 = I.getOperand(0);
347 Value *V1 = I.getOperand(1);
348 Value *Cond, *SLHS, *SRHS;
349 bool Match = false;
350
351 if (match(V0, m_Select(m_Value(Cond), m_Value(SLHS), m_Value(SRHS)))) {
352 Match = true;
353 } else if (match(V1, m_Select(m_Value(Cond), m_Value(SLHS),
354 m_Value(SRHS)))) {
355 Match = true;
356 std::swap(V0, V1);
357 }
358
359 if (Match) {
360 ConstantFP *C0 = dyn_cast<ConstantFP>(SLHS);
361 ConstantFP *C1 = dyn_cast<ConstantFP>(SRHS);
362
363 if (C0 && C1 &&
364 ((C0->isZero() && C1->isExactlyValue(1.0)) ||
365 (C1->isZero() && C0->isExactlyValue(1.0)))) {
366 Value *T;
367 if (C0->isZero())
368 T = Builder->CreateSelect(Cond, SLHS, V1);
369 else
370 T = Builder->CreateSelect(Cond, V1, SRHS);
371 return ReplaceInstUsesWith(I, T);
372 }
373 }
374 }
375
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000376 return Changed ? &I : 0;
377}
378
379/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
380/// instruction.
381bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
382 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
383
384 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
385 int NonNullOperand = -1;
386 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
387 if (ST->isNullValue())
388 NonNullOperand = 2;
389 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
390 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
391 if (ST->isNullValue())
392 NonNullOperand = 1;
393
394 if (NonNullOperand == -1)
395 return false;
396
397 Value *SelectCond = SI->getOperand(0);
398
399 // Change the div/rem to use 'Y' instead of the select.
400 I.setOperand(1, SI->getOperand(NonNullOperand));
401
402 // Okay, we know we replace the operand of the div/rem with 'Y' with no
403 // problem. However, the select, or the condition of the select may have
404 // multiple uses. Based on our knowledge that the operand must be non-zero,
405 // propagate the known value for the select into other uses of it, and
406 // propagate a known value of the condition into its other users.
407
408 // If the select and condition only have a single use, don't bother with this,
409 // early exit.
410 if (SI->use_empty() && SelectCond->hasOneUse())
411 return true;
412
413 // Scan the current block backward, looking for other uses of SI.
414 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
415
416 while (BBI != BBFront) {
417 --BBI;
418 // If we found a call to a function, we can't assume it will return, so
419 // information from below it cannot be propagated above it.
420 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
421 break;
422
423 // Replace uses of the select or its condition with the known values.
424 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
425 I != E; ++I) {
426 if (*I == SI) {
427 *I = SI->getOperand(NonNullOperand);
428 Worklist.Add(BBI);
429 } else if (*I == SelectCond) {
430 *I = NonNullOperand == 1 ? ConstantInt::getTrue(BBI->getContext()) :
431 ConstantInt::getFalse(BBI->getContext());
432 Worklist.Add(BBI);
433 }
434 }
435
436 // If we past the instruction, quit looking for it.
437 if (&*BBI == SI)
438 SI = 0;
439 if (&*BBI == SelectCond)
440 SelectCond = 0;
441
442 // If we ran out of things to eliminate, break out of the loop.
443 if (SelectCond == 0 && SI == 0)
444 break;
445
446 }
447 return true;
448}
449
450
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000451/// This function implements the transforms common to both integer division
452/// instructions (udiv and sdiv). It is called by the visitors to those integer
453/// division instructions.
454/// @brief Common integer divide transforms
455Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
456 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
457
Chris Lattner1add46d2011-05-22 18:18:41 +0000458 // The RHS is known non-zero.
459 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
460 I.setOperand(1, V);
461 return &I;
462 }
463
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000464 // Handle cases involving: [su]div X, (select Cond, Y, Z)
465 // This does not apply for fdiv.
466 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
467 return &I;
468
469 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000470 // (X / C1) / C2 -> X / (C1*C2)
471 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
472 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
473 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
474 if (MultiplyOverflows(RHS, LHSRHS,
475 I.getOpcode()==Instruction::SDiv))
476 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000477 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
478 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000479 }
480
481 if (!RHS->isZero()) { // avoid X udiv 0
482 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
483 if (Instruction *R = FoldOpIntoSelect(I, SI))
484 return R;
485 if (isa<PHINode>(Op0))
486 if (Instruction *NV = FoldOpIntoPhi(I))
487 return NV;
488 }
489 }
490
Benjamin Kramer23b02cd2011-04-30 18:16:00 +0000491 // See if we can fold away this div instruction.
492 if (SimplifyDemandedInstructionBits(I))
493 return &I;
494
Duncan Sands593faa52011-01-28 16:51:11 +0000495 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
496 Value *X = 0, *Z = 0;
497 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
498 bool isSigned = I.getOpcode() == Instruction::SDiv;
499 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
500 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
501 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000502 }
503
504 return 0;
505}
506
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +0000507/// dyn_castZExtVal - Checks if V is a zext or constant that can
508/// be truncated to Ty without losing bits.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000509static Value *dyn_castZExtVal(Value *V, Type *Ty) {
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +0000510 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
511 if (Z->getSrcTy() == Ty)
512 return Z->getOperand(0);
513 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
514 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
515 return ConstantExpr::getTrunc(C, Ty);
516 }
517 return 0;
518}
519
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000520Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
521 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
522
Duncan Sands593faa52011-01-28 16:51:11 +0000523 if (Value *V = SimplifyUDivInst(Op0, Op1, TD))
524 return ReplaceInstUsesWith(I, V);
525
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000526 // Handle the integer div common cases
527 if (Instruction *Common = commonIDivTransforms(I))
528 return Common;
Pete Coopera29fc802011-11-07 23:04:49 +0000529
530 {
Owen Anderson5b396202010-01-17 06:49:03 +0000531 // X udiv 2^C -> X >> C
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000532 // Check to see if this is an unsigned division with an exact power of 2,
533 // if so, convert to a right shift.
Pete Coopera29fc802011-11-07 23:04:49 +0000534 const APInt *C;
535 if (match(Op1, m_Power2(C))) {
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000536 BinaryOperator *LShr =
Pete Coopera29fc802011-11-07 23:04:49 +0000537 BinaryOperator::CreateLShr(Op0,
538 ConstantInt::get(Op0->getType(),
539 C->logBase2()));
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000540 if (I.isExact()) LShr->setIsExact();
541 return LShr;
542 }
Pete Coopera29fc802011-11-07 23:04:49 +0000543 }
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000544
Pete Coopera29fc802011-11-07 23:04:49 +0000545 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000546 // X udiv C, where C >= signbit
547 if (C->getValue().isNegative()) {
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000548 Value *IC = Builder->CreateICmpULT(Op0, C);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000549 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
550 ConstantInt::get(I.getType(), 1));
551 }
552 }
553
Benjamin Kramerc81fe9c2012-08-30 15:07:40 +0000554 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
Nadav Rotema694e2a2012-08-28 12:23:22 +0000555 if (ConstantInt *C2 = dyn_cast<ConstantInt>(Op1)) {
Benjamin Krameraac7c652012-08-28 13:08:13 +0000556 Value *X;
557 ConstantInt *C1;
558 if (match(Op0, m_LShr(m_Value(X), m_ConstantInt(C1)))) {
Benjamin Kramer37dca632012-08-28 13:59:23 +0000559 APInt NC = C2->getValue().shl(C1->getLimitedValue(C1->getBitWidth()-1));
Benjamin Krameraac7c652012-08-28 13:08:13 +0000560 return BinaryOperator::CreateUDiv(X, Builder->getInt(NC));
Nadav Rotem9753f0b2012-08-28 10:01:43 +0000561 }
562 }
563
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000564 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000565 { const APInt *CI; Value *N;
Evan Cheng2a5422b2012-06-21 22:52:49 +0000566 if (match(Op1, m_Shl(m_Power2(CI), m_Value(N))) ||
567 match(Op1, m_ZExt(m_Shl(m_Power2(CI), m_Value(N))))) {
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000568 if (*CI != 1)
Benjamin Kramere5bd3cf2012-09-21 16:26:41 +0000569 N = Builder->CreateAdd(N,
570 ConstantInt::get(N->getType(), CI->logBase2()));
Evan Cheng2a5422b2012-06-21 22:52:49 +0000571 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
572 N = Builder->CreateZExt(N, Z->getDestTy());
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000573 if (I.isExact())
574 return BinaryOperator::CreateExactLShr(Op0, N);
575 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000576 }
577 }
578
579 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
580 // where C1&C2 are powers of two.
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000581 { Value *Cond; const APInt *C1, *C2;
582 if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) {
583 // Construct the "on true" case of the select
584 Value *TSI = Builder->CreateLShr(Op0, C1->logBase2(), Op1->getName()+".t",
585 I.isExact());
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000586
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000587 // Construct the "on false" case of the select
588 Value *FSI = Builder->CreateLShr(Op0, C2->logBase2(), Op1->getName()+".f",
589 I.isExact());
590
591 // construct the select instruction and return it.
592 return SelectInst::Create(Cond, TSI, FSI);
593 }
594 }
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +0000595
596 // (zext A) udiv (zext B) --> zext (A udiv B)
597 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
598 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
599 return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
600 I.isExact()),
601 I.getType());
602
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000603 return 0;
604}
605
606Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
607 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
608
Duncan Sands593faa52011-01-28 16:51:11 +0000609 if (Value *V = SimplifySDivInst(Op0, Op1, TD))
610 return ReplaceInstUsesWith(I, V);
611
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000612 // Handle the integer div common cases
613 if (Instruction *Common = commonIDivTransforms(I))
614 return Common;
615
616 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
617 // sdiv X, -1 == -X
618 if (RHS->isAllOnesValue())
619 return BinaryOperator::CreateNeg(Op0);
620
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000621 // sdiv X, C --> ashr exact X, log2(C)
622 if (I.isExact() && RHS->getValue().isNonNegative() &&
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000623 RHS->getValue().isPowerOf2()) {
624 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
625 RHS->getValue().exactLogBase2());
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000626 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000627 }
628
629 // -X/C --> X/-C provided the negation doesn't overflow.
630 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000631 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000632 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
633 ConstantExpr::getNeg(RHS));
634 }
635
636 // If the sign bits of both operands are zero (i.e. we can prove they are
637 // unsigned inputs), turn this into a udiv.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000638 if (I.getType()->isIntegerTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000639 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
640 if (MaskedValueIsZero(Op0, Mask)) {
641 if (MaskedValueIsZero(Op1, Mask)) {
Sylvestre Ledru94c22712012-09-27 10:14:43 +0000642 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000643 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
644 }
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000645
646 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000647 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
648 // Safe because the only negative value (1 << Y) can take on is
649 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
650 // the sign bit set.
651 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
652 }
653 }
654 }
655
656 return 0;
657}
658
Frits van Bommel31726c12011-01-29 17:50:27 +0000659Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
660 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
661
662 if (Value *V = SimplifyFDivInst(Op0, Op1, TD))
663 return ReplaceInstUsesWith(I, V);
664
Benjamin Kramer54673962011-03-30 15:42:35 +0000665 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
666 const APFloat &Op1F = Op1C->getValueAPF();
667
668 // If the divisor has an exact multiplicative inverse we can turn the fdiv
669 // into a cheaper fmul.
670 APFloat Reciprocal(Op1F.getSemantics());
671 if (Op1F.getExactInverse(&Reciprocal)) {
672 ConstantFP *RFP = ConstantFP::get(Builder->getContext(), Reciprocal);
673 return BinaryOperator::CreateFMul(Op0, RFP);
674 }
675 }
676
Frits van Bommel31726c12011-01-29 17:50:27 +0000677 return 0;
678}
679
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000680/// This function implements the transforms common to both integer remainder
681/// instructions (urem and srem). It is called by the visitors to those integer
682/// remainder instructions.
683/// @brief Common integer remainder transforms
684Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
685 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
686
Chris Lattner1add46d2011-05-22 18:18:41 +0000687 // The RHS is known non-zero.
688 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
689 I.setOperand(1, V);
690 return &I;
691 }
692
Duncan Sandsf24ed772011-05-02 16:27:02 +0000693 // Handle cases involving: rem X, (select Cond, Y, Z)
694 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
695 return &I;
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000696
Duncan Sands00676a62011-05-02 18:41:29 +0000697 if (isa<ConstantInt>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000698 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
699 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
700 if (Instruction *R = FoldOpIntoSelect(I, SI))
701 return R;
702 } else if (isa<PHINode>(Op0I)) {
703 if (Instruction *NV = FoldOpIntoPhi(I))
704 return NV;
705 }
706
707 // See if we can fold away this rem instruction.
708 if (SimplifyDemandedInstructionBits(I))
709 return &I;
710 }
711 }
712
713 return 0;
714}
715
716Instruction *InstCombiner::visitURem(BinaryOperator &I) {
717 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
718
Duncan Sandsf24ed772011-05-02 16:27:02 +0000719 if (Value *V = SimplifyURemInst(Op0, Op1, TD))
720 return ReplaceInstUsesWith(I, V);
721
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000722 if (Instruction *common = commonIRemTransforms(I))
723 return common;
724
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000725 // X urem C^2 -> X and C-1
726 { const APInt *C;
727 if (match(Op1, m_Power2(C)))
728 return BinaryOperator::CreateAnd(Op0,
729 ConstantInt::get(I.getType(), *C-1));
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000730 }
731
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000732 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
733 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
734 Constant *N1 = Constant::getAllOnesValue(I.getType());
Benjamin Kramera9390a42011-09-27 20:39:19 +0000735 Value *Add = Builder->CreateAdd(Op1, N1);
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000736 return BinaryOperator::CreateAnd(Op0, Add);
737 }
738
739 // urem X, (select Cond, 2^C1, 2^C2) -->
740 // select Cond, (and X, C1-1), (and X, C2-1)
741 // when C1&C2 are powers of two.
742 { Value *Cond; const APInt *C1, *C2;
743 if (match(Op1, m_Select(m_Value(Cond), m_Power2(C1), m_Power2(C2)))) {
744 Value *TrueAnd = Builder->CreateAnd(Op0, *C1-1, Op1->getName()+".t");
745 Value *FalseAnd = Builder->CreateAnd(Op0, *C2-1, Op1->getName()+".f");
746 return SelectInst::Create(Cond, TrueAnd, FalseAnd);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000747 }
748 }
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +0000749
750 // (zext A) urem (zext B) --> zext (A urem B)
751 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
752 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
753 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
754 I.getType());
755
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000756 return 0;
757}
758
759Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
760 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
761
Duncan Sandsf24ed772011-05-02 16:27:02 +0000762 if (Value *V = SimplifySRemInst(Op0, Op1, TD))
763 return ReplaceInstUsesWith(I, V);
764
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000765 // Handle the integer rem common cases
766 if (Instruction *Common = commonIRemTransforms(I))
767 return Common;
768
769 if (Value *RHSNeg = dyn_castNegVal(Op1))
770 if (!isa<Constant>(RHSNeg) ||
771 (isa<ConstantInt>(RHSNeg) &&
772 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
773 // X % -Y -> X % Y
774 Worklist.AddValue(I.getOperand(1));
775 I.setOperand(1, RHSNeg);
776 return &I;
777 }
778
779 // If the sign bits of both operands are zero (i.e. we can prove they are
780 // unsigned inputs), turn this into a urem.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000781 if (I.getType()->isIntegerTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000782 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
783 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Sylvestre Ledru94c22712012-09-27 10:14:43 +0000784 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000785 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
786 }
787 }
788
789 // If it's a constant vector, flip any negative values positive.
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000790 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
791 Constant *C = cast<Constant>(Op1);
792 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000793
794 bool hasNegative = false;
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000795 bool hasMissing = false;
796 for (unsigned i = 0; i != VWidth; ++i) {
797 Constant *Elt = C->getAggregateElement(i);
798 if (Elt == 0) {
799 hasMissing = true;
800 break;
801 }
802
803 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerc73b24d2011-07-15 06:08:15 +0000804 if (RHS->isNegative())
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000805 hasNegative = true;
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000806 }
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000807
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000808 if (hasNegative && !hasMissing) {
Chris Lattner4ca829e2012-01-25 06:02:56 +0000809 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000810 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner7302d802012-02-06 21:56:39 +0000811 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000812 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerc73b24d2011-07-15 06:08:15 +0000813 if (RHS->isNegative())
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000814 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000815 }
816 }
817
818 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000819 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000820 Worklist.AddValue(I.getOperand(1));
821 I.setOperand(1, NewRHSV);
822 return &I;
823 }
824 }
825 }
826
827 return 0;
828}
829
830Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsf24ed772011-05-02 16:27:02 +0000831 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000832
Duncan Sandsf24ed772011-05-02 16:27:02 +0000833 if (Value *V = SimplifyFRemInst(Op0, Op1, TD))
834 return ReplaceInstUsesWith(I, V);
835
836 // Handle cases involving: rem X, (select Cond, Y, Z)
837 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
838 return &I;
839
840 return 0;
841}