blob: b18c10dd57b62327a7f534381bee6529b4bd4841 [file] [log] [blame]
Chris Lattner82aa8882010-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 Topper58713212013-07-15 04:27:47 +000015#include "llvm/ADT/STLExtras.h"
Chris Lattner82aa8882010-01-05 07:18:46 +000016#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/DataLayout.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000018#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000019#include "llvm/IR/PatternMatch.h"
Chris Lattner82aa8882010-01-05 07:18:46 +000020using namespace llvm;
21using namespace PatternMatch;
22
Chandler Carruth964daaa2014-04-22 02:55:47 +000023#define DEBUG_TYPE "instcombine"
24
Shuxin Yang37a1efe2012-12-18 23:10:12 +000025namespace {
26
27 /// Class representing coefficient of floating-point addend.
28 /// This class needs to be highly efficient, which is especially true for
29 /// the constructor. As of I write this comment, the cost of the default
Jim Grosbachbdbd7342013-04-05 21:20:12 +000030 /// constructor is merely 4-byte-store-zero (Assuming compiler is able to
Shuxin Yang37a1efe2012-12-18 23:10:12 +000031 /// perform write-merging).
Jim Grosbachbdbd7342013-04-05 21:20:12 +000032 ///
Shuxin Yang37a1efe2012-12-18 23:10:12 +000033 class FAddendCoef {
34 public:
Suyog Sardade409fd2014-07-17 06:09:34 +000035 // The constructor has to initialize a APFloat, which is unnecessary for
Shuxin Yang37a1efe2012-12-18 23:10:12 +000036 // most addends which have coefficient either 1 or -1. So, the constructor
37 // is expensive. In order to avoid the cost of the constructor, we should
38 // reuse some instances whenever possible. The pre-created instances
39 // FAddCombine::Add[0-5] embodies this idea.
40 //
41 FAddendCoef() : IsFp(false), BufHasFpVal(false), IntVal(0) {}
42 ~FAddendCoef();
Jim Grosbachbdbd7342013-04-05 21:20:12 +000043
Shuxin Yang37a1efe2012-12-18 23:10:12 +000044 void set(short C) {
45 assert(!insaneIntVal(C) && "Insane coefficient");
46 IsFp = false; IntVal = C;
47 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000048
Shuxin Yang37a1efe2012-12-18 23:10:12 +000049 void set(const APFloat& C);
Shuxin Yang389ed4b2013-03-25 20:43:41 +000050
Shuxin Yang37a1efe2012-12-18 23:10:12 +000051 void negate();
Jim Grosbachbdbd7342013-04-05 21:20:12 +000052
Shuxin Yang37a1efe2012-12-18 23:10:12 +000053 bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); }
54 Value *getValue(Type *) const;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000055
Shuxin Yang37a1efe2012-12-18 23:10:12 +000056 // If possible, don't define operator+/operator- etc because these
57 // operators inevitably call FAddendCoef's constructor which is not cheap.
58 void operator=(const FAddendCoef &A);
59 void operator+=(const FAddendCoef &A);
60 void operator-=(const FAddendCoef &A);
61 void operator*=(const FAddendCoef &S);
Jim Grosbachbdbd7342013-04-05 21:20:12 +000062
Shuxin Yang37a1efe2012-12-18 23:10:12 +000063 bool isOne() const { return isInt() && IntVal == 1; }
64 bool isTwo() const { return isInt() && IntVal == 2; }
65 bool isMinusOne() const { return isInt() && IntVal == -1; }
66 bool isMinusTwo() const { return isInt() && IntVal == -2; }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000067
Shuxin Yang37a1efe2012-12-18 23:10:12 +000068 private:
69 bool insaneIntVal(int V) { return V > 4 || V < -4; }
70 APFloat *getFpValPtr(void)
Shuxin Yang5b841c42012-12-19 01:10:17 +000071 { return reinterpret_cast<APFloat*>(&FpValBuf.buffer[0]); }
David Greene530430b2013-01-14 21:04:40 +000072 const APFloat *getFpValPtr(void) const
73 { return reinterpret_cast<const APFloat*>(&FpValBuf.buffer[0]); }
Shuxin Yang37a1efe2012-12-18 23:10:12 +000074
75 const APFloat &getFpVal(void) const {
76 assert(IsFp && BufHasFpVal && "Incorret state");
David Greene530430b2013-01-14 21:04:40 +000077 return *getFpValPtr();
Shuxin Yang37a1efe2012-12-18 23:10:12 +000078 }
79
Jim Grosbachbdbd7342013-04-05 21:20:12 +000080 APFloat &getFpVal(void) {
81 assert(IsFp && BufHasFpVal && "Incorret state");
82 return *getFpValPtr();
83 }
84
Shuxin Yang37a1efe2012-12-18 23:10:12 +000085 bool isInt() const { return !IsFp; }
86
Shuxin Yang389ed4b2013-03-25 20:43:41 +000087 // If the coefficient is represented by an integer, promote it to a
Jim Grosbachbdbd7342013-04-05 21:20:12 +000088 // floating point.
Shuxin Yang389ed4b2013-03-25 20:43:41 +000089 void convertToFpType(const fltSemantics &Sem);
90
91 // Construct an APFloat from a signed integer.
92 // TODO: We should get rid of this function when APFloat can be constructed
Jim Grosbachbdbd7342013-04-05 21:20:12 +000093 // from an *SIGNED* integer.
Shuxin Yang389ed4b2013-03-25 20:43:41 +000094 APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val);
Shuxin Yang37a1efe2012-12-18 23:10:12 +000095 private:
Shuxin Yang5b841c42012-12-19 01:10:17 +000096
Shuxin Yang37a1efe2012-12-18 23:10:12 +000097 bool IsFp;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000098
Shuxin Yang37a1efe2012-12-18 23:10:12 +000099 // True iff FpValBuf contains an instance of APFloat.
100 bool BufHasFpVal;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000101
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000102 // The integer coefficient of an individual addend is either 1 or -1,
103 // and we try to simplify at most 4 addends from neighboring at most
104 // two instructions. So the range of <IntVal> falls in [-4, 4]. APInt
105 // is overkill of this end.
106 short IntVal;
Shuxin Yang5b841c42012-12-19 01:10:17 +0000107
108 AlignedCharArrayUnion<APFloat> FpValBuf;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000109 };
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000110
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000111 /// FAddend is used to represent floating-point addend. An addend is
112 /// represented as <C, V>, where the V is a symbolic value, and C is a
113 /// constant coefficient. A constant addend is represented as <C, 0>.
114 ///
115 class FAddend {
116 public:
Craig Topperf40110f2014-04-25 05:29:35 +0000117 FAddend() { Val = nullptr; }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000118
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000119 Value *getSymVal (void) const { return Val; }
120 const FAddendCoef &getCoef(void) const { return Coeff; }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000121
Craig Topperf40110f2014-04-25 05:29:35 +0000122 bool isConstant() const { return Val == nullptr; }
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000123 bool isZero() const { return Coeff.isZero(); }
124
125 void set(short Coefficient, Value *V) { Coeff.set(Coefficient), Val = V; }
126 void set(const APFloat& Coefficient, Value *V)
127 { Coeff.set(Coefficient); Val = V; }
128 void set(const ConstantFP* Coefficient, Value *V)
129 { Coeff.set(Coefficient->getValueAPF()); Val = V; }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000130
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000131 void negate() { Coeff.negate(); }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000132
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000133 /// Drill down the U-D chain one step to find the definition of V, and
134 /// try to break the definition into one or two addends.
135 static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000136
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000137 /// Similar to FAddend::drillDownOneStep() except that the value being
138 /// splitted is the addend itself.
139 unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000140
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000141 void operator+=(const FAddend &T) {
142 assert((Val == T.Val) && "Symbolic-values disagree");
143 Coeff += T.Coeff;
144 }
145
146 private:
147 void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000148
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000149 // This addend has the value of "Coeff * Val".
150 Value *Val;
151 FAddendCoef Coeff;
152 };
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000153
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000154 /// FAddCombine is the class for optimizing an unsafe fadd/fsub along
155 /// with its neighboring at most two instructions.
156 ///
157 class FAddCombine {
158 public:
Craig Topperf40110f2014-04-25 05:29:35 +0000159 FAddCombine(InstCombiner::BuilderTy *B) : Builder(B), Instr(nullptr) {}
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000160 Value *simplify(Instruction *FAdd);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000161
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000162 private:
163 typedef SmallVector<const FAddend*, 4> AddendVect;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000164
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000165 Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000166
167 Value *performFactorization(Instruction *I);
168
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000169 /// Convert given addend to a Value
170 Value *createAddendVal(const FAddend &A, bool& NeedNeg);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000171
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000172 /// Return the number of instructions needed to emit the N-ary addition.
173 unsigned calcInstrNumber(const AddendVect& Vect);
174 Value *createFSub(Value *Opnd0, Value *Opnd1);
175 Value *createFAdd(Value *Opnd0, Value *Opnd1);
176 Value *createFMul(Value *Opnd0, Value *Opnd1);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000177 Value *createFDiv(Value *Opnd0, Value *Opnd1);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000178 Value *createFNeg(Value *V);
179 Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
Owen Anderson1664dc82014-01-20 07:44:53 +0000180 void createInstPostProc(Instruction *NewInst, bool NoNumber = false);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000181
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000182 InstCombiner::BuilderTy *Builder;
183 Instruction *Instr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000184
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000185 private:
186 // Debugging stuff are clustered here.
187 #ifndef NDEBUG
188 unsigned CreateInstrNum;
189 void initCreateInstNum() { CreateInstrNum = 0; }
190 void incCreateInstNum() { CreateInstrNum++; }
191 #else
192 void initCreateInstNum() {}
193 void incCreateInstNum() {}
194 #endif
195 };
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000196}
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000197
198//===----------------------------------------------------------------------===//
199//
200// Implementation of
201// {FAddendCoef, FAddend, FAddition, FAddCombine}.
202//
203//===----------------------------------------------------------------------===//
204FAddendCoef::~FAddendCoef() {
205 if (BufHasFpVal)
206 getFpValPtr()->~APFloat();
207}
208
209void FAddendCoef::set(const APFloat& C) {
210 APFloat *P = getFpValPtr();
211
212 if (isInt()) {
213 // As the buffer is meanless byte stream, we cannot call
214 // APFloat::operator=().
215 new(P) APFloat(C);
216 } else
217 *P = C;
218
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000219 IsFp = BufHasFpVal = true;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000220}
221
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000222void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
223 if (!isInt())
224 return;
225
226 APFloat *P = getFpValPtr();
227 if (IntVal > 0)
228 new(P) APFloat(Sem, IntVal);
229 else {
230 new(P) APFloat(Sem, 0 - IntVal);
231 P->changeSign();
232 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000233 IsFp = BufHasFpVal = true;
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000234}
235
236APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
237 if (Val >= 0)
238 return APFloat(Sem, Val);
239
240 APFloat T(Sem, 0 - Val);
241 T.changeSign();
242
243 return T;
244}
245
246void FAddendCoef::operator=(const FAddendCoef &That) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000247 if (That.isInt())
248 set(That.IntVal);
249 else
250 set(That.getFpVal());
251}
252
253void FAddendCoef::operator+=(const FAddendCoef &That) {
254 enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
255 if (isInt() == That.isInt()) {
256 if (isInt())
257 IntVal += That.IntVal;
258 else
259 getFpVal().add(That.getFpVal(), RndMode);
260 return;
261 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000262
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000263 if (isInt()) {
264 const APFloat &T = That.getFpVal();
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000265 convertToFpType(T.getSemantics());
266 getFpVal().add(T, RndMode);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000267 return;
268 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000269
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000270 APFloat &T = getFpVal();
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000271 T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000272}
273
274void FAddendCoef::operator-=(const FAddendCoef &That) {
275 enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
276 if (isInt() == That.isInt()) {
277 if (isInt())
278 IntVal -= That.IntVal;
279 else
280 getFpVal().subtract(That.getFpVal(), RndMode);
281 return;
282 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000283
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000284 if (isInt()) {
285 const APFloat &T = That.getFpVal();
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000286 convertToFpType(T.getSemantics());
287 getFpVal().subtract(T, RndMode);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000288 return;
289 }
290
291 APFloat &T = getFpVal();
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000292 T.subtract(createAPFloatFromInt(T.getSemantics(), IntVal), RndMode);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000293}
294
295void FAddendCoef::operator*=(const FAddendCoef &That) {
296 if (That.isOne())
297 return;
298
299 if (That.isMinusOne()) {
300 negate();
301 return;
302 }
303
304 if (isInt() && That.isInt()) {
305 int Res = IntVal * (int)That.IntVal;
306 assert(!insaneIntVal(Res) && "Insane int value");
307 IntVal = Res;
308 return;
309 }
310
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000311 const fltSemantics &Semantic =
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000312 isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
313
314 if (isInt())
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000315 convertToFpType(Semantic);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000316 APFloat &F0 = getFpVal();
317
318 if (That.isInt())
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000319 F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
320 APFloat::rmNearestTiesToEven);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000321 else
322 F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven);
323
324 return;
325}
326
327void FAddendCoef::negate() {
328 if (isInt())
329 IntVal = 0 - IntVal;
330 else
331 getFpVal().changeSign();
332}
333
334Value *FAddendCoef::getValue(Type *Ty) const {
335 return isInt() ?
336 ConstantFP::get(Ty, float(IntVal)) :
337 ConstantFP::get(Ty->getContext(), getFpVal());
338}
339
340// The definition of <Val> Addends
341// =========================================
342// A + B <1, A>, <1,B>
343// A - B <1, A>, <1,B>
344// 0 - B <-1, B>
345// C * A, <C, A>
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000346// A + C <1, A> <C, NULL>
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000347// 0 +/- 0 <0, NULL> (corner case)
348//
349// Legend: A and B are not constant, C is constant
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000350//
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000351unsigned FAddend::drillValueDownOneStep
352 (Value *Val, FAddend &Addend0, FAddend &Addend1) {
Craig Topperf40110f2014-04-25 05:29:35 +0000353 Instruction *I = nullptr;
354 if (!Val || !(I = dyn_cast<Instruction>(Val)))
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000355 return 0;
356
357 unsigned Opcode = I->getOpcode();
358
359 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
360 ConstantFP *C0, *C1;
361 Value *Opnd0 = I->getOperand(0);
362 Value *Opnd1 = I->getOperand(1);
363 if ((C0 = dyn_cast<ConstantFP>(Opnd0)) && C0->isZero())
Craig Topperf40110f2014-04-25 05:29:35 +0000364 Opnd0 = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000365
366 if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
Craig Topperf40110f2014-04-25 05:29:35 +0000367 Opnd1 = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000368
369 if (Opnd0) {
370 if (!C0)
371 Addend0.set(1, Opnd0);
372 else
Craig Topperf40110f2014-04-25 05:29:35 +0000373 Addend0.set(C0, nullptr);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000374 }
375
376 if (Opnd1) {
377 FAddend &Addend = Opnd0 ? Addend1 : Addend0;
378 if (!C1)
379 Addend.set(1, Opnd1);
380 else
Craig Topperf40110f2014-04-25 05:29:35 +0000381 Addend.set(C1, nullptr);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000382 if (Opcode == Instruction::FSub)
383 Addend.negate();
384 }
385
386 if (Opnd0 || Opnd1)
387 return Opnd0 && Opnd1 ? 2 : 1;
388
389 // Both operands are zero. Weird!
Craig Topperf40110f2014-04-25 05:29:35 +0000390 Addend0.set(APFloat(C0->getValueAPF().getSemantics()), nullptr);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000391 return 1;
392 }
393
394 if (I->getOpcode() == Instruction::FMul) {
395 Value *V0 = I->getOperand(0);
396 Value *V1 = I->getOperand(1);
397 if (ConstantFP *C = dyn_cast<ConstantFP>(V0)) {
398 Addend0.set(C, V1);
399 return 1;
400 }
401
402 if (ConstantFP *C = dyn_cast<ConstantFP>(V1)) {
403 Addend0.set(C, V0);
404 return 1;
405 }
406 }
407
408 return 0;
409}
410
411// Try to break *this* addend into two addends. e.g. Suppose this addend is
412// <2.3, V>, and V = X + Y, by calling this function, we obtain two addends,
413// i.e. <2.3, X> and <2.3, Y>.
414//
415unsigned FAddend::drillAddendDownOneStep
416 (FAddend &Addend0, FAddend &Addend1) const {
417 if (isConstant())
418 return 0;
419
420 unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000421 if (!BreakNum || Coeff.isOne())
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000422 return BreakNum;
423
424 Addend0.Scale(Coeff);
425
426 if (BreakNum == 2)
427 Addend1.Scale(Coeff);
428
429 return BreakNum;
430}
431
Shuxin Yang2eca6022013-03-14 18:08:26 +0000432// Try to perform following optimization on the input instruction I. Return the
433// simplified expression if was successful; otherwise, return 0.
434//
435// Instruction "I" is Simplified into
436// -------------------------------------------------------
437// (x * y) +/- (x * z) x * (y +/- z)
438// (y / x) +/- (z / x) (y +/- z) / x
439//
440Value *FAddCombine::performFactorization(Instruction *I) {
441 assert((I->getOpcode() == Instruction::FAdd ||
442 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000443
Shuxin Yang2eca6022013-03-14 18:08:26 +0000444 Instruction *I0 = dyn_cast<Instruction>(I->getOperand(0));
445 Instruction *I1 = dyn_cast<Instruction>(I->getOperand(1));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000446
Shuxin Yang2eca6022013-03-14 18:08:26 +0000447 if (!I0 || !I1 || I0->getOpcode() != I1->getOpcode())
Craig Topperf40110f2014-04-25 05:29:35 +0000448 return nullptr;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000449
450 bool isMpy = false;
451 if (I0->getOpcode() == Instruction::FMul)
452 isMpy = true;
453 else if (I0->getOpcode() != Instruction::FDiv)
Craig Topperf40110f2014-04-25 05:29:35 +0000454 return nullptr;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000455
456 Value *Opnd0_0 = I0->getOperand(0);
457 Value *Opnd0_1 = I0->getOperand(1);
458 Value *Opnd1_0 = I1->getOperand(0);
459 Value *Opnd1_1 = I1->getOperand(1);
460
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000461 // Input Instr I Factor AddSub0 AddSub1
Shuxin Yang2eca6022013-03-14 18:08:26 +0000462 // ----------------------------------------------
463 // (x*y) +/- (x*z) x y z
464 // (y/x) +/- (z/x) x y z
465 //
Craig Topperf40110f2014-04-25 05:29:35 +0000466 Value *Factor = nullptr;
467 Value *AddSub0 = nullptr, *AddSub1 = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000468
Shuxin Yang2eca6022013-03-14 18:08:26 +0000469 if (isMpy) {
470 if (Opnd0_0 == Opnd1_0 || Opnd0_0 == Opnd1_1)
471 Factor = Opnd0_0;
472 else if (Opnd0_1 == Opnd1_0 || Opnd0_1 == Opnd1_1)
473 Factor = Opnd0_1;
474
475 if (Factor) {
476 AddSub0 = (Factor == Opnd0_0) ? Opnd0_1 : Opnd0_0;
477 AddSub1 = (Factor == Opnd1_0) ? Opnd1_1 : Opnd1_0;
478 }
479 } else if (Opnd0_1 == Opnd1_1) {
480 Factor = Opnd0_1;
481 AddSub0 = Opnd0_0;
482 AddSub1 = Opnd1_0;
483 }
484
485 if (!Factor)
Craig Topperf40110f2014-04-25 05:29:35 +0000486 return nullptr;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000487
Owen Anderson1664dc82014-01-20 07:44:53 +0000488 FastMathFlags Flags;
489 Flags.setUnsafeAlgebra();
490 if (I0) Flags &= I->getFastMathFlags();
491 if (I1) Flags &= I->getFastMathFlags();
492
Shuxin Yang2eca6022013-03-14 18:08:26 +0000493 // Create expression "NewAddSub = AddSub0 +/- AddsSub1"
494 Value *NewAddSub = (I->getOpcode() == Instruction::FAdd) ?
495 createFAdd(AddSub0, AddSub1) :
496 createFSub(AddSub0, AddSub1);
497 if (ConstantFP *CFP = dyn_cast<ConstantFP>(NewAddSub)) {
498 const APFloat &F = CFP->getValueAPF();
Michael Gottesmanc2af8d62013-06-26 23:17:31 +0000499 if (!F.isNormal())
Craig Topperf40110f2014-04-25 05:29:35 +0000500 return nullptr;
Owen Anderson1664dc82014-01-20 07:44:53 +0000501 } else if (Instruction *II = dyn_cast<Instruction>(NewAddSub))
502 II->setFastMathFlags(Flags);
503
504 if (isMpy) {
505 Value *RI = createFMul(Factor, NewAddSub);
506 if (Instruction *II = dyn_cast<Instruction>(RI))
507 II->setFastMathFlags(Flags);
508 return RI;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000509 }
510
Owen Anderson1664dc82014-01-20 07:44:53 +0000511 Value *RI = createFDiv(NewAddSub, Factor);
512 if (Instruction *II = dyn_cast<Instruction>(RI))
513 II->setFastMathFlags(Flags);
514 return RI;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000515}
516
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000517Value *FAddCombine::simplify(Instruction *I) {
518 assert(I->hasUnsafeAlgebra() && "Should be in unsafe mode");
519
520 // Currently we are not able to handle vector type.
521 if (I->getType()->isVectorTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000522 return nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000523
524 assert((I->getOpcode() == Instruction::FAdd ||
525 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
526
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000527 // Save the instruction before calling other member-functions.
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000528 Instr = I;
529
530 FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
531
532 unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
533
534 // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
535 unsigned Opnd0_ExpNum = 0;
536 unsigned Opnd1_ExpNum = 0;
537
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000538 if (!Opnd0.isConstant())
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000539 Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
540
541 // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
542 if (OpndNum == 2 && !Opnd1.isConstant())
543 Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
544
545 // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
546 if (Opnd0_ExpNum && Opnd1_ExpNum) {
547 AddendVect AllOpnds;
548 AllOpnds.push_back(&Opnd0_0);
549 AllOpnds.push_back(&Opnd1_0);
550 if (Opnd0_ExpNum == 2)
551 AllOpnds.push_back(&Opnd0_1);
552 if (Opnd1_ExpNum == 2)
553 AllOpnds.push_back(&Opnd1_1);
554
555 // Compute instruction quota. We should save at least one instruction.
556 unsigned InstQuota = 0;
557
558 Value *V0 = I->getOperand(0);
559 Value *V1 = I->getOperand(1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000560 InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000561 (!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
562
563 if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
564 return R;
565 }
566
567 if (OpndNum != 2) {
568 // The input instruction is : "I=0.0 +/- V". If the "V" were able to be
569 // splitted into two addends, say "V = X - Y", the instruction would have
570 // been optimized into "I = Y - X" in the previous steps.
571 //
572 const FAddendCoef &CE = Opnd0.getCoef();
Craig Topperf40110f2014-04-25 05:29:35 +0000573 return CE.isOne() ? Opnd0.getSymVal() : nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000574 }
575
576 // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
577 if (Opnd1_ExpNum) {
578 AddendVect AllOpnds;
579 AllOpnds.push_back(&Opnd0);
580 AllOpnds.push_back(&Opnd1_0);
581 if (Opnd1_ExpNum == 2)
582 AllOpnds.push_back(&Opnd1_1);
583
584 if (Value *R = simplifyFAdd(AllOpnds, 1))
585 return R;
586 }
587
588 // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
589 if (Opnd0_ExpNum) {
590 AddendVect AllOpnds;
591 AllOpnds.push_back(&Opnd1);
592 AllOpnds.push_back(&Opnd0_0);
593 if (Opnd0_ExpNum == 2)
594 AllOpnds.push_back(&Opnd0_1);
595
596 if (Value *R = simplifyFAdd(AllOpnds, 1))
597 return R;
598 }
599
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000600 // step 6: Try factorization as the last resort,
Shuxin Yang2eca6022013-03-14 18:08:26 +0000601 return performFactorization(I);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000602}
603
604Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
605
606 unsigned AddendNum = Addends.size();
607 assert(AddendNum <= 4 && "Too many addends");
608
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000609 // For saving intermediate results;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000610 unsigned NextTmpIdx = 0;
611 FAddend TmpResult[3];
612
613 // Points to the constant addend of the resulting simplified expression.
614 // If the resulting expr has constant-addend, this constant-addend is
615 // desirable to reside at the top of the resulting expression tree. Placing
616 // constant close to supper-expr(s) will potentially reveal some optimization
617 // opportunities in super-expr(s).
618 //
Craig Topperf40110f2014-04-25 05:29:35 +0000619 const FAddend *ConstAdd = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000620
621 // Simplified addends are placed <SimpVect>.
622 AddendVect SimpVect;
623
624 // The outer loop works on one symbolic-value at a time. Suppose the input
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000625 // addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000626 // The symbolic-values will be processed in this order: x, y, z.
627 //
628 for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
629
630 const FAddend *ThisAddend = Addends[SymIdx];
631 if (!ThisAddend) {
632 // This addend was processed before.
633 continue;
634 }
635
636 Value *Val = ThisAddend->getSymVal();
637 unsigned StartIdx = SimpVect.size();
638 SimpVect.push_back(ThisAddend);
639
640 // The inner loop collects addends sharing same symbolic-value, and these
641 // addends will be later on folded into a single addend. Following above
642 // example, if the symbolic value "y" is being processed, the inner loop
643 // will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
644 // be later on folded into "<b1+b2, y>".
645 //
646 for (unsigned SameSymIdx = SymIdx + 1;
647 SameSymIdx < AddendNum; SameSymIdx++) {
648 const FAddend *T = Addends[SameSymIdx];
649 if (T && T->getSymVal() == Val) {
650 // Set null such that next iteration of the outer loop will not process
651 // this addend again.
Craig Topperf40110f2014-04-25 05:29:35 +0000652 Addends[SameSymIdx] = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000653 SimpVect.push_back(T);
654 }
655 }
656
657 // If multiple addends share same symbolic value, fold them together.
658 if (StartIdx + 1 != SimpVect.size()) {
659 FAddend &R = TmpResult[NextTmpIdx ++];
660 R = *SimpVect[StartIdx];
661 for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
662 R += *SimpVect[Idx];
663
664 // Pop all addends being folded and push the resulting folded addend.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000665 SimpVect.resize(StartIdx);
Craig Topperf40110f2014-04-25 05:29:35 +0000666 if (Val) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000667 if (!R.isZero()) {
668 SimpVect.push_back(&R);
669 }
670 } else {
671 // Don't push constant addend at this time. It will be the last element
672 // of <SimpVect>.
673 ConstAdd = &R;
674 }
675 }
676 }
677
Craig Topper58713212013-07-15 04:27:47 +0000678 assert((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000679 "out-of-bound access");
680
681 if (ConstAdd)
682 SimpVect.push_back(ConstAdd);
683
684 Value *Result;
685 if (!SimpVect.empty())
686 Result = createNaryFAdd(SimpVect, InstrQuota);
687 else {
688 // The addition is folded to 0.0.
689 Result = ConstantFP::get(Instr->getType(), 0.0);
690 }
691
692 return Result;
693}
694
695Value *FAddCombine::createNaryFAdd
696 (const AddendVect &Opnds, unsigned InstrQuota) {
697 assert(!Opnds.empty() && "Expect at least one addend");
698
699 // Step 1: Check if the # of instructions needed exceeds the quota.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000700 //
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000701 unsigned InstrNeeded = calcInstrNumber(Opnds);
702 if (InstrNeeded > InstrQuota)
Craig Topperf40110f2014-04-25 05:29:35 +0000703 return nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000704
705 initCreateInstNum();
706
707 // step 2: Emit the N-ary addition.
708 // Note that at most three instructions are involved in Fadd-InstCombine: the
709 // addition in question, and at most two neighboring instructions.
710 // The resulting optimized addition should have at least one less instruction
711 // than the original addition expression tree. This implies that the resulting
712 // N-ary addition has at most two instructions, and we don't need to worry
713 // about tree-height when constructing the N-ary addition.
714
Craig Topperf40110f2014-04-25 05:29:35 +0000715 Value *LastVal = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000716 bool LastValNeedNeg = false;
717
718 // Iterate the addends, creating fadd/fsub using adjacent two addends.
719 for (AddendVect::const_iterator I = Opnds.begin(), E = Opnds.end();
720 I != E; I++) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000721 bool NeedNeg;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000722 Value *V = createAddendVal(**I, NeedNeg);
723 if (!LastVal) {
724 LastVal = V;
725 LastValNeedNeg = NeedNeg;
726 continue;
727 }
728
729 if (LastValNeedNeg == NeedNeg) {
730 LastVal = createFAdd(LastVal, V);
731 continue;
732 }
733
734 if (LastValNeedNeg)
735 LastVal = createFSub(V, LastVal);
736 else
737 LastVal = createFSub(LastVal, V);
738
739 LastValNeedNeg = false;
740 }
741
742 if (LastValNeedNeg) {
743 LastVal = createFNeg(LastVal);
744 }
745
746 #ifndef NDEBUG
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000747 assert(CreateInstrNum == InstrNeeded &&
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000748 "Inconsistent in instruction numbers");
749 #endif
750
751 return LastVal;
752}
753
754Value *FAddCombine::createFSub
755 (Value *Opnd0, Value *Opnd1) {
756 Value *V = Builder->CreateFSub(Opnd0, Opnd1);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000757 if (Instruction *I = dyn_cast<Instruction>(V))
758 createInstPostProc(I);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000759 return V;
760}
761
762Value *FAddCombine::createFNeg(Value *V) {
763 Value *Zero = cast<Value>(ConstantFP::get(V->getType(), 0.0));
Owen Anderson1664dc82014-01-20 07:44:53 +0000764 Value *NewV = createFSub(Zero, V);
765 if (Instruction *I = dyn_cast<Instruction>(NewV))
766 createInstPostProc(I, true); // fneg's don't receive instruction numbers.
767 return NewV;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000768}
769
770Value *FAddCombine::createFAdd
771 (Value *Opnd0, Value *Opnd1) {
772 Value *V = Builder->CreateFAdd(Opnd0, Opnd1);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000773 if (Instruction *I = dyn_cast<Instruction>(V))
774 createInstPostProc(I);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000775 return V;
776}
777
778Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
779 Value *V = Builder->CreateFMul(Opnd0, Opnd1);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000780 if (Instruction *I = dyn_cast<Instruction>(V))
781 createInstPostProc(I);
782 return V;
783}
784
785Value *FAddCombine::createFDiv(Value *Opnd0, Value *Opnd1) {
786 Value *V = Builder->CreateFDiv(Opnd0, Opnd1);
787 if (Instruction *I = dyn_cast<Instruction>(V))
788 createInstPostProc(I);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000789 return V;
790}
791
Owen Anderson1664dc82014-01-20 07:44:53 +0000792void FAddCombine::createInstPostProc(Instruction *NewInstr,
793 bool NoNumber) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000794 NewInstr->setDebugLoc(Instr->getDebugLoc());
795
796 // Keep track of the number of instruction created.
Owen Anderson1664dc82014-01-20 07:44:53 +0000797 if (!NoNumber)
798 incCreateInstNum();
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000799
800 // Propagate fast-math flags
801 NewInstr->setFastMathFlags(Instr->getFastMathFlags());
802}
803
804// Return the number of instruction needed to emit the N-ary addition.
805// NOTE: Keep this function in sync with createAddendVal().
806unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
807 unsigned OpndNum = Opnds.size();
808 unsigned InstrNeeded = OpndNum - 1;
809
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000810 // The number of addends in the form of "(-1)*x".
811 unsigned NegOpndNum = 0;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000812
813 // Adjust the number of instructions needed to emit the N-ary add.
814 for (AddendVect::const_iterator I = Opnds.begin(), E = Opnds.end();
815 I != E; I++) {
816 const FAddend *Opnd = *I;
817 if (Opnd->isConstant())
818 continue;
819
820 const FAddendCoef &CE = Opnd->getCoef();
821 if (CE.isMinusOne() || CE.isMinusTwo())
822 NegOpndNum++;
823
824 // Let the addend be "c * x". If "c == +/-1", the value of the addend
825 // is immediately available; otherwise, it needs exactly one instruction
826 // to evaluate the value.
827 if (!CE.isMinusOne() && !CE.isOne())
828 InstrNeeded++;
829 }
830 if (NegOpndNum == OpndNum)
831 InstrNeeded++;
832 return InstrNeeded;
833}
834
835// Input Addend Value NeedNeg(output)
836// ================================================================
837// Constant C C false
838// <+/-1, V> V coefficient is -1
839// <2/-2, V> "fadd V, V" coefficient is -2
840// <C, V> "fmul V, C" false
841//
842// NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
843Value *FAddCombine::createAddendVal
844 (const FAddend &Opnd, bool &NeedNeg) {
845 const FAddendCoef &Coeff = Opnd.getCoef();
846
847 if (Opnd.isConstant()) {
848 NeedNeg = false;
849 return Coeff.getValue(Instr->getType());
850 }
851
852 Value *OpndVal = Opnd.getSymVal();
853
854 if (Coeff.isMinusOne() || Coeff.isOne()) {
855 NeedNeg = Coeff.isMinusOne();
856 return OpndVal;
857 }
858
859 if (Coeff.isTwo() || Coeff.isMinusTwo()) {
860 NeedNeg = Coeff.isMinusTwo();
861 return createFAdd(OpndVal, OpndVal);
862 }
863
864 NeedNeg = false;
865 return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
866}
867
Rafael Espindola04c22582014-06-04 15:39:14 +0000868// If one of the operands only has one non-zero bit, and if the other
869// operand has a known-zero bit in a more significant place than it (not
870// including the sign bit) the ripple may go up to and fill the zero, but
871// won't change the sign. For example, (X & ~4) + 1.
872static bool checkRippleForAdd(const APInt &Op0KnownZero,
873 const APInt &Op1KnownZero) {
874 APInt Op1MaybeOne = ~Op1KnownZero;
875 // Make sure that one of the operand has at most one bit set to 1.
876 if (Op1MaybeOne.countPopulation() != 1)
877 return false;
878
879 // Find the most significant known 0 other than the sign bit.
880 int BitWidth = Op0KnownZero.getBitWidth();
881 APInt Op0KnownZeroTemp(Op0KnownZero);
882 Op0KnownZeroTemp.clearBit(BitWidth - 1);
883 int Op0ZeroPosition = BitWidth - Op0KnownZeroTemp.countLeadingZeros() - 1;
884
885 int Op1OnePosition = BitWidth - Op1MaybeOne.countLeadingZeros() - 1;
886 assert(Op1OnePosition >= 0);
887
888 // This also covers the case of no known zero, since in that case
889 // Op0ZeroPosition is -1.
890 return Op0ZeroPosition >= Op1OnePosition;
891}
Chris Lattner82aa8882010-01-05 07:18:46 +0000892
893/// WillNotOverflowSignedAdd - Return true if we can prove that:
894/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
895/// This basically requires proving that the add in the original type would not
896/// overflow to change the sign bit or have a carry out.
Rafael Espindola04c22582014-06-04 15:39:14 +0000897/// TODO: Handle this for Vectors.
Chris Lattner82aa8882010-01-05 07:18:46 +0000898bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
899 // There are different heuristics we can use for this. Here are some simple
900 // ones.
Michael Ilseman9fc0f252012-12-12 20:57:53 +0000901
Rafael Espindolad1a2c2d2014-06-02 22:01:04 +0000902 // If LHS and RHS each have at least two sign bits, the addition will look
903 // like
904 //
905 // XX..... +
906 // YY.....
907 //
908 // If the carry into the most significant position is 0, X and Y can't both
909 // be 1 and therefore the carry out of the addition is also 0.
910 //
911 // If the carry into the most significant position is 1, X and Y can't both
912 // be 0 and therefore the carry out of the addition is also 1.
913 //
914 // Since the carry into the most significant position is always equal to
915 // the carry out of the addition, there is no signed overflow.
Chris Lattner82aa8882010-01-05 07:18:46 +0000916 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
917 return true;
Michael Ilseman9fc0f252012-12-12 20:57:53 +0000918
Rafael Espindola04c22582014-06-04 15:39:14 +0000919 if (IntegerType *IT = dyn_cast<IntegerType>(LHS->getType())) {
920 int BitWidth = IT->getBitWidth();
921 APInt LHSKnownZero(BitWidth, 0);
922 APInt LHSKnownOne(BitWidth, 0);
923 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne);
Michael Ilseman9fc0f252012-12-12 20:57:53 +0000924
Rafael Espindola04c22582014-06-04 15:39:14 +0000925 APInt RHSKnownZero(BitWidth, 0);
926 APInt RHSKnownOne(BitWidth, 0);
927 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne);
Michael Ilseman9fc0f252012-12-12 20:57:53 +0000928
Rafael Espindola04c22582014-06-04 15:39:14 +0000929 // Addition of two 2's compliment numbers having opposite signs will never
930 // overflow.
931 if ((LHSKnownOne[BitWidth - 1] && RHSKnownZero[BitWidth - 1]) ||
932 (LHSKnownZero[BitWidth - 1] && RHSKnownOne[BitWidth - 1]))
933 return true;
Michael Ilseman9fc0f252012-12-12 20:57:53 +0000934
Rafael Espindola04c22582014-06-04 15:39:14 +0000935 // Check if carry bit of addition will not cause overflow.
936 if (checkRippleForAdd(LHSKnownZero, RHSKnownZero))
937 return true;
938 if (checkRippleForAdd(RHSKnownZero, LHSKnownZero))
939 return true;
940 }
Chris Lattner82aa8882010-01-05 07:18:46 +0000941 return false;
942}
943
Jingyue Wu33bd53d2014-06-17 00:42:07 +0000944/// WillNotOverflowUnsignedAdd - Return true if we can prove that:
945/// (zext (add LHS, RHS)) === (add (zext LHS), (zext RHS))
946bool InstCombiner::WillNotOverflowUnsignedAdd(Value *LHS, Value *RHS) {
947 // There are different heuristics we can use for this. Here is a simple one.
948 // If the sign bit of LHS and that of RHS are both zero, no unsigned wrap.
949 bool LHSKnownNonNegative, LHSKnownNegative;
950 bool RHSKnownNonNegative, RHSKnownNegative;
951 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, DL, 0);
952 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, DL, 0);
953 if (LHSKnownNonNegative && RHSKnownNonNegative)
954 return true;
955
956 return false;
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000957}
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000958
959// Checks if any operand is negative and we can convert add to sub.
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000960// This function checks for following negative patterns
961// ADD(XOR(OR(Z, NOT(C)), C)), 1) == NEG(AND(Z, C))
962// ADD(XOR(AND(Z, C), C), 1) == NEG(OR(Z, ~C))
963// XOR(AND(Z, C), (C + 1)) == NEG(OR(Z, ~C)) if C is even
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000964static Value *checkForNegativeOperand(BinaryOperator &I,
965 InstCombiner::BuilderTy *Builder) {
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000966 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000967
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000968 // This function creates 2 instructions to replace ADD, we need at least one
969 // of LHS or RHS to have one use to ensure benefit in transform.
970 if (!LHS->hasOneUse() && !RHS->hasOneUse())
971 return nullptr;
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000972
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000973 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
974 const APInt *C1 = nullptr, *C2 = nullptr;
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000975
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000976 // if ONE is on other side, swap
977 if (match(RHS, m_Add(m_Value(X), m_One())))
978 std::swap(LHS, RHS);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000979
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000980 if (match(LHS, m_Add(m_Value(X), m_One()))) {
981 // if XOR on other side, swap
982 if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
983 std::swap(X, RHS);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000984
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000985 if (match(X, m_Xor(m_Value(Y), m_APInt(C1)))) {
986 // X = XOR(Y, C1), Y = OR(Z, C2), C2 = NOT(C1) ==> X == NOT(AND(Z, C1))
987 // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, AND(Z, C1))
988 if (match(Y, m_Or(m_Value(Z), m_APInt(C2))) && (*C2 == ~(*C1))) {
989 Value *NewAnd = Builder->CreateAnd(Z, *C1);
990 return Builder->CreateSub(RHS, NewAnd, "sub");
991 } else if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && (*C1 == *C2)) {
992 // X = XOR(Y, C1), Y = AND(Z, C2), C2 == C1 ==> X == NOT(OR(Z, ~C1))
993 // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, OR(Z, ~C1))
994 Value *NewOr = Builder->CreateOr(Z, ~(*C1));
995 return Builder->CreateSub(RHS, NewOr, "sub");
996 }
997 }
998 }
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000999
Dinesh Dwivediadc07732014-06-27 07:47:35 +00001000 // Restore LHS and RHS
1001 LHS = I.getOperand(0);
1002 RHS = I.getOperand(1);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001003
Dinesh Dwivediadc07732014-06-27 07:47:35 +00001004 // if XOR is on other side, swap
1005 if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
1006 std::swap(LHS, RHS);
1007
1008 // C2 is ODD
1009 // LHS = XOR(Y, C1), Y = AND(Z, C2), C1 == (C2 + 1) => LHS == NEG(OR(Z, ~C2))
1010 // ADD(LHS, RHS) == SUB(RHS, OR(Z, ~C2))
1011 if (match(LHS, m_Xor(m_Value(Y), m_APInt(C1))))
1012 if (C1->countTrailingZeros() == 0)
1013 if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && *C1 == (*C2 + 1)) {
1014 Value *NewOr = Builder->CreateOr(Z, ~(*C2));
1015 return Builder->CreateSub(RHS, NewOr, "sub");
1016 }
1017 return nullptr;
1018}
1019
1020Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Dinesh Dwivedia71617352014-06-26 05:40:22 +00001021 bool Changed = SimplifyAssociativeOrCommutative(I);
1022 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Jingyue Wu33bd53d2014-06-17 00:42:07 +00001023
Dinesh Dwivedia71617352014-06-26 05:40:22 +00001024 if (Value *V = SimplifyVectorOp(I))
1025 return ReplaceInstUsesWith(I, V);
Chris Lattner82aa8882010-01-05 07:18:46 +00001026
Dinesh Dwivedia71617352014-06-26 05:40:22 +00001027 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
1028 I.hasNoUnsignedWrap(), DL))
1029 return ReplaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001030
Dinesh Dwivedia71617352014-06-26 05:40:22 +00001031 // (A*B)+(A*C) -> A*(B+C) etc
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001032 if (Value *V = SimplifyUsingDistributiveLaws(I))
1033 return ReplaceInstUsesWith(I, V);
1034
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001035 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1036 // X + (signbit) --> X ^ signbit
1037 const APInt &Val = CI->getValue();
1038 if (Val.isSignBit())
1039 return BinaryOperator::CreateXor(LHS, RHS);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001040
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001041 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1042 // (X & 254)+1 -> (X&254)|1
1043 if (SimplifyDemandedInstructionBits(I))
1044 return &I;
1045
1046 // zext(bool) + C -> bool ? C + 1 : C
1047 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
1048 if (ZI->getSrcTy()->isIntegerTy(1))
1049 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001050
Craig Topperf40110f2014-04-25 05:29:35 +00001051 Value *XorLHS = nullptr; ConstantInt *XorRHS = nullptr;
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001052 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001053 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001054 const APInt &RHSVal = CI->getValue();
Eli Friedmana2cc2872010-01-31 04:29:12 +00001055 unsigned ExtendAmt = 0;
1056 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1057 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1058 if (XorRHS->getValue() == -RHSVal) {
1059 if (RHSVal.isPowerOf2())
1060 ExtendAmt = TySizeBits - RHSVal.logBase2() - 1;
1061 else if (XorRHS->getValue().isPowerOf2())
1062 ExtendAmt = TySizeBits - XorRHS->getValue().logBase2() - 1;
Chris Lattner82aa8882010-01-05 07:18:46 +00001063 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001064
Eli Friedmana2cc2872010-01-31 04:29:12 +00001065 if (ExtendAmt) {
1066 APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt);
1067 if (!MaskedValueIsZero(XorLHS, Mask))
1068 ExtendAmt = 0;
1069 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001070
Eli Friedmana2cc2872010-01-31 04:29:12 +00001071 if (ExtendAmt) {
1072 Constant *ShAmt = ConstantInt::get(I.getType(), ExtendAmt);
1073 Value *NewShl = Builder->CreateShl(XorLHS, ShAmt, "sext");
1074 return BinaryOperator::CreateAShr(NewShl, ShAmt);
Chris Lattner82aa8882010-01-05 07:18:46 +00001075 }
Benjamin Kramerb16bd772011-12-24 17:31:53 +00001076
1077 // If this is a xor that was canonicalized from a sub, turn it back into
1078 // a sub and fuse this add with it.
1079 if (LHS->hasOneUse() && (XorRHS->getValue()+1).isPowerOf2()) {
1080 IntegerType *IT = cast<IntegerType>(I.getType());
Benjamin Kramerb16bd772011-12-24 17:31:53 +00001081 APInt LHSKnownOne(IT->getBitWidth(), 0);
1082 APInt LHSKnownZero(IT->getBitWidth(), 0);
Jay Foada0653a32014-05-14 21:14:37 +00001083 computeKnownBits(XorLHS, LHSKnownZero, LHSKnownOne);
Benjamin Kramerb16bd772011-12-24 17:31:53 +00001084 if ((XorRHS->getValue() | LHSKnownZero).isAllOnesValue())
1085 return BinaryOperator::CreateSub(ConstantExpr::getAdd(XorRHS, CI),
1086 XorLHS);
1087 }
David Majnemer70f286d2013-05-06 21:21:31 +00001088 // (X + signbit) + C could have gotten canonicalized to (X ^ signbit) + C,
1089 // transform them into (X + (signbit ^ C))
1090 if (XorRHS->getValue().isSignBit())
1091 return BinaryOperator::CreateAdd(XorLHS,
1092 ConstantExpr::getXor(XorRHS, CI));
Chris Lattner82aa8882010-01-05 07:18:46 +00001093 }
1094 }
1095
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001096 if (isa<Constant>(RHS) && isa<PHINode>(LHS))
1097 if (Instruction *NV = FoldOpIntoPhi(I))
1098 return NV;
1099
Benjamin Kramer72196f32014-01-19 15:24:22 +00001100 if (I.getType()->getScalarType()->isIntegerTy(1))
Chris Lattner82aa8882010-01-05 07:18:46 +00001101 return BinaryOperator::CreateXor(LHS, RHS);
1102
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001103 // X + X --> X << 1
Chris Lattnerd4067642011-02-17 20:55:29 +00001104 if (LHS == RHS) {
Chris Lattner55920712011-02-17 02:23:02 +00001105 BinaryOperator *New =
1106 BinaryOperator::CreateShl(LHS, ConstantInt::get(I.getType(), 1));
1107 New->setHasNoSignedWrap(I.hasNoSignedWrap());
1108 New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1109 return New;
1110 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001111
1112 // -A + B --> B - A
1113 // -A + -B --> -(A + B)
1114 if (Value *LHSV = dyn_castNegVal(LHS)) {
Nuno Lopes2710f1b2012-06-08 22:30:05 +00001115 if (!isa<Constant>(RHS))
1116 if (Value *RHSV = dyn_castNegVal(RHS)) {
1117 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
1118 return BinaryOperator::CreateNeg(NewAdd);
1119 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001120
Chris Lattner82aa8882010-01-05 07:18:46 +00001121 return BinaryOperator::CreateSub(RHS, LHSV);
1122 }
1123
1124 // A + -B --> A - B
1125 if (!isa<Constant>(RHS))
1126 if (Value *V = dyn_castNegVal(RHS))
1127 return BinaryOperator::CreateSub(LHS, V);
1128
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001129 if (Value *V = checkForNegativeOperand(I, Builder))
1130 return ReplaceInstUsesWith(I, V);
1131
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001132 // A+B --> A|B iff A and B have no bits set in common.
Chris Lattner229907c2011-07-18 04:54:35 +00001133 if (IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001134 APInt LHSKnownOne(IT->getBitWidth(), 0);
1135 APInt LHSKnownZero(IT->getBitWidth(), 0);
Jay Foada0653a32014-05-14 21:14:37 +00001136 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne);
Chris Lattner82aa8882010-01-05 07:18:46 +00001137 if (LHSKnownZero != 0) {
1138 APInt RHSKnownOne(IT->getBitWidth(), 0);
1139 APInt RHSKnownZero(IT->getBitWidth(), 0);
Jay Foada0653a32014-05-14 21:14:37 +00001140 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001141
Chris Lattner82aa8882010-01-05 07:18:46 +00001142 // No bits in common -> bitwise or.
1143 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
1144 return BinaryOperator::CreateOr(LHS, RHS);
1145 }
1146 }
1147
Benjamin Kramer72196f32014-01-19 15:24:22 +00001148 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
1149 Value *X;
1150 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Chris Lattner82aa8882010-01-05 07:18:46 +00001151 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Benjamin Kramer72196f32014-01-19 15:24:22 +00001152 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001153
Benjamin Kramer72196f32014-01-19 15:24:22 +00001154 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001155 // (X & FF00) + xx00 -> (X+xx00) & FF00
Benjamin Kramer72196f32014-01-19 15:24:22 +00001156 Value *X;
1157 ConstantInt *C2;
Chris Lattner82aa8882010-01-05 07:18:46 +00001158 if (LHS->hasOneUse() &&
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001159 match(LHS, m_And(m_Value(X), m_ConstantInt(C2))) &&
1160 CRHS->getValue() == (CRHS->getValue() & C2->getValue())) {
1161 // See if all bits from the first bit set in the Add RHS up are included
1162 // in the mask. First, get the rightmost bit.
1163 const APInt &AddRHSV = CRHS->getValue();
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001164
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001165 // Form a mask of all bits from the lowest bit added through the top.
1166 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattner82aa8882010-01-05 07:18:46 +00001167
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001168 // See if the and mask includes all of these bits.
1169 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Chris Lattner82aa8882010-01-05 07:18:46 +00001170
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001171 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1172 // Okay, the xform is safe. Insert the new add pronto.
1173 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
1174 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattner82aa8882010-01-05 07:18:46 +00001175 }
1176 }
1177
1178 // Try to fold constant add into select arguments.
1179 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1180 if (Instruction *R = FoldOpIntoSelect(I, SI))
1181 return R;
1182 }
1183
1184 // add (select X 0 (sub n A)) A --> select X A n
1185 {
1186 SelectInst *SI = dyn_cast<SelectInst>(LHS);
1187 Value *A = RHS;
1188 if (!SI) {
1189 SI = dyn_cast<SelectInst>(RHS);
1190 A = LHS;
1191 }
1192 if (SI && SI->hasOneUse()) {
1193 Value *TV = SI->getTrueValue();
1194 Value *FV = SI->getFalseValue();
1195 Value *N;
1196
1197 // Can we fold the add into the argument of the select?
1198 // We check both true and false select arguments for a matching subtract.
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001199 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner82aa8882010-01-05 07:18:46 +00001200 // Fold the add into the true select value.
1201 return SelectInst::Create(SI->getCondition(), N, A);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001202
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001203 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner82aa8882010-01-05 07:18:46 +00001204 // Fold the add into the false select value.
1205 return SelectInst::Create(SI->getCondition(), A, N);
1206 }
1207 }
1208
1209 // Check for (add (sext x), y), see if we can merge this into an
1210 // integer add followed by a sext.
1211 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
1212 // (add (sext x), cst) --> (sext (add x, cst'))
1213 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001214 Constant *CI =
Chris Lattner82aa8882010-01-05 07:18:46 +00001215 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
1216 if (LHSConv->hasOneUse() &&
1217 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
1218 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
1219 // Insert the new, smaller add.
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001220 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner82aa8882010-01-05 07:18:46 +00001221 CI, "addconv");
1222 return new SExtInst(NewAdd, I.getType());
1223 }
1224 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001225
Chris Lattner82aa8882010-01-05 07:18:46 +00001226 // (add (sext x), (sext y)) --> (sext (add int x, y))
1227 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
1228 // Only do this if x/y have the same type, if at last one of them has a
1229 // single use (so we don't increase the number of sexts), and if the
1230 // integer add will not overflow.
1231 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
1232 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1233 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
1234 RHSConv->getOperand(0))) {
1235 // Insert the new integer add.
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001236 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattnerdec68472010-01-05 20:56:24 +00001237 RHSConv->getOperand(0), "addconv");
Chris Lattner82aa8882010-01-05 07:18:46 +00001238 return new SExtInst(NewAdd, I.getType());
1239 }
1240 }
1241 }
1242
David Majnemerab07f002014-08-11 22:32:02 +00001243 // (add (xor A, B) (and A, B)) --> (or A, B)
Chad Rosier7813dce2012-04-26 23:29:14 +00001244 {
Craig Topperf40110f2014-04-25 05:29:35 +00001245 Value *A = nullptr, *B = nullptr;
Chad Rosier7813dce2012-04-26 23:29:14 +00001246 if (match(RHS, m_Xor(m_Value(A), m_Value(B))) &&
1247 (match(LHS, m_And(m_Specific(A), m_Specific(B))) ||
1248 match(LHS, m_And(m_Specific(B), m_Specific(A)))))
1249 return BinaryOperator::CreateOr(A, B);
1250
1251 if (match(LHS, m_Xor(m_Value(A), m_Value(B))) &&
1252 (match(RHS, m_And(m_Specific(A), m_Specific(B))) ||
1253 match(RHS, m_And(m_Specific(B), m_Specific(A)))))
1254 return BinaryOperator::CreateOr(A, B);
1255 }
1256
David Majnemerab07f002014-08-11 22:32:02 +00001257 // (add (or A, B) (and A, B)) --> (add A, B)
1258 {
1259 Value *A = nullptr, *B = nullptr;
1260 if (match(RHS, m_Or(m_Value(A), m_Value(B))) &&
1261 (match(LHS, m_And(m_Specific(A), m_Specific(B))) ||
1262 match(LHS, m_And(m_Specific(B), m_Specific(A))))) {
1263 auto *New = BinaryOperator::CreateAdd(A, B);
1264 New->setHasNoSignedWrap(I.hasNoSignedWrap());
1265 New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1266 return New;
1267 }
1268
1269 if (match(LHS, m_Or(m_Value(A), m_Value(B))) &&
1270 (match(RHS, m_And(m_Specific(A), m_Specific(B))) ||
1271 match(RHS, m_And(m_Specific(B), m_Specific(A))))) {
1272 auto *New = BinaryOperator::CreateAdd(A, B);
1273 New->setHasNoSignedWrap(I.hasNoSignedWrap());
1274 New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1275 return New;
1276 }
1277 }
1278
Jingyue Wu33bd53d2014-06-17 00:42:07 +00001279 // TODO(jingyue): Consider WillNotOverflowSignedAdd and
1280 // WillNotOverflowUnsignedAdd to reduce the number of invocations of
1281 // computeKnownBits.
Rafael Espindolad1a2c2d2014-06-02 22:01:04 +00001282 if (!I.hasNoSignedWrap() && WillNotOverflowSignedAdd(LHS, RHS)) {
1283 Changed = true;
1284 I.setHasNoSignedWrap(true);
1285 }
Jingyue Wu33bd53d2014-06-17 00:42:07 +00001286 if (!I.hasNoUnsignedWrap() && WillNotOverflowUnsignedAdd(LHS, RHS)) {
1287 Changed = true;
1288 I.setHasNoUnsignedWrap(true);
1289 }
Rafael Espindolad1a2c2d2014-06-02 22:01:04 +00001290
Craig Topperf40110f2014-04-25 05:29:35 +00001291 return Changed ? &I : nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001292}
1293
1294Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001295 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner82aa8882010-01-05 07:18:46 +00001296 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1297
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001298 if (Value *V = SimplifyVectorOp(I))
1299 return ReplaceInstUsesWith(I, V);
1300
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001301 if (Value *V = SimplifyFAddInst(LHS, RHS, I.getFastMathFlags(), DL))
Michael Ilsemand5787be2012-12-12 00:28:32 +00001302 return ReplaceInstUsesWith(I, V);
Chris Lattner82aa8882010-01-05 07:18:46 +00001303
Stephen Lina9b57f62013-07-20 07:13:13 +00001304 if (isa<Constant>(RHS)) {
1305 if (isa<PHINode>(LHS))
1306 if (Instruction *NV = FoldOpIntoPhi(I))
1307 return NV;
1308
1309 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1310 if (Instruction *NV = FoldOpIntoSelect(I, SI))
1311 return NV;
1312 }
Michael Ilsemane2754dc2012-12-14 22:08:26 +00001313
Chris Lattner82aa8882010-01-05 07:18:46 +00001314 // -A + B --> B - A
1315 // -A + -B --> -(A + B)
Owen Andersone7321662014-01-16 21:26:02 +00001316 if (Value *LHSV = dyn_castFNegVal(LHS)) {
1317 Instruction *RI = BinaryOperator::CreateFSub(RHS, LHSV);
1318 RI->copyFastMathFlags(&I);
1319 return RI;
1320 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001321
1322 // A + -B --> A - B
1323 if (!isa<Constant>(RHS))
Owen Andersone7321662014-01-16 21:26:02 +00001324 if (Value *V = dyn_castFNegVal(RHS)) {
1325 Instruction *RI = BinaryOperator::CreateFSub(LHS, V);
1326 RI->copyFastMathFlags(&I);
1327 return RI;
1328 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001329
Dan Gohman6f34abd2010-03-02 01:11:08 +00001330 // Check for (fadd double (sitofp x), y), see if we can merge this into an
Chris Lattner82aa8882010-01-05 07:18:46 +00001331 // integer add followed by a promotion.
1332 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
Dan Gohman6f34abd2010-03-02 01:11:08 +00001333 // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
Chris Lattner82aa8882010-01-05 07:18:46 +00001334 // ... if the constant fits in the integer value. This is useful for things
1335 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
1336 // requires a constant pool load, and generally allows the add to be better
1337 // instcombined.
1338 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001339 Constant *CI =
Chris Lattner82aa8882010-01-05 07:18:46 +00001340 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
1341 if (LHSConv->hasOneUse() &&
1342 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
1343 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
1344 // Insert the new integer add.
1345 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1346 CI, "addconv");
1347 return new SIToFPInst(NewAdd, I.getType());
1348 }
1349 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001350
Dan Gohman6f34abd2010-03-02 01:11:08 +00001351 // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
Chris Lattner82aa8882010-01-05 07:18:46 +00001352 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
1353 // Only do this if x/y have the same type, if at last one of them has a
1354 // single use (so we don't increase the number of int->fp conversions),
1355 // and if the integer add will not overflow.
1356 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
1357 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1358 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
1359 RHSConv->getOperand(0))) {
1360 // Insert the new integer add.
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001361 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner82aa8882010-01-05 07:18:46 +00001362 RHSConv->getOperand(0),"addconv");
1363 return new SIToFPInst(NewAdd, I.getType());
1364 }
1365 }
1366 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001367
Jean-Luc Duprat3e4fc3e2013-05-06 16:55:50 +00001368 // select C, 0, B + select C, A, 0 -> select C, A, B
1369 {
1370 Value *A1, *B1, *C1, *A2, *B2, *C2;
1371 if (match(LHS, m_Select(m_Value(C1), m_Value(A1), m_Value(B1))) &&
1372 match(RHS, m_Select(m_Value(C2), m_Value(A2), m_Value(B2)))) {
1373 if (C1 == C2) {
Craig Topperf40110f2014-04-25 05:29:35 +00001374 Constant *Z1=nullptr, *Z2=nullptr;
Jean-Luc Duprat3e4fc3e2013-05-06 16:55:50 +00001375 Value *A, *B, *C=C1;
1376 if (match(A1, m_AnyZero()) && match(B2, m_AnyZero())) {
1377 Z1 = dyn_cast<Constant>(A1); A = A2;
1378 Z2 = dyn_cast<Constant>(B2); B = B1;
1379 } else if (match(B1, m_AnyZero()) && match(A2, m_AnyZero())) {
1380 Z1 = dyn_cast<Constant>(B1); B = B2;
1381 Z2 = dyn_cast<Constant>(A2); A = A1;
1382 }
1383
1384 if (Z1 && Z2 &&
1385 (I.hasNoSignedZeros() ||
1386 (Z1->isNegativeZeroValue() && Z2->isNegativeZeroValue()))) {
1387 return SelectInst::Create(C, A, B);
1388 }
1389 }
1390 }
1391 }
1392
Shuxin Yang37a1efe2012-12-18 23:10:12 +00001393 if (I.hasUnsafeAlgebra()) {
1394 if (Value *V = FAddCombine(Builder).simplify(&I))
1395 return ReplaceInstUsesWith(I, V);
1396 }
1397
Craig Topperf40110f2014-04-25 05:29:35 +00001398 return Changed ? &I : nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001399}
1400
1401
Chris Lattner82aa8882010-01-05 07:18:46 +00001402/// Optimize pointer differences into the same array into a size. Consider:
1403/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
1404/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
1405///
1406Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
Chris Lattner229907c2011-07-18 04:54:35 +00001407 Type *Ty) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001408 assert(DL && "Must have target data info for this");
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001409
Chris Lattner82aa8882010-01-05 07:18:46 +00001410 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
1411 // this.
1412 bool Swapped = false;
Craig Topperf40110f2014-04-25 05:29:35 +00001413 GEPOperator *GEP1 = nullptr, *GEP2 = nullptr;
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001414
Chris Lattner82aa8882010-01-05 07:18:46 +00001415 // For now we require one side to be the base pointer "A" or a constant
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001416 // GEP derived from it.
1417 if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001418 // (gep X, ...) - X
1419 if (LHSGEP->getOperand(0) == RHS) {
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001420 GEP1 = LHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001421 Swapped = false;
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001422 } else if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1423 // (gep X, ...) - (gep X, ...)
1424 if (LHSGEP->getOperand(0)->stripPointerCasts() ==
1425 RHSGEP->getOperand(0)->stripPointerCasts()) {
1426 GEP2 = RHSGEP;
1427 GEP1 = LHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001428 Swapped = false;
1429 }
1430 }
1431 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001432
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001433 if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001434 // X - (gep X, ...)
1435 if (RHSGEP->getOperand(0) == LHS) {
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001436 GEP1 = RHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001437 Swapped = true;
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001438 } else if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1439 // (gep X, ...) - (gep X, ...)
1440 if (RHSGEP->getOperand(0)->stripPointerCasts() ==
1441 LHSGEP->getOperand(0)->stripPointerCasts()) {
1442 GEP2 = LHSGEP;
1443 GEP1 = RHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001444 Swapped = true;
1445 }
1446 }
1447 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001448
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001449 // Avoid duplicating the arithmetic if GEP2 has non-constant indices and
1450 // multiple users.
Craig Topperf40110f2014-04-25 05:29:35 +00001451 if (!GEP1 ||
1452 (GEP2 && !GEP2->hasAllConstantIndices() && !GEP2->hasOneUse()))
1453 return nullptr;
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001454
Chris Lattner82aa8882010-01-05 07:18:46 +00001455 // Emit the offset of the GEP and an intptr_t.
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001456 Value *Result = EmitGEPOffset(GEP1);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001457
Chris Lattner82aa8882010-01-05 07:18:46 +00001458 // If we had a constant expression GEP on the other side offsetting the
1459 // pointer, subtract it from the offset we have.
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001460 if (GEP2) {
1461 Value *Offset = EmitGEPOffset(GEP2);
1462 Result = Builder->CreateSub(Result, Offset);
Chris Lattner82aa8882010-01-05 07:18:46 +00001463 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001464
1465 // If we have p - gep(p, ...) then we have to negate the result.
1466 if (Swapped)
1467 Result = Builder->CreateNeg(Result, "diff.neg");
1468
1469 return Builder->CreateIntCast(Result, Ty, true);
1470}
1471
1472
1473Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1474 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1475
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001476 if (Value *V = SimplifyVectorOp(I))
1477 return ReplaceInstUsesWith(I, V);
1478
Duncan Sands0a2c41682010-12-15 14:07:39 +00001479 if (Value *V = SimplifySubInst(Op0, Op1, I.hasNoSignedWrap(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001480 I.hasNoUnsignedWrap(), DL))
Duncan Sands0a2c41682010-12-15 14:07:39 +00001481 return ReplaceInstUsesWith(I, V);
Chris Lattner82aa8882010-01-05 07:18:46 +00001482
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001483 // (A*B)-(A*C) -> A*(B-C) etc
1484 if (Value *V = SimplifyUsingDistributiveLaws(I))
1485 return ReplaceInstUsesWith(I, V);
1486
David Majnemera92687d2014-07-31 04:49:29 +00001487 // If this is a 'B = x-(-A)', change to B = x+A.
Chris Lattner82aa8882010-01-05 07:18:46 +00001488 if (Value *V = dyn_castNegVal(Op1)) {
1489 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
David Majnemera92687d2014-07-31 04:49:29 +00001490
1491 if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
1492 assert(BO->getOpcode() == Instruction::Sub &&
1493 "Expected a subtraction operator!");
1494 if (BO->hasNoSignedWrap() && I.hasNoSignedWrap())
1495 Res->setHasNoSignedWrap(true);
1496 }
1497
Chris Lattner82aa8882010-01-05 07:18:46 +00001498 return Res;
1499 }
1500
Duncan Sands9dff9be2010-02-15 16:12:20 +00001501 if (I.getType()->isIntegerTy(1))
Chris Lattner82aa8882010-01-05 07:18:46 +00001502 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001503
1504 // Replace (-1 - A) with (~A).
1505 if (match(Op0, m_AllOnes()))
1506 return BinaryOperator::CreateNot(Op1);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001507
Benjamin Kramer72196f32014-01-19 15:24:22 +00001508 if (Constant *C = dyn_cast<Constant>(Op0)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001509 // C - ~X == X + (1+C)
Craig Topperf40110f2014-04-25 05:29:35 +00001510 Value *X = nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001511 if (match(Op1, m_Not(m_Value(X))))
1512 return BinaryOperator::CreateAdd(X, AddOne(C));
1513
Benjamin Kramer72196f32014-01-19 15:24:22 +00001514 // Try to fold constant sub into select arguments.
1515 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1516 if (Instruction *R = FoldOpIntoSelect(I, SI))
1517 return R;
1518
1519 // C-(X+C2) --> (C-C2)-X
1520 Constant *C2;
1521 if (match(Op1, m_Add(m_Value(X), m_Constant(C2))))
1522 return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
1523
1524 if (SimplifyDemandedInstructionBits(I))
1525 return &I;
1526
1527 // Fold (sub 0, (zext bool to B)) --> (sext bool to B)
1528 if (C->isNullValue() && match(Op1, m_ZExt(m_Value(X))))
1529 if (X->getType()->getScalarType()->isIntegerTy(1))
1530 return CastInst::CreateSExtOrBitCast(X, Op1->getType());
1531
1532 // Fold (sub 0, (sext bool to B)) --> (zext bool to B)
1533 if (C->isNullValue() && match(Op1, m_SExt(m_Value(X))))
1534 if (X->getType()->getScalarType()->isIntegerTy(1))
1535 return CastInst::CreateZExtOrBitCast(X, Op1->getType());
1536 }
1537
1538 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001539 // -(X >>u 31) -> (X >>s 31)
1540 // -(X >>s 31) -> (X >>u 31)
1541 if (C->isZero()) {
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001542 Value *X; ConstantInt *CI;
1543 if (match(Op1, m_LShr(m_Value(X), m_ConstantInt(CI))) &&
1544 // Verify we are shifting out everything but the sign bit.
1545 CI->getValue() == I.getType()->getPrimitiveSizeInBits()-1)
1546 return BinaryOperator::CreateAShr(X, CI);
1547
1548 if (match(Op1, m_AShr(m_Value(X), m_ConstantInt(CI))) &&
1549 // Verify we are shifting out everything but the sign bit.
1550 CI->getValue() == I.getType()->getPrimitiveSizeInBits()-1)
1551 return BinaryOperator::CreateLShr(X, CI);
Chris Lattner82aa8882010-01-05 07:18:46 +00001552 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001553 }
1554
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001555
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001556 { Value *Y;
1557 // X-(X+Y) == -Y X-(Y+X) == -Y
1558 if (match(Op1, m_Add(m_Specific(Op0), m_Value(Y))) ||
1559 match(Op1, m_Add(m_Value(Y), m_Specific(Op0))))
1560 return BinaryOperator::CreateNeg(Y);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001561
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001562 // (X-Y)-X == -Y
1563 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
1564 return BinaryOperator::CreateNeg(Y);
1565 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001566
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001567 if (Op1->hasOneUse()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001568 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
1569 Constant *C = nullptr;
1570 Constant *CI = nullptr;
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001571
1572 // (X - (Y - Z)) --> (X + (Z - Y)).
1573 if (match(Op1, m_Sub(m_Value(Y), m_Value(Z))))
1574 return BinaryOperator::CreateAdd(Op0,
1575 Builder->CreateSub(Z, Y, Op1->getName()));
1576
1577 // (X - (X & Y)) --> (X & ~Y)
1578 //
1579 if (match(Op1, m_And(m_Value(Y), m_Specific(Op0))) ||
1580 match(Op1, m_And(m_Specific(Op0), m_Value(Y))))
1581 return BinaryOperator::CreateAnd(Op0,
1582 Builder->CreateNot(Y, Y->getName() + ".not"));
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001583
David Majnemerbdeef602014-07-02 06:07:09 +00001584 // 0 - (X sdiv C) -> (X sdiv -C) provided the negation doesn't overflow.
1585 if (match(Op1, m_SDiv(m_Value(X), m_Constant(C))) && match(Op0, m_Zero()) &&
1586 !C->isMinSignedValue())
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001587 return BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(C));
1588
1589 // 0 - (X << Y) -> (-X << Y) when X is freely negatable.
1590 if (match(Op1, m_Shl(m_Value(X), m_Value(Y))) && match(Op0, m_Zero()))
1591 if (Value *XNeg = dyn_castNegVal(X))
1592 return BinaryOperator::CreateShl(XNeg, Y);
1593
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001594 // X - A*-B -> X + A*B
1595 // X - -A*B -> X + A*B
1596 Value *A, *B;
1597 if (match(Op1, m_Mul(m_Value(A), m_Neg(m_Value(B)))) ||
1598 match(Op1, m_Mul(m_Neg(m_Value(A)), m_Value(B))))
1599 return BinaryOperator::CreateAdd(Op0, Builder->CreateMul(A, B));
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001600
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001601 // X - A*CI -> X + A*-CI
1602 // X - CI*A -> X + A*-CI
Benjamin Kramer72196f32014-01-19 15:24:22 +00001603 if (match(Op1, m_Mul(m_Value(A), m_Constant(CI))) ||
1604 match(Op1, m_Mul(m_Constant(CI), m_Value(A)))) {
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001605 Value *NewMul = Builder->CreateMul(A, ConstantExpr::getNeg(CI));
1606 return BinaryOperator::CreateAdd(Op0, NewMul);
Chris Lattner82aa8882010-01-05 07:18:46 +00001607 }
1608 }
1609
Chris Lattner82aa8882010-01-05 07:18:46 +00001610 // Optimize pointer differences into the same array into a size. Consider:
1611 // &A[10] - &A[0]: we should compile this to "10".
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001612 if (DL) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001613 Value *LHSOp, *RHSOp;
1614 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
1615 match(Op1, m_PtrToInt(m_Value(RHSOp))))
1616 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1617 return ReplaceInstUsesWith(I, Res);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001618
Chris Lattner82aa8882010-01-05 07:18:46 +00001619 // trunc(p)-trunc(q) -> trunc(p-q)
1620 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
1621 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
1622 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1623 return ReplaceInstUsesWith(I, Res);
Dinesh Dwivediadc07732014-06-27 07:47:35 +00001624 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001625
Craig Topperf40110f2014-04-25 05:29:35 +00001626 return nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001627}
1628
1629Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
1630 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1631
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001632 if (Value *V = SimplifyVectorOp(I))
1633 return ReplaceInstUsesWith(I, V);
1634
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001635 if (Value *V = SimplifyFSubInst(Op0, Op1, I.getFastMathFlags(), DL))
Michael Ilsemand5787be2012-12-12 00:28:32 +00001636 return ReplaceInstUsesWith(I, V);
1637
Stephen Lina9b57f62013-07-20 07:13:13 +00001638 if (isa<Constant>(Op0))
1639 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1640 if (Instruction *NV = FoldOpIntoSelect(I, SI))
1641 return NV;
1642
Owen Andersone37c2e42013-07-26 21:40:29 +00001643 // If this is a 'B = x-(-A)', change to B = x+A, potentially looking
1644 // through FP extensions/truncations along the way.
Owen Andersonc7be5192013-07-30 23:53:17 +00001645 if (Value *V = dyn_castFNegVal(Op1)) {
1646 Instruction *NewI = BinaryOperator::CreateFAdd(Op0, V);
1647 NewI->copyFastMathFlags(&I);
1648 return NewI;
1649 }
Owen Andersone37c2e42013-07-26 21:40:29 +00001650 if (FPTruncInst *FPTI = dyn_cast<FPTruncInst>(Op1)) {
1651 if (Value *V = dyn_castFNegVal(FPTI->getOperand(0))) {
1652 Value *NewTrunc = Builder->CreateFPTrunc(V, I.getType());
Owen Andersonc7be5192013-07-30 23:53:17 +00001653 Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewTrunc);
1654 NewI->copyFastMathFlags(&I);
1655 return NewI;
Owen Andersone37c2e42013-07-26 21:40:29 +00001656 }
1657 } else if (FPExtInst *FPEI = dyn_cast<FPExtInst>(Op1)) {
1658 if (Value *V = dyn_castFNegVal(FPEI->getOperand(0))) {
Owen Andersond6d4da02013-07-26 22:06:21 +00001659 Value *NewExt = Builder->CreateFPExt(V, I.getType());
Owen Andersonc7be5192013-07-30 23:53:17 +00001660 Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewExt);
1661 NewI->copyFastMathFlags(&I);
1662 return NewI;
Owen Andersone37c2e42013-07-26 21:40:29 +00001663 }
1664 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001665
Shuxin Yang37a1efe2012-12-18 23:10:12 +00001666 if (I.hasUnsafeAlgebra()) {
1667 if (Value *V = FAddCombine(Builder).simplify(&I))
1668 return ReplaceInstUsesWith(I, V);
1669 }
1670
Craig Topperf40110f2014-04-25 05:29:35 +00001671 return nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001672}