blob: 686978ac98545b2ba991cd671cecf28afd3c95e5 [file] [log] [blame]
Chris Lattner53a19b72010-01-05 07:18:46 +00001//===- InstCombineAddSub.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 add, fadd, sub, and fsub.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombine.h"
Craig Topperb9df53a2013-07-15 04:27:47 +000015#include "llvm/ADT/STLExtras.h"
Chris Lattner53a19b72010-01-05 07:18:46 +000016#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000017#include "llvm/IR/DataLayout.h"
Chris Lattner53a19b72010-01-05 07:18:46 +000018#include "llvm/Support/GetElementPtrTypeIterator.h"
19#include "llvm/Support/PatternMatch.h"
20using namespace llvm;
21using namespace PatternMatch;
22
Shuxin Yang1a315002012-12-18 23:10:12 +000023namespace {
24
25 /// Class representing coefficient of floating-point addend.
26 /// This class needs to be highly efficient, which is especially true for
27 /// the constructor. As of I write this comment, the cost of the default
Jim Grosbach03fceff2013-04-05 21:20:12 +000028 /// constructor is merely 4-byte-store-zero (Assuming compiler is able to
Shuxin Yang1a315002012-12-18 23:10:12 +000029 /// perform write-merging).
Jim Grosbach03fceff2013-04-05 21:20:12 +000030 ///
Shuxin Yang1a315002012-12-18 23:10:12 +000031 class FAddendCoef {
32 public:
33 // The constructor has to initialize a APFloat, which is uncessary for
34 // most addends which have coefficient either 1 or -1. So, the constructor
35 // is expensive. In order to avoid the cost of the constructor, we should
36 // reuse some instances whenever possible. The pre-created instances
37 // FAddCombine::Add[0-5] embodies this idea.
38 //
39 FAddendCoef() : IsFp(false), BufHasFpVal(false), IntVal(0) {}
40 ~FAddendCoef();
Jim Grosbach03fceff2013-04-05 21:20:12 +000041
Shuxin Yang1a315002012-12-18 23:10:12 +000042 void set(short C) {
43 assert(!insaneIntVal(C) && "Insane coefficient");
44 IsFp = false; IntVal = C;
45 }
Jim Grosbach03fceff2013-04-05 21:20:12 +000046
Shuxin Yang1a315002012-12-18 23:10:12 +000047 void set(const APFloat& C);
Shuxin Yangc76067b2013-03-25 20:43:41 +000048
Shuxin Yang1a315002012-12-18 23:10:12 +000049 void negate();
Jim Grosbach03fceff2013-04-05 21:20:12 +000050
Shuxin Yang1a315002012-12-18 23:10:12 +000051 bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); }
52 Value *getValue(Type *) const;
Jim Grosbach03fceff2013-04-05 21:20:12 +000053
Shuxin Yang1a315002012-12-18 23:10:12 +000054 // If possible, don't define operator+/operator- etc because these
55 // operators inevitably call FAddendCoef's constructor which is not cheap.
56 void operator=(const FAddendCoef &A);
57 void operator+=(const FAddendCoef &A);
58 void operator-=(const FAddendCoef &A);
59 void operator*=(const FAddendCoef &S);
Jim Grosbach03fceff2013-04-05 21:20:12 +000060
Shuxin Yang1a315002012-12-18 23:10:12 +000061 bool isOne() const { return isInt() && IntVal == 1; }
62 bool isTwo() const { return isInt() && IntVal == 2; }
63 bool isMinusOne() const { return isInt() && IntVal == -1; }
64 bool isMinusTwo() const { return isInt() && IntVal == -2; }
Jim Grosbach03fceff2013-04-05 21:20:12 +000065
Shuxin Yang1a315002012-12-18 23:10:12 +000066 private:
67 bool insaneIntVal(int V) { return V > 4 || V < -4; }
68 APFloat *getFpValPtr(void)
Shuxin Yangd6b51d12012-12-19 01:10:17 +000069 { return reinterpret_cast<APFloat*>(&FpValBuf.buffer[0]); }
David Greene4ee576f2013-01-14 21:04:40 +000070 const APFloat *getFpValPtr(void) const
71 { return reinterpret_cast<const APFloat*>(&FpValBuf.buffer[0]); }
Shuxin Yang1a315002012-12-18 23:10:12 +000072
73 const APFloat &getFpVal(void) const {
74 assert(IsFp && BufHasFpVal && "Incorret state");
David Greene4ee576f2013-01-14 21:04:40 +000075 return *getFpValPtr();
Shuxin Yang1a315002012-12-18 23:10:12 +000076 }
77
Jim Grosbach03fceff2013-04-05 21:20:12 +000078 APFloat &getFpVal(void) {
79 assert(IsFp && BufHasFpVal && "Incorret state");
80 return *getFpValPtr();
81 }
82
Shuxin Yang1a315002012-12-18 23:10:12 +000083 bool isInt() const { return !IsFp; }
84
Shuxin Yangc76067b2013-03-25 20:43:41 +000085 // If the coefficient is represented by an integer, promote it to a
Jim Grosbach03fceff2013-04-05 21:20:12 +000086 // floating point.
Shuxin Yangc76067b2013-03-25 20:43:41 +000087 void convertToFpType(const fltSemantics &Sem);
88
89 // Construct an APFloat from a signed integer.
90 // TODO: We should get rid of this function when APFloat can be constructed
Jim Grosbach03fceff2013-04-05 21:20:12 +000091 // from an *SIGNED* integer.
Shuxin Yangc76067b2013-03-25 20:43:41 +000092 APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val);
Shuxin Yang1a315002012-12-18 23:10:12 +000093 private:
Shuxin Yangd6b51d12012-12-19 01:10:17 +000094
Shuxin Yang1a315002012-12-18 23:10:12 +000095 bool IsFp;
Jim Grosbach03fceff2013-04-05 21:20:12 +000096
Shuxin Yang1a315002012-12-18 23:10:12 +000097 // True iff FpValBuf contains an instance of APFloat.
98 bool BufHasFpVal;
Jim Grosbach03fceff2013-04-05 21:20:12 +000099
Shuxin Yang1a315002012-12-18 23:10:12 +0000100 // The integer coefficient of an individual addend is either 1 or -1,
101 // and we try to simplify at most 4 addends from neighboring at most
102 // two instructions. So the range of <IntVal> falls in [-4, 4]. APInt
103 // is overkill of this end.
104 short IntVal;
Shuxin Yangd6b51d12012-12-19 01:10:17 +0000105
106 AlignedCharArrayUnion<APFloat> FpValBuf;
Shuxin Yang1a315002012-12-18 23:10:12 +0000107 };
Jim Grosbach03fceff2013-04-05 21:20:12 +0000108
Shuxin Yang1a315002012-12-18 23:10:12 +0000109 /// FAddend is used to represent floating-point addend. An addend is
110 /// represented as <C, V>, where the V is a symbolic value, and C is a
111 /// constant coefficient. A constant addend is represented as <C, 0>.
112 ///
113 class FAddend {
114 public:
115 FAddend() { Val = 0; }
Jim Grosbach03fceff2013-04-05 21:20:12 +0000116
Shuxin Yang1a315002012-12-18 23:10:12 +0000117 Value *getSymVal (void) const { return Val; }
118 const FAddendCoef &getCoef(void) const { return Coeff; }
Jim Grosbach03fceff2013-04-05 21:20:12 +0000119
Shuxin Yang1a315002012-12-18 23:10:12 +0000120 bool isConstant() const { return Val == 0; }
121 bool isZero() const { return Coeff.isZero(); }
122
123 void set(short Coefficient, Value *V) { Coeff.set(Coefficient), Val = V; }
124 void set(const APFloat& Coefficient, Value *V)
125 { Coeff.set(Coefficient); Val = V; }
126 void set(const ConstantFP* Coefficient, Value *V)
127 { Coeff.set(Coefficient->getValueAPF()); Val = V; }
Jim Grosbach03fceff2013-04-05 21:20:12 +0000128
Shuxin Yang1a315002012-12-18 23:10:12 +0000129 void negate() { Coeff.negate(); }
Jim Grosbach03fceff2013-04-05 21:20:12 +0000130
Shuxin Yang1a315002012-12-18 23:10:12 +0000131 /// Drill down the U-D chain one step to find the definition of V, and
132 /// try to break the definition into one or two addends.
133 static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
Jim Grosbach03fceff2013-04-05 21:20:12 +0000134
Shuxin Yang1a315002012-12-18 23:10:12 +0000135 /// Similar to FAddend::drillDownOneStep() except that the value being
136 /// splitted is the addend itself.
137 unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
Jim Grosbach03fceff2013-04-05 21:20:12 +0000138
Shuxin Yang1a315002012-12-18 23:10:12 +0000139 void operator+=(const FAddend &T) {
140 assert((Val == T.Val) && "Symbolic-values disagree");
141 Coeff += T.Coeff;
142 }
143
144 private:
145 void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
Jim Grosbach03fceff2013-04-05 21:20:12 +0000146
Shuxin Yang1a315002012-12-18 23:10:12 +0000147 // This addend has the value of "Coeff * Val".
148 Value *Val;
149 FAddendCoef Coeff;
150 };
Jim Grosbach03fceff2013-04-05 21:20:12 +0000151
Shuxin Yang1a315002012-12-18 23:10:12 +0000152 /// FAddCombine is the class for optimizing an unsafe fadd/fsub along
153 /// with its neighboring at most two instructions.
154 ///
155 class FAddCombine {
156 public:
157 FAddCombine(InstCombiner::BuilderTy *B) : Builder(B), Instr(0) {}
158 Value *simplify(Instruction *FAdd);
Jim Grosbach03fceff2013-04-05 21:20:12 +0000159
Shuxin Yang1a315002012-12-18 23:10:12 +0000160 private:
161 typedef SmallVector<const FAddend*, 4> AddendVect;
Jim Grosbach03fceff2013-04-05 21:20:12 +0000162
Shuxin Yang1a315002012-12-18 23:10:12 +0000163 Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
Shuxin Yanga0c99392013-03-14 18:08:26 +0000164
165 Value *performFactorization(Instruction *I);
166
Shuxin Yang1a315002012-12-18 23:10:12 +0000167 /// Convert given addend to a Value
168 Value *createAddendVal(const FAddend &A, bool& NeedNeg);
Jim Grosbach03fceff2013-04-05 21:20:12 +0000169
Shuxin Yang1a315002012-12-18 23:10:12 +0000170 /// Return the number of instructions needed to emit the N-ary addition.
171 unsigned calcInstrNumber(const AddendVect& Vect);
172 Value *createFSub(Value *Opnd0, Value *Opnd1);
173 Value *createFAdd(Value *Opnd0, Value *Opnd1);
174 Value *createFMul(Value *Opnd0, Value *Opnd1);
Shuxin Yanga0c99392013-03-14 18:08:26 +0000175 Value *createFDiv(Value *Opnd0, Value *Opnd1);
Shuxin Yang1a315002012-12-18 23:10:12 +0000176 Value *createFNeg(Value *V);
177 Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
178 void createInstPostProc(Instruction *NewInst);
Jim Grosbach03fceff2013-04-05 21:20:12 +0000179
Shuxin Yang1a315002012-12-18 23:10:12 +0000180 InstCombiner::BuilderTy *Builder;
181 Instruction *Instr;
Jim Grosbach03fceff2013-04-05 21:20:12 +0000182
Shuxin Yang1a315002012-12-18 23:10:12 +0000183 private:
184 // Debugging stuff are clustered here.
185 #ifndef NDEBUG
186 unsigned CreateInstrNum;
187 void initCreateInstNum() { CreateInstrNum = 0; }
188 void incCreateInstNum() { CreateInstrNum++; }
189 #else
190 void initCreateInstNum() {}
191 void incCreateInstNum() {}
192 #endif
193 };
Jim Grosbach03fceff2013-04-05 21:20:12 +0000194}
Shuxin Yang1a315002012-12-18 23:10:12 +0000195
196//===----------------------------------------------------------------------===//
197//
198// Implementation of
199// {FAddendCoef, FAddend, FAddition, FAddCombine}.
200//
201//===----------------------------------------------------------------------===//
202FAddendCoef::~FAddendCoef() {
203 if (BufHasFpVal)
204 getFpValPtr()->~APFloat();
205}
206
207void FAddendCoef::set(const APFloat& C) {
208 APFloat *P = getFpValPtr();
209
210 if (isInt()) {
211 // As the buffer is meanless byte stream, we cannot call
212 // APFloat::operator=().
213 new(P) APFloat(C);
214 } else
215 *P = C;
216
Jim Grosbach03fceff2013-04-05 21:20:12 +0000217 IsFp = BufHasFpVal = true;
Shuxin Yang1a315002012-12-18 23:10:12 +0000218}
219
Shuxin Yangc76067b2013-03-25 20:43:41 +0000220void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
221 if (!isInt())
222 return;
223
224 APFloat *P = getFpValPtr();
225 if (IntVal > 0)
226 new(P) APFloat(Sem, IntVal);
227 else {
228 new(P) APFloat(Sem, 0 - IntVal);
229 P->changeSign();
230 }
Jim Grosbach03fceff2013-04-05 21:20:12 +0000231 IsFp = BufHasFpVal = true;
Shuxin Yangc76067b2013-03-25 20:43:41 +0000232}
233
234APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
235 if (Val >= 0)
236 return APFloat(Sem, Val);
237
238 APFloat T(Sem, 0 - Val);
239 T.changeSign();
240
241 return T;
242}
243
244void FAddendCoef::operator=(const FAddendCoef &That) {
Shuxin Yang1a315002012-12-18 23:10:12 +0000245 if (That.isInt())
246 set(That.IntVal);
247 else
248 set(That.getFpVal());
249}
250
251void FAddendCoef::operator+=(const FAddendCoef &That) {
252 enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
253 if (isInt() == That.isInt()) {
254 if (isInt())
255 IntVal += That.IntVal;
256 else
257 getFpVal().add(That.getFpVal(), RndMode);
258 return;
259 }
Jim Grosbach03fceff2013-04-05 21:20:12 +0000260
Shuxin Yang1a315002012-12-18 23:10:12 +0000261 if (isInt()) {
262 const APFloat &T = That.getFpVal();
Shuxin Yangc76067b2013-03-25 20:43:41 +0000263 convertToFpType(T.getSemantics());
264 getFpVal().add(T, RndMode);
Shuxin Yang1a315002012-12-18 23:10:12 +0000265 return;
266 }
Jim Grosbach03fceff2013-04-05 21:20:12 +0000267
Shuxin Yang1a315002012-12-18 23:10:12 +0000268 APFloat &T = getFpVal();
Shuxin Yangc76067b2013-03-25 20:43:41 +0000269 T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
Shuxin Yang1a315002012-12-18 23:10:12 +0000270}
271
272void FAddendCoef::operator-=(const FAddendCoef &That) {
273 enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
274 if (isInt() == That.isInt()) {
275 if (isInt())
276 IntVal -= That.IntVal;
277 else
278 getFpVal().subtract(That.getFpVal(), RndMode);
279 return;
280 }
Jim Grosbach03fceff2013-04-05 21:20:12 +0000281
Shuxin Yang1a315002012-12-18 23:10:12 +0000282 if (isInt()) {
283 const APFloat &T = That.getFpVal();
Shuxin Yangc76067b2013-03-25 20:43:41 +0000284 convertToFpType(T.getSemantics());
285 getFpVal().subtract(T, RndMode);
Shuxin Yang1a315002012-12-18 23:10:12 +0000286 return;
287 }
288
289 APFloat &T = getFpVal();
Shuxin Yangc76067b2013-03-25 20:43:41 +0000290 T.subtract(createAPFloatFromInt(T.getSemantics(), IntVal), RndMode);
Shuxin Yang1a315002012-12-18 23:10:12 +0000291}
292
293void FAddendCoef::operator*=(const FAddendCoef &That) {
294 if (That.isOne())
295 return;
296
297 if (That.isMinusOne()) {
298 negate();
299 return;
300 }
301
302 if (isInt() && That.isInt()) {
303 int Res = IntVal * (int)That.IntVal;
304 assert(!insaneIntVal(Res) && "Insane int value");
305 IntVal = Res;
306 return;
307 }
308
Jim Grosbach03fceff2013-04-05 21:20:12 +0000309 const fltSemantics &Semantic =
Shuxin Yang1a315002012-12-18 23:10:12 +0000310 isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
311
312 if (isInt())
Shuxin Yangc76067b2013-03-25 20:43:41 +0000313 convertToFpType(Semantic);
Shuxin Yang1a315002012-12-18 23:10:12 +0000314 APFloat &F0 = getFpVal();
315
316 if (That.isInt())
Shuxin Yangc76067b2013-03-25 20:43:41 +0000317 F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
318 APFloat::rmNearestTiesToEven);
Shuxin Yang1a315002012-12-18 23:10:12 +0000319 else
320 F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven);
321
322 return;
323}
324
325void FAddendCoef::negate() {
326 if (isInt())
327 IntVal = 0 - IntVal;
328 else
329 getFpVal().changeSign();
330}
331
332Value *FAddendCoef::getValue(Type *Ty) const {
333 return isInt() ?
334 ConstantFP::get(Ty, float(IntVal)) :
335 ConstantFP::get(Ty->getContext(), getFpVal());
336}
337
338// The definition of <Val> Addends
339// =========================================
340// A + B <1, A>, <1,B>
341// A - B <1, A>, <1,B>
342// 0 - B <-1, B>
343// C * A, <C, A>
Jim Grosbach03fceff2013-04-05 21:20:12 +0000344// A + C <1, A> <C, NULL>
Shuxin Yang1a315002012-12-18 23:10:12 +0000345// 0 +/- 0 <0, NULL> (corner case)
346//
347// Legend: A and B are not constant, C is constant
Jim Grosbach03fceff2013-04-05 21:20:12 +0000348//
Shuxin Yang1a315002012-12-18 23:10:12 +0000349unsigned FAddend::drillValueDownOneStep
350 (Value *Val, FAddend &Addend0, FAddend &Addend1) {
351 Instruction *I = 0;
352 if (Val == 0 || !(I = dyn_cast<Instruction>(Val)))
353 return 0;
354
355 unsigned Opcode = I->getOpcode();
356
357 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
358 ConstantFP *C0, *C1;
359 Value *Opnd0 = I->getOperand(0);
360 Value *Opnd1 = I->getOperand(1);
361 if ((C0 = dyn_cast<ConstantFP>(Opnd0)) && C0->isZero())
362 Opnd0 = 0;
363
364 if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
365 Opnd1 = 0;
366
367 if (Opnd0) {
368 if (!C0)
369 Addend0.set(1, Opnd0);
370 else
371 Addend0.set(C0, 0);
372 }
373
374 if (Opnd1) {
375 FAddend &Addend = Opnd0 ? Addend1 : Addend0;
376 if (!C1)
377 Addend.set(1, Opnd1);
378 else
379 Addend.set(C1, 0);
380 if (Opcode == Instruction::FSub)
381 Addend.negate();
382 }
383
384 if (Opnd0 || Opnd1)
385 return Opnd0 && Opnd1 ? 2 : 1;
386
387 // Both operands are zero. Weird!
388 Addend0.set(APFloat(C0->getValueAPF().getSemantics()), 0);
389 return 1;
390 }
391
392 if (I->getOpcode() == Instruction::FMul) {
393 Value *V0 = I->getOperand(0);
394 Value *V1 = I->getOperand(1);
395 if (ConstantFP *C = dyn_cast<ConstantFP>(V0)) {
396 Addend0.set(C, V1);
397 return 1;
398 }
399
400 if (ConstantFP *C = dyn_cast<ConstantFP>(V1)) {
401 Addend0.set(C, V0);
402 return 1;
403 }
404 }
405
406 return 0;
407}
408
409// Try to break *this* addend into two addends. e.g. Suppose this addend is
410// <2.3, V>, and V = X + Y, by calling this function, we obtain two addends,
411// i.e. <2.3, X> and <2.3, Y>.
412//
413unsigned FAddend::drillAddendDownOneStep
414 (FAddend &Addend0, FAddend &Addend1) const {
415 if (isConstant())
416 return 0;
417
418 unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1);
Jim Grosbach03fceff2013-04-05 21:20:12 +0000419 if (!BreakNum || Coeff.isOne())
Shuxin Yang1a315002012-12-18 23:10:12 +0000420 return BreakNum;
421
422 Addend0.Scale(Coeff);
423
424 if (BreakNum == 2)
425 Addend1.Scale(Coeff);
426
427 return BreakNum;
428}
429
Shuxin Yanga0c99392013-03-14 18:08:26 +0000430// Try to perform following optimization on the input instruction I. Return the
431// simplified expression if was successful; otherwise, return 0.
432//
433// Instruction "I" is Simplified into
434// -------------------------------------------------------
435// (x * y) +/- (x * z) x * (y +/- z)
436// (y / x) +/- (z / x) (y +/- z) / x
437//
438Value *FAddCombine::performFactorization(Instruction *I) {
439 assert((I->getOpcode() == Instruction::FAdd ||
440 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
Jim Grosbach03fceff2013-04-05 21:20:12 +0000441
Shuxin Yanga0c99392013-03-14 18:08:26 +0000442 Instruction *I0 = dyn_cast<Instruction>(I->getOperand(0));
443 Instruction *I1 = dyn_cast<Instruction>(I->getOperand(1));
Jim Grosbach03fceff2013-04-05 21:20:12 +0000444
Shuxin Yanga0c99392013-03-14 18:08:26 +0000445 if (!I0 || !I1 || I0->getOpcode() != I1->getOpcode())
446 return 0;
447
448 bool isMpy = false;
449 if (I0->getOpcode() == Instruction::FMul)
450 isMpy = true;
451 else if (I0->getOpcode() != Instruction::FDiv)
452 return 0;
453
454 Value *Opnd0_0 = I0->getOperand(0);
455 Value *Opnd0_1 = I0->getOperand(1);
456 Value *Opnd1_0 = I1->getOperand(0);
457 Value *Opnd1_1 = I1->getOperand(1);
458
Jim Grosbach03fceff2013-04-05 21:20:12 +0000459 // Input Instr I Factor AddSub0 AddSub1
Shuxin Yanga0c99392013-03-14 18:08:26 +0000460 // ----------------------------------------------
461 // (x*y) +/- (x*z) x y z
462 // (y/x) +/- (z/x) x y z
463 //
464 Value *Factor = 0;
465 Value *AddSub0 = 0, *AddSub1 = 0;
Jim Grosbach03fceff2013-04-05 21:20:12 +0000466
Shuxin Yanga0c99392013-03-14 18:08:26 +0000467 if (isMpy) {
468 if (Opnd0_0 == Opnd1_0 || Opnd0_0 == Opnd1_1)
469 Factor = Opnd0_0;
470 else if (Opnd0_1 == Opnd1_0 || Opnd0_1 == Opnd1_1)
471 Factor = Opnd0_1;
472
473 if (Factor) {
474 AddSub0 = (Factor == Opnd0_0) ? Opnd0_1 : Opnd0_0;
475 AddSub1 = (Factor == Opnd1_0) ? Opnd1_1 : Opnd1_0;
476 }
477 } else if (Opnd0_1 == Opnd1_1) {
478 Factor = Opnd0_1;
479 AddSub0 = Opnd0_0;
480 AddSub1 = Opnd1_0;
481 }
482
483 if (!Factor)
484 return 0;
485
486 // Create expression "NewAddSub = AddSub0 +/- AddsSub1"
487 Value *NewAddSub = (I->getOpcode() == Instruction::FAdd) ?
488 createFAdd(AddSub0, AddSub1) :
489 createFSub(AddSub0, AddSub1);
490 if (ConstantFP *CFP = dyn_cast<ConstantFP>(NewAddSub)) {
491 const APFloat &F = CFP->getValueAPF();
Michael Gottesmanc3cfe532013-06-26 23:17:31 +0000492 if (!F.isNormal())
Shuxin Yanga0c99392013-03-14 18:08:26 +0000493 return 0;
494 }
495
496 if (isMpy)
497 return createFMul(Factor, NewAddSub);
Jim Grosbach03fceff2013-04-05 21:20:12 +0000498
Shuxin Yanga0c99392013-03-14 18:08:26 +0000499 return createFDiv(NewAddSub, Factor);
500}
501
Shuxin Yang1a315002012-12-18 23:10:12 +0000502Value *FAddCombine::simplify(Instruction *I) {
503 assert(I->hasUnsafeAlgebra() && "Should be in unsafe mode");
504
505 // Currently we are not able to handle vector type.
506 if (I->getType()->isVectorTy())
507 return 0;
508
509 assert((I->getOpcode() == Instruction::FAdd ||
510 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
511
Jim Grosbach03fceff2013-04-05 21:20:12 +0000512 // Save the instruction before calling other member-functions.
Shuxin Yang1a315002012-12-18 23:10:12 +0000513 Instr = I;
514
515 FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
516
517 unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
518
519 // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
520 unsigned Opnd0_ExpNum = 0;
521 unsigned Opnd1_ExpNum = 0;
522
Jim Grosbach03fceff2013-04-05 21:20:12 +0000523 if (!Opnd0.isConstant())
Shuxin Yang1a315002012-12-18 23:10:12 +0000524 Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
525
526 // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
527 if (OpndNum == 2 && !Opnd1.isConstant())
528 Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
529
530 // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
531 if (Opnd0_ExpNum && Opnd1_ExpNum) {
532 AddendVect AllOpnds;
533 AllOpnds.push_back(&Opnd0_0);
534 AllOpnds.push_back(&Opnd1_0);
535 if (Opnd0_ExpNum == 2)
536 AllOpnds.push_back(&Opnd0_1);
537 if (Opnd1_ExpNum == 2)
538 AllOpnds.push_back(&Opnd1_1);
539
540 // Compute instruction quota. We should save at least one instruction.
541 unsigned InstQuota = 0;
542
543 Value *V0 = I->getOperand(0);
544 Value *V1 = I->getOperand(1);
Jim Grosbach03fceff2013-04-05 21:20:12 +0000545 InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
Shuxin Yang1a315002012-12-18 23:10:12 +0000546 (!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
547
548 if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
549 return R;
550 }
551
552 if (OpndNum != 2) {
553 // The input instruction is : "I=0.0 +/- V". If the "V" were able to be
554 // splitted into two addends, say "V = X - Y", the instruction would have
555 // been optimized into "I = Y - X" in the previous steps.
556 //
557 const FAddendCoef &CE = Opnd0.getCoef();
558 return CE.isOne() ? Opnd0.getSymVal() : 0;
559 }
560
561 // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
562 if (Opnd1_ExpNum) {
563 AddendVect AllOpnds;
564 AllOpnds.push_back(&Opnd0);
565 AllOpnds.push_back(&Opnd1_0);
566 if (Opnd1_ExpNum == 2)
567 AllOpnds.push_back(&Opnd1_1);
568
569 if (Value *R = simplifyFAdd(AllOpnds, 1))
570 return R;
571 }
572
573 // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
574 if (Opnd0_ExpNum) {
575 AddendVect AllOpnds;
576 AllOpnds.push_back(&Opnd1);
577 AllOpnds.push_back(&Opnd0_0);
578 if (Opnd0_ExpNum == 2)
579 AllOpnds.push_back(&Opnd0_1);
580
581 if (Value *R = simplifyFAdd(AllOpnds, 1))
582 return R;
583 }
584
Jim Grosbach03fceff2013-04-05 21:20:12 +0000585 // step 6: Try factorization as the last resort,
Shuxin Yanga0c99392013-03-14 18:08:26 +0000586 return performFactorization(I);
Shuxin Yang1a315002012-12-18 23:10:12 +0000587}
588
589Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
590
591 unsigned AddendNum = Addends.size();
592 assert(AddendNum <= 4 && "Too many addends");
593
Jim Grosbach03fceff2013-04-05 21:20:12 +0000594 // For saving intermediate results;
Shuxin Yang1a315002012-12-18 23:10:12 +0000595 unsigned NextTmpIdx = 0;
596 FAddend TmpResult[3];
597
598 // Points to the constant addend of the resulting simplified expression.
599 // If the resulting expr has constant-addend, this constant-addend is
600 // desirable to reside at the top of the resulting expression tree. Placing
601 // constant close to supper-expr(s) will potentially reveal some optimization
602 // opportunities in super-expr(s).
603 //
604 const FAddend *ConstAdd = 0;
605
606 // Simplified addends are placed <SimpVect>.
607 AddendVect SimpVect;
608
609 // The outer loop works on one symbolic-value at a time. Suppose the input
Jim Grosbach03fceff2013-04-05 21:20:12 +0000610 // addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
Shuxin Yang1a315002012-12-18 23:10:12 +0000611 // The symbolic-values will be processed in this order: x, y, z.
612 //
613 for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
614
615 const FAddend *ThisAddend = Addends[SymIdx];
616 if (!ThisAddend) {
617 // This addend was processed before.
618 continue;
619 }
620
621 Value *Val = ThisAddend->getSymVal();
622 unsigned StartIdx = SimpVect.size();
623 SimpVect.push_back(ThisAddend);
624
625 // The inner loop collects addends sharing same symbolic-value, and these
626 // addends will be later on folded into a single addend. Following above
627 // example, if the symbolic value "y" is being processed, the inner loop
628 // will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
629 // be later on folded into "<b1+b2, y>".
630 //
631 for (unsigned SameSymIdx = SymIdx + 1;
632 SameSymIdx < AddendNum; SameSymIdx++) {
633 const FAddend *T = Addends[SameSymIdx];
634 if (T && T->getSymVal() == Val) {
635 // Set null such that next iteration of the outer loop will not process
636 // this addend again.
Jim Grosbach03fceff2013-04-05 21:20:12 +0000637 Addends[SameSymIdx] = 0;
Shuxin Yang1a315002012-12-18 23:10:12 +0000638 SimpVect.push_back(T);
639 }
640 }
641
642 // If multiple addends share same symbolic value, fold them together.
643 if (StartIdx + 1 != SimpVect.size()) {
644 FAddend &R = TmpResult[NextTmpIdx ++];
645 R = *SimpVect[StartIdx];
646 for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
647 R += *SimpVect[Idx];
648
649 // Pop all addends being folded and push the resulting folded addend.
Jim Grosbach03fceff2013-04-05 21:20:12 +0000650 SimpVect.resize(StartIdx);
Shuxin Yang1a315002012-12-18 23:10:12 +0000651 if (Val != 0) {
652 if (!R.isZero()) {
653 SimpVect.push_back(&R);
654 }
655 } else {
656 // Don't push constant addend at this time. It will be the last element
657 // of <SimpVect>.
658 ConstAdd = &R;
659 }
660 }
661 }
662
Craig Topperb9df53a2013-07-15 04:27:47 +0000663 assert((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&
Shuxin Yang1a315002012-12-18 23:10:12 +0000664 "out-of-bound access");
665
666 if (ConstAdd)
667 SimpVect.push_back(ConstAdd);
668
669 Value *Result;
670 if (!SimpVect.empty())
671 Result = createNaryFAdd(SimpVect, InstrQuota);
672 else {
673 // The addition is folded to 0.0.
674 Result = ConstantFP::get(Instr->getType(), 0.0);
675 }
676
677 return Result;
678}
679
680Value *FAddCombine::createNaryFAdd
681 (const AddendVect &Opnds, unsigned InstrQuota) {
682 assert(!Opnds.empty() && "Expect at least one addend");
683
684 // Step 1: Check if the # of instructions needed exceeds the quota.
Jim Grosbach03fceff2013-04-05 21:20:12 +0000685 //
Shuxin Yang1a315002012-12-18 23:10:12 +0000686 unsigned InstrNeeded = calcInstrNumber(Opnds);
687 if (InstrNeeded > InstrQuota)
688 return 0;
689
690 initCreateInstNum();
691
692 // step 2: Emit the N-ary addition.
693 // Note that at most three instructions are involved in Fadd-InstCombine: the
694 // addition in question, and at most two neighboring instructions.
695 // The resulting optimized addition should have at least one less instruction
696 // than the original addition expression tree. This implies that the resulting
697 // N-ary addition has at most two instructions, and we don't need to worry
698 // about tree-height when constructing the N-ary addition.
699
700 Value *LastVal = 0;
701 bool LastValNeedNeg = false;
702
703 // Iterate the addends, creating fadd/fsub using adjacent two addends.
704 for (AddendVect::const_iterator I = Opnds.begin(), E = Opnds.end();
705 I != E; I++) {
Jim Grosbach03fceff2013-04-05 21:20:12 +0000706 bool NeedNeg;
Shuxin Yang1a315002012-12-18 23:10:12 +0000707 Value *V = createAddendVal(**I, NeedNeg);
708 if (!LastVal) {
709 LastVal = V;
710 LastValNeedNeg = NeedNeg;
711 continue;
712 }
713
714 if (LastValNeedNeg == NeedNeg) {
715 LastVal = createFAdd(LastVal, V);
716 continue;
717 }
718
719 if (LastValNeedNeg)
720 LastVal = createFSub(V, LastVal);
721 else
722 LastVal = createFSub(LastVal, V);
723
724 LastValNeedNeg = false;
725 }
726
727 if (LastValNeedNeg) {
728 LastVal = createFNeg(LastVal);
729 }
730
731 #ifndef NDEBUG
Jim Grosbach03fceff2013-04-05 21:20:12 +0000732 assert(CreateInstrNum == InstrNeeded &&
Shuxin Yang1a315002012-12-18 23:10:12 +0000733 "Inconsistent in instruction numbers");
734 #endif
735
736 return LastVal;
737}
738
739Value *FAddCombine::createFSub
740 (Value *Opnd0, Value *Opnd1) {
741 Value *V = Builder->CreateFSub(Opnd0, Opnd1);
Shuxin Yanga0c99392013-03-14 18:08:26 +0000742 if (Instruction *I = dyn_cast<Instruction>(V))
743 createInstPostProc(I);
Shuxin Yang1a315002012-12-18 23:10:12 +0000744 return V;
745}
746
747Value *FAddCombine::createFNeg(Value *V) {
748 Value *Zero = cast<Value>(ConstantFP::get(V->getType(), 0.0));
749 return createFSub(Zero, V);
750}
751
752Value *FAddCombine::createFAdd
753 (Value *Opnd0, Value *Opnd1) {
754 Value *V = Builder->CreateFAdd(Opnd0, Opnd1);
Shuxin Yanga0c99392013-03-14 18:08:26 +0000755 if (Instruction *I = dyn_cast<Instruction>(V))
756 createInstPostProc(I);
Shuxin Yang1a315002012-12-18 23:10:12 +0000757 return V;
758}
759
760Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
761 Value *V = Builder->CreateFMul(Opnd0, Opnd1);
Shuxin Yanga0c99392013-03-14 18:08:26 +0000762 if (Instruction *I = dyn_cast<Instruction>(V))
763 createInstPostProc(I);
764 return V;
765}
766
767Value *FAddCombine::createFDiv(Value *Opnd0, Value *Opnd1) {
768 Value *V = Builder->CreateFDiv(Opnd0, Opnd1);
769 if (Instruction *I = dyn_cast<Instruction>(V))
770 createInstPostProc(I);
Shuxin Yang1a315002012-12-18 23:10:12 +0000771 return V;
772}
773
774void FAddCombine::createInstPostProc(Instruction *NewInstr) {
775 NewInstr->setDebugLoc(Instr->getDebugLoc());
776
777 // Keep track of the number of instruction created.
778 incCreateInstNum();
779
780 // Propagate fast-math flags
781 NewInstr->setFastMathFlags(Instr->getFastMathFlags());
782}
783
784// Return the number of instruction needed to emit the N-ary addition.
785// NOTE: Keep this function in sync with createAddendVal().
786unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
787 unsigned OpndNum = Opnds.size();
788 unsigned InstrNeeded = OpndNum - 1;
789
Jim Grosbach03fceff2013-04-05 21:20:12 +0000790 // The number of addends in the form of "(-1)*x".
791 unsigned NegOpndNum = 0;
Shuxin Yang1a315002012-12-18 23:10:12 +0000792
793 // Adjust the number of instructions needed to emit the N-ary add.
794 for (AddendVect::const_iterator I = Opnds.begin(), E = Opnds.end();
795 I != E; I++) {
796 const FAddend *Opnd = *I;
797 if (Opnd->isConstant())
798 continue;
799
800 const FAddendCoef &CE = Opnd->getCoef();
801 if (CE.isMinusOne() || CE.isMinusTwo())
802 NegOpndNum++;
803
804 // Let the addend be "c * x". If "c == +/-1", the value of the addend
805 // is immediately available; otherwise, it needs exactly one instruction
806 // to evaluate the value.
807 if (!CE.isMinusOne() && !CE.isOne())
808 InstrNeeded++;
809 }
810 if (NegOpndNum == OpndNum)
811 InstrNeeded++;
812 return InstrNeeded;
813}
814
815// Input Addend Value NeedNeg(output)
816// ================================================================
817// Constant C C false
818// <+/-1, V> V coefficient is -1
819// <2/-2, V> "fadd V, V" coefficient is -2
820// <C, V> "fmul V, C" false
821//
822// NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
823Value *FAddCombine::createAddendVal
824 (const FAddend &Opnd, bool &NeedNeg) {
825 const FAddendCoef &Coeff = Opnd.getCoef();
826
827 if (Opnd.isConstant()) {
828 NeedNeg = false;
829 return Coeff.getValue(Instr->getType());
830 }
831
832 Value *OpndVal = Opnd.getSymVal();
833
834 if (Coeff.isMinusOne() || Coeff.isOne()) {
835 NeedNeg = Coeff.isMinusOne();
836 return OpndVal;
837 }
838
839 if (Coeff.isTwo() || Coeff.isMinusTwo()) {
840 NeedNeg = Coeff.isMinusTwo();
841 return createFAdd(OpndVal, OpndVal);
842 }
843
844 NeedNeg = false;
845 return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
846}
847
Chris Lattner53a19b72010-01-05 07:18:46 +0000848/// AddOne - Add one to a ConstantInt.
849static Constant *AddOne(Constant *C) {
850 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
851}
Shuxin Yang1a315002012-12-18 23:10:12 +0000852
Chris Lattner53a19b72010-01-05 07:18:46 +0000853/// SubOne - Subtract one from a ConstantInt.
854static Constant *SubOne(ConstantInt *C) {
855 return ConstantInt::get(C->getContext(), C->getValue()-1);
856}
857
858
859// dyn_castFoldableMul - If this value is a multiply that can be folded into
860// other computations (because it has a constant operand), return the
861// non-constant operand of the multiply, and set CST to point to the multiplier.
862// Otherwise, return null.
863//
864static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000865 if (!V->hasOneUse() || !V->getType()->isIntegerTy())
Chris Lattner3168c7d2010-01-05 20:56:24 +0000866 return 0;
Michael Ilseman4d96e6f2012-12-12 20:57:53 +0000867
Chris Lattner3168c7d2010-01-05 20:56:24 +0000868 Instruction *I = dyn_cast<Instruction>(V);
869 if (I == 0) return 0;
Michael Ilseman4d96e6f2012-12-12 20:57:53 +0000870
Chris Lattner3168c7d2010-01-05 20:56:24 +0000871 if (I->getOpcode() == Instruction::Mul)
872 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
873 return I->getOperand(0);
874 if (I->getOpcode() == Instruction::Shl)
875 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
876 // The multiplier is really 1 << CST.
877 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
878 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
879 CST = ConstantInt::get(V->getType()->getContext(),
Benjamin Kramer0a230e02013-07-11 16:05:50 +0000880 APInt::getOneBitSet(BitWidth, CSTVal));
Chris Lattner3168c7d2010-01-05 20:56:24 +0000881 return I->getOperand(0);
Chris Lattner53a19b72010-01-05 07:18:46 +0000882 }
883 return 0;
884}
885
886
887/// WillNotOverflowSignedAdd - Return true if we can prove that:
888/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
889/// This basically requires proving that the add in the original type would not
890/// overflow to change the sign bit or have a carry out.
891bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
892 // There are different heuristics we can use for this. Here are some simple
893 // ones.
Michael Ilseman4d96e6f2012-12-12 20:57:53 +0000894
895 // Add has the property that adding any two 2's complement numbers can only
Chris Lattner53a19b72010-01-05 07:18:46 +0000896 // have one carry bit which can change a sign. As such, if LHS and RHS each
897 // have at least two sign bits, we know that the addition of the two values
898 // will sign extend fine.
899 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
900 return true;
Michael Ilseman4d96e6f2012-12-12 20:57:53 +0000901
902
Chris Lattner53a19b72010-01-05 07:18:46 +0000903 // If one of the operands only has one non-zero bit, and if the other operand
904 // has a known-zero bit in a more significant place than it (not including the
905 // sign bit) the ripple may go up to and fill the zero, but won't change the
906 // sign. For example, (X & ~4) + 1.
Michael Ilseman4d96e6f2012-12-12 20:57:53 +0000907
Chris Lattner53a19b72010-01-05 07:18:46 +0000908 // TODO: Implement.
Michael Ilseman4d96e6f2012-12-12 20:57:53 +0000909
Chris Lattner53a19b72010-01-05 07:18:46 +0000910 return false;
911}
912
913Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Duncan Sands096aa792010-11-13 15:10:37 +0000914 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner53a19b72010-01-05 07:18:46 +0000915 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
916
917 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
918 I.hasNoUnsignedWrap(), TD))
919 return ReplaceInstUsesWith(I, V);
920
Duncan Sands37bf92b2010-12-22 13:36:08 +0000921 // (A*B)+(A*C) -> A*(B+C) etc
922 if (Value *V = SimplifyUsingDistributiveLaws(I))
923 return ReplaceInstUsesWith(I, V);
924
Chris Lattnerb9b90442011-02-10 05:14:58 +0000925 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
926 // X + (signbit) --> X ^ signbit
927 const APInt &Val = CI->getValue();
928 if (Val.isSignBit())
929 return BinaryOperator::CreateXor(LHS, RHS);
Michael Ilseman4d96e6f2012-12-12 20:57:53 +0000930
Chris Lattnerb9b90442011-02-10 05:14:58 +0000931 // See if SimplifyDemandedBits can simplify this. This handles stuff like
932 // (X & 254)+1 -> (X&254)|1
933 if (SimplifyDemandedInstructionBits(I))
934 return &I;
935
936 // zext(bool) + C -> bool ? C + 1 : C
937 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
938 if (ZI->getSrcTy()->isIntegerTy(1))
939 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Michael Ilseman4d96e6f2012-12-12 20:57:53 +0000940
Chris Lattnerb9b90442011-02-10 05:14:58 +0000941 Value *XorLHS = 0; ConstantInt *XorRHS = 0;
942 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner53a19b72010-01-05 07:18:46 +0000943 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Chris Lattnerb9b90442011-02-10 05:14:58 +0000944 const APInt &RHSVal = CI->getValue();
Eli Friedmanbe7cfa62010-01-31 04:29:12 +0000945 unsigned ExtendAmt = 0;
946 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
947 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
948 if (XorRHS->getValue() == -RHSVal) {
949 if (RHSVal.isPowerOf2())
950 ExtendAmt = TySizeBits - RHSVal.logBase2() - 1;
951 else if (XorRHS->getValue().isPowerOf2())
952 ExtendAmt = TySizeBits - XorRHS->getValue().logBase2() - 1;
Chris Lattner53a19b72010-01-05 07:18:46 +0000953 }
Michael Ilseman4d96e6f2012-12-12 20:57:53 +0000954
Eli Friedmanbe7cfa62010-01-31 04:29:12 +0000955 if (ExtendAmt) {
956 APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt);
957 if (!MaskedValueIsZero(XorLHS, Mask))
958 ExtendAmt = 0;
959 }
Michael Ilseman4d96e6f2012-12-12 20:57:53 +0000960
Eli Friedmanbe7cfa62010-01-31 04:29:12 +0000961 if (ExtendAmt) {
962 Constant *ShAmt = ConstantInt::get(I.getType(), ExtendAmt);
963 Value *NewShl = Builder->CreateShl(XorLHS, ShAmt, "sext");
964 return BinaryOperator::CreateAShr(NewShl, ShAmt);
Chris Lattner53a19b72010-01-05 07:18:46 +0000965 }
Benjamin Kramer49064ff2011-12-24 17:31:53 +0000966
967 // If this is a xor that was canonicalized from a sub, turn it back into
968 // a sub and fuse this add with it.
969 if (LHS->hasOneUse() && (XorRHS->getValue()+1).isPowerOf2()) {
970 IntegerType *IT = cast<IntegerType>(I.getType());
Benjamin Kramer49064ff2011-12-24 17:31:53 +0000971 APInt LHSKnownOne(IT->getBitWidth(), 0);
972 APInt LHSKnownZero(IT->getBitWidth(), 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +0000973 ComputeMaskedBits(XorLHS, LHSKnownZero, LHSKnownOne);
Benjamin Kramer49064ff2011-12-24 17:31:53 +0000974 if ((XorRHS->getValue() | LHSKnownZero).isAllOnesValue())
975 return BinaryOperator::CreateSub(ConstantExpr::getAdd(XorRHS, CI),
976 XorLHS);
977 }
David Majnemer8ec23cb2013-05-06 21:21:31 +0000978 // (X + signbit) + C could have gotten canonicalized to (X ^ signbit) + C,
979 // transform them into (X + (signbit ^ C))
980 if (XorRHS->getValue().isSignBit())
981 return BinaryOperator::CreateAdd(XorLHS,
982 ConstantExpr::getXor(XorRHS, CI));
Chris Lattner53a19b72010-01-05 07:18:46 +0000983 }
984 }
985
Chris Lattnerb9b90442011-02-10 05:14:58 +0000986 if (isa<Constant>(RHS) && isa<PHINode>(LHS))
987 if (Instruction *NV = FoldOpIntoPhi(I))
988 return NV;
989
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000990 if (I.getType()->isIntegerTy(1))
Chris Lattner53a19b72010-01-05 07:18:46 +0000991 return BinaryOperator::CreateXor(LHS, RHS);
992
Chris Lattnerb9b90442011-02-10 05:14:58 +0000993 // X + X --> X << 1
Chris Lattnerbd9f6bf2011-02-17 20:55:29 +0000994 if (LHS == RHS) {
Chris Lattner41429e32011-02-17 02:23:02 +0000995 BinaryOperator *New =
996 BinaryOperator::CreateShl(LHS, ConstantInt::get(I.getType(), 1));
997 New->setHasNoSignedWrap(I.hasNoSignedWrap());
998 New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
999 return New;
1000 }
Chris Lattner53a19b72010-01-05 07:18:46 +00001001
1002 // -A + B --> B - A
1003 // -A + -B --> -(A + B)
1004 if (Value *LHSV = dyn_castNegVal(LHS)) {
Nuno Lopes0f68fbb2012-06-08 22:30:05 +00001005 if (!isa<Constant>(RHS))
1006 if (Value *RHSV = dyn_castNegVal(RHS)) {
1007 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
1008 return BinaryOperator::CreateNeg(NewAdd);
1009 }
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001010
Chris Lattner53a19b72010-01-05 07:18:46 +00001011 return BinaryOperator::CreateSub(RHS, LHSV);
1012 }
1013
1014 // A + -B --> A - B
1015 if (!isa<Constant>(RHS))
1016 if (Value *V = dyn_castNegVal(RHS))
1017 return BinaryOperator::CreateSub(LHS, V);
1018
1019
1020 ConstantInt *C2;
1021 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1022 if (X == RHS) // X*C + X --> X * (C+1)
1023 return BinaryOperator::CreateMul(RHS, AddOne(C2));
1024
1025 // X*C1 + X*C2 --> X * (C1+C2)
1026 ConstantInt *C1;
1027 if (X == dyn_castFoldableMul(RHS, C1))
1028 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
1029 }
1030
1031 // X + X*C --> X * (C+1)
1032 if (dyn_castFoldableMul(RHS, C2) == LHS)
1033 return BinaryOperator::CreateMul(LHS, AddOne(C2));
1034
Sylvestre Ledru94c22712012-09-27 10:14:43 +00001035 // A+B --> A|B iff A and B have no bits set in common.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001036 if (IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
Chris Lattner53a19b72010-01-05 07:18:46 +00001037 APInt LHSKnownOne(IT->getBitWidth(), 0);
1038 APInt LHSKnownZero(IT->getBitWidth(), 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00001039 ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
Chris Lattner53a19b72010-01-05 07:18:46 +00001040 if (LHSKnownZero != 0) {
1041 APInt RHSKnownOne(IT->getBitWidth(), 0);
1042 APInt RHSKnownZero(IT->getBitWidth(), 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00001043 ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001044
Chris Lattner53a19b72010-01-05 07:18:46 +00001045 // No bits in common -> bitwise or.
1046 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
1047 return BinaryOperator::CreateOr(LHS, RHS);
1048 }
1049 }
1050
Sylvestre Ledru94c22712012-09-27 10:14:43 +00001051 // W*X + Y*Z --> W * (X+Z) iff W == Y
Chris Lattnerb9b90442011-02-10 05:14:58 +00001052 {
Chris Lattner53a19b72010-01-05 07:18:46 +00001053 Value *W, *X, *Y, *Z;
1054 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
1055 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
1056 if (W != Y) {
1057 if (W == Z) {
1058 std::swap(Y, Z);
1059 } else if (Y == X) {
1060 std::swap(W, X);
1061 } else if (X == Z) {
1062 std::swap(Y, Z);
1063 std::swap(W, X);
1064 }
1065 }
1066
1067 if (W == Y) {
1068 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
1069 return BinaryOperator::CreateMul(W, NewAdd);
1070 }
1071 }
1072 }
1073
1074 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1075 Value *X = 0;
1076 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
1077 return BinaryOperator::CreateSub(SubOne(CRHS), X);
1078
1079 // (X & FF00) + xx00 -> (X+xx00) & FF00
1080 if (LHS->hasOneUse() &&
Chris Lattnerb9b90442011-02-10 05:14:58 +00001081 match(LHS, m_And(m_Value(X), m_ConstantInt(C2))) &&
1082 CRHS->getValue() == (CRHS->getValue() & C2->getValue())) {
1083 // See if all bits from the first bit set in the Add RHS up are included
1084 // in the mask. First, get the rightmost bit.
1085 const APInt &AddRHSV = CRHS->getValue();
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001086
Chris Lattnerb9b90442011-02-10 05:14:58 +00001087 // Form a mask of all bits from the lowest bit added through the top.
1088 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattner53a19b72010-01-05 07:18:46 +00001089
Chris Lattnerb9b90442011-02-10 05:14:58 +00001090 // See if the and mask includes all of these bits.
1091 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Chris Lattner53a19b72010-01-05 07:18:46 +00001092
Chris Lattnerb9b90442011-02-10 05:14:58 +00001093 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1094 // Okay, the xform is safe. Insert the new add pronto.
1095 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
1096 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattner53a19b72010-01-05 07:18:46 +00001097 }
1098 }
1099
1100 // Try to fold constant add into select arguments.
1101 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1102 if (Instruction *R = FoldOpIntoSelect(I, SI))
1103 return R;
1104 }
1105
1106 // add (select X 0 (sub n A)) A --> select X A n
1107 {
1108 SelectInst *SI = dyn_cast<SelectInst>(LHS);
1109 Value *A = RHS;
1110 if (!SI) {
1111 SI = dyn_cast<SelectInst>(RHS);
1112 A = LHS;
1113 }
1114 if (SI && SI->hasOneUse()) {
1115 Value *TV = SI->getTrueValue();
1116 Value *FV = SI->getFalseValue();
1117 Value *N;
1118
1119 // Can we fold the add into the argument of the select?
1120 // We check both true and false select arguments for a matching subtract.
Chris Lattnerb9b90442011-02-10 05:14:58 +00001121 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner53a19b72010-01-05 07:18:46 +00001122 // Fold the add into the true select value.
1123 return SelectInst::Create(SI->getCondition(), N, A);
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001124
Chris Lattnerb9b90442011-02-10 05:14:58 +00001125 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner53a19b72010-01-05 07:18:46 +00001126 // Fold the add into the false select value.
1127 return SelectInst::Create(SI->getCondition(), A, N);
1128 }
1129 }
1130
1131 // Check for (add (sext x), y), see if we can merge this into an
1132 // integer add followed by a sext.
1133 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
1134 // (add (sext x), cst) --> (sext (add x, cst'))
1135 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001136 Constant *CI =
Chris Lattner53a19b72010-01-05 07:18:46 +00001137 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
1138 if (LHSConv->hasOneUse() &&
1139 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
1140 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
1141 // Insert the new, smaller add.
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001142 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner53a19b72010-01-05 07:18:46 +00001143 CI, "addconv");
1144 return new SExtInst(NewAdd, I.getType());
1145 }
1146 }
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001147
Chris Lattner53a19b72010-01-05 07:18:46 +00001148 // (add (sext x), (sext y)) --> (sext (add int x, y))
1149 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
1150 // Only do this if x/y have the same type, if at last one of them has a
1151 // single use (so we don't increase the number of sexts), and if the
1152 // integer add will not overflow.
1153 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
1154 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1155 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
1156 RHSConv->getOperand(0))) {
1157 // Insert the new integer add.
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001158 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner3168c7d2010-01-05 20:56:24 +00001159 RHSConv->getOperand(0), "addconv");
Chris Lattner53a19b72010-01-05 07:18:46 +00001160 return new SExtInst(NewAdd, I.getType());
1161 }
1162 }
1163 }
1164
Chad Rosierc1fc5e42012-04-26 23:29:14 +00001165 // Check for (x & y) + (x ^ y)
1166 {
1167 Value *A = 0, *B = 0;
1168 if (match(RHS, m_Xor(m_Value(A), m_Value(B))) &&
1169 (match(LHS, m_And(m_Specific(A), m_Specific(B))) ||
1170 match(LHS, m_And(m_Specific(B), m_Specific(A)))))
1171 return BinaryOperator::CreateOr(A, B);
1172
1173 if (match(LHS, m_Xor(m_Value(A), m_Value(B))) &&
1174 (match(RHS, m_And(m_Specific(A), m_Specific(B))) ||
1175 match(RHS, m_And(m_Specific(B), m_Specific(A)))))
1176 return BinaryOperator::CreateOr(A, B);
1177 }
1178
Chris Lattner53a19b72010-01-05 07:18:46 +00001179 return Changed ? &I : 0;
1180}
1181
1182Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
Duncan Sands096aa792010-11-13 15:10:37 +00001183 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner53a19b72010-01-05 07:18:46 +00001184 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1185
Michael Ilsemanc244f382012-12-12 00:28:32 +00001186 if (Value *V = SimplifyFAddInst(LHS, RHS, I.getFastMathFlags(), TD))
1187 return ReplaceInstUsesWith(I, V);
Chris Lattner53a19b72010-01-05 07:18:46 +00001188
Michael Ilseman07acee72012-12-14 22:08:26 +00001189 if (isa<Constant>(RHS) && isa<PHINode>(LHS))
1190 if (Instruction *NV = FoldOpIntoPhi(I))
1191 return NV;
1192
Chris Lattner53a19b72010-01-05 07:18:46 +00001193 // -A + B --> B - A
1194 // -A + -B --> -(A + B)
1195 if (Value *LHSV = dyn_castFNegVal(LHS))
1196 return BinaryOperator::CreateFSub(RHS, LHSV);
1197
1198 // A + -B --> A - B
1199 if (!isa<Constant>(RHS))
1200 if (Value *V = dyn_castFNegVal(RHS))
1201 return BinaryOperator::CreateFSub(LHS, V);
1202
Dan Gohmana9445e12010-03-02 01:11:08 +00001203 // Check for (fadd double (sitofp x), y), see if we can merge this into an
Chris Lattner53a19b72010-01-05 07:18:46 +00001204 // integer add followed by a promotion.
1205 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
Dan Gohmana9445e12010-03-02 01:11:08 +00001206 // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
Chris Lattner53a19b72010-01-05 07:18:46 +00001207 // ... if the constant fits in the integer value. This is useful for things
1208 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
1209 // requires a constant pool load, and generally allows the add to be better
1210 // instcombined.
1211 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001212 Constant *CI =
Chris Lattner53a19b72010-01-05 07:18:46 +00001213 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
1214 if (LHSConv->hasOneUse() &&
1215 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
1216 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
1217 // Insert the new integer add.
1218 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1219 CI, "addconv");
1220 return new SIToFPInst(NewAdd, I.getType());
1221 }
1222 }
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001223
Dan Gohmana9445e12010-03-02 01:11:08 +00001224 // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
Chris Lattner53a19b72010-01-05 07:18:46 +00001225 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
1226 // Only do this if x/y have the same type, if at last one of them has a
1227 // single use (so we don't increase the number of int->fp conversions),
1228 // and if the integer add will not overflow.
1229 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
1230 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1231 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
1232 RHSConv->getOperand(0))) {
1233 // Insert the new integer add.
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001234 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner53a19b72010-01-05 07:18:46 +00001235 RHSConv->getOperand(0),"addconv");
1236 return new SIToFPInst(NewAdd, I.getType());
1237 }
1238 }
1239 }
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001240
Jean-Luc Dupratc5cf6e52013-05-06 16:55:50 +00001241 // select C, 0, B + select C, A, 0 -> select C, A, B
1242 {
1243 Value *A1, *B1, *C1, *A2, *B2, *C2;
1244 if (match(LHS, m_Select(m_Value(C1), m_Value(A1), m_Value(B1))) &&
1245 match(RHS, m_Select(m_Value(C2), m_Value(A2), m_Value(B2)))) {
1246 if (C1 == C2) {
1247 Constant *Z1=0, *Z2=0;
1248 Value *A, *B, *C=C1;
1249 if (match(A1, m_AnyZero()) && match(B2, m_AnyZero())) {
1250 Z1 = dyn_cast<Constant>(A1); A = A2;
1251 Z2 = dyn_cast<Constant>(B2); B = B1;
1252 } else if (match(B1, m_AnyZero()) && match(A2, m_AnyZero())) {
1253 Z1 = dyn_cast<Constant>(B1); B = B2;
1254 Z2 = dyn_cast<Constant>(A2); A = A1;
1255 }
1256
1257 if (Z1 && Z2 &&
1258 (I.hasNoSignedZeros() ||
1259 (Z1->isNegativeZeroValue() && Z2->isNegativeZeroValue()))) {
1260 return SelectInst::Create(C, A, B);
1261 }
1262 }
1263 }
1264 }
1265
Jean-Luc Duprat5e6cabd2013-05-22 18:29:31 +00001266 // A * (1 - uitofp i1 C) + B * (uitofp i1 C) -> select C, B, A
1267 {
1268 if (I.hasNoNaNs() && I.hasNoInfs() && I.hasNoSignedZeros()) {
1269 Value *M1L, *M1R, *M2L, *M2R;
1270 if (match(LHS, m_FMul(m_Value(M1L), m_Value(M1R))) &&
1271 match(RHS, m_FMul(m_Value(M2L), m_Value(M2R)))) {
1272
1273 Value *A, *B, *C1, *C2;
1274 if (!match(M1R, m_FSub(m_FPOne(), m_UIToFp(m_Value(C1)))))
1275 std::swap(M1L, M1R);
1276 if (!match(M2R, m_UIToFp(m_Value(C2))))
1277 std::swap(M2L, M2R);
1278
1279 if (match(M1R, m_FSub(m_FPOne(), m_UIToFp(m_Value(C1)))) &&
1280 match(M2R, m_UIToFp(m_Value(C2))) &&
1281 C2->getType()->isIntegerTy(1) &&
1282 C1 == C2) {
1283 A = M1L;
1284 B = M2L;
1285 return SelectInst::Create(C1, B, A);
1286 }
1287
1288 std::swap(M1L, M2L);
1289 std::swap(M1R, M2R);
1290
1291 if (!match(M1R, m_FSub(m_FPOne(), m_UIToFp(m_Value(C1)))))
1292 std::swap(M1L, M1R);
1293 if (!match(M2R, m_UIToFp(m_Value(C2))))
1294 std::swap(M2L, M2R);
1295
1296 if (match(M1R, m_FSub(m_FPOne(), m_UIToFp(m_Value(C1)))) &&
1297 match(M2R, m_UIToFp(m_Value(C2))) &&
1298 C2->getType()->isIntegerTy(1) &&
1299 C1 == C2) {
1300 A = M1L;
1301 B = M2L;
1302 return SelectInst::Create(C1, B, A);
1303 }
1304 }
1305 }
1306 }
1307
1308
Shuxin Yang1a315002012-12-18 23:10:12 +00001309 if (I.hasUnsafeAlgebra()) {
1310 if (Value *V = FAddCombine(Builder).simplify(&I))
1311 return ReplaceInstUsesWith(I, V);
1312 }
1313
Chris Lattner53a19b72010-01-05 07:18:46 +00001314 return Changed ? &I : 0;
1315}
1316
1317
Chris Lattner53a19b72010-01-05 07:18:46 +00001318/// Optimize pointer differences into the same array into a size. Consider:
1319/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
1320/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
1321///
1322Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001323 Type *Ty) {
Chris Lattner53a19b72010-01-05 07:18:46 +00001324 assert(TD && "Must have target data info for this");
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001325
Chris Lattner53a19b72010-01-05 07:18:46 +00001326 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
1327 // this.
1328 bool Swapped = false;
Benjamin Kramerd2348632012-02-20 14:34:57 +00001329 GEPOperator *GEP1 = 0, *GEP2 = 0;
1330
Chris Lattner53a19b72010-01-05 07:18:46 +00001331 // For now we require one side to be the base pointer "A" or a constant
Benjamin Kramerd2348632012-02-20 14:34:57 +00001332 // GEP derived from it.
1333 if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
Chris Lattner53a19b72010-01-05 07:18:46 +00001334 // (gep X, ...) - X
1335 if (LHSGEP->getOperand(0) == RHS) {
Benjamin Kramerd2348632012-02-20 14:34:57 +00001336 GEP1 = LHSGEP;
Chris Lattner53a19b72010-01-05 07:18:46 +00001337 Swapped = false;
Benjamin Kramerd2348632012-02-20 14:34:57 +00001338 } else if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1339 // (gep X, ...) - (gep X, ...)
1340 if (LHSGEP->getOperand(0)->stripPointerCasts() ==
1341 RHSGEP->getOperand(0)->stripPointerCasts()) {
1342 GEP2 = RHSGEP;
1343 GEP1 = LHSGEP;
Chris Lattner53a19b72010-01-05 07:18:46 +00001344 Swapped = false;
1345 }
1346 }
1347 }
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001348
Benjamin Kramerd2348632012-02-20 14:34:57 +00001349 if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
Chris Lattner53a19b72010-01-05 07:18:46 +00001350 // X - (gep X, ...)
1351 if (RHSGEP->getOperand(0) == LHS) {
Benjamin Kramerd2348632012-02-20 14:34:57 +00001352 GEP1 = RHSGEP;
Chris Lattner53a19b72010-01-05 07:18:46 +00001353 Swapped = true;
Benjamin Kramerd2348632012-02-20 14:34:57 +00001354 } else if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1355 // (gep X, ...) - (gep X, ...)
1356 if (RHSGEP->getOperand(0)->stripPointerCasts() ==
1357 LHSGEP->getOperand(0)->stripPointerCasts()) {
1358 GEP2 = LHSGEP;
1359 GEP1 = RHSGEP;
Chris Lattner53a19b72010-01-05 07:18:46 +00001360 Swapped = true;
1361 }
1362 }
1363 }
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001364
Benjamin Kramerd2348632012-02-20 14:34:57 +00001365 // Avoid duplicating the arithmetic if GEP2 has non-constant indices and
1366 // multiple users.
1367 if (GEP1 == 0 ||
1368 (GEP2 != 0 && !GEP2->hasAllConstantIndices() && !GEP2->hasOneUse()))
Chris Lattner53a19b72010-01-05 07:18:46 +00001369 return 0;
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001370
Chris Lattner53a19b72010-01-05 07:18:46 +00001371 // Emit the offset of the GEP and an intptr_t.
Benjamin Kramerd2348632012-02-20 14:34:57 +00001372 Value *Result = EmitGEPOffset(GEP1);
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001373
Chris Lattner53a19b72010-01-05 07:18:46 +00001374 // If we had a constant expression GEP on the other side offsetting the
1375 // pointer, subtract it from the offset we have.
Benjamin Kramerd2348632012-02-20 14:34:57 +00001376 if (GEP2) {
1377 Value *Offset = EmitGEPOffset(GEP2);
1378 Result = Builder->CreateSub(Result, Offset);
Chris Lattner53a19b72010-01-05 07:18:46 +00001379 }
Chris Lattner53a19b72010-01-05 07:18:46 +00001380
1381 // If we have p - gep(p, ...) then we have to negate the result.
1382 if (Swapped)
1383 Result = Builder->CreateNeg(Result, "diff.neg");
1384
1385 return Builder->CreateIntCast(Result, Ty, true);
1386}
1387
1388
1389Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1390 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1391
Duncan Sandsfea3b212010-12-15 14:07:39 +00001392 if (Value *V = SimplifySubInst(Op0, Op1, I.hasNoSignedWrap(),
1393 I.hasNoUnsignedWrap(), TD))
1394 return ReplaceInstUsesWith(I, V);
Chris Lattner53a19b72010-01-05 07:18:46 +00001395
Duncan Sands37bf92b2010-12-22 13:36:08 +00001396 // (A*B)-(A*C) -> A*(B-C) etc
1397 if (Value *V = SimplifyUsingDistributiveLaws(I))
1398 return ReplaceInstUsesWith(I, V);
1399
Chris Lattner53a19b72010-01-05 07:18:46 +00001400 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
1401 if (Value *V = dyn_castNegVal(Op1)) {
1402 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
1403 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
1404 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1405 return Res;
1406 }
1407
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001408 if (I.getType()->isIntegerTy(1))
Chris Lattner53a19b72010-01-05 07:18:46 +00001409 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattnerb9b90442011-02-10 05:14:58 +00001410
1411 // Replace (-1 - A) with (~A).
1412 if (match(Op0, m_AllOnes()))
1413 return BinaryOperator::CreateNot(Op1);
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001414
Chris Lattner53a19b72010-01-05 07:18:46 +00001415 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner53a19b72010-01-05 07:18:46 +00001416 // C - ~X == X + (1+C)
1417 Value *X = 0;
1418 if (match(Op1, m_Not(m_Value(X))))
1419 return BinaryOperator::CreateAdd(X, AddOne(C));
1420
1421 // -(X >>u 31) -> (X >>s 31)
1422 // -(X >>s 31) -> (X >>u 31)
1423 if (C->isZero()) {
Chris Lattnerb9b90442011-02-10 05:14:58 +00001424 Value *X; ConstantInt *CI;
1425 if (match(Op1, m_LShr(m_Value(X), m_ConstantInt(CI))) &&
1426 // Verify we are shifting out everything but the sign bit.
1427 CI->getValue() == I.getType()->getPrimitiveSizeInBits()-1)
1428 return BinaryOperator::CreateAShr(X, CI);
1429
1430 if (match(Op1, m_AShr(m_Value(X), m_ConstantInt(CI))) &&
1431 // Verify we are shifting out everything but the sign bit.
1432 CI->getValue() == I.getType()->getPrimitiveSizeInBits()-1)
1433 return BinaryOperator::CreateLShr(X, CI);
Chris Lattner53a19b72010-01-05 07:18:46 +00001434 }
1435
1436 // Try to fold constant sub into select arguments.
1437 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1438 if (Instruction *R = FoldOpIntoSelect(I, SI))
1439 return R;
1440
Chris Lattnerb9b90442011-02-10 05:14:58 +00001441 // C-(X+C2) --> (C-C2)-X
1442 ConstantInt *C2;
1443 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(C2))))
1444 return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
Benjamin Kramer1fdfae02011-12-24 17:31:38 +00001445
1446 if (SimplifyDemandedInstructionBits(I))
1447 return &I;
Paul Redmond8e528102013-01-21 21:57:20 +00001448
1449 // Fold (sub 0, (zext bool to B)) --> (sext bool to B)
1450 if (C->isZero() && match(Op1, m_ZExt(m_Value(X))))
1451 if (X->getType()->isIntegerTy(1))
1452 return CastInst::CreateSExtOrBitCast(X, Op1->getType());
1453
1454 // Fold (sub 0, (sext bool to B)) --> (zext bool to B)
1455 if (C->isZero() && match(Op1, m_SExt(m_Value(X))))
1456 if (X->getType()->isIntegerTy(1))
1457 return CastInst::CreateZExtOrBitCast(X, Op1->getType());
Chris Lattner53a19b72010-01-05 07:18:46 +00001458 }
1459
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001460
Chris Lattnerb9b90442011-02-10 05:14:58 +00001461 { Value *Y;
1462 // X-(X+Y) == -Y X-(Y+X) == -Y
1463 if (match(Op1, m_Add(m_Specific(Op0), m_Value(Y))) ||
1464 match(Op1, m_Add(m_Value(Y), m_Specific(Op0))))
1465 return BinaryOperator::CreateNeg(Y);
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001466
Chris Lattnerb9b90442011-02-10 05:14:58 +00001467 // (X-Y)-X == -Y
1468 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
1469 return BinaryOperator::CreateNeg(Y);
1470 }
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001471
Chris Lattnerb9b90442011-02-10 05:14:58 +00001472 if (Op1->hasOneUse()) {
1473 Value *X = 0, *Y = 0, *Z = 0;
1474 Constant *C = 0;
1475 ConstantInt *CI = 0;
1476
1477 // (X - (Y - Z)) --> (X + (Z - Y)).
1478 if (match(Op1, m_Sub(m_Value(Y), m_Value(Z))))
1479 return BinaryOperator::CreateAdd(Op0,
1480 Builder->CreateSub(Z, Y, Op1->getName()));
1481
1482 // (X - (X & Y)) --> (X & ~Y)
1483 //
1484 if (match(Op1, m_And(m_Value(Y), m_Specific(Op0))) ||
1485 match(Op1, m_And(m_Specific(Op0), m_Value(Y))))
1486 return BinaryOperator::CreateAnd(Op0,
1487 Builder->CreateNot(Y, Y->getName() + ".not"));
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001488
Chris Lattnerb9b90442011-02-10 05:14:58 +00001489 // 0 - (X sdiv C) -> (X sdiv -C)
1490 if (match(Op1, m_SDiv(m_Value(X), m_Constant(C))) &&
1491 match(Op0, m_Zero()))
1492 return BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(C));
1493
1494 // 0 - (X << Y) -> (-X << Y) when X is freely negatable.
1495 if (match(Op1, m_Shl(m_Value(X), m_Value(Y))) && match(Op0, m_Zero()))
1496 if (Value *XNeg = dyn_castNegVal(X))
1497 return BinaryOperator::CreateShl(XNeg, Y);
1498
1499 // X - X*C --> X * (1-C)
1500 if (match(Op1, m_Mul(m_Specific(Op0), m_ConstantInt(CI)))) {
1501 Constant *CP1 = ConstantExpr::getSub(ConstantInt::get(I.getType(),1), CI);
1502 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattner53a19b72010-01-05 07:18:46 +00001503 }
1504
Chris Lattnerb9b90442011-02-10 05:14:58 +00001505 // X - X<<C --> X * (1-(1<<C))
1506 if (match(Op1, m_Shl(m_Specific(Op0), m_ConstantInt(CI)))) {
1507 Constant *One = ConstantInt::get(I.getType(), 1);
1508 C = ConstantExpr::getSub(One, ConstantExpr::getShl(One, CI));
1509 return BinaryOperator::CreateMul(Op0, C);
1510 }
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001511
Chris Lattnerb9b90442011-02-10 05:14:58 +00001512 // X - A*-B -> X + A*B
1513 // X - -A*B -> X + A*B
1514 Value *A, *B;
1515 if (match(Op1, m_Mul(m_Value(A), m_Neg(m_Value(B)))) ||
1516 match(Op1, m_Mul(m_Neg(m_Value(A)), m_Value(B))))
1517 return BinaryOperator::CreateAdd(Op0, Builder->CreateMul(A, B));
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001518
Chris Lattnerb9b90442011-02-10 05:14:58 +00001519 // X - A*CI -> X + A*-CI
1520 // X - CI*A -> X + A*-CI
1521 if (match(Op1, m_Mul(m_Value(A), m_ConstantInt(CI))) ||
1522 match(Op1, m_Mul(m_ConstantInt(CI), m_Value(A)))) {
1523 Value *NewMul = Builder->CreateMul(A, ConstantExpr::getNeg(CI));
1524 return BinaryOperator::CreateAdd(Op0, NewMul);
Chris Lattner53a19b72010-01-05 07:18:46 +00001525 }
1526 }
1527
1528 ConstantInt *C1;
1529 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1530 if (X == Op1) // X*C - X --> X * (C-1)
1531 return BinaryOperator::CreateMul(Op1, SubOne(C1));
1532
1533 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1534 if (X == dyn_castFoldableMul(Op1, C2))
1535 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
1536 }
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001537
Chris Lattner53a19b72010-01-05 07:18:46 +00001538 // Optimize pointer differences into the same array into a size. Consider:
1539 // &A[10] - &A[0]: we should compile this to "10".
1540 if (TD) {
1541 Value *LHSOp, *RHSOp;
1542 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
1543 match(Op1, m_PtrToInt(m_Value(RHSOp))))
1544 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1545 return ReplaceInstUsesWith(I, Res);
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001546
Chris Lattner53a19b72010-01-05 07:18:46 +00001547 // trunc(p)-trunc(q) -> trunc(p-q)
1548 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
1549 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
1550 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1551 return ReplaceInstUsesWith(I, Res);
1552 }
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001553
Chris Lattner53a19b72010-01-05 07:18:46 +00001554 return 0;
1555}
1556
1557Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
1558 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1559
Michael Ilsemanc244f382012-12-12 00:28:32 +00001560 if (Value *V = SimplifyFSubInst(Op0, Op1, I.getFastMathFlags(), TD))
1561 return ReplaceInstUsesWith(I, V);
1562
Chris Lattner53a19b72010-01-05 07:18:46 +00001563 // If this is a 'B = x-(-A)', change to B = x+A...
1564 if (Value *V = dyn_castFNegVal(Op1))
1565 return BinaryOperator::CreateFAdd(Op0, V);
1566
Shuxin Yang1a315002012-12-18 23:10:12 +00001567 if (I.hasUnsafeAlgebra()) {
1568 if (Value *V = FAddCombine(Builder).simplify(&I))
1569 return ReplaceInstUsesWith(I, V);
1570 }
1571
Chris Lattner53a19b72010-01-05 07:18:46 +00001572 return 0;
1573}