blob: 9996ebc2e7449937971961d88214b340101e6446 [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"
Stephen Hines36b56882014-04-23 16:57:46 -070018#include "llvm/IR/PatternMatch.h"
Chris Lattnerd12c27c2010-01-05 06:09:35 +000019using namespace llvm;
20using namespace PatternMatch;
21
Stephen Hinesdce4a402014-05-29 02:49:00 -070022#define DEBUG_TYPE "instcombine"
23
Chris Lattner1add46d2011-05-22 18:18:41 +000024
25/// simplifyValueKnownNonZero - The specific integer value is used in a context
26/// where it is known to be non-zero. If this allows us to simplify the
27/// computation, do so and return the new operand, otherwise return null.
28static Value *simplifyValueKnownNonZero(Value *V, InstCombiner &IC) {
29 // If V has multiple uses, then we would have to do more analysis to determine
30 // if this is safe. For example, the use could be in dynamically unreached
31 // code.
Stephen Hinesdce4a402014-05-29 02:49:00 -070032 if (!V->hasOneUse()) return nullptr;
Jim Grosbach03fceff2013-04-05 21:20:12 +000033
Chris Lattner613f1a32011-05-23 00:32:19 +000034 bool MadeChange = false;
35
Chris Lattner1add46d2011-05-22 18:18:41 +000036 // ((1 << A) >>u B) --> (1 << (A-B))
37 // Because V cannot be zero, we know that B is less than A.
Stephen Hinesdce4a402014-05-29 02:49:00 -070038 Value *A = nullptr, *B = nullptr, *PowerOf2 = nullptr;
Chris Lattner6083bb92011-05-23 00:09:55 +000039 if (match(V, m_LShr(m_OneUse(m_Shl(m_Value(PowerOf2), m_Value(A))),
Chris Lattner1add46d2011-05-22 18:18:41 +000040 m_Value(B))) &&
41 // The "1" can be any value known to be a power of 2.
Rafael Espindoladbaa2372012-12-13 03:37:24 +000042 isKnownToBeAPowerOfTwo(PowerOf2)) {
Benjamin Kramera9390a42011-09-27 20:39:19 +000043 A = IC.Builder->CreateSub(A, B);
Chris Lattner6083bb92011-05-23 00:09:55 +000044 return IC.Builder->CreateShl(PowerOf2, A);
Chris Lattner1add46d2011-05-22 18:18:41 +000045 }
Jim Grosbach03fceff2013-04-05 21:20:12 +000046
Chris Lattner613f1a32011-05-23 00:32:19 +000047 // (PowerOfTwo >>u B) --> isExact since shifting out the result would make it
48 // inexact. Similarly for <<.
49 if (BinaryOperator *I = dyn_cast<BinaryOperator>(V))
Rafael Espindoladbaa2372012-12-13 03:37:24 +000050 if (I->isLogicalShift() && isKnownToBeAPowerOfTwo(I->getOperand(0))) {
Chris Lattner613f1a32011-05-23 00:32:19 +000051 // We know that this is an exact/nuw shift and that the input is a
52 // non-zero context as well.
53 if (Value *V2 = simplifyValueKnownNonZero(I->getOperand(0), IC)) {
54 I->setOperand(0, V2);
55 MadeChange = true;
56 }
Jim Grosbach03fceff2013-04-05 21:20:12 +000057
Chris Lattner613f1a32011-05-23 00:32:19 +000058 if (I->getOpcode() == Instruction::LShr && !I->isExact()) {
59 I->setIsExact();
60 MadeChange = true;
61 }
Jim Grosbach03fceff2013-04-05 21:20:12 +000062
Chris Lattner613f1a32011-05-23 00:32:19 +000063 if (I->getOpcode() == Instruction::Shl && !I->hasNoUnsignedWrap()) {
64 I->setHasNoUnsignedWrap();
65 MadeChange = true;
66 }
67 }
68
Chris Lattner6c9b8d32011-05-22 18:26:48 +000069 // TODO: Lots more we could do here:
Chris Lattner6c9b8d32011-05-22 18:26:48 +000070 // If V is a phi node, we can call this on each of its operands.
71 // "select cond, X, 0" can simplify to "X".
Jim Grosbach03fceff2013-04-05 21:20:12 +000072
Stephen Hinesdce4a402014-05-29 02:49:00 -070073 return MadeChange ? V : nullptr;
Chris Lattner1add46d2011-05-22 18:18:41 +000074}
75
76
Chris Lattnerd12c27c2010-01-05 06:09:35 +000077/// MultiplyOverflows - True if the multiply can not be expressed in an int
78/// this size.
79static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
80 uint32_t W = C1->getBitWidth();
81 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
82 if (sign) {
Jay Foad40f8f622010-12-07 08:25:19 +000083 LHSExt = LHSExt.sext(W * 2);
84 RHSExt = RHSExt.sext(W * 2);
Chris Lattnerd12c27c2010-01-05 06:09:35 +000085 } else {
Jay Foad40f8f622010-12-07 08:25:19 +000086 LHSExt = LHSExt.zext(W * 2);
87 RHSExt = RHSExt.zext(W * 2);
Chris Lattnerd12c27c2010-01-05 06:09:35 +000088 }
Jim Grosbach03fceff2013-04-05 21:20:12 +000089
Chris Lattnerd12c27c2010-01-05 06:09:35 +000090 APInt MulExt = LHSExt * RHSExt;
Jim Grosbach03fceff2013-04-05 21:20:12 +000091
Chris Lattnerd12c27c2010-01-05 06:09:35 +000092 if (!sign)
93 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
Jim Grosbach03fceff2013-04-05 21:20:12 +000094
Chris Lattnerd12c27c2010-01-05 06:09:35 +000095 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
96 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
97 return MulExt.slt(Min) || MulExt.sgt(Max);
98}
99
Rafael Espindola4f3d7ee2013-05-31 14:27:15 +0000100/// \brief A helper routine of InstCombiner::visitMul().
101///
102/// If C is a vector of known powers of 2, then this function returns
103/// a new vector obtained from C replacing each element with its logBase2.
104/// Return a null pointer otherwise.
105static Constant *getLogBase2Vector(ConstantDataVector *CV) {
106 const APInt *IVal;
107 SmallVector<Constant *, 4> Elts;
108
109 for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
110 Constant *Elt = CV->getElementAsConstant(I);
111 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
Stephen Hinesdce4a402014-05-29 02:49:00 -0700112 return nullptr;
Rafael Espindola4f3d7ee2013-05-31 14:27:15 +0000113 Elts.push_back(ConstantInt::get(Elt->getType(), IVal->logBase2()));
114 }
115
116 return ConstantVector::get(Elts);
117}
118
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000119Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Duncan Sands096aa792010-11-13 15:10:37 +0000120 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000121 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
122
Stephen Hinesdce4a402014-05-29 02:49:00 -0700123 if (Value *V = SimplifyVectorOp(I))
124 return ReplaceInstUsesWith(I, V);
125
Stephen Hines36b56882014-04-23 16:57:46 -0700126 if (Value *V = SimplifyMulInst(Op0, Op1, DL))
Duncan Sands82fdab32010-12-21 14:00:22 +0000127 return ReplaceInstUsesWith(I, V);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000128
Duncan Sands37bf92b2010-12-22 13:36:08 +0000129 if (Value *V = SimplifyUsingDistributiveLaws(I))
130 return ReplaceInstUsesWith(I, V);
131
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000132 if (match(Op1, m_AllOnes())) // X * -1 == 0 - X
133 return BinaryOperator::CreateNeg(Op0, I.getName());
Jim Grosbach03fceff2013-04-05 21:20:12 +0000134
Rafael Espindola4f3d7ee2013-05-31 14:27:15 +0000135 // Also allow combining multiply instructions on vectors.
136 {
137 Value *NewOp;
138 Constant *C1, *C2;
139 const APInt *IVal;
140 if (match(&I, m_Mul(m_Shl(m_Value(NewOp), m_Constant(C2)),
141 m_Constant(C1))) &&
142 match(C1, m_APInt(IVal)))
143 // ((X << C1)*C2) == (X * (C2 << C1))
144 return BinaryOperator::CreateMul(NewOp, ConstantExpr::getShl(C1, C2));
Jim Grosbach03fceff2013-04-05 21:20:12 +0000145
Rafael Espindola4f3d7ee2013-05-31 14:27:15 +0000146 if (match(&I, m_Mul(m_Value(NewOp), m_Constant(C1)))) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700147 Constant *NewCst = nullptr;
Rafael Espindola4f3d7ee2013-05-31 14:27:15 +0000148 if (match(C1, m_APInt(IVal)) && IVal->isPowerOf2())
149 // Replace X*(2^C) with X << C, where C is either a scalar or a splat.
150 NewCst = ConstantInt::get(NewOp->getType(), IVal->logBase2());
151 else if (ConstantDataVector *CV = dyn_cast<ConstantDataVector>(C1))
152 // Replace X*(2^C) with X << C, where C is a vector of known
153 // constant powers of 2.
154 NewCst = getLogBase2Vector(CV);
Jim Grosbach03fceff2013-04-05 21:20:12 +0000155
Rafael Espindola4f3d7ee2013-05-31 14:27:15 +0000156 if (NewCst) {
157 BinaryOperator *Shl = BinaryOperator::CreateShl(NewOp, NewCst);
158 if (I.hasNoSignedWrap()) Shl->setHasNoSignedWrap();
159 if (I.hasNoUnsignedWrap()) Shl->setHasNoUnsignedWrap();
160 return Shl;
161 }
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000162 }
Rafael Espindola4f3d7ee2013-05-31 14:27:15 +0000163 }
Jim Grosbach03fceff2013-04-05 21:20:12 +0000164
Rafael Espindola4f3d7ee2013-05-31 14:27:15 +0000165 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Stuart Hastingsf1002822011-06-01 16:42:47 +0000166 // (Y - X) * (-(2**n)) -> (X - Y) * (2**n), for positive nonzero n
167 // (Y + const) * (-(2**n)) -> (-constY) * (2**n), for positive nonzero n
168 // The "* (2**n)" thus becomes a potential shifting opportunity.
Stuart Hastingsacbf1072011-05-30 20:00:33 +0000169 {
170 const APInt & Val = CI->getValue();
171 const APInt &PosVal = Val.abs();
172 if (Val.isNegative() && PosVal.isPowerOf2()) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700173 Value *X = nullptr, *Y = nullptr;
Stuart Hastingsf1002822011-06-01 16:42:47 +0000174 if (Op0->hasOneUse()) {
175 ConstantInt *C1;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700176 Value *Sub = nullptr;
Stuart Hastingsf1002822011-06-01 16:42:47 +0000177 if (match(Op0, m_Sub(m_Value(Y), m_Value(X))))
178 Sub = Builder->CreateSub(X, Y, "suba");
179 else if (match(Op0, m_Add(m_Value(Y), m_ConstantInt(C1))))
180 Sub = Builder->CreateSub(Builder->CreateNeg(C1), Y, "subc");
181 if (Sub)
182 return
183 BinaryOperator::CreateMul(Sub,
184 ConstantInt::get(Y->getType(), PosVal));
Stuart Hastingsacbf1072011-05-30 20:00:33 +0000185 }
186 }
187 }
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000188 }
Jim Grosbach03fceff2013-04-05 21:20:12 +0000189
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000190 // Simplify mul instructions with a constant RHS.
Jim Grosbach03fceff2013-04-05 21:20:12 +0000191 if (isa<Constant>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000192 // Try to fold constant mul into select arguments.
193 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
194 if (Instruction *R = FoldOpIntoSelect(I, SI))
195 return R;
196
197 if (isa<PHINode>(Op0))
198 if (Instruction *NV = FoldOpIntoPhi(I))
199 return NV;
Stephen Hines36b56882014-04-23 16:57:46 -0700200
201 // Canonicalize (X+C1)*CI -> X*CI+C1*CI.
202 {
203 Value *X;
204 Constant *C1;
205 if (match(Op0, m_OneUse(m_Add(m_Value(X), m_Constant(C1))))) {
206 Value *Add = Builder->CreateMul(X, Op1);
207 return BinaryOperator::CreateAdd(Add, Builder->CreateMul(C1, Op1));
208 }
209 }
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000210 }
211
212 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
213 if (Value *Op1v = dyn_castNegVal(Op1))
214 return BinaryOperator::CreateMul(Op0v, Op1v);
215
216 // (X / Y) * Y = X - (X % Y)
217 // (X / Y) * -Y = (X % Y) - X
218 {
219 Value *Op1C = Op1;
220 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
221 if (!BO ||
Jim Grosbach03fceff2013-04-05 21:20:12 +0000222 (BO->getOpcode() != Instruction::UDiv &&
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000223 BO->getOpcode() != Instruction::SDiv)) {
224 Op1C = Op0;
225 BO = dyn_cast<BinaryOperator>(Op1);
226 }
227 Value *Neg = dyn_castNegVal(Op1C);
228 if (BO && BO->hasOneUse() &&
229 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
230 (BO->getOpcode() == Instruction::UDiv ||
231 BO->getOpcode() == Instruction::SDiv)) {
232 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
233
Chris Lattner35bda892011-02-06 21:44:57 +0000234 // If the division is exact, X % Y is zero, so we end up with X or -X.
235 if (PossiblyExactOperator *SDiv = dyn_cast<PossiblyExactOperator>(BO))
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000236 if (SDiv->isExact()) {
237 if (Op1BO == Op1C)
238 return ReplaceInstUsesWith(I, Op0BO);
239 return BinaryOperator::CreateNeg(Op0BO);
240 }
241
242 Value *Rem;
243 if (BO->getOpcode() == Instruction::UDiv)
244 Rem = Builder->CreateURem(Op0BO, Op1BO);
245 else
246 Rem = Builder->CreateSRem(Op0BO, Op1BO);
247 Rem->takeName(BO);
248
249 if (Op1BO == Op1C)
250 return BinaryOperator::CreateSub(Op0BO, Rem);
251 return BinaryOperator::CreateSub(Rem, Op0BO);
252 }
253 }
254
255 /// i1 mul -> i1 and.
Stephen Hines36b56882014-04-23 16:57:46 -0700256 if (I.getType()->getScalarType()->isIntegerTy(1))
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000257 return BinaryOperator::CreateAnd(Op0, Op1);
258
259 // X*(1 << Y) --> X << Y
260 // (1 << Y)*X --> X << Y
261 {
262 Value *Y;
263 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
264 return BinaryOperator::CreateShl(Op1, Y);
265 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
266 return BinaryOperator::CreateShl(Op0, Y);
267 }
Jim Grosbach03fceff2013-04-05 21:20:12 +0000268
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000269 // If one of the operands of the multiply is a cast from a boolean value, then
270 // we know the bool is either zero or one, so this is a 'masking' multiply.
271 // X * Y (where Y is 0 or 1) -> X & (0-Y)
Duncan Sands1df98592010-02-16 11:11:14 +0000272 if (!I.getType()->isVectorTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000273 // -2 is "-1 << 1" so it is all bits set except the low one.
274 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Jim Grosbach03fceff2013-04-05 21:20:12 +0000275
Stephen Hinesdce4a402014-05-29 02:49:00 -0700276 Value *BoolCast = nullptr, *OtherOp = nullptr;
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000277 if (MaskedValueIsZero(Op0, Negative2))
278 BoolCast = Op0, OtherOp = Op1;
279 else if (MaskedValueIsZero(Op1, Negative2))
280 BoolCast = Op1, OtherOp = Op0;
281
282 if (BoolCast) {
283 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
Benjamin Kramera9390a42011-09-27 20:39:19 +0000284 BoolCast);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000285 return BinaryOperator::CreateAnd(V, OtherOp);
286 }
287 }
288
Stephen Hinesdce4a402014-05-29 02:49:00 -0700289 return Changed ? &I : nullptr;
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000290}
291
Pedro Artigasc2a08d22012-11-30 22:07:05 +0000292//
293// Detect pattern:
294//
295// log2(Y*0.5)
296//
297// And check for corresponding fast math flags
298//
299
300static void detectLog2OfHalf(Value *&Op, Value *&Y, IntrinsicInst *&Log2) {
Pedro Artigasef2ef3e2012-11-30 22:47:15 +0000301
302 if (!Op->hasOneUse())
303 return;
304
305 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op);
306 if (!II)
307 return;
308 if (II->getIntrinsicID() != Intrinsic::log2 || !II->hasUnsafeAlgebra())
309 return;
310 Log2 = II;
311
312 Value *OpLog2Of = II->getArgOperand(0);
313 if (!OpLog2Of->hasOneUse())
314 return;
315
316 Instruction *I = dyn_cast<Instruction>(OpLog2Of);
317 if (!I)
318 return;
319 if (I->getOpcode() != Instruction::FMul || !I->hasUnsafeAlgebra())
320 return;
Jim Grosbach03fceff2013-04-05 21:20:12 +0000321
Stephen Hines36b56882014-04-23 16:57:46 -0700322 if (match(I->getOperand(0), m_SpecificFP(0.5)))
Pedro Artigasef2ef3e2012-11-30 22:47:15 +0000323 Y = I->getOperand(1);
Stephen Hines36b56882014-04-23 16:57:46 -0700324 else if (match(I->getOperand(1), m_SpecificFP(0.5)))
Pedro Artigasef2ef3e2012-11-30 22:47:15 +0000325 Y = I->getOperand(0);
Jim Grosbach03fceff2013-04-05 21:20:12 +0000326}
Pedro Artigasc2a08d22012-11-30 22:07:05 +0000327
Stephen Hines36b56882014-04-23 16:57:46 -0700328static bool isFiniteNonZeroFp(Constant *C) {
329 if (C->getType()->isVectorTy()) {
330 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
331 ++I) {
332 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
333 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
334 return false;
335 }
336 return true;
337 }
338
339 return isa<ConstantFP>(C) &&
340 cast<ConstantFP>(C)->getValueAPF().isFiniteNonZero();
341}
342
343static bool isNormalFp(Constant *C) {
344 if (C->getType()->isVectorTy()) {
345 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E;
346 ++I) {
347 ConstantFP *CFP = dyn_cast<ConstantFP>(C->getAggregateElement(I));
348 if (!CFP || !CFP->getValueAPF().isNormal())
349 return false;
350 }
351 return true;
352 }
353
354 return isa<ConstantFP>(C) && cast<ConstantFP>(C)->getValueAPF().isNormal();
355}
356
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000357/// Helper function of InstCombiner::visitFMul(BinaryOperator(). It returns
358/// true iff the given value is FMul or FDiv with one and only one operand
359/// being a normal constant (i.e. not Zero/NaN/Infinity).
360static bool isFMulOrFDivWithConstant(Value *V) {
361 Instruction *I = dyn_cast<Instruction>(V);
Jim Grosbach03fceff2013-04-05 21:20:12 +0000362 if (!I || (I->getOpcode() != Instruction::FMul &&
Shuxin Yangf2797312013-01-07 22:41:28 +0000363 I->getOpcode() != Instruction::FDiv))
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000364 return false;
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000365
Stephen Hines36b56882014-04-23 16:57:46 -0700366 Constant *C0 = dyn_cast<Constant>(I->getOperand(0));
367 Constant *C1 = dyn_cast<Constant>(I->getOperand(1));
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000368
369 if (C0 && C1)
370 return false;
371
Stephen Hines36b56882014-04-23 16:57:46 -0700372 return (C0 && isFiniteNonZeroFp(C0)) || (C1 && isFiniteNonZeroFp(C1));
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000373}
374
375/// foldFMulConst() is a helper routine of InstCombiner::visitFMul().
376/// The input \p FMulOrDiv is a FMul/FDiv with one and only one operand
377/// being a constant (i.e. isFMulOrFDivWithConstant(FMulOrDiv) == true).
Jim Grosbach03fceff2013-04-05 21:20:12 +0000378/// This function is to simplify "FMulOrDiv * C" and returns the
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000379/// resulting expression. Note that this function could return NULL in
380/// case the constants cannot be folded into a normal floating-point.
Jim Grosbach03fceff2013-04-05 21:20:12 +0000381///
Stephen Hines36b56882014-04-23 16:57:46 -0700382Value *InstCombiner::foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yangf2797312013-01-07 22:41:28 +0000383 Instruction *InsertBefore) {
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000384 assert(isFMulOrFDivWithConstant(FMulOrDiv) && "V is invalid");
385
386 Value *Opnd0 = FMulOrDiv->getOperand(0);
387 Value *Opnd1 = FMulOrDiv->getOperand(1);
388
Stephen Hines36b56882014-04-23 16:57:46 -0700389 Constant *C0 = dyn_cast<Constant>(Opnd0);
390 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000391
Stephen Hinesdce4a402014-05-29 02:49:00 -0700392 BinaryOperator *R = nullptr;
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000393
394 // (X * C0) * C => X * (C0*C)
395 if (FMulOrDiv->getOpcode() == Instruction::FMul) {
396 Constant *F = ConstantExpr::getFMul(C1 ? C1 : C0, C);
Stephen Hines36b56882014-04-23 16:57:46 -0700397 if (isNormalFp(F))
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000398 R = BinaryOperator::CreateFMul(C1 ? Opnd0 : Opnd1, F);
399 } else {
400 if (C0) {
401 // (C0 / X) * C => (C0 * C) / X
Shuxin Yangb1ccfb32013-09-19 21:13:46 +0000402 if (FMulOrDiv->hasOneUse()) {
403 // It would otherwise introduce another div.
Stephen Hines36b56882014-04-23 16:57:46 -0700404 Constant *F = ConstantExpr::getFMul(C0, C);
Shuxin Yangb1ccfb32013-09-19 21:13:46 +0000405 if (isNormalFp(F))
406 R = BinaryOperator::CreateFDiv(F, Opnd1);
407 }
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000408 } else {
409 // (X / C1) * C => X * (C/C1) if C/C1 is not a denormal
Stephen Hines36b56882014-04-23 16:57:46 -0700410 Constant *F = ConstantExpr::getFDiv(C, C1);
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000411 if (isNormalFp(F)) {
412 R = BinaryOperator::CreateFMul(Opnd0, F);
413 } else {
Jim Grosbach03fceff2013-04-05 21:20:12 +0000414 // (X / C1) * C => X / (C1/C)
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000415 Constant *F = ConstantExpr::getFDiv(C1, C);
Stephen Hines36b56882014-04-23 16:57:46 -0700416 if (isNormalFp(F))
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000417 R = BinaryOperator::CreateFDiv(Opnd0, F);
418 }
419 }
420 }
421
422 if (R) {
423 R->setHasUnsafeAlgebra(true);
424 InsertNewInstWith(R, *InsertBefore);
425 }
426
427 return R;
428}
429
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000430Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
Duncan Sands096aa792010-11-13 15:10:37 +0000431 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000432 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
433
Stephen Hinesdce4a402014-05-29 02:49:00 -0700434 if (Value *V = SimplifyVectorOp(I))
435 return ReplaceInstUsesWith(I, V);
436
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000437 if (isa<Constant>(Op0))
438 std::swap(Op0, Op1);
439
Stephen Hines36b56882014-04-23 16:57:46 -0700440 if (Value *V = SimplifyFMulInst(Op0, Op1, I.getFastMathFlags(), DL))
Michael Ilsemanc244f382012-12-12 00:28:32 +0000441 return ReplaceInstUsesWith(I, V);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000442
Shuxin Yanga1444212013-01-15 21:09:32 +0000443 bool AllowReassociate = I.hasUnsafeAlgebra();
444
Michael Ilsemanc244f382012-12-12 00:28:32 +0000445 // Simplify mul instructions with a constant RHS.
446 if (isa<Constant>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000447 // Try to fold constant mul into select arguments.
448 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
449 if (Instruction *R = FoldOpIntoSelect(I, SI))
450 return R;
451
452 if (isa<PHINode>(Op0))
453 if (Instruction *NV = FoldOpIntoPhi(I))
454 return NV;
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000455
Stephen Hines36b56882014-04-23 16:57:46 -0700456 // (fmul X, -1.0) --> (fsub -0.0, X)
457 if (match(Op1, m_SpecificFP(-1.0))) {
458 Constant *NegZero = ConstantFP::getNegativeZero(Op1->getType());
459 Instruction *RI = BinaryOperator::CreateFSub(NegZero, Op0);
460 RI->copyFastMathFlags(&I);
461 return RI;
462 }
463
464 Constant *C = cast<Constant>(Op1);
465 if (AllowReassociate && isFiniteNonZeroFp(C)) {
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000466 // Let MDC denote an expression in one of these forms:
467 // X * C, C/X, X/C, where C is a constant.
468 //
469 // Try to simplify "MDC * Constant"
Stephen Hines36b56882014-04-23 16:57:46 -0700470 if (isFMulOrFDivWithConstant(Op0))
471 if (Value *V = foldFMulConst(cast<Instruction>(Op0), C, &I))
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000472 return ReplaceInstUsesWith(I, V);
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000473
Quentin Colombetc5a4c252013-02-28 21:12:40 +0000474 // (MDC +/- C1) * C => (MDC * C) +/- (C1 * C)
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000475 Instruction *FAddSub = dyn_cast<Instruction>(Op0);
476 if (FAddSub &&
477 (FAddSub->getOpcode() == Instruction::FAdd ||
478 FAddSub->getOpcode() == Instruction::FSub)) {
479 Value *Opnd0 = FAddSub->getOperand(0);
480 Value *Opnd1 = FAddSub->getOperand(1);
Stephen Hines36b56882014-04-23 16:57:46 -0700481 Constant *C0 = dyn_cast<Constant>(Opnd0);
482 Constant *C1 = dyn_cast<Constant>(Opnd1);
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000483 bool Swap = false;
484 if (C0) {
Shuxin Yangf2797312013-01-07 22:41:28 +0000485 std::swap(C0, C1);
486 std::swap(Opnd0, Opnd1);
Jim Grosbach03fceff2013-04-05 21:20:12 +0000487 Swap = true;
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000488 }
489
Stephen Hines36b56882014-04-23 16:57:46 -0700490 if (C1 && isFiniteNonZeroFp(C1) && isFMulOrFDivWithConstant(Opnd0)) {
Quentin Colombetc5a4c252013-02-28 21:12:40 +0000491 Value *M1 = ConstantExpr::getFMul(C1, C);
Stephen Hines36b56882014-04-23 16:57:46 -0700492 Value *M0 = isNormalFp(cast<Constant>(M1)) ?
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000493 foldFMulConst(cast<Instruction>(Opnd0), C, &I) :
Stephen Hinesdce4a402014-05-29 02:49:00 -0700494 nullptr;
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000495 if (M0 && M1) {
496 if (Swap && FAddSub->getOpcode() == Instruction::FSub)
497 std::swap(M0, M1);
498
Benjamin Kramer6dc5c6b2013-09-30 15:39:59 +0000499 Instruction *RI = (FAddSub->getOpcode() == Instruction::FAdd)
500 ? BinaryOperator::CreateFAdd(M0, M1)
501 : BinaryOperator::CreateFSub(M0, M1);
Shuxin Yanga1444212013-01-15 21:09:32 +0000502 RI->copyFastMathFlags(&I);
Shuxin Yangd3ae2862013-01-07 21:39:23 +0000503 return RI;
504 }
505 }
506 }
507 }
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000508 }
509
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000510
Pedro Artigas84030dc2012-11-30 19:09:41 +0000511 // Under unsafe algebra do:
512 // X * log2(0.5*Y) = X*log2(Y) - X
513 if (I.hasUnsafeAlgebra()) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700514 Value *OpX = nullptr;
515 Value *OpY = nullptr;
Pedro Artigas84030dc2012-11-30 19:09:41 +0000516 IntrinsicInst *Log2;
Pedro Artigasc2a08d22012-11-30 22:07:05 +0000517 detectLog2OfHalf(Op0, OpY, Log2);
518 if (OpY) {
519 OpX = Op1;
520 } else {
521 detectLog2OfHalf(Op1, OpY, Log2);
522 if (OpY) {
523 OpX = Op0;
Pedro Artigas84030dc2012-11-30 19:09:41 +0000524 }
525 }
526 // if pattern detected emit alternate sequence
527 if (OpX && OpY) {
Benjamin Kramer6dc5c6b2013-09-30 15:39:59 +0000528 BuilderTy::FastMathFlagGuard Guard(*Builder);
529 Builder->SetFastMathFlags(Log2->getFastMathFlags());
Pedro Artigas84030dc2012-11-30 19:09:41 +0000530 Log2->setArgOperand(0, OpY);
531 Value *FMulVal = Builder->CreateFMul(OpX, Log2);
Benjamin Kramer6dc5c6b2013-09-30 15:39:59 +0000532 Value *FSub = Builder->CreateFSub(FMulVal, OpX);
533 FSub->takeName(&I);
534 return ReplaceInstUsesWith(I, FSub);
Pedro Artigas84030dc2012-11-30 19:09:41 +0000535 }
536 }
537
Shuxin Yanga1444212013-01-15 21:09:32 +0000538 // Handle symmetric situation in a 2-iteration loop
539 Value *Opnd0 = Op0;
540 Value *Opnd1 = Op1;
541 for (int i = 0; i < 2; i++) {
542 bool IgnoreZeroSign = I.hasNoSignedZeros();
543 if (BinaryOperator::isFNeg(Opnd0, IgnoreZeroSign)) {
Benjamin Kramer6dc5c6b2013-09-30 15:39:59 +0000544 BuilderTy::FastMathFlagGuard Guard(*Builder);
545 Builder->SetFastMathFlags(I.getFastMathFlags());
546
Shuxin Yanga1444212013-01-15 21:09:32 +0000547 Value *N0 = dyn_castFNegVal(Opnd0, IgnoreZeroSign);
548 Value *N1 = dyn_castFNegVal(Opnd1, IgnoreZeroSign);
Shuxin Yanga5ed0312012-12-14 18:46:06 +0000549
Shuxin Yanga1444212013-01-15 21:09:32 +0000550 // -X * -Y => X*Y
Stephen Hines36b56882014-04-23 16:57:46 -0700551 if (N1) {
552 Value *FMul = Builder->CreateFMul(N0, N1);
553 FMul->takeName(&I);
554 return ReplaceInstUsesWith(I, FMul);
555 }
Shuxin Yanga5ed0312012-12-14 18:46:06 +0000556
Shuxin Yanga1444212013-01-15 21:09:32 +0000557 if (Opnd0->hasOneUse()) {
558 // -X * Y => -(X*Y) (Promote negation as high as possible)
559 Value *T = Builder->CreateFMul(N0, Opnd1);
Benjamin Kramer6dc5c6b2013-09-30 15:39:59 +0000560 Value *Neg = Builder->CreateFNeg(T);
561 Neg->takeName(&I);
562 return ReplaceInstUsesWith(I, Neg);
Shuxin Yanga5ed0312012-12-14 18:46:06 +0000563 }
564 }
Shuxin Yanga1444212013-01-15 21:09:32 +0000565
566 // (X*Y) * X => (X*X) * Y where Y != X
Jim Grosbach03fceff2013-04-05 21:20:12 +0000567 // The purpose is two-fold:
Shuxin Yanga1444212013-01-15 21:09:32 +0000568 // 1) to form a power expression (of X).
569 // 2) potentially shorten the critical path: After transformation, the
570 // latency of the instruction Y is amortized by the expression of X*X,
571 // and therefore Y is in a "less critical" position compared to what it
572 // was before the transformation.
573 //
574 if (AllowReassociate) {
575 Value *Opnd0_0, *Opnd0_1;
576 if (Opnd0->hasOneUse() &&
577 match(Opnd0, m_FMul(m_Value(Opnd0_0), m_Value(Opnd0_1)))) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700578 Value *Y = nullptr;
Shuxin Yanga1444212013-01-15 21:09:32 +0000579 if (Opnd0_0 == Opnd1 && Opnd0_1 != Opnd1)
580 Y = Opnd0_1;
581 else if (Opnd0_1 == Opnd1 && Opnd0_0 != Opnd1)
582 Y = Opnd0_0;
583
584 if (Y) {
Benjamin Kramer6dc5c6b2013-09-30 15:39:59 +0000585 BuilderTy::FastMathFlagGuard Guard(*Builder);
586 Builder->SetFastMathFlags(I.getFastMathFlags());
587 Value *T = Builder->CreateFMul(Opnd1, Opnd1);
Shuxin Yanga1444212013-01-15 21:09:32 +0000588
Benjamin Kramer6dc5c6b2013-09-30 15:39:59 +0000589 Value *R = Builder->CreateFMul(T, Y);
590 R->takeName(&I);
591 return ReplaceInstUsesWith(I, R);
Shuxin Yanga1444212013-01-15 21:09:32 +0000592 }
593 }
594 }
595
Stephen Lin54bf58a2013-07-17 20:06:03 +0000596 // B * (uitofp i1 C) -> select C, B, 0
597 if (I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) {
598 Value *LHS = Op0, *RHS = Op1;
599 Value *B, *C;
Stephen Lin3b6bb792013-07-26 17:55:00 +0000600 if (!match(RHS, m_UIToFP(m_Value(C))))
Stephen Lin54bf58a2013-07-17 20:06:03 +0000601 std::swap(LHS, RHS);
602
Stephen Hines36b56882014-04-23 16:57:46 -0700603 if (match(RHS, m_UIToFP(m_Value(C))) &&
604 C->getType()->getScalarType()->isIntegerTy(1)) {
Stephen Lin54bf58a2013-07-17 20:06:03 +0000605 B = LHS;
606 Value *Zero = ConstantFP::getNegativeZero(B->getType());
607 return SelectInst::Create(C, B, Zero);
608 }
609 }
610
611 // A * (1 - uitofp i1 C) -> select C, 0, A
612 if (I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) {
613 Value *LHS = Op0, *RHS = Op1;
614 Value *A, *C;
Stephen Lin3b6bb792013-07-26 17:55:00 +0000615 if (!match(RHS, m_FSub(m_FPOne(), m_UIToFP(m_Value(C)))))
Stephen Lin54bf58a2013-07-17 20:06:03 +0000616 std::swap(LHS, RHS);
617
Stephen Lin3b6bb792013-07-26 17:55:00 +0000618 if (match(RHS, m_FSub(m_FPOne(), m_UIToFP(m_Value(C)))) &&
Stephen Hines36b56882014-04-23 16:57:46 -0700619 C->getType()->getScalarType()->isIntegerTy(1)) {
Stephen Lin54bf58a2013-07-17 20:06:03 +0000620 A = LHS;
621 Value *Zero = ConstantFP::getNegativeZero(A->getType());
622 return SelectInst::Create(C, Zero, A);
623 }
624 }
625
Shuxin Yanga1444212013-01-15 21:09:32 +0000626 if (!isa<Constant>(Op1))
627 std::swap(Opnd0, Opnd1);
628 else
629 break;
Shuxin Yanga5ed0312012-12-14 18:46:06 +0000630 }
631
Stephen Hinesdce4a402014-05-29 02:49:00 -0700632 return Changed ? &I : nullptr;
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000633}
634
635/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
636/// instruction.
637bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
638 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
Jim Grosbach03fceff2013-04-05 21:20:12 +0000639
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000640 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
641 int NonNullOperand = -1;
642 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
643 if (ST->isNullValue())
644 NonNullOperand = 2;
645 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
646 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
647 if (ST->isNullValue())
648 NonNullOperand = 1;
Jim Grosbach03fceff2013-04-05 21:20:12 +0000649
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000650 if (NonNullOperand == -1)
651 return false;
Jim Grosbach03fceff2013-04-05 21:20:12 +0000652
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000653 Value *SelectCond = SI->getOperand(0);
Jim Grosbach03fceff2013-04-05 21:20:12 +0000654
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000655 // Change the div/rem to use 'Y' instead of the select.
656 I.setOperand(1, SI->getOperand(NonNullOperand));
Jim Grosbach03fceff2013-04-05 21:20:12 +0000657
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000658 // Okay, we know we replace the operand of the div/rem with 'Y' with no
659 // problem. However, the select, or the condition of the select may have
660 // multiple uses. Based on our knowledge that the operand must be non-zero,
661 // propagate the known value for the select into other uses of it, and
662 // propagate a known value of the condition into its other users.
Jim Grosbach03fceff2013-04-05 21:20:12 +0000663
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000664 // If the select and condition only have a single use, don't bother with this,
665 // early exit.
666 if (SI->use_empty() && SelectCond->hasOneUse())
667 return true;
Jim Grosbach03fceff2013-04-05 21:20:12 +0000668
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000669 // Scan the current block backward, looking for other uses of SI.
670 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
Jim Grosbach03fceff2013-04-05 21:20:12 +0000671
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000672 while (BBI != BBFront) {
673 --BBI;
674 // If we found a call to a function, we can't assume it will return, so
675 // information from below it cannot be propagated above it.
676 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
677 break;
Jim Grosbach03fceff2013-04-05 21:20:12 +0000678
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000679 // Replace uses of the select or its condition with the known values.
680 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
681 I != E; ++I) {
682 if (*I == SI) {
683 *I = SI->getOperand(NonNullOperand);
684 Worklist.Add(BBI);
685 } else if (*I == SelectCond) {
Jakub Staszak6a72c842013-06-06 23:34:59 +0000686 *I = Builder->getInt1(NonNullOperand == 1);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000687 Worklist.Add(BBI);
688 }
689 }
Jim Grosbach03fceff2013-04-05 21:20:12 +0000690
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000691 // If we past the instruction, quit looking for it.
692 if (&*BBI == SI)
Stephen Hinesdce4a402014-05-29 02:49:00 -0700693 SI = nullptr;
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000694 if (&*BBI == SelectCond)
Stephen Hinesdce4a402014-05-29 02:49:00 -0700695 SelectCond = nullptr;
Jim Grosbach03fceff2013-04-05 21:20:12 +0000696
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000697 // If we ran out of things to eliminate, break out of the loop.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700698 if (!SelectCond && !SI)
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000699 break;
Jim Grosbach03fceff2013-04-05 21:20:12 +0000700
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000701 }
702 return true;
703}
704
705
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000706/// This function implements the transforms common to both integer division
707/// instructions (udiv and sdiv). It is called by the visitors to those integer
708/// division instructions.
709/// @brief Common integer divide transforms
710Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
711 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
712
Chris Lattner1add46d2011-05-22 18:18:41 +0000713 // The RHS is known non-zero.
714 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
715 I.setOperand(1, V);
716 return &I;
717 }
Jim Grosbach03fceff2013-04-05 21:20:12 +0000718
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000719 // Handle cases involving: [su]div X, (select Cond, Y, Z)
720 // This does not apply for fdiv.
721 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
722 return &I;
723
724 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000725 // (X / C1) / C2 -> X / (C1*C2)
726 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
727 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
728 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
729 if (MultiplyOverflows(RHS, LHSRHS,
Stephen Hinesdce4a402014-05-29 02:49:00 -0700730 I.getOpcode() == Instruction::SDiv))
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000731 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000732 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
733 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000734 }
735
736 if (!RHS->isZero()) { // avoid X udiv 0
737 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
738 if (Instruction *R = FoldOpIntoSelect(I, SI))
739 return R;
740 if (isa<PHINode>(Op0))
741 if (Instruction *NV = FoldOpIntoPhi(I))
742 return NV;
743 }
744 }
745
Stephen Hinesdce4a402014-05-29 02:49:00 -0700746 if (ConstantInt *One = dyn_cast<ConstantInt>(Op0)) {
747 if (One->isOne() && !I.getType()->isIntegerTy(1)) {
748 bool isSigned = I.getOpcode() == Instruction::SDiv;
749 if (isSigned) {
750 // If Op1 is 0 then it's undefined behaviour, if Op1 is 1 then the
751 // result is one, if Op1 is -1 then the result is minus one, otherwise
752 // it's zero.
753 Value *Inc = Builder->CreateAdd(Op1, One);
754 Value *Cmp = Builder->CreateICmpULT(
755 Inc, ConstantInt::get(I.getType(), 3));
756 return SelectInst::Create(Cmp, Op1, ConstantInt::get(I.getType(), 0));
757 } else {
758 // If Op1 is 0 then it's undefined behaviour. If Op1 is 1 then the
759 // result is one, otherwise it's zero.
760 return new ZExtInst(Builder->CreateICmpEQ(Op1, One), I.getType());
761 }
762 }
763 }
764
Benjamin Kramer23b02cd2011-04-30 18:16:00 +0000765 // See if we can fold away this div instruction.
766 if (SimplifyDemandedInstructionBits(I))
767 return &I;
768
Duncan Sands593faa52011-01-28 16:51:11 +0000769 // (X - (X rem Y)) / Y -> X / Y; usually originates as ((X / Y) * Y) / Y
Stephen Hinesdce4a402014-05-29 02:49:00 -0700770 Value *X = nullptr, *Z = nullptr;
Duncan Sands593faa52011-01-28 16:51:11 +0000771 if (match(Op0, m_Sub(m_Value(X), m_Value(Z)))) { // (X - Z) / Y; Y = Op1
772 bool isSigned = I.getOpcode() == Instruction::SDiv;
773 if ((isSigned && match(Z, m_SRem(m_Specific(X), m_Specific(Op1)))) ||
774 (!isSigned && match(Z, m_URem(m_Specific(X), m_Specific(Op1)))))
775 return BinaryOperator::Create(I.getOpcode(), X, Op1);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000776 }
777
Stephen Hinesdce4a402014-05-29 02:49:00 -0700778 return nullptr;
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000779}
780
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +0000781/// dyn_castZExtVal - Checks if V is a zext or constant that can
782/// be truncated to Ty without losing bits.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000783static Value *dyn_castZExtVal(Value *V, Type *Ty) {
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +0000784 if (ZExtInst *Z = dyn_cast<ZExtInst>(V)) {
785 if (Z->getSrcTy() == Ty)
786 return Z->getOperand(0);
787 } else if (ConstantInt *C = dyn_cast<ConstantInt>(V)) {
788 if (C->getValue().getActiveBits() <= cast<IntegerType>(Ty)->getBitWidth())
789 return ConstantExpr::getTrunc(C, Ty);
790 }
Stephen Hinesdce4a402014-05-29 02:49:00 -0700791 return nullptr;
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +0000792}
793
David Majnemere7006bb2013-07-04 21:17:49 +0000794namespace {
795const unsigned MaxDepth = 6;
796typedef Instruction *(*FoldUDivOperandCb)(Value *Op0, Value *Op1,
797 const BinaryOperator &I,
798 InstCombiner &IC);
799
800/// \brief Used to maintain state for visitUDivOperand().
801struct UDivFoldAction {
802 FoldUDivOperandCb FoldAction; ///< Informs visitUDiv() how to fold this
803 ///< operand. This can be zero if this action
804 ///< joins two actions together.
805
806 Value *OperandToFold; ///< Which operand to fold.
807 union {
808 Instruction *FoldResult; ///< The instruction returned when FoldAction is
809 ///< invoked.
810
811 size_t SelectLHSIdx; ///< Stores the LHS action index if this action
812 ///< joins two actions together.
813 };
814
815 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand)
Stephen Hinesdce4a402014-05-29 02:49:00 -0700816 : FoldAction(FA), OperandToFold(InputOperand), FoldResult(nullptr) {}
David Majnemere7006bb2013-07-04 21:17:49 +0000817 UDivFoldAction(FoldUDivOperandCb FA, Value *InputOperand, size_t SLHS)
818 : FoldAction(FA), OperandToFold(InputOperand), SelectLHSIdx(SLHS) {}
819};
820}
821
822// X udiv 2^C -> X >> C
823static Instruction *foldUDivPow2Cst(Value *Op0, Value *Op1,
824 const BinaryOperator &I, InstCombiner &IC) {
825 const APInt &C = cast<Constant>(Op1)->getUniqueInteger();
826 BinaryOperator *LShr = BinaryOperator::CreateLShr(
827 Op0, ConstantInt::get(Op0->getType(), C.logBase2()));
828 if (I.isExact()) LShr->setIsExact();
829 return LShr;
830}
831
832// X udiv C, where C >= signbit
833static Instruction *foldUDivNegCst(Value *Op0, Value *Op1,
834 const BinaryOperator &I, InstCombiner &IC) {
835 Value *ICI = IC.Builder->CreateICmpULT(Op0, cast<ConstantInt>(Op1));
836
837 return SelectInst::Create(ICI, Constant::getNullValue(I.getType()),
838 ConstantInt::get(I.getType(), 1));
839}
840
841// X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
842static Instruction *foldUDivShl(Value *Op0, Value *Op1, const BinaryOperator &I,
843 InstCombiner &IC) {
844 Instruction *ShiftLeft = cast<Instruction>(Op1);
845 if (isa<ZExtInst>(ShiftLeft))
846 ShiftLeft = cast<Instruction>(ShiftLeft->getOperand(0));
847
848 const APInt &CI =
849 cast<Constant>(ShiftLeft->getOperand(0))->getUniqueInteger();
850 Value *N = ShiftLeft->getOperand(1);
851 if (CI != 1)
852 N = IC.Builder->CreateAdd(N, ConstantInt::get(N->getType(), CI.logBase2()));
853 if (ZExtInst *Z = dyn_cast<ZExtInst>(Op1))
854 N = IC.Builder->CreateZExt(N, Z->getDestTy());
855 BinaryOperator *LShr = BinaryOperator::CreateLShr(Op0, N);
856 if (I.isExact()) LShr->setIsExact();
857 return LShr;
858}
859
860// \brief Recursively visits the possible right hand operands of a udiv
861// instruction, seeing through select instructions, to determine if we can
862// replace the udiv with something simpler. If we find that an operand is not
863// able to simplify the udiv, we abort the entire transformation.
864static size_t visitUDivOperand(Value *Op0, Value *Op1, const BinaryOperator &I,
865 SmallVectorImpl<UDivFoldAction> &Actions,
866 unsigned Depth = 0) {
867 // Check to see if this is an unsigned division with an exact power of 2,
868 // if so, convert to a right shift.
869 if (match(Op1, m_Power2())) {
870 Actions.push_back(UDivFoldAction(foldUDivPow2Cst, Op1));
871 return Actions.size();
872 }
873
874 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1))
875 // X udiv C, where C >= signbit
876 if (C->getValue().isNegative()) {
877 Actions.push_back(UDivFoldAction(foldUDivNegCst, C));
878 return Actions.size();
879 }
880
881 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
882 if (match(Op1, m_Shl(m_Power2(), m_Value())) ||
883 match(Op1, m_ZExt(m_Shl(m_Power2(), m_Value())))) {
884 Actions.push_back(UDivFoldAction(foldUDivShl, Op1));
885 return Actions.size();
886 }
887
888 // The remaining tests are all recursive, so bail out if we hit the limit.
889 if (Depth++ == MaxDepth)
890 return 0;
891
892 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
893 if (size_t LHSIdx = visitUDivOperand(Op0, SI->getOperand(1), I, Actions))
894 if (visitUDivOperand(Op0, SI->getOperand(2), I, Actions)) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700895 Actions.push_back(UDivFoldAction((FoldUDivOperandCb)nullptr, Op1,
896 LHSIdx-1));
David Majnemere7006bb2013-07-04 21:17:49 +0000897 return Actions.size();
898 }
899
900 return 0;
901}
902
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000903Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
904 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
905
Stephen Hinesdce4a402014-05-29 02:49:00 -0700906 if (Value *V = SimplifyVectorOp(I))
907 return ReplaceInstUsesWith(I, V);
908
Stephen Hines36b56882014-04-23 16:57:46 -0700909 if (Value *V = SimplifyUDivInst(Op0, Op1, DL))
Duncan Sands593faa52011-01-28 16:51:11 +0000910 return ReplaceInstUsesWith(I, V);
911
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000912 // Handle the integer div common cases
913 if (Instruction *Common = commonIDivTransforms(I))
914 return Common;
Jim Grosbach03fceff2013-04-05 21:20:12 +0000915
Benjamin Kramerc81fe9c2012-08-30 15:07:40 +0000916 // (x lshr C1) udiv C2 --> x udiv (C2 << C1)
Stephen Hines36b56882014-04-23 16:57:46 -0700917 if (Constant *C2 = dyn_cast<Constant>(Op1)) {
Benjamin Krameraac7c652012-08-28 13:08:13 +0000918 Value *X;
Stephen Hines36b56882014-04-23 16:57:46 -0700919 Constant *C1;
920 if (match(Op0, m_LShr(m_Value(X), m_Constant(C1))))
921 return BinaryOperator::CreateUDiv(X, ConstantExpr::getShl(C2, C1));
Nadav Rotem9753f0b2012-08-28 10:01:43 +0000922 }
923
Benjamin Kramer7d6eb5a2011-04-30 18:16:07 +0000924 // (zext A) udiv (zext B) --> zext (A udiv B)
925 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
926 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
927 return new ZExtInst(Builder->CreateUDiv(ZOp0->getOperand(0), ZOp1, "div",
928 I.isExact()),
929 I.getType());
930
David Majnemere7006bb2013-07-04 21:17:49 +0000931 // (LHS udiv (select (select (...)))) -> (LHS >> (select (select (...))))
932 SmallVector<UDivFoldAction, 6> UDivActions;
933 if (visitUDivOperand(Op0, Op1, I, UDivActions))
934 for (unsigned i = 0, e = UDivActions.size(); i != e; ++i) {
935 FoldUDivOperandCb Action = UDivActions[i].FoldAction;
936 Value *ActionOp1 = UDivActions[i].OperandToFold;
937 Instruction *Inst;
938 if (Action)
939 Inst = Action(Op0, ActionOp1, I, *this);
940 else {
941 // This action joins two actions together. The RHS of this action is
942 // simply the last action we processed, we saved the LHS action index in
943 // the joining action.
944 size_t SelectRHSIdx = i - 1;
945 Value *SelectRHS = UDivActions[SelectRHSIdx].FoldResult;
946 size_t SelectLHSIdx = UDivActions[i].SelectLHSIdx;
947 Value *SelectLHS = UDivActions[SelectLHSIdx].FoldResult;
948 Inst = SelectInst::Create(cast<SelectInst>(ActionOp1)->getCondition(),
949 SelectLHS, SelectRHS);
950 }
951
952 // If this is the last action to process, return it to the InstCombiner.
953 // Otherwise, we insert it before the UDiv and record it so that we may
954 // use it as part of a joining action (i.e., a SelectInst).
955 if (e - i != 1) {
956 Inst->insertBefore(&I);
957 UDivActions[i].FoldResult = Inst;
958 } else
959 return Inst;
960 }
961
Stephen Hinesdce4a402014-05-29 02:49:00 -0700962 return nullptr;
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000963}
964
965Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
966 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
967
Stephen Hinesdce4a402014-05-29 02:49:00 -0700968 if (Value *V = SimplifyVectorOp(I))
969 return ReplaceInstUsesWith(I, V);
970
Stephen Hines36b56882014-04-23 16:57:46 -0700971 if (Value *V = SimplifySDivInst(Op0, Op1, DL))
Duncan Sands593faa52011-01-28 16:51:11 +0000972 return ReplaceInstUsesWith(I, V);
973
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000974 // Handle the integer div common cases
975 if (Instruction *Common = commonIDivTransforms(I))
976 return Common;
977
Stephen Hines36b56882014-04-23 16:57:46 -0700978 // sdiv X, -1 == -X
979 if (match(Op1, m_AllOnes()))
980 return BinaryOperator::CreateNeg(Op0);
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000981
Stephen Hines36b56882014-04-23 16:57:46 -0700982 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000983 // sdiv X, C --> ashr exact X, log2(C)
984 if (I.isExact() && RHS->getValue().isNonNegative() &&
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000985 RHS->getValue().isPowerOf2()) {
986 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
987 RHS->getValue().exactLogBase2());
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000988 return BinaryOperator::CreateExactAShr(Op0, ShAmt, I.getName());
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000989 }
Stephen Hines36b56882014-04-23 16:57:46 -0700990 }
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000991
Stephen Hines36b56882014-04-23 16:57:46 -0700992 if (Constant *RHS = dyn_cast<Constant>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000993 // -X/C --> X/-C provided the negation doesn't overflow.
994 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
Chris Lattner7a6aa1a2011-02-10 05:36:31 +0000995 if (match(Sub->getOperand(0), m_Zero()) && Sub->hasNoSignedWrap())
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000996 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
997 ConstantExpr::getNeg(RHS));
998 }
999
1000 // If the sign bits of both operands are zero (i.e. we can prove they are
1001 // unsigned inputs), turn this into a udiv.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001002 if (I.getType()->isIntegerTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001003 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1004 if (MaskedValueIsZero(Op0, Mask)) {
1005 if (MaskedValueIsZero(Op1, Mask)) {
Sylvestre Ledru94c22712012-09-27 10:14:43 +00001006 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001007 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1008 }
Jim Grosbach03fceff2013-04-05 21:20:12 +00001009
Chris Lattner7a6aa1a2011-02-10 05:36:31 +00001010 if (match(Op1, m_Shl(m_Power2(), m_Value()))) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001011 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
1012 // Safe because the only negative value (1 << Y) can take on is
1013 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
1014 // the sign bit set.
1015 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
1016 }
1017 }
1018 }
Jim Grosbach03fceff2013-04-05 21:20:12 +00001019
Stephen Hinesdce4a402014-05-29 02:49:00 -07001020 return nullptr;
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001021}
1022
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001023/// CvtFDivConstToReciprocal tries to convert X/C into X*1/C if C not a special
1024/// FP value and:
Jim Grosbach03fceff2013-04-05 21:20:12 +00001025/// 1) 1/C is exact, or
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001026/// 2) reciprocal is allowed.
Sylvestre Ledruda2ed452013-05-14 23:36:24 +00001027/// If the conversion was successful, the simplified expression "X * 1/C" is
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001028/// returned; otherwise, NULL is returned.
1029///
1030static Instruction *CvtFDivConstToReciprocal(Value *Dividend,
Stephen Hines36b56882014-04-23 16:57:46 -07001031 Constant *Divisor,
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001032 bool AllowReciprocal) {
Stephen Hines36b56882014-04-23 16:57:46 -07001033 if (!isa<ConstantFP>(Divisor)) // TODO: handle vectors.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001034 return nullptr;
Stephen Hines36b56882014-04-23 16:57:46 -07001035
1036 const APFloat &FpVal = cast<ConstantFP>(Divisor)->getValueAPF();
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001037 APFloat Reciprocal(FpVal.getSemantics());
1038 bool Cvt = FpVal.getExactInverse(&Reciprocal);
Jim Grosbach03fceff2013-04-05 21:20:12 +00001039
Michael Gottesman07969dc2013-06-19 21:23:18 +00001040 if (!Cvt && AllowReciprocal && FpVal.isFiniteNonZero()) {
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001041 Reciprocal = APFloat(FpVal.getSemantics(), 1.0f);
1042 (void)Reciprocal.divide(FpVal, APFloat::rmNearestTiesToEven);
1043 Cvt = !Reciprocal.isDenormal();
1044 }
1045
1046 if (!Cvt)
Stephen Hinesdce4a402014-05-29 02:49:00 -07001047 return nullptr;
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001048
1049 ConstantFP *R;
1050 R = ConstantFP::get(Dividend->getType()->getContext(), Reciprocal);
1051 return BinaryOperator::CreateFMul(Dividend, R);
1052}
1053
Frits van Bommel31726c12011-01-29 17:50:27 +00001054Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
1055 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1056
Stephen Hinesdce4a402014-05-29 02:49:00 -07001057 if (Value *V = SimplifyVectorOp(I))
1058 return ReplaceInstUsesWith(I, V);
1059
Stephen Hines36b56882014-04-23 16:57:46 -07001060 if (Value *V = SimplifyFDivInst(Op0, Op1, DL))
Frits van Bommel31726c12011-01-29 17:50:27 +00001061 return ReplaceInstUsesWith(I, V);
1062
Stephen Lina98ce502013-07-20 07:13:13 +00001063 if (isa<Constant>(Op0))
1064 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1065 if (Instruction *R = FoldOpIntoSelect(I, SI))
1066 return R;
1067
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001068 bool AllowReassociate = I.hasUnsafeAlgebra();
1069 bool AllowReciprocal = I.hasAllowReciprocal();
Benjamin Kramer54673962011-03-30 15:42:35 +00001070
Stephen Hines36b56882014-04-23 16:57:46 -07001071 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Stephen Lina98ce502013-07-20 07:13:13 +00001072 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1073 if (Instruction *R = FoldOpIntoSelect(I, SI))
1074 return R;
1075
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001076 if (AllowReassociate) {
Stephen Hinesdce4a402014-05-29 02:49:00 -07001077 Constant *C1 = nullptr;
Stephen Hines36b56882014-04-23 16:57:46 -07001078 Constant *C2 = Op1C;
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001079 Value *X;
Stephen Hinesdce4a402014-05-29 02:49:00 -07001080 Instruction *Res = nullptr;
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001081
Stephen Hines36b56882014-04-23 16:57:46 -07001082 if (match(Op0, m_FMul(m_Value(X), m_Constant(C1)))) {
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001083 // (X*C1)/C2 => X * (C1/C2)
1084 //
1085 Constant *C = ConstantExpr::getFDiv(C1, C2);
Stephen Hines36b56882014-04-23 16:57:46 -07001086 if (isNormalFp(C))
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001087 Res = BinaryOperator::CreateFMul(X, C);
Stephen Hines36b56882014-04-23 16:57:46 -07001088 } else if (match(Op0, m_FDiv(m_Value(X), m_Constant(C1)))) {
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001089 // (X/C1)/C2 => X /(C2*C1) [=> X * 1/(C2*C1) if reciprocal is allowed]
1090 //
1091 Constant *C = ConstantExpr::getFMul(C1, C2);
Stephen Hines36b56882014-04-23 16:57:46 -07001092 if (isNormalFp(C)) {
1093 Res = CvtFDivConstToReciprocal(X, C, AllowReciprocal);
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001094 if (!Res)
Jim Grosbach03fceff2013-04-05 21:20:12 +00001095 Res = BinaryOperator::CreateFDiv(X, C);
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001096 }
1097 }
1098
1099 if (Res) {
1100 Res->setFastMathFlags(I.getFastMathFlags());
1101 return Res;
1102 }
1103 }
1104
1105 // X / C => X * 1/C
Stephen Hines36b56882014-04-23 16:57:46 -07001106 if (Instruction *T = CvtFDivConstToReciprocal(Op0, Op1C, AllowReciprocal)) {
1107 T->copyFastMathFlags(&I);
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001108 return T;
Stephen Hines36b56882014-04-23 16:57:46 -07001109 }
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001110
Stephen Hinesdce4a402014-05-29 02:49:00 -07001111 return nullptr;
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001112 }
1113
Stephen Hines36b56882014-04-23 16:57:46 -07001114 if (AllowReassociate && isa<Constant>(Op0)) {
1115 Constant *C1 = cast<Constant>(Op0), *C2;
Stephen Hinesdce4a402014-05-29 02:49:00 -07001116 Constant *Fold = nullptr;
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001117 Value *X;
1118 bool CreateDiv = true;
1119
1120 // C1 / (X*C2) => (C1/C2) / X
Stephen Hines36b56882014-04-23 16:57:46 -07001121 if (match(Op1, m_FMul(m_Value(X), m_Constant(C2))))
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001122 Fold = ConstantExpr::getFDiv(C1, C2);
Stephen Hines36b56882014-04-23 16:57:46 -07001123 else if (match(Op1, m_FDiv(m_Value(X), m_Constant(C2)))) {
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001124 // C1 / (X/C2) => (C1*C2) / X
1125 Fold = ConstantExpr::getFMul(C1, C2);
Stephen Hines36b56882014-04-23 16:57:46 -07001126 } else if (match(Op1, m_FDiv(m_Constant(C2), m_Value(X)))) {
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001127 // C1 / (C2/X) => (C1/C2) * X
1128 Fold = ConstantExpr::getFDiv(C1, C2);
1129 CreateDiv = false;
1130 }
1131
Stephen Hines36b56882014-04-23 16:57:46 -07001132 if (Fold && isNormalFp(Fold)) {
1133 Instruction *R = CreateDiv ? BinaryOperator::CreateFDiv(Fold, X)
1134 : BinaryOperator::CreateFMul(X, Fold);
1135 R->setFastMathFlags(I.getFastMathFlags());
1136 return R;
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001137 }
Stephen Hinesdce4a402014-05-29 02:49:00 -07001138 return nullptr;
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001139 }
1140
1141 if (AllowReassociate) {
1142 Value *X, *Y;
Stephen Hinesdce4a402014-05-29 02:49:00 -07001143 Value *NewInst = nullptr;
1144 Instruction *SimpR = nullptr;
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001145
1146 if (Op0->hasOneUse() && match(Op0, m_FDiv(m_Value(X), m_Value(Y)))) {
1147 // (X/Y) / Z => X / (Y*Z)
1148 //
Stephen Hines36b56882014-04-23 16:57:46 -07001149 if (!isa<Constant>(Y) || !isa<Constant>(Op1)) {
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001150 NewInst = Builder->CreateFMul(Y, Op1);
Stephen Hines36b56882014-04-23 16:57:46 -07001151 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1152 FastMathFlags Flags = I.getFastMathFlags();
1153 Flags &= cast<Instruction>(Op0)->getFastMathFlags();
1154 RI->setFastMathFlags(Flags);
1155 }
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001156 SimpR = BinaryOperator::CreateFDiv(X, NewInst);
1157 }
1158 } else if (Op1->hasOneUse() && match(Op1, m_FDiv(m_Value(X), m_Value(Y)))) {
1159 // Z / (X/Y) => Z*Y / X
1160 //
Stephen Hines36b56882014-04-23 16:57:46 -07001161 if (!isa<Constant>(Y) || !isa<Constant>(Op0)) {
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001162 NewInst = Builder->CreateFMul(Op0, Y);
Stephen Hines36b56882014-04-23 16:57:46 -07001163 if (Instruction *RI = dyn_cast<Instruction>(NewInst)) {
1164 FastMathFlags Flags = I.getFastMathFlags();
1165 Flags &= cast<Instruction>(Op1)->getFastMathFlags();
1166 RI->setFastMathFlags(Flags);
1167 }
Shuxin Yang7d72cf82013-01-14 22:48:41 +00001168 SimpR = BinaryOperator::CreateFDiv(NewInst, X);
1169 }
1170 }
1171
1172 if (NewInst) {
1173 if (Instruction *T = dyn_cast<Instruction>(NewInst))
1174 T->setDebugLoc(I.getDebugLoc());
1175 SimpR->setFastMathFlags(I.getFastMathFlags());
1176 return SimpR;
Benjamin Kramer54673962011-03-30 15:42:35 +00001177 }
1178 }
1179
Stephen Hinesdce4a402014-05-29 02:49:00 -07001180 return nullptr;
Frits van Bommel31726c12011-01-29 17:50:27 +00001181}
1182
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001183/// This function implements the transforms common to both integer remainder
1184/// instructions (urem and srem). It is called by the visitors to those integer
1185/// remainder instructions.
1186/// @brief Common integer remainder transforms
1187Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
1188 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1189
Chris Lattner1add46d2011-05-22 18:18:41 +00001190 // The RHS is known non-zero.
1191 if (Value *V = simplifyValueKnownNonZero(I.getOperand(1), *this)) {
1192 I.setOperand(1, V);
1193 return &I;
1194 }
1195
Duncan Sandsf24ed772011-05-02 16:27:02 +00001196 // Handle cases involving: rem X, (select Cond, Y, Z)
1197 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1198 return &I;
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001199
Stephen Hines36b56882014-04-23 16:57:46 -07001200 if (isa<Constant>(Op1)) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001201 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1202 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1203 if (Instruction *R = FoldOpIntoSelect(I, SI))
1204 return R;
1205 } else if (isa<PHINode>(Op0I)) {
1206 if (Instruction *NV = FoldOpIntoPhi(I))
1207 return NV;
1208 }
1209
1210 // See if we can fold away this rem instruction.
1211 if (SimplifyDemandedInstructionBits(I))
1212 return &I;
1213 }
1214 }
1215
Stephen Hinesdce4a402014-05-29 02:49:00 -07001216 return nullptr;
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001217}
1218
1219Instruction *InstCombiner::visitURem(BinaryOperator &I) {
1220 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1221
Stephen Hinesdce4a402014-05-29 02:49:00 -07001222 if (Value *V = SimplifyVectorOp(I))
1223 return ReplaceInstUsesWith(I, V);
1224
Stephen Hines36b56882014-04-23 16:57:46 -07001225 if (Value *V = SimplifyURemInst(Op0, Op1, DL))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001226 return ReplaceInstUsesWith(I, V);
1227
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001228 if (Instruction *common = commonIRemTransforms(I))
1229 return common;
Jim Grosbach03fceff2013-04-05 21:20:12 +00001230
David Majnemerfa49d7d2013-05-12 00:07:05 +00001231 // (zext A) urem (zext B) --> zext (A urem B)
1232 if (ZExtInst *ZOp0 = dyn_cast<ZExtInst>(Op0))
1233 if (Value *ZOp1 = dyn_castZExtVal(Op1, ZOp0->getSrcTy()))
1234 return new ZExtInst(Builder->CreateURem(ZOp0->getOperand(0), ZOp1),
1235 I.getType());
1236
David Majnemera8ccefc2013-05-11 09:01:28 +00001237 // X urem Y -> X and Y-1, where Y is a power of 2,
1238 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true)) {
Chris Lattner7a6aa1a2011-02-10 05:36:31 +00001239 Constant *N1 = Constant::getAllOnesValue(I.getType());
Benjamin Kramera9390a42011-09-27 20:39:19 +00001240 Value *Add = Builder->CreateAdd(Op1, N1);
Chris Lattner7a6aa1a2011-02-10 05:36:31 +00001241 return BinaryOperator::CreateAnd(Op0, Add);
1242 }
1243
Nick Lewycky75681bb2013-07-13 01:16:47 +00001244 // 1 urem X -> zext(X != 1)
1245 if (match(Op0, m_One())) {
1246 Value *Cmp = Builder->CreateICmpNE(Op1, Op0);
1247 Value *Ext = Builder->CreateZExt(Cmp, I.getType());
1248 return ReplaceInstUsesWith(I, Ext);
1249 }
1250
Stephen Hinesdce4a402014-05-29 02:49:00 -07001251 return nullptr;
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001252}
1253
1254Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
1255 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1256
Stephen Hinesdce4a402014-05-29 02:49:00 -07001257 if (Value *V = SimplifyVectorOp(I))
1258 return ReplaceInstUsesWith(I, V);
1259
Stephen Hines36b56882014-04-23 16:57:46 -07001260 if (Value *V = SimplifySRemInst(Op0, Op1, DL))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001261 return ReplaceInstUsesWith(I, V);
1262
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001263 // Handle the integer rem common cases
1264 if (Instruction *Common = commonIRemTransforms(I))
1265 return Common;
Jim Grosbach03fceff2013-04-05 21:20:12 +00001266
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001267 if (Value *RHSNeg = dyn_castNegVal(Op1))
1268 if (!isa<Constant>(RHSNeg) ||
1269 (isa<ConstantInt>(RHSNeg) &&
1270 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
1271 // X % -Y -> X % Y
1272 Worklist.AddValue(I.getOperand(1));
1273 I.setOperand(1, RHSNeg);
1274 return &I;
1275 }
1276
1277 // If the sign bits of both operands are zero (i.e. we can prove they are
1278 // unsigned inputs), turn this into a urem.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001279 if (I.getType()->isIntegerTy()) {
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001280 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
1281 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Sylvestre Ledru94c22712012-09-27 10:14:43 +00001282 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001283 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
1284 }
1285 }
1286
1287 // If it's a constant vector, flip any negative values positive.
Chris Lattnera78fa8c2012-01-27 03:08:05 +00001288 if (isa<ConstantVector>(Op1) || isa<ConstantDataVector>(Op1)) {
1289 Constant *C = cast<Constant>(Op1);
1290 unsigned VWidth = C->getType()->getVectorNumElements();
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001291
1292 bool hasNegative = false;
Chris Lattnera78fa8c2012-01-27 03:08:05 +00001293 bool hasMissing = false;
1294 for (unsigned i = 0; i != VWidth; ++i) {
1295 Constant *Elt = C->getAggregateElement(i);
Stephen Hinesdce4a402014-05-29 02:49:00 -07001296 if (!Elt) {
Chris Lattnera78fa8c2012-01-27 03:08:05 +00001297 hasMissing = true;
1298 break;
1299 }
1300
1301 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elt))
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001302 if (RHS->isNegative())
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001303 hasNegative = true;
Chris Lattnera78fa8c2012-01-27 03:08:05 +00001304 }
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001305
Chris Lattnera78fa8c2012-01-27 03:08:05 +00001306 if (hasNegative && !hasMissing) {
Chris Lattner4ca829e2012-01-25 06:02:56 +00001307 SmallVector<Constant *, 16> Elts(VWidth);
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001308 for (unsigned i = 0; i != VWidth; ++i) {
Chris Lattner7302d802012-02-06 21:56:39 +00001309 Elts[i] = C->getAggregateElement(i); // Handle undef, etc.
Chris Lattnera78fa8c2012-01-27 03:08:05 +00001310 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Elts[i])) {
Chris Lattnerc73b24d2011-07-15 06:08:15 +00001311 if (RHS->isNegative())
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001312 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001313 }
1314 }
1315
1316 Constant *NewRHSV = ConstantVector::get(Elts);
Chris Lattnera78fa8c2012-01-27 03:08:05 +00001317 if (NewRHSV != C) { // Don't loop on -MININT
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001318 Worklist.AddValue(I.getOperand(1));
1319 I.setOperand(1, NewRHSV);
1320 return &I;
1321 }
1322 }
1323 }
1324
Stephen Hinesdce4a402014-05-29 02:49:00 -07001325 return nullptr;
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001326}
1327
1328Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Duncan Sandsf24ed772011-05-02 16:27:02 +00001329 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerd12c27c2010-01-05 06:09:35 +00001330
Stephen Hinesdce4a402014-05-29 02:49:00 -07001331 if (Value *V = SimplifyVectorOp(I))
1332 return ReplaceInstUsesWith(I, V);
1333
Stephen Hines36b56882014-04-23 16:57:46 -07001334 if (Value *V = SimplifyFRemInst(Op0, Op1, DL))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001335 return ReplaceInstUsesWith(I, V);
1336
1337 // Handle cases involving: rem X, (select Cond, Y, Z)
1338 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
1339 return &I;
1340
Stephen Hinesdce4a402014-05-29 02:49:00 -07001341 return nullptr;
Duncan Sandsf24ed772011-05-02 16:27:02 +00001342}