blob: 97910c7b45953a84ccdbf55883624df5d3fa2d0d [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"
Stephen Hines36b56882014-04-23 16:57:46 -070018#include "llvm/IR/GetElementPtrTypeIterator.h"
19#include "llvm/IR/PatternMatch.h"
Chris Lattner53a19b72010-01-05 07:18:46 +000020using 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);
Stephen Hines36b56882014-04-23 16:57:46 -0700178 void createInstPostProc(Instruction *NewInst, bool NoNumber = false);
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
Stephen Hines36b56882014-04-23 16:57:46 -0700486 FastMathFlags Flags;
487 Flags.setUnsafeAlgebra();
488 if (I0) Flags &= I->getFastMathFlags();
489 if (I1) Flags &= I->getFastMathFlags();
490
Shuxin Yanga0c99392013-03-14 18:08:26 +0000491 // Create expression "NewAddSub = AddSub0 +/- AddsSub1"
492 Value *NewAddSub = (I->getOpcode() == Instruction::FAdd) ?
493 createFAdd(AddSub0, AddSub1) :
494 createFSub(AddSub0, AddSub1);
495 if (ConstantFP *CFP = dyn_cast<ConstantFP>(NewAddSub)) {
496 const APFloat &F = CFP->getValueAPF();
Michael Gottesmanc3cfe532013-06-26 23:17:31 +0000497 if (!F.isNormal())
Shuxin Yanga0c99392013-03-14 18:08:26 +0000498 return 0;
Stephen Hines36b56882014-04-23 16:57:46 -0700499 } else if (Instruction *II = dyn_cast<Instruction>(NewAddSub))
500 II->setFastMathFlags(Flags);
501
502 if (isMpy) {
503 Value *RI = createFMul(Factor, NewAddSub);
504 if (Instruction *II = dyn_cast<Instruction>(RI))
505 II->setFastMathFlags(Flags);
506 return RI;
Shuxin Yanga0c99392013-03-14 18:08:26 +0000507 }
508
Stephen Hines36b56882014-04-23 16:57:46 -0700509 Value *RI = createFDiv(NewAddSub, Factor);
510 if (Instruction *II = dyn_cast<Instruction>(RI))
511 II->setFastMathFlags(Flags);
512 return RI;
Shuxin Yanga0c99392013-03-14 18:08:26 +0000513}
514
Shuxin Yang1a315002012-12-18 23:10:12 +0000515Value *FAddCombine::simplify(Instruction *I) {
516 assert(I->hasUnsafeAlgebra() && "Should be in unsafe mode");
517
518 // Currently we are not able to handle vector type.
519 if (I->getType()->isVectorTy())
520 return 0;
521
522 assert((I->getOpcode() == Instruction::FAdd ||
523 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
524
Jim Grosbach03fceff2013-04-05 21:20:12 +0000525 // Save the instruction before calling other member-functions.
Shuxin Yang1a315002012-12-18 23:10:12 +0000526 Instr = I;
527
528 FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
529
530 unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
531
532 // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
533 unsigned Opnd0_ExpNum = 0;
534 unsigned Opnd1_ExpNum = 0;
535
Jim Grosbach03fceff2013-04-05 21:20:12 +0000536 if (!Opnd0.isConstant())
Shuxin Yang1a315002012-12-18 23:10:12 +0000537 Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
538
539 // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
540 if (OpndNum == 2 && !Opnd1.isConstant())
541 Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
542
543 // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
544 if (Opnd0_ExpNum && Opnd1_ExpNum) {
545 AddendVect AllOpnds;
546 AllOpnds.push_back(&Opnd0_0);
547 AllOpnds.push_back(&Opnd1_0);
548 if (Opnd0_ExpNum == 2)
549 AllOpnds.push_back(&Opnd0_1);
550 if (Opnd1_ExpNum == 2)
551 AllOpnds.push_back(&Opnd1_1);
552
553 // Compute instruction quota. We should save at least one instruction.
554 unsigned InstQuota = 0;
555
556 Value *V0 = I->getOperand(0);
557 Value *V1 = I->getOperand(1);
Jim Grosbach03fceff2013-04-05 21:20:12 +0000558 InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
Shuxin Yang1a315002012-12-18 23:10:12 +0000559 (!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
560
561 if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
562 return R;
563 }
564
565 if (OpndNum != 2) {
566 // The input instruction is : "I=0.0 +/- V". If the "V" were able to be
567 // splitted into two addends, say "V = X - Y", the instruction would have
568 // been optimized into "I = Y - X" in the previous steps.
569 //
570 const FAddendCoef &CE = Opnd0.getCoef();
571 return CE.isOne() ? Opnd0.getSymVal() : 0;
572 }
573
574 // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
575 if (Opnd1_ExpNum) {
576 AddendVect AllOpnds;
577 AllOpnds.push_back(&Opnd0);
578 AllOpnds.push_back(&Opnd1_0);
579 if (Opnd1_ExpNum == 2)
580 AllOpnds.push_back(&Opnd1_1);
581
582 if (Value *R = simplifyFAdd(AllOpnds, 1))
583 return R;
584 }
585
586 // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
587 if (Opnd0_ExpNum) {
588 AddendVect AllOpnds;
589 AllOpnds.push_back(&Opnd1);
590 AllOpnds.push_back(&Opnd0_0);
591 if (Opnd0_ExpNum == 2)
592 AllOpnds.push_back(&Opnd0_1);
593
594 if (Value *R = simplifyFAdd(AllOpnds, 1))
595 return R;
596 }
597
Jim Grosbach03fceff2013-04-05 21:20:12 +0000598 // step 6: Try factorization as the last resort,
Shuxin Yanga0c99392013-03-14 18:08:26 +0000599 return performFactorization(I);
Shuxin Yang1a315002012-12-18 23:10:12 +0000600}
601
602Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
603
604 unsigned AddendNum = Addends.size();
605 assert(AddendNum <= 4 && "Too many addends");
606
Jim Grosbach03fceff2013-04-05 21:20:12 +0000607 // For saving intermediate results;
Shuxin Yang1a315002012-12-18 23:10:12 +0000608 unsigned NextTmpIdx = 0;
609 FAddend TmpResult[3];
610
611 // Points to the constant addend of the resulting simplified expression.
612 // If the resulting expr has constant-addend, this constant-addend is
613 // desirable to reside at the top of the resulting expression tree. Placing
614 // constant close to supper-expr(s) will potentially reveal some optimization
615 // opportunities in super-expr(s).
616 //
617 const FAddend *ConstAdd = 0;
618
619 // Simplified addends are placed <SimpVect>.
620 AddendVect SimpVect;
621
622 // The outer loop works on one symbolic-value at a time. Suppose the input
Jim Grosbach03fceff2013-04-05 21:20:12 +0000623 // addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
Shuxin Yang1a315002012-12-18 23:10:12 +0000624 // The symbolic-values will be processed in this order: x, y, z.
625 //
626 for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
627
628 const FAddend *ThisAddend = Addends[SymIdx];
629 if (!ThisAddend) {
630 // This addend was processed before.
631 continue;
632 }
633
634 Value *Val = ThisAddend->getSymVal();
635 unsigned StartIdx = SimpVect.size();
636 SimpVect.push_back(ThisAddend);
637
638 // The inner loop collects addends sharing same symbolic-value, and these
639 // addends will be later on folded into a single addend. Following above
640 // example, if the symbolic value "y" is being processed, the inner loop
641 // will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
642 // be later on folded into "<b1+b2, y>".
643 //
644 for (unsigned SameSymIdx = SymIdx + 1;
645 SameSymIdx < AddendNum; SameSymIdx++) {
646 const FAddend *T = Addends[SameSymIdx];
647 if (T && T->getSymVal() == Val) {
648 // Set null such that next iteration of the outer loop will not process
649 // this addend again.
Jim Grosbach03fceff2013-04-05 21:20:12 +0000650 Addends[SameSymIdx] = 0;
Shuxin Yang1a315002012-12-18 23:10:12 +0000651 SimpVect.push_back(T);
652 }
653 }
654
655 // If multiple addends share same symbolic value, fold them together.
656 if (StartIdx + 1 != SimpVect.size()) {
657 FAddend &R = TmpResult[NextTmpIdx ++];
658 R = *SimpVect[StartIdx];
659 for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
660 R += *SimpVect[Idx];
661
662 // Pop all addends being folded and push the resulting folded addend.
Jim Grosbach03fceff2013-04-05 21:20:12 +0000663 SimpVect.resize(StartIdx);
Shuxin Yang1a315002012-12-18 23:10:12 +0000664 if (Val != 0) {
665 if (!R.isZero()) {
666 SimpVect.push_back(&R);
667 }
668 } else {
669 // Don't push constant addend at this time. It will be the last element
670 // of <SimpVect>.
671 ConstAdd = &R;
672 }
673 }
674 }
675
Craig Topperb9df53a2013-07-15 04:27:47 +0000676 assert((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&
Shuxin Yang1a315002012-12-18 23:10:12 +0000677 "out-of-bound access");
678
679 if (ConstAdd)
680 SimpVect.push_back(ConstAdd);
681
682 Value *Result;
683 if (!SimpVect.empty())
684 Result = createNaryFAdd(SimpVect, InstrQuota);
685 else {
686 // The addition is folded to 0.0.
687 Result = ConstantFP::get(Instr->getType(), 0.0);
688 }
689
690 return Result;
691}
692
693Value *FAddCombine::createNaryFAdd
694 (const AddendVect &Opnds, unsigned InstrQuota) {
695 assert(!Opnds.empty() && "Expect at least one addend");
696
697 // Step 1: Check if the # of instructions needed exceeds the quota.
Jim Grosbach03fceff2013-04-05 21:20:12 +0000698 //
Shuxin Yang1a315002012-12-18 23:10:12 +0000699 unsigned InstrNeeded = calcInstrNumber(Opnds);
700 if (InstrNeeded > InstrQuota)
701 return 0;
702
703 initCreateInstNum();
704
705 // step 2: Emit the N-ary addition.
706 // Note that at most three instructions are involved in Fadd-InstCombine: the
707 // addition in question, and at most two neighboring instructions.
708 // The resulting optimized addition should have at least one less instruction
709 // than the original addition expression tree. This implies that the resulting
710 // N-ary addition has at most two instructions, and we don't need to worry
711 // about tree-height when constructing the N-ary addition.
712
713 Value *LastVal = 0;
714 bool LastValNeedNeg = false;
715
716 // Iterate the addends, creating fadd/fsub using adjacent two addends.
717 for (AddendVect::const_iterator I = Opnds.begin(), E = Opnds.end();
718 I != E; I++) {
Jim Grosbach03fceff2013-04-05 21:20:12 +0000719 bool NeedNeg;
Shuxin Yang1a315002012-12-18 23:10:12 +0000720 Value *V = createAddendVal(**I, NeedNeg);
721 if (!LastVal) {
722 LastVal = V;
723 LastValNeedNeg = NeedNeg;
724 continue;
725 }
726
727 if (LastValNeedNeg == NeedNeg) {
728 LastVal = createFAdd(LastVal, V);
729 continue;
730 }
731
732 if (LastValNeedNeg)
733 LastVal = createFSub(V, LastVal);
734 else
735 LastVal = createFSub(LastVal, V);
736
737 LastValNeedNeg = false;
738 }
739
740 if (LastValNeedNeg) {
741 LastVal = createFNeg(LastVal);
742 }
743
744 #ifndef NDEBUG
Jim Grosbach03fceff2013-04-05 21:20:12 +0000745 assert(CreateInstrNum == InstrNeeded &&
Shuxin Yang1a315002012-12-18 23:10:12 +0000746 "Inconsistent in instruction numbers");
747 #endif
748
749 return LastVal;
750}
751
752Value *FAddCombine::createFSub
753 (Value *Opnd0, Value *Opnd1) {
754 Value *V = Builder->CreateFSub(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::createFNeg(Value *V) {
761 Value *Zero = cast<Value>(ConstantFP::get(V->getType(), 0.0));
Stephen Hines36b56882014-04-23 16:57:46 -0700762 Value *NewV = createFSub(Zero, V);
763 if (Instruction *I = dyn_cast<Instruction>(NewV))
764 createInstPostProc(I, true); // fneg's don't receive instruction numbers.
765 return NewV;
Shuxin Yang1a315002012-12-18 23:10:12 +0000766}
767
768Value *FAddCombine::createFAdd
769 (Value *Opnd0, Value *Opnd1) {
770 Value *V = Builder->CreateFAdd(Opnd0, Opnd1);
Shuxin Yanga0c99392013-03-14 18:08:26 +0000771 if (Instruction *I = dyn_cast<Instruction>(V))
772 createInstPostProc(I);
Shuxin Yang1a315002012-12-18 23:10:12 +0000773 return V;
774}
775
776Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
777 Value *V = Builder->CreateFMul(Opnd0, Opnd1);
Shuxin Yanga0c99392013-03-14 18:08:26 +0000778 if (Instruction *I = dyn_cast<Instruction>(V))
779 createInstPostProc(I);
780 return V;
781}
782
783Value *FAddCombine::createFDiv(Value *Opnd0, Value *Opnd1) {
784 Value *V = Builder->CreateFDiv(Opnd0, Opnd1);
785 if (Instruction *I = dyn_cast<Instruction>(V))
786 createInstPostProc(I);
Shuxin Yang1a315002012-12-18 23:10:12 +0000787 return V;
788}
789
Stephen Hines36b56882014-04-23 16:57:46 -0700790void FAddCombine::createInstPostProc(Instruction *NewInstr,
791 bool NoNumber) {
Shuxin Yang1a315002012-12-18 23:10:12 +0000792 NewInstr->setDebugLoc(Instr->getDebugLoc());
793
794 // Keep track of the number of instruction created.
Stephen Hines36b56882014-04-23 16:57:46 -0700795 if (!NoNumber)
796 incCreateInstNum();
Shuxin Yang1a315002012-12-18 23:10:12 +0000797
798 // Propagate fast-math flags
799 NewInstr->setFastMathFlags(Instr->getFastMathFlags());
800}
801
802// Return the number of instruction needed to emit the N-ary addition.
803// NOTE: Keep this function in sync with createAddendVal().
804unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
805 unsigned OpndNum = Opnds.size();
806 unsigned InstrNeeded = OpndNum - 1;
807
Jim Grosbach03fceff2013-04-05 21:20:12 +0000808 // The number of addends in the form of "(-1)*x".
809 unsigned NegOpndNum = 0;
Shuxin Yang1a315002012-12-18 23:10:12 +0000810
811 // Adjust the number of instructions needed to emit the N-ary add.
812 for (AddendVect::const_iterator I = Opnds.begin(), E = Opnds.end();
813 I != E; I++) {
814 const FAddend *Opnd = *I;
815 if (Opnd->isConstant())
816 continue;
817
818 const FAddendCoef &CE = Opnd->getCoef();
819 if (CE.isMinusOne() || CE.isMinusTwo())
820 NegOpndNum++;
821
822 // Let the addend be "c * x". If "c == +/-1", the value of the addend
823 // is immediately available; otherwise, it needs exactly one instruction
824 // to evaluate the value.
825 if (!CE.isMinusOne() && !CE.isOne())
826 InstrNeeded++;
827 }
828 if (NegOpndNum == OpndNum)
829 InstrNeeded++;
830 return InstrNeeded;
831}
832
833// Input Addend Value NeedNeg(output)
834// ================================================================
835// Constant C C false
836// <+/-1, V> V coefficient is -1
837// <2/-2, V> "fadd V, V" coefficient is -2
838// <C, V> "fmul V, C" false
839//
840// NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
841Value *FAddCombine::createAddendVal
842 (const FAddend &Opnd, bool &NeedNeg) {
843 const FAddendCoef &Coeff = Opnd.getCoef();
844
845 if (Opnd.isConstant()) {
846 NeedNeg = false;
847 return Coeff.getValue(Instr->getType());
848 }
849
850 Value *OpndVal = Opnd.getSymVal();
851
852 if (Coeff.isMinusOne() || Coeff.isOne()) {
853 NeedNeg = Coeff.isMinusOne();
854 return OpndVal;
855 }
856
857 if (Coeff.isTwo() || Coeff.isMinusTwo()) {
858 NeedNeg = Coeff.isMinusTwo();
859 return createFAdd(OpndVal, OpndVal);
860 }
861
862 NeedNeg = false;
863 return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
864}
865
Chris Lattner53a19b72010-01-05 07:18:46 +0000866// dyn_castFoldableMul - If this value is a multiply that can be folded into
867// other computations (because it has a constant operand), return the
868// non-constant operand of the multiply, and set CST to point to the multiplier.
869// Otherwise, return null.
870//
Stephen Hines36b56882014-04-23 16:57:46 -0700871static inline Value *dyn_castFoldableMul(Value *V, Constant *&CST) {
872 if (!V->hasOneUse() || !V->getType()->isIntOrIntVectorTy())
Chris Lattner3168c7d2010-01-05 20:56:24 +0000873 return 0;
Michael Ilseman4d96e6f2012-12-12 20:57:53 +0000874
Chris Lattner3168c7d2010-01-05 20:56:24 +0000875 Instruction *I = dyn_cast<Instruction>(V);
876 if (I == 0) return 0;
Michael Ilseman4d96e6f2012-12-12 20:57:53 +0000877
Chris Lattner3168c7d2010-01-05 20:56:24 +0000878 if (I->getOpcode() == Instruction::Mul)
Stephen Hines36b56882014-04-23 16:57:46 -0700879 if ((CST = dyn_cast<Constant>(I->getOperand(1))))
Chris Lattner3168c7d2010-01-05 20:56:24 +0000880 return I->getOperand(0);
881 if (I->getOpcode() == Instruction::Shl)
Stephen Hines36b56882014-04-23 16:57:46 -0700882 if ((CST = dyn_cast<Constant>(I->getOperand(1)))) {
Chris Lattner3168c7d2010-01-05 20:56:24 +0000883 // The multiplier is really 1 << CST.
Stephen Hines36b56882014-04-23 16:57:46 -0700884 CST = ConstantExpr::getShl(ConstantInt::get(V->getType(), 1), CST);
Chris Lattner3168c7d2010-01-05 20:56:24 +0000885 return I->getOperand(0);
Chris Lattner53a19b72010-01-05 07:18:46 +0000886 }
887 return 0;
888}
889
890
891/// WillNotOverflowSignedAdd - Return true if we can prove that:
892/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
893/// This basically requires proving that the add in the original type would not
894/// overflow to change the sign bit or have a carry out.
895bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
896 // There are different heuristics we can use for this. Here are some simple
897 // ones.
Michael Ilseman4d96e6f2012-12-12 20:57:53 +0000898
899 // Add has the property that adding any two 2's complement numbers can only
Chris Lattner53a19b72010-01-05 07:18:46 +0000900 // have one carry bit which can change a sign. As such, if LHS and RHS each
901 // have at least two sign bits, we know that the addition of the two values
902 // will sign extend fine.
903 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
904 return true;
Michael Ilseman4d96e6f2012-12-12 20:57:53 +0000905
906
Chris Lattner53a19b72010-01-05 07:18:46 +0000907 // If one of the operands only has one non-zero bit, and if the other operand
908 // has a known-zero bit in a more significant place than it (not including the
909 // sign bit) the ripple may go up to and fill the zero, but won't change the
910 // sign. For example, (X & ~4) + 1.
Michael Ilseman4d96e6f2012-12-12 20:57:53 +0000911
Chris Lattner53a19b72010-01-05 07:18:46 +0000912 // TODO: Implement.
Michael Ilseman4d96e6f2012-12-12 20:57:53 +0000913
Chris Lattner53a19b72010-01-05 07:18:46 +0000914 return false;
915}
916
917Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Duncan Sands096aa792010-11-13 15:10:37 +0000918 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner53a19b72010-01-05 07:18:46 +0000919 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
920
921 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
Stephen Hines36b56882014-04-23 16:57:46 -0700922 I.hasNoUnsignedWrap(), DL))
Chris Lattner53a19b72010-01-05 07:18:46 +0000923 return ReplaceInstUsesWith(I, V);
924
Duncan Sands37bf92b2010-12-22 13:36:08 +0000925 // (A*B)+(A*C) -> A*(B+C) etc
926 if (Value *V = SimplifyUsingDistributiveLaws(I))
927 return ReplaceInstUsesWith(I, V);
928
Chris Lattnerb9b90442011-02-10 05:14:58 +0000929 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
930 // X + (signbit) --> X ^ signbit
931 const APInt &Val = CI->getValue();
932 if (Val.isSignBit())
933 return BinaryOperator::CreateXor(LHS, RHS);
Michael Ilseman4d96e6f2012-12-12 20:57:53 +0000934
Chris Lattnerb9b90442011-02-10 05:14:58 +0000935 // See if SimplifyDemandedBits can simplify this. This handles stuff like
936 // (X & 254)+1 -> (X&254)|1
937 if (SimplifyDemandedInstructionBits(I))
938 return &I;
939
940 // zext(bool) + C -> bool ? C + 1 : C
941 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
942 if (ZI->getSrcTy()->isIntegerTy(1))
943 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Michael Ilseman4d96e6f2012-12-12 20:57:53 +0000944
Chris Lattnerb9b90442011-02-10 05:14:58 +0000945 Value *XorLHS = 0; ConstantInt *XorRHS = 0;
946 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner53a19b72010-01-05 07:18:46 +0000947 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Chris Lattnerb9b90442011-02-10 05:14:58 +0000948 const APInt &RHSVal = CI->getValue();
Eli Friedmanbe7cfa62010-01-31 04:29:12 +0000949 unsigned ExtendAmt = 0;
950 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
951 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
952 if (XorRHS->getValue() == -RHSVal) {
953 if (RHSVal.isPowerOf2())
954 ExtendAmt = TySizeBits - RHSVal.logBase2() - 1;
955 else if (XorRHS->getValue().isPowerOf2())
956 ExtendAmt = TySizeBits - XorRHS->getValue().logBase2() - 1;
Chris Lattner53a19b72010-01-05 07:18:46 +0000957 }
Michael Ilseman4d96e6f2012-12-12 20:57:53 +0000958
Eli Friedmanbe7cfa62010-01-31 04:29:12 +0000959 if (ExtendAmt) {
960 APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt);
961 if (!MaskedValueIsZero(XorLHS, Mask))
962 ExtendAmt = 0;
963 }
Michael Ilseman4d96e6f2012-12-12 20:57:53 +0000964
Eli Friedmanbe7cfa62010-01-31 04:29:12 +0000965 if (ExtendAmt) {
966 Constant *ShAmt = ConstantInt::get(I.getType(), ExtendAmt);
967 Value *NewShl = Builder->CreateShl(XorLHS, ShAmt, "sext");
968 return BinaryOperator::CreateAShr(NewShl, ShAmt);
Chris Lattner53a19b72010-01-05 07:18:46 +0000969 }
Benjamin Kramer49064ff2011-12-24 17:31:53 +0000970
971 // If this is a xor that was canonicalized from a sub, turn it back into
972 // a sub and fuse this add with it.
973 if (LHS->hasOneUse() && (XorRHS->getValue()+1).isPowerOf2()) {
974 IntegerType *IT = cast<IntegerType>(I.getType());
Benjamin Kramer49064ff2011-12-24 17:31:53 +0000975 APInt LHSKnownOne(IT->getBitWidth(), 0);
976 APInt LHSKnownZero(IT->getBitWidth(), 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +0000977 ComputeMaskedBits(XorLHS, LHSKnownZero, LHSKnownOne);
Benjamin Kramer49064ff2011-12-24 17:31:53 +0000978 if ((XorRHS->getValue() | LHSKnownZero).isAllOnesValue())
979 return BinaryOperator::CreateSub(ConstantExpr::getAdd(XorRHS, CI),
980 XorLHS);
981 }
David Majnemer8ec23cb2013-05-06 21:21:31 +0000982 // (X + signbit) + C could have gotten canonicalized to (X ^ signbit) + C,
983 // transform them into (X + (signbit ^ C))
984 if (XorRHS->getValue().isSignBit())
985 return BinaryOperator::CreateAdd(XorLHS,
986 ConstantExpr::getXor(XorRHS, CI));
Chris Lattner53a19b72010-01-05 07:18:46 +0000987 }
988 }
989
Chris Lattnerb9b90442011-02-10 05:14:58 +0000990 if (isa<Constant>(RHS) && isa<PHINode>(LHS))
991 if (Instruction *NV = FoldOpIntoPhi(I))
992 return NV;
993
Stephen Hines36b56882014-04-23 16:57:46 -0700994 if (I.getType()->getScalarType()->isIntegerTy(1))
Chris Lattner53a19b72010-01-05 07:18:46 +0000995 return BinaryOperator::CreateXor(LHS, RHS);
996
Chris Lattnerb9b90442011-02-10 05:14:58 +0000997 // X + X --> X << 1
Chris Lattnerbd9f6bf2011-02-17 20:55:29 +0000998 if (LHS == RHS) {
Chris Lattner41429e32011-02-17 02:23:02 +0000999 BinaryOperator *New =
1000 BinaryOperator::CreateShl(LHS, ConstantInt::get(I.getType(), 1));
1001 New->setHasNoSignedWrap(I.hasNoSignedWrap());
1002 New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1003 return New;
1004 }
Chris Lattner53a19b72010-01-05 07:18:46 +00001005
1006 // -A + B --> B - A
1007 // -A + -B --> -(A + B)
1008 if (Value *LHSV = dyn_castNegVal(LHS)) {
Nuno Lopes0f68fbb2012-06-08 22:30:05 +00001009 if (!isa<Constant>(RHS))
1010 if (Value *RHSV = dyn_castNegVal(RHS)) {
1011 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
1012 return BinaryOperator::CreateNeg(NewAdd);
1013 }
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001014
Chris Lattner53a19b72010-01-05 07:18:46 +00001015 return BinaryOperator::CreateSub(RHS, LHSV);
1016 }
1017
1018 // A + -B --> A - B
1019 if (!isa<Constant>(RHS))
1020 if (Value *V = dyn_castNegVal(RHS))
1021 return BinaryOperator::CreateSub(LHS, V);
1022
1023
Stephen Hines36b56882014-04-23 16:57:46 -07001024 {
1025 Constant *C2;
1026 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1027 if (X == RHS) // X*C + X --> X * (C+1)
1028 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner53a19b72010-01-05 07:18:46 +00001029
Stephen Hines36b56882014-04-23 16:57:46 -07001030 // X*C1 + X*C2 --> X * (C1+C2)
1031 Constant *C1;
1032 if (X == dyn_castFoldableMul(RHS, C1))
1033 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
1034 }
1035
1036 // X + X*C --> X * (C+1)
1037 if (dyn_castFoldableMul(RHS, C2) == LHS)
1038 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner53a19b72010-01-05 07:18:46 +00001039 }
1040
Sylvestre Ledru94c22712012-09-27 10:14:43 +00001041 // A+B --> A|B iff A and B have no bits set in common.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001042 if (IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
Chris Lattner53a19b72010-01-05 07:18:46 +00001043 APInt LHSKnownOne(IT->getBitWidth(), 0);
1044 APInt LHSKnownZero(IT->getBitWidth(), 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00001045 ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
Chris Lattner53a19b72010-01-05 07:18:46 +00001046 if (LHSKnownZero != 0) {
1047 APInt RHSKnownOne(IT->getBitWidth(), 0);
1048 APInt RHSKnownZero(IT->getBitWidth(), 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +00001049 ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001050
Chris Lattner53a19b72010-01-05 07:18:46 +00001051 // No bits in common -> bitwise or.
1052 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
1053 return BinaryOperator::CreateOr(LHS, RHS);
1054 }
1055 }
1056
Sylvestre Ledru94c22712012-09-27 10:14:43 +00001057 // W*X + Y*Z --> W * (X+Z) iff W == Y
Chris Lattnerb9b90442011-02-10 05:14:58 +00001058 {
Chris Lattner53a19b72010-01-05 07:18:46 +00001059 Value *W, *X, *Y, *Z;
1060 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
1061 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
1062 if (W != Y) {
1063 if (W == Z) {
1064 std::swap(Y, Z);
1065 } else if (Y == X) {
1066 std::swap(W, X);
1067 } else if (X == Z) {
1068 std::swap(Y, Z);
1069 std::swap(W, X);
1070 }
1071 }
1072
1073 if (W == Y) {
1074 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
1075 return BinaryOperator::CreateMul(W, NewAdd);
1076 }
1077 }
1078 }
1079
Stephen Hines36b56882014-04-23 16:57:46 -07001080 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
1081 Value *X;
1082 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Chris Lattner53a19b72010-01-05 07:18:46 +00001083 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Stephen Hines36b56882014-04-23 16:57:46 -07001084 }
Chris Lattner53a19b72010-01-05 07:18:46 +00001085
Stephen Hines36b56882014-04-23 16:57:46 -07001086 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner53a19b72010-01-05 07:18:46 +00001087 // (X & FF00) + xx00 -> (X+xx00) & FF00
Stephen Hines36b56882014-04-23 16:57:46 -07001088 Value *X;
1089 ConstantInt *C2;
Chris Lattner53a19b72010-01-05 07:18:46 +00001090 if (LHS->hasOneUse() &&
Chris Lattnerb9b90442011-02-10 05:14:58 +00001091 match(LHS, m_And(m_Value(X), m_ConstantInt(C2))) &&
1092 CRHS->getValue() == (CRHS->getValue() & C2->getValue())) {
1093 // See if all bits from the first bit set in the Add RHS up are included
1094 // in the mask. First, get the rightmost bit.
1095 const APInt &AddRHSV = CRHS->getValue();
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001096
Chris Lattnerb9b90442011-02-10 05:14:58 +00001097 // Form a mask of all bits from the lowest bit added through the top.
1098 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattner53a19b72010-01-05 07:18:46 +00001099
Chris Lattnerb9b90442011-02-10 05:14:58 +00001100 // See if the and mask includes all of these bits.
1101 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Chris Lattner53a19b72010-01-05 07:18:46 +00001102
Chris Lattnerb9b90442011-02-10 05:14:58 +00001103 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1104 // Okay, the xform is safe. Insert the new add pronto.
1105 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
1106 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattner53a19b72010-01-05 07:18:46 +00001107 }
1108 }
1109
1110 // Try to fold constant add into select arguments.
1111 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1112 if (Instruction *R = FoldOpIntoSelect(I, SI))
1113 return R;
1114 }
1115
1116 // add (select X 0 (sub n A)) A --> select X A n
1117 {
1118 SelectInst *SI = dyn_cast<SelectInst>(LHS);
1119 Value *A = RHS;
1120 if (!SI) {
1121 SI = dyn_cast<SelectInst>(RHS);
1122 A = LHS;
1123 }
1124 if (SI && SI->hasOneUse()) {
1125 Value *TV = SI->getTrueValue();
1126 Value *FV = SI->getFalseValue();
1127 Value *N;
1128
1129 // Can we fold the add into the argument of the select?
1130 // We check both true and false select arguments for a matching subtract.
Chris Lattnerb9b90442011-02-10 05:14:58 +00001131 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner53a19b72010-01-05 07:18:46 +00001132 // Fold the add into the true select value.
1133 return SelectInst::Create(SI->getCondition(), N, A);
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001134
Chris Lattnerb9b90442011-02-10 05:14:58 +00001135 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner53a19b72010-01-05 07:18:46 +00001136 // Fold the add into the false select value.
1137 return SelectInst::Create(SI->getCondition(), A, N);
1138 }
1139 }
1140
1141 // Check for (add (sext x), y), see if we can merge this into an
1142 // integer add followed by a sext.
1143 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
1144 // (add (sext x), cst) --> (sext (add x, cst'))
1145 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001146 Constant *CI =
Chris Lattner53a19b72010-01-05 07:18:46 +00001147 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
1148 if (LHSConv->hasOneUse() &&
1149 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
1150 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
1151 // Insert the new, smaller add.
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001152 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner53a19b72010-01-05 07:18:46 +00001153 CI, "addconv");
1154 return new SExtInst(NewAdd, I.getType());
1155 }
1156 }
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001157
Chris Lattner53a19b72010-01-05 07:18:46 +00001158 // (add (sext x), (sext y)) --> (sext (add int x, y))
1159 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
1160 // Only do this if x/y have the same type, if at last one of them has a
1161 // single use (so we don't increase the number of sexts), and if the
1162 // integer add will not overflow.
1163 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
1164 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1165 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
1166 RHSConv->getOperand(0))) {
1167 // Insert the new integer add.
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001168 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner3168c7d2010-01-05 20:56:24 +00001169 RHSConv->getOperand(0), "addconv");
Chris Lattner53a19b72010-01-05 07:18:46 +00001170 return new SExtInst(NewAdd, I.getType());
1171 }
1172 }
1173 }
1174
Chad Rosierc1fc5e42012-04-26 23:29:14 +00001175 // Check for (x & y) + (x ^ y)
1176 {
1177 Value *A = 0, *B = 0;
1178 if (match(RHS, m_Xor(m_Value(A), m_Value(B))) &&
1179 (match(LHS, m_And(m_Specific(A), m_Specific(B))) ||
1180 match(LHS, m_And(m_Specific(B), m_Specific(A)))))
1181 return BinaryOperator::CreateOr(A, B);
1182
1183 if (match(LHS, m_Xor(m_Value(A), m_Value(B))) &&
1184 (match(RHS, m_And(m_Specific(A), m_Specific(B))) ||
1185 match(RHS, m_And(m_Specific(B), m_Specific(A)))))
1186 return BinaryOperator::CreateOr(A, B);
1187 }
1188
Chris Lattner53a19b72010-01-05 07:18:46 +00001189 return Changed ? &I : 0;
1190}
1191
1192Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
Duncan Sands096aa792010-11-13 15:10:37 +00001193 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner53a19b72010-01-05 07:18:46 +00001194 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1195
Stephen Hines36b56882014-04-23 16:57:46 -07001196 if (Value *V = SimplifyFAddInst(LHS, RHS, I.getFastMathFlags(), DL))
Michael Ilsemanc244f382012-12-12 00:28:32 +00001197 return ReplaceInstUsesWith(I, V);
Chris Lattner53a19b72010-01-05 07:18:46 +00001198
Stephen Lina98ce502013-07-20 07:13:13 +00001199 if (isa<Constant>(RHS)) {
1200 if (isa<PHINode>(LHS))
1201 if (Instruction *NV = FoldOpIntoPhi(I))
1202 return NV;
1203
1204 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1205 if (Instruction *NV = FoldOpIntoSelect(I, SI))
1206 return NV;
1207 }
Michael Ilseman07acee72012-12-14 22:08:26 +00001208
Chris Lattner53a19b72010-01-05 07:18:46 +00001209 // -A + B --> B - A
1210 // -A + -B --> -(A + B)
Stephen Hines36b56882014-04-23 16:57:46 -07001211 if (Value *LHSV = dyn_castFNegVal(LHS)) {
1212 Instruction *RI = BinaryOperator::CreateFSub(RHS, LHSV);
1213 RI->copyFastMathFlags(&I);
1214 return RI;
1215 }
Chris Lattner53a19b72010-01-05 07:18:46 +00001216
1217 // A + -B --> A - B
1218 if (!isa<Constant>(RHS))
Stephen Hines36b56882014-04-23 16:57:46 -07001219 if (Value *V = dyn_castFNegVal(RHS)) {
1220 Instruction *RI = BinaryOperator::CreateFSub(LHS, V);
1221 RI->copyFastMathFlags(&I);
1222 return RI;
1223 }
Chris Lattner53a19b72010-01-05 07:18:46 +00001224
Dan Gohmana9445e12010-03-02 01:11:08 +00001225 // Check for (fadd double (sitofp x), y), see if we can merge this into an
Chris Lattner53a19b72010-01-05 07:18:46 +00001226 // integer add followed by a promotion.
1227 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
Dan Gohmana9445e12010-03-02 01:11:08 +00001228 // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
Chris Lattner53a19b72010-01-05 07:18:46 +00001229 // ... if the constant fits in the integer value. This is useful for things
1230 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
1231 // requires a constant pool load, and generally allows the add to be better
1232 // instcombined.
1233 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001234 Constant *CI =
Chris Lattner53a19b72010-01-05 07:18:46 +00001235 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
1236 if (LHSConv->hasOneUse() &&
1237 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
1238 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
1239 // Insert the new integer add.
1240 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1241 CI, "addconv");
1242 return new SIToFPInst(NewAdd, I.getType());
1243 }
1244 }
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001245
Dan Gohmana9445e12010-03-02 01:11:08 +00001246 // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
Chris Lattner53a19b72010-01-05 07:18:46 +00001247 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
1248 // Only do this if x/y have the same type, if at last one of them has a
1249 // single use (so we don't increase the number of int->fp conversions),
1250 // and if the integer add will not overflow.
1251 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
1252 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1253 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
1254 RHSConv->getOperand(0))) {
1255 // Insert the new integer add.
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001256 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner53a19b72010-01-05 07:18:46 +00001257 RHSConv->getOperand(0),"addconv");
1258 return new SIToFPInst(NewAdd, I.getType());
1259 }
1260 }
1261 }
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001262
Jean-Luc Dupratc5cf6e52013-05-06 16:55:50 +00001263 // select C, 0, B + select C, A, 0 -> select C, A, B
1264 {
1265 Value *A1, *B1, *C1, *A2, *B2, *C2;
1266 if (match(LHS, m_Select(m_Value(C1), m_Value(A1), m_Value(B1))) &&
1267 match(RHS, m_Select(m_Value(C2), m_Value(A2), m_Value(B2)))) {
1268 if (C1 == C2) {
1269 Constant *Z1=0, *Z2=0;
1270 Value *A, *B, *C=C1;
1271 if (match(A1, m_AnyZero()) && match(B2, m_AnyZero())) {
1272 Z1 = dyn_cast<Constant>(A1); A = A2;
1273 Z2 = dyn_cast<Constant>(B2); B = B1;
1274 } else if (match(B1, m_AnyZero()) && match(A2, m_AnyZero())) {
1275 Z1 = dyn_cast<Constant>(B1); B = B2;
1276 Z2 = dyn_cast<Constant>(A2); A = A1;
1277 }
1278
1279 if (Z1 && Z2 &&
1280 (I.hasNoSignedZeros() ||
1281 (Z1->isNegativeZeroValue() && Z2->isNegativeZeroValue()))) {
1282 return SelectInst::Create(C, A, B);
1283 }
1284 }
1285 }
1286 }
1287
Shuxin Yang1a315002012-12-18 23:10:12 +00001288 if (I.hasUnsafeAlgebra()) {
1289 if (Value *V = FAddCombine(Builder).simplify(&I))
1290 return ReplaceInstUsesWith(I, V);
1291 }
1292
Chris Lattner53a19b72010-01-05 07:18:46 +00001293 return Changed ? &I : 0;
1294}
1295
1296
Chris Lattner53a19b72010-01-05 07:18:46 +00001297/// Optimize pointer differences into the same array into a size. Consider:
1298/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
1299/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
1300///
1301Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001302 Type *Ty) {
Stephen Hines36b56882014-04-23 16:57:46 -07001303 assert(DL && "Must have target data info for this");
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001304
Chris Lattner53a19b72010-01-05 07:18:46 +00001305 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
1306 // this.
1307 bool Swapped = false;
Benjamin Kramerd2348632012-02-20 14:34:57 +00001308 GEPOperator *GEP1 = 0, *GEP2 = 0;
1309
Chris Lattner53a19b72010-01-05 07:18:46 +00001310 // For now we require one side to be the base pointer "A" or a constant
Benjamin Kramerd2348632012-02-20 14:34:57 +00001311 // GEP derived from it.
1312 if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
Chris Lattner53a19b72010-01-05 07:18:46 +00001313 // (gep X, ...) - X
1314 if (LHSGEP->getOperand(0) == RHS) {
Benjamin Kramerd2348632012-02-20 14:34:57 +00001315 GEP1 = LHSGEP;
Chris Lattner53a19b72010-01-05 07:18:46 +00001316 Swapped = false;
Benjamin Kramerd2348632012-02-20 14:34:57 +00001317 } else if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1318 // (gep X, ...) - (gep X, ...)
1319 if (LHSGEP->getOperand(0)->stripPointerCasts() ==
1320 RHSGEP->getOperand(0)->stripPointerCasts()) {
1321 GEP2 = RHSGEP;
1322 GEP1 = LHSGEP;
Chris Lattner53a19b72010-01-05 07:18:46 +00001323 Swapped = false;
1324 }
1325 }
1326 }
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001327
Benjamin Kramerd2348632012-02-20 14:34:57 +00001328 if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
Chris Lattner53a19b72010-01-05 07:18:46 +00001329 // X - (gep X, ...)
1330 if (RHSGEP->getOperand(0) == LHS) {
Benjamin Kramerd2348632012-02-20 14:34:57 +00001331 GEP1 = RHSGEP;
Chris Lattner53a19b72010-01-05 07:18:46 +00001332 Swapped = true;
Benjamin Kramerd2348632012-02-20 14:34:57 +00001333 } else if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1334 // (gep X, ...) - (gep X, ...)
1335 if (RHSGEP->getOperand(0)->stripPointerCasts() ==
1336 LHSGEP->getOperand(0)->stripPointerCasts()) {
1337 GEP2 = LHSGEP;
1338 GEP1 = RHSGEP;
Chris Lattner53a19b72010-01-05 07:18:46 +00001339 Swapped = true;
1340 }
1341 }
1342 }
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001343
Benjamin Kramerd2348632012-02-20 14:34:57 +00001344 // Avoid duplicating the arithmetic if GEP2 has non-constant indices and
1345 // multiple users.
1346 if (GEP1 == 0 ||
1347 (GEP2 != 0 && !GEP2->hasAllConstantIndices() && !GEP2->hasOneUse()))
Chris Lattner53a19b72010-01-05 07:18:46 +00001348 return 0;
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001349
Chris Lattner53a19b72010-01-05 07:18:46 +00001350 // Emit the offset of the GEP and an intptr_t.
Benjamin Kramerd2348632012-02-20 14:34:57 +00001351 Value *Result = EmitGEPOffset(GEP1);
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001352
Chris Lattner53a19b72010-01-05 07:18:46 +00001353 // If we had a constant expression GEP on the other side offsetting the
1354 // pointer, subtract it from the offset we have.
Benjamin Kramerd2348632012-02-20 14:34:57 +00001355 if (GEP2) {
1356 Value *Offset = EmitGEPOffset(GEP2);
1357 Result = Builder->CreateSub(Result, Offset);
Chris Lattner53a19b72010-01-05 07:18:46 +00001358 }
Chris Lattner53a19b72010-01-05 07:18:46 +00001359
1360 // If we have p - gep(p, ...) then we have to negate the result.
1361 if (Swapped)
1362 Result = Builder->CreateNeg(Result, "diff.neg");
1363
1364 return Builder->CreateIntCast(Result, Ty, true);
1365}
1366
1367
1368Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1369 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1370
Duncan Sandsfea3b212010-12-15 14:07:39 +00001371 if (Value *V = SimplifySubInst(Op0, Op1, I.hasNoSignedWrap(),
Stephen Hines36b56882014-04-23 16:57:46 -07001372 I.hasNoUnsignedWrap(), DL))
Duncan Sandsfea3b212010-12-15 14:07:39 +00001373 return ReplaceInstUsesWith(I, V);
Chris Lattner53a19b72010-01-05 07:18:46 +00001374
Duncan Sands37bf92b2010-12-22 13:36:08 +00001375 // (A*B)-(A*C) -> A*(B-C) etc
1376 if (Value *V = SimplifyUsingDistributiveLaws(I))
1377 return ReplaceInstUsesWith(I, V);
1378
Chris Lattner53a19b72010-01-05 07:18:46 +00001379 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
1380 if (Value *V = dyn_castNegVal(Op1)) {
1381 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
1382 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
1383 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1384 return Res;
1385 }
1386
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001387 if (I.getType()->isIntegerTy(1))
Chris Lattner53a19b72010-01-05 07:18:46 +00001388 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattnerb9b90442011-02-10 05:14:58 +00001389
1390 // Replace (-1 - A) with (~A).
1391 if (match(Op0, m_AllOnes()))
1392 return BinaryOperator::CreateNot(Op1);
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001393
Stephen Hines36b56882014-04-23 16:57:46 -07001394 if (Constant *C = dyn_cast<Constant>(Op0)) {
Chris Lattner53a19b72010-01-05 07:18:46 +00001395 // C - ~X == X + (1+C)
1396 Value *X = 0;
1397 if (match(Op1, m_Not(m_Value(X))))
1398 return BinaryOperator::CreateAdd(X, AddOne(C));
1399
Stephen Hines36b56882014-04-23 16:57:46 -07001400 // Try to fold constant sub into select arguments.
1401 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1402 if (Instruction *R = FoldOpIntoSelect(I, SI))
1403 return R;
1404
1405 // C-(X+C2) --> (C-C2)-X
1406 Constant *C2;
1407 if (match(Op1, m_Add(m_Value(X), m_Constant(C2))))
1408 return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
1409
1410 if (SimplifyDemandedInstructionBits(I))
1411 return &I;
1412
1413 // Fold (sub 0, (zext bool to B)) --> (sext bool to B)
1414 if (C->isNullValue() && match(Op1, m_ZExt(m_Value(X))))
1415 if (X->getType()->getScalarType()->isIntegerTy(1))
1416 return CastInst::CreateSExtOrBitCast(X, Op1->getType());
1417
1418 // Fold (sub 0, (sext bool to B)) --> (zext bool to B)
1419 if (C->isNullValue() && match(Op1, m_SExt(m_Value(X))))
1420 if (X->getType()->getScalarType()->isIntegerTy(1))
1421 return CastInst::CreateZExtOrBitCast(X, Op1->getType());
1422 }
1423
1424 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner53a19b72010-01-05 07:18:46 +00001425 // -(X >>u 31) -> (X >>s 31)
1426 // -(X >>s 31) -> (X >>u 31)
1427 if (C->isZero()) {
Chris Lattnerb9b90442011-02-10 05:14:58 +00001428 Value *X; ConstantInt *CI;
1429 if (match(Op1, m_LShr(m_Value(X), m_ConstantInt(CI))) &&
1430 // Verify we are shifting out everything but the sign bit.
1431 CI->getValue() == I.getType()->getPrimitiveSizeInBits()-1)
1432 return BinaryOperator::CreateAShr(X, CI);
1433
1434 if (match(Op1, m_AShr(m_Value(X), m_ConstantInt(CI))) &&
1435 // Verify we are shifting out everything but the sign bit.
1436 CI->getValue() == I.getType()->getPrimitiveSizeInBits()-1)
1437 return BinaryOperator::CreateLShr(X, CI);
Chris Lattner53a19b72010-01-05 07:18:46 +00001438 }
Chris Lattner53a19b72010-01-05 07:18:46 +00001439 }
1440
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001441
Chris Lattnerb9b90442011-02-10 05:14:58 +00001442 { Value *Y;
1443 // X-(X+Y) == -Y X-(Y+X) == -Y
1444 if (match(Op1, m_Add(m_Specific(Op0), m_Value(Y))) ||
1445 match(Op1, m_Add(m_Value(Y), m_Specific(Op0))))
1446 return BinaryOperator::CreateNeg(Y);
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001447
Chris Lattnerb9b90442011-02-10 05:14:58 +00001448 // (X-Y)-X == -Y
1449 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
1450 return BinaryOperator::CreateNeg(Y);
1451 }
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001452
Chris Lattnerb9b90442011-02-10 05:14:58 +00001453 if (Op1->hasOneUse()) {
1454 Value *X = 0, *Y = 0, *Z = 0;
1455 Constant *C = 0;
Stephen Hines36b56882014-04-23 16:57:46 -07001456 Constant *CI = 0;
Chris Lattnerb9b90442011-02-10 05:14:58 +00001457
1458 // (X - (Y - Z)) --> (X + (Z - Y)).
1459 if (match(Op1, m_Sub(m_Value(Y), m_Value(Z))))
1460 return BinaryOperator::CreateAdd(Op0,
1461 Builder->CreateSub(Z, Y, Op1->getName()));
1462
1463 // (X - (X & Y)) --> (X & ~Y)
1464 //
1465 if (match(Op1, m_And(m_Value(Y), m_Specific(Op0))) ||
1466 match(Op1, m_And(m_Specific(Op0), m_Value(Y))))
1467 return BinaryOperator::CreateAnd(Op0,
1468 Builder->CreateNot(Y, Y->getName() + ".not"));
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001469
Chris Lattnerb9b90442011-02-10 05:14:58 +00001470 // 0 - (X sdiv C) -> (X sdiv -C)
1471 if (match(Op1, m_SDiv(m_Value(X), m_Constant(C))) &&
1472 match(Op0, m_Zero()))
1473 return BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(C));
1474
1475 // 0 - (X << Y) -> (-X << Y) when X is freely negatable.
1476 if (match(Op1, m_Shl(m_Value(X), m_Value(Y))) && match(Op0, m_Zero()))
1477 if (Value *XNeg = dyn_castNegVal(X))
1478 return BinaryOperator::CreateShl(XNeg, Y);
1479
1480 // X - X*C --> X * (1-C)
Stephen Hines36b56882014-04-23 16:57:46 -07001481 if (match(Op1, m_Mul(m_Specific(Op0), m_Constant(CI)))) {
Chris Lattnerb9b90442011-02-10 05:14:58 +00001482 Constant *CP1 = ConstantExpr::getSub(ConstantInt::get(I.getType(),1), CI);
1483 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattner53a19b72010-01-05 07:18:46 +00001484 }
1485
Chris Lattnerb9b90442011-02-10 05:14:58 +00001486 // X - X<<C --> X * (1-(1<<C))
Stephen Hines36b56882014-04-23 16:57:46 -07001487 if (match(Op1, m_Shl(m_Specific(Op0), m_Constant(CI)))) {
Chris Lattnerb9b90442011-02-10 05:14:58 +00001488 Constant *One = ConstantInt::get(I.getType(), 1);
1489 C = ConstantExpr::getSub(One, ConstantExpr::getShl(One, CI));
1490 return BinaryOperator::CreateMul(Op0, C);
1491 }
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001492
Chris Lattnerb9b90442011-02-10 05:14:58 +00001493 // X - A*-B -> X + A*B
1494 // X - -A*B -> X + A*B
1495 Value *A, *B;
1496 if (match(Op1, m_Mul(m_Value(A), m_Neg(m_Value(B)))) ||
1497 match(Op1, m_Mul(m_Neg(m_Value(A)), m_Value(B))))
1498 return BinaryOperator::CreateAdd(Op0, Builder->CreateMul(A, B));
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001499
Chris Lattnerb9b90442011-02-10 05:14:58 +00001500 // X - A*CI -> X + A*-CI
1501 // X - CI*A -> X + A*-CI
Stephen Hines36b56882014-04-23 16:57:46 -07001502 if (match(Op1, m_Mul(m_Value(A), m_Constant(CI))) ||
1503 match(Op1, m_Mul(m_Constant(CI), m_Value(A)))) {
Chris Lattnerb9b90442011-02-10 05:14:58 +00001504 Value *NewMul = Builder->CreateMul(A, ConstantExpr::getNeg(CI));
1505 return BinaryOperator::CreateAdd(Op0, NewMul);
Chris Lattner53a19b72010-01-05 07:18:46 +00001506 }
1507 }
1508
Stephen Hines36b56882014-04-23 16:57:46 -07001509 Constant *C1;
Chris Lattner53a19b72010-01-05 07:18:46 +00001510 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1511 if (X == Op1) // X*C - X --> X * (C-1)
1512 return BinaryOperator::CreateMul(Op1, SubOne(C1));
1513
Stephen Hines36b56882014-04-23 16:57:46 -07001514 Constant *C2; // X*C1 - X*C2 -> X * (C1-C2)
Chris Lattner53a19b72010-01-05 07:18:46 +00001515 if (X == dyn_castFoldableMul(Op1, C2))
1516 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
1517 }
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001518
Chris Lattner53a19b72010-01-05 07:18:46 +00001519 // Optimize pointer differences into the same array into a size. Consider:
1520 // &A[10] - &A[0]: we should compile this to "10".
Stephen Hines36b56882014-04-23 16:57:46 -07001521 if (DL) {
Chris Lattner53a19b72010-01-05 07:18:46 +00001522 Value *LHSOp, *RHSOp;
1523 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
1524 match(Op1, m_PtrToInt(m_Value(RHSOp))))
1525 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1526 return ReplaceInstUsesWith(I, Res);
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001527
Chris Lattner53a19b72010-01-05 07:18:46 +00001528 // trunc(p)-trunc(q) -> trunc(p-q)
1529 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
1530 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
1531 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1532 return ReplaceInstUsesWith(I, Res);
1533 }
Michael Ilseman4d96e6f2012-12-12 20:57:53 +00001534
Chris Lattner53a19b72010-01-05 07:18:46 +00001535 return 0;
1536}
1537
1538Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
1539 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1540
Stephen Hines36b56882014-04-23 16:57:46 -07001541 if (Value *V = SimplifyFSubInst(Op0, Op1, I.getFastMathFlags(), DL))
Michael Ilsemanc244f382012-12-12 00:28:32 +00001542 return ReplaceInstUsesWith(I, V);
1543
Stephen Lina98ce502013-07-20 07:13:13 +00001544 if (isa<Constant>(Op0))
1545 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1546 if (Instruction *NV = FoldOpIntoSelect(I, SI))
1547 return NV;
1548
Owen Anderson0c326f02013-07-26 21:40:29 +00001549 // If this is a 'B = x-(-A)', change to B = x+A, potentially looking
1550 // through FP extensions/truncations along the way.
Owen Anderson605b3422013-07-30 23:53:17 +00001551 if (Value *V = dyn_castFNegVal(Op1)) {
1552 Instruction *NewI = BinaryOperator::CreateFAdd(Op0, V);
1553 NewI->copyFastMathFlags(&I);
1554 return NewI;
1555 }
Owen Anderson0c326f02013-07-26 21:40:29 +00001556 if (FPTruncInst *FPTI = dyn_cast<FPTruncInst>(Op1)) {
1557 if (Value *V = dyn_castFNegVal(FPTI->getOperand(0))) {
1558 Value *NewTrunc = Builder->CreateFPTrunc(V, I.getType());
Owen Anderson605b3422013-07-30 23:53:17 +00001559 Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewTrunc);
1560 NewI->copyFastMathFlags(&I);
1561 return NewI;
Owen Anderson0c326f02013-07-26 21:40:29 +00001562 }
1563 } else if (FPExtInst *FPEI = dyn_cast<FPExtInst>(Op1)) {
1564 if (Value *V = dyn_castFNegVal(FPEI->getOperand(0))) {
Owen Anderson107c5782013-07-26 22:06:21 +00001565 Value *NewExt = Builder->CreateFPExt(V, I.getType());
Owen Anderson605b3422013-07-30 23:53:17 +00001566 Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewExt);
1567 NewI->copyFastMathFlags(&I);
1568 return NewI;
Owen Anderson0c326f02013-07-26 21:40:29 +00001569 }
1570 }
Chris Lattner53a19b72010-01-05 07:18:46 +00001571
Shuxin Yang1a315002012-12-18 23:10:12 +00001572 if (I.hasUnsafeAlgebra()) {
1573 if (Value *V = FAddCombine(Builder).simplify(&I))
1574 return ReplaceInstUsesWith(I, V);
1575 }
1576
Chris Lattner53a19b72010-01-05 07:18:46 +00001577 return 0;
1578}