blob: 9e3cf3041a07be38b48e89017e2c4cd39c5fbb33 [file] [log] [blame]
Eugene Zelenkoffec81c2015-11-04 22:32:32 +00001//===- InstCombineAddSub.cpp ------------------------------------*- C++ -*-===//
Chris Lattner82aa8882010-01-05 07:18:46 +00002//
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
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.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"
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000020
Chris Lattner82aa8882010-01-05 07:18:46 +000021using namespace llvm;
22using namespace PatternMatch;
23
Chandler Carruth964daaa2014-04-22 02:55:47 +000024#define DEBUG_TYPE "instcombine"
25
Shuxin Yang37a1efe2012-12-18 23:10:12 +000026namespace {
27
28 /// Class representing coefficient of floating-point addend.
29 /// This class needs to be highly efficient, which is especially true for
30 /// the constructor. As of I write this comment, the cost of the default
Jim Grosbachbdbd7342013-04-05 21:20:12 +000031 /// constructor is merely 4-byte-store-zero (Assuming compiler is able to
Shuxin Yang37a1efe2012-12-18 23:10:12 +000032 /// perform write-merging).
Jim Grosbachbdbd7342013-04-05 21:20:12 +000033 ///
Shuxin Yang37a1efe2012-12-18 23:10:12 +000034 class FAddendCoef {
35 public:
Suyog Sardade409fd2014-07-17 06:09:34 +000036 // The constructor has to initialize a APFloat, which is unnecessary for
Shuxin Yang37a1efe2012-12-18 23:10:12 +000037 // most addends which have coefficient either 1 or -1. So, the constructor
38 // is expensive. In order to avoid the cost of the constructor, we should
39 // reuse some instances whenever possible. The pre-created instances
40 // FAddCombine::Add[0-5] embodies this idea.
41 //
42 FAddendCoef() : IsFp(false), BufHasFpVal(false), IntVal(0) {}
43 ~FAddendCoef();
Jim Grosbachbdbd7342013-04-05 21:20:12 +000044
Shuxin Yang37a1efe2012-12-18 23:10:12 +000045 void set(short C) {
46 assert(!insaneIntVal(C) && "Insane coefficient");
47 IsFp = false; IntVal = C;
48 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000049
Shuxin Yang37a1efe2012-12-18 23:10:12 +000050 void set(const APFloat& C);
Shuxin Yang389ed4b2013-03-25 20:43:41 +000051
Shuxin Yang37a1efe2012-12-18 23:10:12 +000052 void negate();
Jim Grosbachbdbd7342013-04-05 21:20:12 +000053
Shuxin Yang37a1efe2012-12-18 23:10:12 +000054 bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); }
55 Value *getValue(Type *) const;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000056
Shuxin Yang37a1efe2012-12-18 23:10:12 +000057 // If possible, don't define operator+/operator- etc because these
58 // operators inevitably call FAddendCoef's constructor which is not cheap.
59 void operator=(const FAddendCoef &A);
60 void operator+=(const FAddendCoef &A);
61 void operator-=(const FAddendCoef &A);
62 void operator*=(const FAddendCoef &S);
Jim Grosbachbdbd7342013-04-05 21:20:12 +000063
Shuxin Yang37a1efe2012-12-18 23:10:12 +000064 bool isOne() const { return isInt() && IntVal == 1; }
65 bool isTwo() const { return isInt() && IntVal == 2; }
66 bool isMinusOne() const { return isInt() && IntVal == -1; }
67 bool isMinusTwo() const { return isInt() && IntVal == -2; }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000068
Shuxin Yang37a1efe2012-12-18 23:10:12 +000069 private:
70 bool insaneIntVal(int V) { return V > 4 || V < -4; }
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000071 APFloat *getFpValPtr()
Shuxin Yang5b841c42012-12-19 01:10:17 +000072 { return reinterpret_cast<APFloat*>(&FpValBuf.buffer[0]); }
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000073 const APFloat *getFpValPtr() const
David Greene530430b2013-01-14 21:04:40 +000074 { return reinterpret_cast<const APFloat*>(&FpValBuf.buffer[0]); }
Shuxin Yang37a1efe2012-12-18 23:10:12 +000075
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000076 const APFloat &getFpVal() const {
Shuxin Yang37a1efe2012-12-18 23:10:12 +000077 assert(IsFp && BufHasFpVal && "Incorret state");
David Greene530430b2013-01-14 21:04:40 +000078 return *getFpValPtr();
Shuxin Yang37a1efe2012-12-18 23:10:12 +000079 }
80
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000081 APFloat &getFpVal() {
Jim Grosbachbdbd7342013-04-05 21:20:12 +000082 assert(IsFp && BufHasFpVal && "Incorret state");
83 return *getFpValPtr();
84 }
85
Shuxin Yang37a1efe2012-12-18 23:10:12 +000086 bool isInt() const { return !IsFp; }
87
Shuxin Yang389ed4b2013-03-25 20:43:41 +000088 // If the coefficient is represented by an integer, promote it to a
Jim Grosbachbdbd7342013-04-05 21:20:12 +000089 // floating point.
Shuxin Yang389ed4b2013-03-25 20:43:41 +000090 void convertToFpType(const fltSemantics &Sem);
91
92 // Construct an APFloat from a signed integer.
93 // TODO: We should get rid of this function when APFloat can be constructed
Jim Grosbachbdbd7342013-04-05 21:20:12 +000094 // from an *SIGNED* integer.
Shuxin Yang389ed4b2013-03-25 20:43:41 +000095 APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val);
Shuxin Yang5b841c42012-12-19 01:10:17 +000096
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000097 private:
Shuxin Yang37a1efe2012-12-18 23:10:12 +000098 bool IsFp;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000099
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000100 // True iff FpValBuf contains an instance of APFloat.
101 bool BufHasFpVal;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000102
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000103 // The integer coefficient of an individual addend is either 1 or -1,
104 // and we try to simplify at most 4 addends from neighboring at most
105 // two instructions. So the range of <IntVal> falls in [-4, 4]. APInt
106 // is overkill of this end.
107 short IntVal;
Shuxin Yang5b841c42012-12-19 01:10:17 +0000108
109 AlignedCharArrayUnion<APFloat> FpValBuf;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000110 };
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000111
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000112 /// FAddend is used to represent floating-point addend. An addend is
113 /// represented as <C, V>, where the V is a symbolic value, and C is a
114 /// constant coefficient. A constant addend is represented as <C, 0>.
115 ///
116 class FAddend {
117 public:
Eugene Zelenkoffec81c2015-11-04 22:32:32 +0000118 FAddend() : Val(nullptr) {}
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000119
Eugene Zelenkoffec81c2015-11-04 22:32:32 +0000120 Value *getSymVal() const { return Val; }
121 const FAddendCoef &getCoef() const { return Coeff; }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000122
Craig Topperf40110f2014-04-25 05:29:35 +0000123 bool isConstant() const { return Val == nullptr; }
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000124 bool isZero() const { return Coeff.isZero(); }
125
Richard Trieu7a083812016-02-18 22:09:30 +0000126 void set(short Coefficient, Value *V) {
127 Coeff.set(Coefficient);
128 Val = V;
129 }
130 void set(const APFloat &Coefficient, Value *V) {
131 Coeff.set(Coefficient);
132 Val = V;
133 }
134 void set(const ConstantFP *Coefficient, Value *V) {
135 Coeff.set(Coefficient->getValueAPF());
136 Val = V;
137 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000138
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000139 void negate() { Coeff.negate(); }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000140
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000141 /// Drill down the U-D chain one step to find the definition of V, and
142 /// try to break the definition into one or two addends.
143 static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000144
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000145 /// Similar to FAddend::drillDownOneStep() except that the value being
146 /// splitted is the addend itself.
147 unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000148
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000149 void operator+=(const FAddend &T) {
150 assert((Val == T.Val) && "Symbolic-values disagree");
151 Coeff += T.Coeff;
152 }
153
154 private:
155 void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000156
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000157 // This addend has the value of "Coeff * Val".
158 Value *Val;
159 FAddendCoef Coeff;
160 };
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000161
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000162 /// FAddCombine is the class for optimizing an unsafe fadd/fsub along
163 /// with its neighboring at most two instructions.
164 ///
165 class FAddCombine {
166 public:
Craig Topperf40110f2014-04-25 05:29:35 +0000167 FAddCombine(InstCombiner::BuilderTy *B) : Builder(B), Instr(nullptr) {}
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000168 Value *simplify(Instruction *FAdd);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000169
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000170 private:
171 typedef SmallVector<const FAddend*, 4> AddendVect;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000172
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000173 Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000174
175 Value *performFactorization(Instruction *I);
176
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000177 /// Convert given addend to a Value
178 Value *createAddendVal(const FAddend &A, bool& NeedNeg);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000179
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000180 /// Return the number of instructions needed to emit the N-ary addition.
181 unsigned calcInstrNumber(const AddendVect& Vect);
182 Value *createFSub(Value *Opnd0, Value *Opnd1);
183 Value *createFAdd(Value *Opnd0, Value *Opnd1);
184 Value *createFMul(Value *Opnd0, Value *Opnd1);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000185 Value *createFDiv(Value *Opnd0, Value *Opnd1);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000186 Value *createFNeg(Value *V);
187 Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
Owen Anderson1664dc82014-01-20 07:44:53 +0000188 void createInstPostProc(Instruction *NewInst, bool NoNumber = false);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000189
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000190 InstCombiner::BuilderTy *Builder;
191 Instruction *Instr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000192
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000193 // Debugging stuff are clustered here.
194 #ifndef NDEBUG
195 unsigned CreateInstrNum;
196 void initCreateInstNum() { CreateInstrNum = 0; }
197 void incCreateInstNum() { CreateInstrNum++; }
198 #else
199 void initCreateInstNum() {}
200 void incCreateInstNum() {}
201 #endif
202 };
Eugene Zelenkoffec81c2015-11-04 22:32:32 +0000203
204} // anonymous namespace
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000205
206//===----------------------------------------------------------------------===//
207//
208// Implementation of
209// {FAddendCoef, FAddend, FAddition, FAddCombine}.
210//
211//===----------------------------------------------------------------------===//
212FAddendCoef::~FAddendCoef() {
213 if (BufHasFpVal)
214 getFpValPtr()->~APFloat();
215}
216
217void FAddendCoef::set(const APFloat& C) {
218 APFloat *P = getFpValPtr();
219
220 if (isInt()) {
221 // As the buffer is meanless byte stream, we cannot call
222 // APFloat::operator=().
223 new(P) APFloat(C);
224 } else
225 *P = C;
226
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000227 IsFp = BufHasFpVal = true;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000228}
229
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000230void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
231 if (!isInt())
232 return;
233
234 APFloat *P = getFpValPtr();
235 if (IntVal > 0)
236 new(P) APFloat(Sem, IntVal);
237 else {
238 new(P) APFloat(Sem, 0 - IntVal);
239 P->changeSign();
240 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000241 IsFp = BufHasFpVal = true;
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000242}
243
244APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
245 if (Val >= 0)
246 return APFloat(Sem, Val);
247
248 APFloat T(Sem, 0 - Val);
249 T.changeSign();
250
251 return T;
252}
253
254void FAddendCoef::operator=(const FAddendCoef &That) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000255 if (That.isInt())
256 set(That.IntVal);
257 else
258 set(That.getFpVal());
259}
260
261void FAddendCoef::operator+=(const FAddendCoef &That) {
262 enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
263 if (isInt() == That.isInt()) {
264 if (isInt())
265 IntVal += That.IntVal;
266 else
267 getFpVal().add(That.getFpVal(), RndMode);
268 return;
269 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000270
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000271 if (isInt()) {
272 const APFloat &T = That.getFpVal();
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000273 convertToFpType(T.getSemantics());
274 getFpVal().add(T, RndMode);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000275 return;
276 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000277
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000278 APFloat &T = getFpVal();
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000279 T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000280}
281
282void FAddendCoef::operator-=(const FAddendCoef &That) {
283 enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
284 if (isInt() == That.isInt()) {
285 if (isInt())
286 IntVal -= That.IntVal;
287 else
288 getFpVal().subtract(That.getFpVal(), RndMode);
289 return;
290 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000291
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000292 if (isInt()) {
293 const APFloat &T = That.getFpVal();
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000294 convertToFpType(T.getSemantics());
295 getFpVal().subtract(T, RndMode);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000296 return;
297 }
298
299 APFloat &T = getFpVal();
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000300 T.subtract(createAPFloatFromInt(T.getSemantics(), IntVal), RndMode);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000301}
302
303void FAddendCoef::operator*=(const FAddendCoef &That) {
304 if (That.isOne())
305 return;
306
307 if (That.isMinusOne()) {
308 negate();
309 return;
310 }
311
312 if (isInt() && That.isInt()) {
313 int Res = IntVal * (int)That.IntVal;
314 assert(!insaneIntVal(Res) && "Insane int value");
315 IntVal = Res;
316 return;
317 }
318
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000319 const fltSemantics &Semantic =
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000320 isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
321
322 if (isInt())
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000323 convertToFpType(Semantic);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000324 APFloat &F0 = getFpVal();
325
326 if (That.isInt())
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000327 F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
328 APFloat::rmNearestTiesToEven);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000329 else
330 F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000331}
332
333void FAddendCoef::negate() {
334 if (isInt())
335 IntVal = 0 - IntVal;
336 else
337 getFpVal().changeSign();
338}
339
340Value *FAddendCoef::getValue(Type *Ty) const {
341 return isInt() ?
342 ConstantFP::get(Ty, float(IntVal)) :
343 ConstantFP::get(Ty->getContext(), getFpVal());
344}
345
346// The definition of <Val> Addends
347// =========================================
348// A + B <1, A>, <1,B>
349// A - B <1, A>, <1,B>
350// 0 - B <-1, B>
351// C * A, <C, A>
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000352// A + C <1, A> <C, NULL>
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000353// 0 +/- 0 <0, NULL> (corner case)
354//
355// Legend: A and B are not constant, C is constant
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000356//
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000357unsigned FAddend::drillValueDownOneStep
358 (Value *Val, FAddend &Addend0, FAddend &Addend1) {
Craig Topperf40110f2014-04-25 05:29:35 +0000359 Instruction *I = nullptr;
360 if (!Val || !(I = dyn_cast<Instruction>(Val)))
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000361 return 0;
362
363 unsigned Opcode = I->getOpcode();
364
365 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
366 ConstantFP *C0, *C1;
367 Value *Opnd0 = I->getOperand(0);
368 Value *Opnd1 = I->getOperand(1);
369 if ((C0 = dyn_cast<ConstantFP>(Opnd0)) && C0->isZero())
Craig Topperf40110f2014-04-25 05:29:35 +0000370 Opnd0 = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000371
372 if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
Craig Topperf40110f2014-04-25 05:29:35 +0000373 Opnd1 = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000374
375 if (Opnd0) {
376 if (!C0)
377 Addend0.set(1, Opnd0);
378 else
Craig Topperf40110f2014-04-25 05:29:35 +0000379 Addend0.set(C0, nullptr);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000380 }
381
382 if (Opnd1) {
383 FAddend &Addend = Opnd0 ? Addend1 : Addend0;
384 if (!C1)
385 Addend.set(1, Opnd1);
386 else
Craig Topperf40110f2014-04-25 05:29:35 +0000387 Addend.set(C1, nullptr);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000388 if (Opcode == Instruction::FSub)
389 Addend.negate();
390 }
391
392 if (Opnd0 || Opnd1)
393 return Opnd0 && Opnd1 ? 2 : 1;
394
395 // Both operands are zero. Weird!
Craig Topperf40110f2014-04-25 05:29:35 +0000396 Addend0.set(APFloat(C0->getValueAPF().getSemantics()), nullptr);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000397 return 1;
398 }
399
400 if (I->getOpcode() == Instruction::FMul) {
401 Value *V0 = I->getOperand(0);
402 Value *V1 = I->getOperand(1);
403 if (ConstantFP *C = dyn_cast<ConstantFP>(V0)) {
404 Addend0.set(C, V1);
405 return 1;
406 }
407
408 if (ConstantFP *C = dyn_cast<ConstantFP>(V1)) {
409 Addend0.set(C, V0);
410 return 1;
411 }
412 }
413
414 return 0;
415}
416
417// Try to break *this* addend into two addends. e.g. Suppose this addend is
418// <2.3, V>, and V = X + Y, by calling this function, we obtain two addends,
419// i.e. <2.3, X> and <2.3, Y>.
420//
421unsigned FAddend::drillAddendDownOneStep
422 (FAddend &Addend0, FAddend &Addend1) const {
423 if (isConstant())
424 return 0;
425
426 unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000427 if (!BreakNum || Coeff.isOne())
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000428 return BreakNum;
429
430 Addend0.Scale(Coeff);
431
432 if (BreakNum == 2)
433 Addend1.Scale(Coeff);
434
435 return BreakNum;
436}
437
Shuxin Yang2eca6022013-03-14 18:08:26 +0000438// Try to perform following optimization on the input instruction I. Return the
439// simplified expression if was successful; otherwise, return 0.
440//
441// Instruction "I" is Simplified into
442// -------------------------------------------------------
443// (x * y) +/- (x * z) x * (y +/- z)
444// (y / x) +/- (z / x) (y +/- z) / x
445//
446Value *FAddCombine::performFactorization(Instruction *I) {
447 assert((I->getOpcode() == Instruction::FAdd ||
448 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000449
Shuxin Yang2eca6022013-03-14 18:08:26 +0000450 Instruction *I0 = dyn_cast<Instruction>(I->getOperand(0));
451 Instruction *I1 = dyn_cast<Instruction>(I->getOperand(1));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000452
Shuxin Yang2eca6022013-03-14 18:08:26 +0000453 if (!I0 || !I1 || I0->getOpcode() != I1->getOpcode())
Craig Topperf40110f2014-04-25 05:29:35 +0000454 return nullptr;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000455
456 bool isMpy = false;
457 if (I0->getOpcode() == Instruction::FMul)
458 isMpy = true;
459 else if (I0->getOpcode() != Instruction::FDiv)
Craig Topperf40110f2014-04-25 05:29:35 +0000460 return nullptr;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000461
462 Value *Opnd0_0 = I0->getOperand(0);
463 Value *Opnd0_1 = I0->getOperand(1);
464 Value *Opnd1_0 = I1->getOperand(0);
465 Value *Opnd1_1 = I1->getOperand(1);
466
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000467 // Input Instr I Factor AddSub0 AddSub1
Shuxin Yang2eca6022013-03-14 18:08:26 +0000468 // ----------------------------------------------
469 // (x*y) +/- (x*z) x y z
470 // (y/x) +/- (z/x) x y z
471 //
Craig Topperf40110f2014-04-25 05:29:35 +0000472 Value *Factor = nullptr;
473 Value *AddSub0 = nullptr, *AddSub1 = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000474
Shuxin Yang2eca6022013-03-14 18:08:26 +0000475 if (isMpy) {
476 if (Opnd0_0 == Opnd1_0 || Opnd0_0 == Opnd1_1)
477 Factor = Opnd0_0;
478 else if (Opnd0_1 == Opnd1_0 || Opnd0_1 == Opnd1_1)
479 Factor = Opnd0_1;
480
481 if (Factor) {
482 AddSub0 = (Factor == Opnd0_0) ? Opnd0_1 : Opnd0_0;
483 AddSub1 = (Factor == Opnd1_0) ? Opnd1_1 : Opnd1_0;
484 }
485 } else if (Opnd0_1 == Opnd1_1) {
486 Factor = Opnd0_1;
487 AddSub0 = Opnd0_0;
488 AddSub1 = Opnd1_0;
489 }
490
491 if (!Factor)
Craig Topperf40110f2014-04-25 05:29:35 +0000492 return nullptr;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000493
Owen Anderson1664dc82014-01-20 07:44:53 +0000494 FastMathFlags Flags;
495 Flags.setUnsafeAlgebra();
496 if (I0) Flags &= I->getFastMathFlags();
497 if (I1) Flags &= I->getFastMathFlags();
498
Shuxin Yang2eca6022013-03-14 18:08:26 +0000499 // Create expression "NewAddSub = AddSub0 +/- AddsSub1"
500 Value *NewAddSub = (I->getOpcode() == Instruction::FAdd) ?
501 createFAdd(AddSub0, AddSub1) :
502 createFSub(AddSub0, AddSub1);
503 if (ConstantFP *CFP = dyn_cast<ConstantFP>(NewAddSub)) {
504 const APFloat &F = CFP->getValueAPF();
Michael Gottesmanc2af8d62013-06-26 23:17:31 +0000505 if (!F.isNormal())
Craig Topperf40110f2014-04-25 05:29:35 +0000506 return nullptr;
Owen Anderson1664dc82014-01-20 07:44:53 +0000507 } else if (Instruction *II = dyn_cast<Instruction>(NewAddSub))
508 II->setFastMathFlags(Flags);
509
510 if (isMpy) {
511 Value *RI = createFMul(Factor, NewAddSub);
512 if (Instruction *II = dyn_cast<Instruction>(RI))
513 II->setFastMathFlags(Flags);
514 return RI;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000515 }
516
Owen Anderson1664dc82014-01-20 07:44:53 +0000517 Value *RI = createFDiv(NewAddSub, Factor);
518 if (Instruction *II = dyn_cast<Instruction>(RI))
519 II->setFastMathFlags(Flags);
520 return RI;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000521}
522
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000523Value *FAddCombine::simplify(Instruction *I) {
524 assert(I->hasUnsafeAlgebra() && "Should be in unsafe mode");
525
526 // Currently we are not able to handle vector type.
527 if (I->getType()->isVectorTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000528 return nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000529
530 assert((I->getOpcode() == Instruction::FAdd ||
531 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
532
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000533 // Save the instruction before calling other member-functions.
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000534 Instr = I;
535
536 FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
537
538 unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
539
540 // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
541 unsigned Opnd0_ExpNum = 0;
542 unsigned Opnd1_ExpNum = 0;
543
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000544 if (!Opnd0.isConstant())
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000545 Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
546
547 // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
548 if (OpndNum == 2 && !Opnd1.isConstant())
549 Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
550
551 // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
552 if (Opnd0_ExpNum && Opnd1_ExpNum) {
553 AddendVect AllOpnds;
554 AllOpnds.push_back(&Opnd0_0);
555 AllOpnds.push_back(&Opnd1_0);
556 if (Opnd0_ExpNum == 2)
557 AllOpnds.push_back(&Opnd0_1);
558 if (Opnd1_ExpNum == 2)
559 AllOpnds.push_back(&Opnd1_1);
560
561 // Compute instruction quota. We should save at least one instruction.
562 unsigned InstQuota = 0;
563
564 Value *V0 = I->getOperand(0);
565 Value *V1 = I->getOperand(1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000566 InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000567 (!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
568
569 if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
570 return R;
571 }
572
573 if (OpndNum != 2) {
574 // The input instruction is : "I=0.0 +/- V". If the "V" were able to be
575 // splitted into two addends, say "V = X - Y", the instruction would have
576 // been optimized into "I = Y - X" in the previous steps.
577 //
578 const FAddendCoef &CE = Opnd0.getCoef();
Craig Topperf40110f2014-04-25 05:29:35 +0000579 return CE.isOne() ? Opnd0.getSymVal() : nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000580 }
581
582 // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
583 if (Opnd1_ExpNum) {
584 AddendVect AllOpnds;
585 AllOpnds.push_back(&Opnd0);
586 AllOpnds.push_back(&Opnd1_0);
587 if (Opnd1_ExpNum == 2)
588 AllOpnds.push_back(&Opnd1_1);
589
590 if (Value *R = simplifyFAdd(AllOpnds, 1))
591 return R;
592 }
593
594 // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
595 if (Opnd0_ExpNum) {
596 AddendVect AllOpnds;
597 AllOpnds.push_back(&Opnd1);
598 AllOpnds.push_back(&Opnd0_0);
599 if (Opnd0_ExpNum == 2)
600 AllOpnds.push_back(&Opnd0_1);
601
602 if (Value *R = simplifyFAdd(AllOpnds, 1))
603 return R;
604 }
605
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000606 // step 6: Try factorization as the last resort,
Shuxin Yang2eca6022013-03-14 18:08:26 +0000607 return performFactorization(I);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000608}
609
610Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000611 unsigned AddendNum = Addends.size();
612 assert(AddendNum <= 4 && "Too many addends");
613
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000614 // For saving intermediate results;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000615 unsigned NextTmpIdx = 0;
616 FAddend TmpResult[3];
617
618 // Points to the constant addend of the resulting simplified expression.
619 // If the resulting expr has constant-addend, this constant-addend is
620 // desirable to reside at the top of the resulting expression tree. Placing
621 // constant close to supper-expr(s) will potentially reveal some optimization
622 // opportunities in super-expr(s).
623 //
Craig Topperf40110f2014-04-25 05:29:35 +0000624 const FAddend *ConstAdd = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000625
626 // Simplified addends are placed <SimpVect>.
627 AddendVect SimpVect;
628
629 // The outer loop works on one symbolic-value at a time. Suppose the input
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000630 // addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000631 // The symbolic-values will be processed in this order: x, y, z.
632 //
633 for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
634
635 const FAddend *ThisAddend = Addends[SymIdx];
636 if (!ThisAddend) {
637 // This addend was processed before.
638 continue;
639 }
640
641 Value *Val = ThisAddend->getSymVal();
642 unsigned StartIdx = SimpVect.size();
643 SimpVect.push_back(ThisAddend);
644
645 // The inner loop collects addends sharing same symbolic-value, and these
646 // addends will be later on folded into a single addend. Following above
647 // example, if the symbolic value "y" is being processed, the inner loop
648 // will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
649 // be later on folded into "<b1+b2, y>".
650 //
651 for (unsigned SameSymIdx = SymIdx + 1;
652 SameSymIdx < AddendNum; SameSymIdx++) {
653 const FAddend *T = Addends[SameSymIdx];
654 if (T && T->getSymVal() == Val) {
655 // Set null such that next iteration of the outer loop will not process
656 // this addend again.
Craig Topperf40110f2014-04-25 05:29:35 +0000657 Addends[SameSymIdx] = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000658 SimpVect.push_back(T);
659 }
660 }
661
662 // If multiple addends share same symbolic value, fold them together.
663 if (StartIdx + 1 != SimpVect.size()) {
664 FAddend &R = TmpResult[NextTmpIdx ++];
665 R = *SimpVect[StartIdx];
666 for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
667 R += *SimpVect[Idx];
668
669 // Pop all addends being folded and push the resulting folded addend.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000670 SimpVect.resize(StartIdx);
Craig Topperf40110f2014-04-25 05:29:35 +0000671 if (Val) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000672 if (!R.isZero()) {
673 SimpVect.push_back(&R);
674 }
675 } else {
676 // Don't push constant addend at this time. It will be the last element
677 // of <SimpVect>.
678 ConstAdd = &R;
679 }
680 }
681 }
682
Craig Topper58713212013-07-15 04:27:47 +0000683 assert((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000684 "out-of-bound access");
685
686 if (ConstAdd)
687 SimpVect.push_back(ConstAdd);
688
689 Value *Result;
690 if (!SimpVect.empty())
691 Result = createNaryFAdd(SimpVect, InstrQuota);
692 else {
693 // The addition is folded to 0.0.
694 Result = ConstantFP::get(Instr->getType(), 0.0);
695 }
696
697 return Result;
698}
699
700Value *FAddCombine::createNaryFAdd
701 (const AddendVect &Opnds, unsigned InstrQuota) {
702 assert(!Opnds.empty() && "Expect at least one addend");
703
704 // Step 1: Check if the # of instructions needed exceeds the quota.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000705 //
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000706 unsigned InstrNeeded = calcInstrNumber(Opnds);
707 if (InstrNeeded > InstrQuota)
Craig Topperf40110f2014-04-25 05:29:35 +0000708 return nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000709
710 initCreateInstNum();
711
712 // step 2: Emit the N-ary addition.
713 // Note that at most three instructions are involved in Fadd-InstCombine: the
714 // addition in question, and at most two neighboring instructions.
715 // The resulting optimized addition should have at least one less instruction
716 // than the original addition expression tree. This implies that the resulting
717 // N-ary addition has at most two instructions, and we don't need to worry
718 // about tree-height when constructing the N-ary addition.
719
Craig Topperf40110f2014-04-25 05:29:35 +0000720 Value *LastVal = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000721 bool LastValNeedNeg = false;
722
723 // Iterate the addends, creating fadd/fsub using adjacent two addends.
724 for (AddendVect::const_iterator I = Opnds.begin(), E = Opnds.end();
725 I != E; I++) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000726 bool NeedNeg;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000727 Value *V = createAddendVal(**I, NeedNeg);
728 if (!LastVal) {
729 LastVal = V;
730 LastValNeedNeg = NeedNeg;
731 continue;
732 }
733
734 if (LastValNeedNeg == NeedNeg) {
735 LastVal = createFAdd(LastVal, V);
736 continue;
737 }
738
739 if (LastValNeedNeg)
740 LastVal = createFSub(V, LastVal);
741 else
742 LastVal = createFSub(LastVal, V);
743
744 LastValNeedNeg = false;
745 }
746
747 if (LastValNeedNeg) {
748 LastVal = createFNeg(LastVal);
749 }
750
751 #ifndef NDEBUG
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000752 assert(CreateInstrNum == InstrNeeded &&
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000753 "Inconsistent in instruction numbers");
754 #endif
755
756 return LastVal;
757}
758
Sanjay Patelc242dbb2014-12-18 21:11:09 +0000759Value *FAddCombine::createFSub(Value *Opnd0, Value *Opnd1) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000760 Value *V = Builder->CreateFSub(Opnd0, Opnd1);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000761 if (Instruction *I = dyn_cast<Instruction>(V))
762 createInstPostProc(I);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000763 return V;
764}
765
766Value *FAddCombine::createFNeg(Value *V) {
Sanjay Patelea3c8022014-12-19 16:44:08 +0000767 Value *Zero = cast<Value>(ConstantFP::getZeroValueForNegation(V->getType()));
Owen Anderson1664dc82014-01-20 07:44:53 +0000768 Value *NewV = createFSub(Zero, V);
769 if (Instruction *I = dyn_cast<Instruction>(NewV))
770 createInstPostProc(I, true); // fneg's don't receive instruction numbers.
771 return NewV;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000772}
773
Sanjay Patelc242dbb2014-12-18 21:11:09 +0000774Value *FAddCombine::createFAdd(Value *Opnd0, Value *Opnd1) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000775 Value *V = Builder->CreateFAdd(Opnd0, Opnd1);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000776 if (Instruction *I = dyn_cast<Instruction>(V))
777 createInstPostProc(I);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000778 return V;
779}
780
781Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
782 Value *V = Builder->CreateFMul(Opnd0, Opnd1);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000783 if (Instruction *I = dyn_cast<Instruction>(V))
784 createInstPostProc(I);
785 return V;
786}
787
788Value *FAddCombine::createFDiv(Value *Opnd0, Value *Opnd1) {
789 Value *V = Builder->CreateFDiv(Opnd0, Opnd1);
790 if (Instruction *I = dyn_cast<Instruction>(V))
791 createInstPostProc(I);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000792 return V;
793}
794
Sanjay Patelc242dbb2014-12-18 21:11:09 +0000795void FAddCombine::createInstPostProc(Instruction *NewInstr, bool NoNumber) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000796 NewInstr->setDebugLoc(Instr->getDebugLoc());
797
798 // Keep track of the number of instruction created.
Owen Anderson1664dc82014-01-20 07:44:53 +0000799 if (!NoNumber)
800 incCreateInstNum();
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000801
802 // Propagate fast-math flags
803 NewInstr->setFastMathFlags(Instr->getFastMathFlags());
804}
805
806// Return the number of instruction needed to emit the N-ary addition.
807// NOTE: Keep this function in sync with createAddendVal().
808unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
809 unsigned OpndNum = Opnds.size();
810 unsigned InstrNeeded = OpndNum - 1;
811
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000812 // The number of addends in the form of "(-1)*x".
813 unsigned NegOpndNum = 0;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000814
815 // Adjust the number of instructions needed to emit the N-ary add.
816 for (AddendVect::const_iterator I = Opnds.begin(), E = Opnds.end();
817 I != E; I++) {
818 const FAddend *Opnd = *I;
819 if (Opnd->isConstant())
820 continue;
821
822 const FAddendCoef &CE = Opnd->getCoef();
823 if (CE.isMinusOne() || CE.isMinusTwo())
824 NegOpndNum++;
825
826 // Let the addend be "c * x". If "c == +/-1", the value of the addend
827 // is immediately available; otherwise, it needs exactly one instruction
828 // to evaluate the value.
829 if (!CE.isMinusOne() && !CE.isOne())
830 InstrNeeded++;
831 }
832 if (NegOpndNum == OpndNum)
833 InstrNeeded++;
834 return InstrNeeded;
835}
836
837// Input Addend Value NeedNeg(output)
838// ================================================================
839// Constant C C false
840// <+/-1, V> V coefficient is -1
841// <2/-2, V> "fadd V, V" coefficient is -2
842// <C, V> "fmul V, C" false
843//
844// NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
Sanjay Patelc242dbb2014-12-18 21:11:09 +0000845Value *FAddCombine::createAddendVal(const FAddend &Opnd, bool &NeedNeg) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000846 const FAddendCoef &Coeff = Opnd.getCoef();
847
848 if (Opnd.isConstant()) {
849 NeedNeg = false;
850 return Coeff.getValue(Instr->getType());
851 }
852
853 Value *OpndVal = Opnd.getSymVal();
854
855 if (Coeff.isMinusOne() || Coeff.isOne()) {
856 NeedNeg = Coeff.isMinusOne();
857 return OpndVal;
858 }
859
860 if (Coeff.isTwo() || Coeff.isMinusTwo()) {
861 NeedNeg = Coeff.isMinusTwo();
862 return createFAdd(OpndVal, OpndVal);
863 }
864
865 NeedNeg = false;
866 return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
867}
868
Rafael Espindola04c22582014-06-04 15:39:14 +0000869// If one of the operands only has one non-zero bit, and if the other
870// operand has a known-zero bit in a more significant place than it (not
871// including the sign bit) the ripple may go up to and fill the zero, but
872// won't change the sign. For example, (X & ~4) + 1.
873static bool checkRippleForAdd(const APInt &Op0KnownZero,
874 const APInt &Op1KnownZero) {
875 APInt Op1MaybeOne = ~Op1KnownZero;
876 // Make sure that one of the operand has at most one bit set to 1.
877 if (Op1MaybeOne.countPopulation() != 1)
878 return false;
879
880 // Find the most significant known 0 other than the sign bit.
881 int BitWidth = Op0KnownZero.getBitWidth();
882 APInt Op0KnownZeroTemp(Op0KnownZero);
883 Op0KnownZeroTemp.clearBit(BitWidth - 1);
884 int Op0ZeroPosition = BitWidth - Op0KnownZeroTemp.countLeadingZeros() - 1;
885
886 int Op1OnePosition = BitWidth - Op1MaybeOne.countLeadingZeros() - 1;
887 assert(Op1OnePosition >= 0);
888
889 // This also covers the case of no known zero, since in that case
890 // Op0ZeroPosition is -1.
891 return Op0ZeroPosition >= Op1OnePosition;
892}
Chris Lattner82aa8882010-01-05 07:18:46 +0000893
Sanjay Patel6eccf482015-09-09 15:24:36 +0000894/// Return true if we can prove that:
Chris Lattner82aa8882010-01-05 07:18:46 +0000895/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
896/// This basically requires proving that the add in the original type would not
897/// overflow to change the sign bit or have a carry out.
Hal Finkel60db0582014-09-07 18:57:58 +0000898bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000899 Instruction &CxtI) {
Chris Lattner82aa8882010-01-05 07:18:46 +0000900 // There are different heuristics we can use for this. Here are some simple
901 // ones.
Michael Ilseman9fc0f252012-12-12 20:57:53 +0000902
Rafael Espindolad1a2c2d2014-06-02 22:01:04 +0000903 // If LHS and RHS each have at least two sign bits, the addition will look
904 // like
905 //
906 // XX..... +
907 // YY.....
908 //
909 // If the carry into the most significant position is 0, X and Y can't both
910 // be 1 and therefore the carry out of the addition is also 0.
911 //
912 // If the carry into the most significant position is 1, X and Y can't both
913 // be 0 and therefore the carry out of the addition is also 1.
914 //
915 // Since the carry into the most significant position is always equal to
916 // the carry out of the addition, there is no signed overflow.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000917 if (ComputeNumSignBits(LHS, 0, &CxtI) > 1 &&
918 ComputeNumSignBits(RHS, 0, &CxtI) > 1)
Chris Lattner82aa8882010-01-05 07:18:46 +0000919 return true;
Michael Ilseman9fc0f252012-12-12 20:57:53 +0000920
David Majnemer54c2ca22014-12-26 09:10:14 +0000921 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
922 APInt LHSKnownZero(BitWidth, 0);
923 APInt LHSKnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000924 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, 0, &CxtI);
Michael Ilseman9fc0f252012-12-12 20:57:53 +0000925
David Majnemer54c2ca22014-12-26 09:10:14 +0000926 APInt RHSKnownZero(BitWidth, 0);
927 APInt RHSKnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000928 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, 0, &CxtI);
Michael Ilseman9fc0f252012-12-12 20:57:53 +0000929
David Majnemer54c2ca22014-12-26 09:10:14 +0000930 // Addition of two 2's compliment numbers having opposite signs will never
931 // overflow.
932 if ((LHSKnownOne[BitWidth - 1] && RHSKnownZero[BitWidth - 1]) ||
933 (LHSKnownZero[BitWidth - 1] && RHSKnownOne[BitWidth - 1]))
934 return true;
Michael Ilseman9fc0f252012-12-12 20:57:53 +0000935
David Majnemer54c2ca22014-12-26 09:10:14 +0000936 // Check if carry bit of addition will not cause overflow.
937 if (checkRippleForAdd(LHSKnownZero, RHSKnownZero))
938 return true;
939 if (checkRippleForAdd(RHSKnownZero, LHSKnownZero))
940 return true;
941
Chris Lattner82aa8882010-01-05 07:18:46 +0000942 return false;
943}
944
David Majnemer57d5bc82014-08-19 23:36:30 +0000945/// \brief Return true if we can prove that:
946/// (sub LHS, RHS) === (sub nsw LHS, RHS)
947/// This basically requires proving that the add in the original type would not
948/// overflow to change the sign bit or have a carry out.
949/// TODO: Handle this for Vectors.
Hal Finkel60db0582014-09-07 18:57:58 +0000950bool InstCombiner::WillNotOverflowSignedSub(Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000951 Instruction &CxtI) {
David Majnemer57d5bc82014-08-19 23:36:30 +0000952 // If LHS and RHS each have at least two sign bits, the subtraction
953 // cannot overflow.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000954 if (ComputeNumSignBits(LHS, 0, &CxtI) > 1 &&
955 ComputeNumSignBits(RHS, 0, &CxtI) > 1)
David Majnemer57d5bc82014-08-19 23:36:30 +0000956 return true;
957
David Majnemer54c2ca22014-12-26 09:10:14 +0000958 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
959 APInt LHSKnownZero(BitWidth, 0);
960 APInt LHSKnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000961 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, 0, &CxtI);
David Majnemer57d5bc82014-08-19 23:36:30 +0000962
David Majnemer54c2ca22014-12-26 09:10:14 +0000963 APInt RHSKnownZero(BitWidth, 0);
964 APInt RHSKnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000965 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, 0, &CxtI);
David Majnemer57d5bc82014-08-19 23:36:30 +0000966
David Majnemer54c2ca22014-12-26 09:10:14 +0000967 // Subtraction of two 2's compliment numbers having identical signs will
968 // never overflow.
969 if ((LHSKnownOne[BitWidth - 1] && RHSKnownOne[BitWidth - 1]) ||
970 (LHSKnownZero[BitWidth - 1] && RHSKnownZero[BitWidth - 1]))
971 return true;
David Majnemer57d5bc82014-08-19 23:36:30 +0000972
David Majnemer54c2ca22014-12-26 09:10:14 +0000973 // TODO: implement logic similar to checkRippleForAdd
David Majnemer57d5bc82014-08-19 23:36:30 +0000974 return false;
975}
976
David Majnemer42158f32014-08-20 07:17:31 +0000977/// \brief Return true if we can prove that:
978/// (sub LHS, RHS) === (sub nuw LHS, RHS)
Hal Finkel60db0582014-09-07 18:57:58 +0000979bool InstCombiner::WillNotOverflowUnsignedSub(Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000980 Instruction &CxtI) {
David Majnemer42158f32014-08-20 07:17:31 +0000981 // If the LHS is negative and the RHS is non-negative, no unsigned wrap.
982 bool LHSKnownNonNegative, LHSKnownNegative;
983 bool RHSKnownNonNegative, RHSKnownNegative;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000984 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, /*Depth=*/0,
985 &CxtI);
986 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, /*Depth=*/0,
987 &CxtI);
David Majnemer42158f32014-08-20 07:17:31 +0000988 if (LHSKnownNegative && RHSKnownNonNegative)
989 return true;
990
991 return false;
992}
993
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000994// Checks if any operand is negative and we can convert add to sub.
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000995// This function checks for following negative patterns
996// ADD(XOR(OR(Z, NOT(C)), C)), 1) == NEG(AND(Z, C))
997// ADD(XOR(AND(Z, C), C), 1) == NEG(OR(Z, ~C))
998// XOR(AND(Z, C), (C + 1)) == NEG(OR(Z, ~C)) if C is even
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000999static Value *checkForNegativeOperand(BinaryOperator &I,
1000 InstCombiner::BuilderTy *Builder) {
Dinesh Dwivediadc07732014-06-27 07:47:35 +00001001 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001002
Dinesh Dwivediadc07732014-06-27 07:47:35 +00001003 // This function creates 2 instructions to replace ADD, we need at least one
1004 // of LHS or RHS to have one use to ensure benefit in transform.
1005 if (!LHS->hasOneUse() && !RHS->hasOneUse())
1006 return nullptr;
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001007
Dinesh Dwivediadc07732014-06-27 07:47:35 +00001008 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
1009 const APInt *C1 = nullptr, *C2 = nullptr;
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001010
Dinesh Dwivediadc07732014-06-27 07:47:35 +00001011 // if ONE is on other side, swap
1012 if (match(RHS, m_Add(m_Value(X), m_One())))
1013 std::swap(LHS, RHS);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001014
Dinesh Dwivediadc07732014-06-27 07:47:35 +00001015 if (match(LHS, m_Add(m_Value(X), m_One()))) {
1016 // if XOR on other side, swap
1017 if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
1018 std::swap(X, RHS);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001019
Dinesh Dwivediadc07732014-06-27 07:47:35 +00001020 if (match(X, m_Xor(m_Value(Y), m_APInt(C1)))) {
1021 // X = XOR(Y, C1), Y = OR(Z, C2), C2 = NOT(C1) ==> X == NOT(AND(Z, C1))
1022 // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, AND(Z, C1))
1023 if (match(Y, m_Or(m_Value(Z), m_APInt(C2))) && (*C2 == ~(*C1))) {
1024 Value *NewAnd = Builder->CreateAnd(Z, *C1);
1025 return Builder->CreateSub(RHS, NewAnd, "sub");
1026 } else if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && (*C1 == *C2)) {
1027 // X = XOR(Y, C1), Y = AND(Z, C2), C2 == C1 ==> X == NOT(OR(Z, ~C1))
1028 // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, OR(Z, ~C1))
1029 Value *NewOr = Builder->CreateOr(Z, ~(*C1));
1030 return Builder->CreateSub(RHS, NewOr, "sub");
1031 }
1032 }
1033 }
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001034
Dinesh Dwivediadc07732014-06-27 07:47:35 +00001035 // Restore LHS and RHS
1036 LHS = I.getOperand(0);
1037 RHS = I.getOperand(1);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001038
Dinesh Dwivediadc07732014-06-27 07:47:35 +00001039 // if XOR is on other side, swap
1040 if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
1041 std::swap(LHS, RHS);
1042
1043 // C2 is ODD
1044 // LHS = XOR(Y, C1), Y = AND(Z, C2), C1 == (C2 + 1) => LHS == NEG(OR(Z, ~C2))
1045 // ADD(LHS, RHS) == SUB(RHS, OR(Z, ~C2))
1046 if (match(LHS, m_Xor(m_Value(Y), m_APInt(C1))))
1047 if (C1->countTrailingZeros() == 0)
1048 if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && *C1 == (*C2 + 1)) {
1049 Value *NewOr = Builder->CreateOr(Z, ~(*C2));
1050 return Builder->CreateSub(RHS, NewOr, "sub");
1051 }
1052 return nullptr;
1053}
1054
1055Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001056 bool Changed = SimplifyAssociativeOrCommutative(I);
1057 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Jingyue Wu33bd53d2014-06-17 00:42:07 +00001058
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001059 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001060 return replaceInstUsesWith(I, V);
Chris Lattner82aa8882010-01-05 07:18:46 +00001061
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001062 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
1063 I.hasNoUnsignedWrap(), DL, TLI, DT, AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001064 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001065
Dinesh Dwivedia71617352014-06-26 05:40:22 +00001066 // (A*B)+(A*C) -> A*(B+C) etc
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001067 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001068 return replaceInstUsesWith(I, V);
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001069
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001070 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1071 // X + (signbit) --> X ^ signbit
1072 const APInt &Val = CI->getValue();
1073 if (Val.isSignBit())
1074 return BinaryOperator::CreateXor(LHS, RHS);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001075
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001076 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1077 // (X & 254)+1 -> (X&254)|1
1078 if (SimplifyDemandedInstructionBits(I))
1079 return &I;
1080
1081 // zext(bool) + C -> bool ? C + 1 : C
1082 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
1083 if (ZI->getSrcTy()->isIntegerTy(1))
1084 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001085
Craig Topperf40110f2014-04-25 05:29:35 +00001086 Value *XorLHS = nullptr; ConstantInt *XorRHS = nullptr;
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001087 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001088 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001089 const APInt &RHSVal = CI->getValue();
Eli Friedmana2cc2872010-01-31 04:29:12 +00001090 unsigned ExtendAmt = 0;
1091 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1092 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1093 if (XorRHS->getValue() == -RHSVal) {
1094 if (RHSVal.isPowerOf2())
1095 ExtendAmt = TySizeBits - RHSVal.logBase2() - 1;
1096 else if (XorRHS->getValue().isPowerOf2())
1097 ExtendAmt = TySizeBits - XorRHS->getValue().logBase2() - 1;
Chris Lattner82aa8882010-01-05 07:18:46 +00001098 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001099
Eli Friedmana2cc2872010-01-31 04:29:12 +00001100 if (ExtendAmt) {
1101 APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt);
Hal Finkel60db0582014-09-07 18:57:58 +00001102 if (!MaskedValueIsZero(XorLHS, Mask, 0, &I))
Eli Friedmana2cc2872010-01-31 04:29:12 +00001103 ExtendAmt = 0;
1104 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001105
Eli Friedmana2cc2872010-01-31 04:29:12 +00001106 if (ExtendAmt) {
1107 Constant *ShAmt = ConstantInt::get(I.getType(), ExtendAmt);
1108 Value *NewShl = Builder->CreateShl(XorLHS, ShAmt, "sext");
1109 return BinaryOperator::CreateAShr(NewShl, ShAmt);
Chris Lattner82aa8882010-01-05 07:18:46 +00001110 }
Benjamin Kramerb16bd772011-12-24 17:31:53 +00001111
1112 // If this is a xor that was canonicalized from a sub, turn it back into
1113 // a sub and fuse this add with it.
1114 if (LHS->hasOneUse() && (XorRHS->getValue()+1).isPowerOf2()) {
1115 IntegerType *IT = cast<IntegerType>(I.getType());
Benjamin Kramerb16bd772011-12-24 17:31:53 +00001116 APInt LHSKnownOne(IT->getBitWidth(), 0);
1117 APInt LHSKnownZero(IT->getBitWidth(), 0);
Hal Finkel60db0582014-09-07 18:57:58 +00001118 computeKnownBits(XorLHS, LHSKnownZero, LHSKnownOne, 0, &I);
Benjamin Kramerb16bd772011-12-24 17:31:53 +00001119 if ((XorRHS->getValue() | LHSKnownZero).isAllOnesValue())
1120 return BinaryOperator::CreateSub(ConstantExpr::getAdd(XorRHS, CI),
1121 XorLHS);
1122 }
David Majnemer70f286d2013-05-06 21:21:31 +00001123 // (X + signbit) + C could have gotten canonicalized to (X ^ signbit) + C,
1124 // transform them into (X + (signbit ^ C))
1125 if (XorRHS->getValue().isSignBit())
Craig Toppereafbd572015-12-21 01:02:28 +00001126 return BinaryOperator::CreateAdd(XorLHS,
1127 ConstantExpr::getXor(XorRHS, CI));
Chris Lattner82aa8882010-01-05 07:18:46 +00001128 }
1129 }
1130
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001131 if (isa<Constant>(RHS) && isa<PHINode>(LHS))
1132 if (Instruction *NV = FoldOpIntoPhi(I))
1133 return NV;
1134
Benjamin Kramer72196f32014-01-19 15:24:22 +00001135 if (I.getType()->getScalarType()->isIntegerTy(1))
Chris Lattner82aa8882010-01-05 07:18:46 +00001136 return BinaryOperator::CreateXor(LHS, RHS);
1137
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001138 // X + X --> X << 1
Chris Lattnerd4067642011-02-17 20:55:29 +00001139 if (LHS == RHS) {
Chris Lattner55920712011-02-17 02:23:02 +00001140 BinaryOperator *New =
1141 BinaryOperator::CreateShl(LHS, ConstantInt::get(I.getType(), 1));
1142 New->setHasNoSignedWrap(I.hasNoSignedWrap());
1143 New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1144 return New;
1145 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001146
1147 // -A + B --> B - A
1148 // -A + -B --> -(A + B)
1149 if (Value *LHSV = dyn_castNegVal(LHS)) {
Nuno Lopes2710f1b2012-06-08 22:30:05 +00001150 if (!isa<Constant>(RHS))
1151 if (Value *RHSV = dyn_castNegVal(RHS)) {
1152 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
1153 return BinaryOperator::CreateNeg(NewAdd);
1154 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001155
Chris Lattner82aa8882010-01-05 07:18:46 +00001156 return BinaryOperator::CreateSub(RHS, LHSV);
1157 }
1158
1159 // A + -B --> A - B
1160 if (!isa<Constant>(RHS))
1161 if (Value *V = dyn_castNegVal(RHS))
1162 return BinaryOperator::CreateSub(LHS, V);
1163
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001164 if (Value *V = checkForNegativeOperand(I, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001165 return replaceInstUsesWith(I, V);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001166
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001167 // A+B --> A|B iff A and B have no bits set in common.
Jingyue Wuca321902015-05-14 23:53:19 +00001168 if (haveNoCommonBitsSet(LHS, RHS, DL, AC, &I, DT))
1169 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner82aa8882010-01-05 07:18:46 +00001170
Benjamin Kramer72196f32014-01-19 15:24:22 +00001171 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
1172 Value *X;
1173 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Chris Lattner82aa8882010-01-05 07:18:46 +00001174 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Benjamin Kramer72196f32014-01-19 15:24:22 +00001175 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001176
Benjamin Kramer72196f32014-01-19 15:24:22 +00001177 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001178 // (X & FF00) + xx00 -> (X+xx00) & FF00
Benjamin Kramer72196f32014-01-19 15:24:22 +00001179 Value *X;
1180 ConstantInt *C2;
Chris Lattner82aa8882010-01-05 07:18:46 +00001181 if (LHS->hasOneUse() &&
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001182 match(LHS, m_And(m_Value(X), m_ConstantInt(C2))) &&
1183 CRHS->getValue() == (CRHS->getValue() & C2->getValue())) {
1184 // See if all bits from the first bit set in the Add RHS up are included
1185 // in the mask. First, get the rightmost bit.
1186 const APInt &AddRHSV = CRHS->getValue();
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001187
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001188 // Form a mask of all bits from the lowest bit added through the top.
1189 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattner82aa8882010-01-05 07:18:46 +00001190
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001191 // See if the and mask includes all of these bits.
1192 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Chris Lattner82aa8882010-01-05 07:18:46 +00001193
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001194 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1195 // Okay, the xform is safe. Insert the new add pronto.
1196 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
1197 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattner82aa8882010-01-05 07:18:46 +00001198 }
1199 }
1200
1201 // Try to fold constant add into select arguments.
1202 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1203 if (Instruction *R = FoldOpIntoSelect(I, SI))
1204 return R;
1205 }
1206
1207 // add (select X 0 (sub n A)) A --> select X A n
1208 {
1209 SelectInst *SI = dyn_cast<SelectInst>(LHS);
1210 Value *A = RHS;
1211 if (!SI) {
1212 SI = dyn_cast<SelectInst>(RHS);
1213 A = LHS;
1214 }
1215 if (SI && SI->hasOneUse()) {
1216 Value *TV = SI->getTrueValue();
1217 Value *FV = SI->getFalseValue();
1218 Value *N;
1219
1220 // Can we fold the add into the argument of the select?
1221 // We check both true and false select arguments for a matching subtract.
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001222 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner82aa8882010-01-05 07:18:46 +00001223 // Fold the add into the true select value.
1224 return SelectInst::Create(SI->getCondition(), N, A);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001225
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001226 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner82aa8882010-01-05 07:18:46 +00001227 // Fold the add into the false select value.
1228 return SelectInst::Create(SI->getCondition(), A, N);
1229 }
1230 }
1231
1232 // Check for (add (sext x), y), see if we can merge this into an
1233 // integer add followed by a sext.
1234 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
1235 // (add (sext x), cst) --> (sext (add x, cst'))
1236 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001237 Constant *CI =
Chris Lattner82aa8882010-01-05 07:18:46 +00001238 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
1239 if (LHSConv->hasOneUse() &&
1240 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001241 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI, I)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001242 // Insert the new, smaller add.
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001243 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner82aa8882010-01-05 07:18:46 +00001244 CI, "addconv");
1245 return new SExtInst(NewAdd, I.getType());
1246 }
1247 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001248
Chris Lattner82aa8882010-01-05 07:18:46 +00001249 // (add (sext x), (sext y)) --> (sext (add int x, y))
1250 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
1251 // Only do this if x/y have the same type, if at last one of them has a
1252 // single use (so we don't increase the number of sexts), and if the
1253 // integer add will not overflow.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001254 if (LHSConv->getOperand(0)->getType() ==
1255 RHSConv->getOperand(0)->getType() &&
Chris Lattner82aa8882010-01-05 07:18:46 +00001256 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1257 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001258 RHSConv->getOperand(0), I)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001259 // Insert the new integer add.
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001260 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattnerdec68472010-01-05 20:56:24 +00001261 RHSConv->getOperand(0), "addconv");
Chris Lattner82aa8882010-01-05 07:18:46 +00001262 return new SExtInst(NewAdd, I.getType());
1263 }
1264 }
1265 }
1266
David Majnemerab07f002014-08-11 22:32:02 +00001267 // (add (xor A, B) (and A, B)) --> (or A, B)
Chad Rosier7813dce2012-04-26 23:29:14 +00001268 {
Craig Topperf40110f2014-04-25 05:29:35 +00001269 Value *A = nullptr, *B = nullptr;
Chad Rosier7813dce2012-04-26 23:29:14 +00001270 if (match(RHS, m_Xor(m_Value(A), m_Value(B))) &&
1271 (match(LHS, m_And(m_Specific(A), m_Specific(B))) ||
1272 match(LHS, m_And(m_Specific(B), m_Specific(A)))))
1273 return BinaryOperator::CreateOr(A, B);
1274
1275 if (match(LHS, m_Xor(m_Value(A), m_Value(B))) &&
1276 (match(RHS, m_And(m_Specific(A), m_Specific(B))) ||
1277 match(RHS, m_And(m_Specific(B), m_Specific(A)))))
1278 return BinaryOperator::CreateOr(A, B);
1279 }
1280
David Majnemerab07f002014-08-11 22:32:02 +00001281 // (add (or A, B) (and A, B)) --> (add A, B)
1282 {
1283 Value *A = nullptr, *B = nullptr;
1284 if (match(RHS, m_Or(m_Value(A), m_Value(B))) &&
1285 (match(LHS, m_And(m_Specific(A), m_Specific(B))) ||
1286 match(LHS, m_And(m_Specific(B), m_Specific(A))))) {
1287 auto *New = BinaryOperator::CreateAdd(A, B);
1288 New->setHasNoSignedWrap(I.hasNoSignedWrap());
1289 New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1290 return New;
1291 }
1292
1293 if (match(LHS, m_Or(m_Value(A), m_Value(B))) &&
1294 (match(RHS, m_And(m_Specific(A), m_Specific(B))) ||
1295 match(RHS, m_And(m_Specific(B), m_Specific(A))))) {
1296 auto *New = BinaryOperator::CreateAdd(A, B);
1297 New->setHasNoSignedWrap(I.hasNoSignedWrap());
1298 New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1299 return New;
1300 }
1301 }
1302
Jingyue Wu33bd53d2014-06-17 00:42:07 +00001303 // TODO(jingyue): Consider WillNotOverflowSignedAdd and
1304 // WillNotOverflowUnsignedAdd to reduce the number of invocations of
1305 // computeKnownBits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001306 if (!I.hasNoSignedWrap() && WillNotOverflowSignedAdd(LHS, RHS, I)) {
Rafael Espindolad1a2c2d2014-06-02 22:01:04 +00001307 Changed = true;
1308 I.setHasNoSignedWrap(true);
1309 }
David Majnemer5310c1e2015-01-07 00:39:50 +00001310 if (!I.hasNoUnsignedWrap() &&
1311 computeOverflowForUnsignedAdd(LHS, RHS, &I) ==
1312 OverflowResult::NeverOverflows) {
Jingyue Wu33bd53d2014-06-17 00:42:07 +00001313 Changed = true;
1314 I.setHasNoUnsignedWrap(true);
1315 }
Rafael Espindolad1a2c2d2014-06-02 22:01:04 +00001316
Craig Topperf40110f2014-04-25 05:29:35 +00001317 return Changed ? &I : nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001318}
1319
1320Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001321 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner82aa8882010-01-05 07:18:46 +00001322 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1323
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001324 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001325 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001326
Chandler Carruth66b31302015-01-04 12:03:27 +00001327 if (Value *V =
1328 SimplifyFAddInst(LHS, RHS, I.getFastMathFlags(), DL, TLI, DT, AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001329 return replaceInstUsesWith(I, V);
Chris Lattner82aa8882010-01-05 07:18:46 +00001330
Stephen Lina9b57f62013-07-20 07:13:13 +00001331 if (isa<Constant>(RHS)) {
1332 if (isa<PHINode>(LHS))
1333 if (Instruction *NV = FoldOpIntoPhi(I))
1334 return NV;
1335
1336 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1337 if (Instruction *NV = FoldOpIntoSelect(I, SI))
1338 return NV;
1339 }
Michael Ilsemane2754dc2012-12-14 22:08:26 +00001340
Chris Lattner82aa8882010-01-05 07:18:46 +00001341 // -A + B --> B - A
1342 // -A + -B --> -(A + B)
Owen Andersone7321662014-01-16 21:26:02 +00001343 if (Value *LHSV = dyn_castFNegVal(LHS)) {
1344 Instruction *RI = BinaryOperator::CreateFSub(RHS, LHSV);
1345 RI->copyFastMathFlags(&I);
1346 return RI;
1347 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001348
1349 // A + -B --> A - B
1350 if (!isa<Constant>(RHS))
Owen Andersone7321662014-01-16 21:26:02 +00001351 if (Value *V = dyn_castFNegVal(RHS)) {
1352 Instruction *RI = BinaryOperator::CreateFSub(LHS, V);
1353 RI->copyFastMathFlags(&I);
1354 return RI;
1355 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001356
Dan Gohman6f34abd2010-03-02 01:11:08 +00001357 // Check for (fadd double (sitofp x), y), see if we can merge this into an
Chris Lattner82aa8882010-01-05 07:18:46 +00001358 // integer add followed by a promotion.
1359 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
Dan Gohman6f34abd2010-03-02 01:11:08 +00001360 // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
Chris Lattner82aa8882010-01-05 07:18:46 +00001361 // ... if the constant fits in the integer value. This is useful for things
1362 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
1363 // requires a constant pool load, and generally allows the add to be better
1364 // instcombined.
1365 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001366 Constant *CI =
Chris Lattner82aa8882010-01-05 07:18:46 +00001367 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
1368 if (LHSConv->hasOneUse() &&
1369 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001370 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI, I)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001371 // Insert the new integer add.
1372 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1373 CI, "addconv");
1374 return new SIToFPInst(NewAdd, I.getType());
1375 }
1376 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001377
Dan Gohman6f34abd2010-03-02 01:11:08 +00001378 // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
Chris Lattner82aa8882010-01-05 07:18:46 +00001379 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
1380 // Only do this if x/y have the same type, if at last one of them has a
1381 // single use (so we don't increase the number of int->fp conversions),
1382 // and if the integer add will not overflow.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001383 if (LHSConv->getOperand(0)->getType() ==
1384 RHSConv->getOperand(0)->getType() &&
Chris Lattner82aa8882010-01-05 07:18:46 +00001385 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1386 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001387 RHSConv->getOperand(0), I)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001388 // Insert the new integer add.
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001389 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner82aa8882010-01-05 07:18:46 +00001390 RHSConv->getOperand(0),"addconv");
1391 return new SIToFPInst(NewAdd, I.getType());
1392 }
1393 }
1394 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001395
Jean-Luc Duprat3e4fc3e2013-05-06 16:55:50 +00001396 // select C, 0, B + select C, A, 0 -> select C, A, B
1397 {
1398 Value *A1, *B1, *C1, *A2, *B2, *C2;
1399 if (match(LHS, m_Select(m_Value(C1), m_Value(A1), m_Value(B1))) &&
1400 match(RHS, m_Select(m_Value(C2), m_Value(A2), m_Value(B2)))) {
1401 if (C1 == C2) {
Craig Topperf40110f2014-04-25 05:29:35 +00001402 Constant *Z1=nullptr, *Z2=nullptr;
Jean-Luc Duprat3e4fc3e2013-05-06 16:55:50 +00001403 Value *A, *B, *C=C1;
1404 if (match(A1, m_AnyZero()) && match(B2, m_AnyZero())) {
1405 Z1 = dyn_cast<Constant>(A1); A = A2;
1406 Z2 = dyn_cast<Constant>(B2); B = B1;
1407 } else if (match(B1, m_AnyZero()) && match(A2, m_AnyZero())) {
1408 Z1 = dyn_cast<Constant>(B1); B = B2;
David Majnemer72a643d2014-11-03 05:53:55 +00001409 Z2 = dyn_cast<Constant>(A2); A = A1;
Jean-Luc Duprat3e4fc3e2013-05-06 16:55:50 +00001410 }
David Majnemer72a643d2014-11-03 05:53:55 +00001411
1412 if (Z1 && Z2 &&
1413 (I.hasNoSignedZeros() ||
Jean-Luc Duprat3e4fc3e2013-05-06 16:55:50 +00001414 (Z1->isNegativeZeroValue() && Z2->isNegativeZeroValue()))) {
1415 return SelectInst::Create(C, A, B);
1416 }
1417 }
1418 }
1419 }
1420
Shuxin Yang37a1efe2012-12-18 23:10:12 +00001421 if (I.hasUnsafeAlgebra()) {
1422 if (Value *V = FAddCombine(Builder).simplify(&I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001423 return replaceInstUsesWith(I, V);
Shuxin Yang37a1efe2012-12-18 23:10:12 +00001424 }
1425
Craig Topperf40110f2014-04-25 05:29:35 +00001426 return Changed ? &I : nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001427}
1428
Chris Lattner82aa8882010-01-05 07:18:46 +00001429/// Optimize pointer differences into the same array into a size. Consider:
1430/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
1431/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
1432///
1433Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
Chris Lattner229907c2011-07-18 04:54:35 +00001434 Type *Ty) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001435 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
1436 // this.
1437 bool Swapped = false;
Craig Topperf40110f2014-04-25 05:29:35 +00001438 GEPOperator *GEP1 = nullptr, *GEP2 = nullptr;
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001439
Chris Lattner82aa8882010-01-05 07:18:46 +00001440 // For now we require one side to be the base pointer "A" or a constant
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001441 // GEP derived from it.
1442 if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001443 // (gep X, ...) - X
1444 if (LHSGEP->getOperand(0) == RHS) {
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001445 GEP1 = LHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001446 Swapped = false;
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001447 } else if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1448 // (gep X, ...) - (gep X, ...)
1449 if (LHSGEP->getOperand(0)->stripPointerCasts() ==
1450 RHSGEP->getOperand(0)->stripPointerCasts()) {
1451 GEP2 = RHSGEP;
1452 GEP1 = LHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001453 Swapped = false;
1454 }
1455 }
1456 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001457
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001458 if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001459 // X - (gep X, ...)
1460 if (RHSGEP->getOperand(0) == LHS) {
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001461 GEP1 = RHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001462 Swapped = true;
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001463 } else if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1464 // (gep X, ...) - (gep X, ...)
1465 if (RHSGEP->getOperand(0)->stripPointerCasts() ==
1466 LHSGEP->getOperand(0)->stripPointerCasts()) {
1467 GEP2 = LHSGEP;
1468 GEP1 = RHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001469 Swapped = true;
1470 }
1471 }
1472 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001473
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001474 // Avoid duplicating the arithmetic if GEP2 has non-constant indices and
1475 // multiple users.
Craig Topperf40110f2014-04-25 05:29:35 +00001476 if (!GEP1 ||
1477 (GEP2 && !GEP2->hasAllConstantIndices() && !GEP2->hasOneUse()))
1478 return nullptr;
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001479
Chris Lattner82aa8882010-01-05 07:18:46 +00001480 // Emit the offset of the GEP and an intptr_t.
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001481 Value *Result = EmitGEPOffset(GEP1);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001482
Chris Lattner82aa8882010-01-05 07:18:46 +00001483 // If we had a constant expression GEP on the other side offsetting the
1484 // pointer, subtract it from the offset we have.
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001485 if (GEP2) {
1486 Value *Offset = EmitGEPOffset(GEP2);
1487 Result = Builder->CreateSub(Result, Offset);
Chris Lattner82aa8882010-01-05 07:18:46 +00001488 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001489
1490 // If we have p - gep(p, ...) then we have to negate the result.
1491 if (Swapped)
1492 Result = Builder->CreateNeg(Result, "diff.neg");
1493
1494 return Builder->CreateIntCast(Result, Ty, true);
1495}
1496
Chris Lattner82aa8882010-01-05 07:18:46 +00001497Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1498 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1499
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001500 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001501 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001502
Duncan Sands0a2c41682010-12-15 14:07:39 +00001503 if (Value *V = SimplifySubInst(Op0, Op1, I.hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00001504 I.hasNoUnsignedWrap(), DL, TLI, DT, AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001505 return replaceInstUsesWith(I, V);
Chris Lattner82aa8882010-01-05 07:18:46 +00001506
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001507 // (A*B)-(A*C) -> A*(B-C) etc
1508 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001509 return replaceInstUsesWith(I, V);
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001510
David Majnemera92687d2014-07-31 04:49:29 +00001511 // If this is a 'B = x-(-A)', change to B = x+A.
Chris Lattner82aa8882010-01-05 07:18:46 +00001512 if (Value *V = dyn_castNegVal(Op1)) {
1513 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
David Majnemera92687d2014-07-31 04:49:29 +00001514
1515 if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
1516 assert(BO->getOpcode() == Instruction::Sub &&
1517 "Expected a subtraction operator!");
1518 if (BO->hasNoSignedWrap() && I.hasNoSignedWrap())
1519 Res->setHasNoSignedWrap(true);
David Majnemer0e6c9862014-08-22 16:41:23 +00001520 } else {
1521 if (cast<Constant>(Op1)->isNotMinSignedValue() && I.hasNoSignedWrap())
1522 Res->setHasNoSignedWrap(true);
David Majnemera92687d2014-07-31 04:49:29 +00001523 }
1524
Chris Lattner82aa8882010-01-05 07:18:46 +00001525 return Res;
1526 }
1527
Duncan Sands9dff9be2010-02-15 16:12:20 +00001528 if (I.getType()->isIntegerTy(1))
Chris Lattner82aa8882010-01-05 07:18:46 +00001529 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001530
1531 // Replace (-1 - A) with (~A).
1532 if (match(Op0, m_AllOnes()))
1533 return BinaryOperator::CreateNot(Op1);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001534
Benjamin Kramer72196f32014-01-19 15:24:22 +00001535 if (Constant *C = dyn_cast<Constant>(Op0)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001536 // C - ~X == X + (1+C)
Craig Topperf40110f2014-04-25 05:29:35 +00001537 Value *X = nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001538 if (match(Op1, m_Not(m_Value(X))))
1539 return BinaryOperator::CreateAdd(X, AddOne(C));
1540
Benjamin Kramer72196f32014-01-19 15:24:22 +00001541 // Try to fold constant sub into select arguments.
1542 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1543 if (Instruction *R = FoldOpIntoSelect(I, SI))
1544 return R;
1545
1546 // C-(X+C2) --> (C-C2)-X
1547 Constant *C2;
1548 if (match(Op1, m_Add(m_Value(X), m_Constant(C2))))
1549 return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
1550
1551 if (SimplifyDemandedInstructionBits(I))
1552 return &I;
1553
1554 // Fold (sub 0, (zext bool to B)) --> (sext bool to B)
1555 if (C->isNullValue() && match(Op1, m_ZExt(m_Value(X))))
1556 if (X->getType()->getScalarType()->isIntegerTy(1))
1557 return CastInst::CreateSExtOrBitCast(X, Op1->getType());
1558
1559 // Fold (sub 0, (sext bool to B)) --> (zext bool to B)
1560 if (C->isNullValue() && match(Op1, m_SExt(m_Value(X))))
1561 if (X->getType()->getScalarType()->isIntegerTy(1))
1562 return CastInst::CreateZExtOrBitCast(X, Op1->getType());
1563 }
1564
1565 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001566 // -(X >>u 31) -> (X >>s 31)
1567 // -(X >>s 31) -> (X >>u 31)
1568 if (C->isZero()) {
David Majnemer72a643d2014-11-03 05:53:55 +00001569 Value *X;
Suyog Sardacba4b1d2014-10-08 08:37:49 +00001570 ConstantInt *CI;
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001571 if (match(Op1, m_LShr(m_Value(X), m_ConstantInt(CI))) &&
1572 // Verify we are shifting out everything but the sign bit.
Suyog Sardacba4b1d2014-10-08 08:37:49 +00001573 CI->getValue() == I.getType()->getPrimitiveSizeInBits() - 1)
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001574 return BinaryOperator::CreateAShr(X, CI);
1575
1576 if (match(Op1, m_AShr(m_Value(X), m_ConstantInt(CI))) &&
1577 // Verify we are shifting out everything but the sign bit.
Suyog Sardacba4b1d2014-10-08 08:37:49 +00001578 CI->getValue() == I.getType()->getPrimitiveSizeInBits() - 1)
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001579 return BinaryOperator::CreateLShr(X, CI);
Chris Lattner82aa8882010-01-05 07:18:46 +00001580 }
Matthias Braunec683342015-04-30 22:04:26 +00001581
1582 // Turn this into a xor if LHS is 2^n-1 and the remaining bits are known
1583 // zero.
1584 APInt IntVal = C->getValue();
1585 if ((IntVal + 1).isPowerOf2()) {
1586 unsigned BitWidth = I.getType()->getScalarSizeInBits();
1587 APInt KnownZero(BitWidth, 0);
1588 APInt KnownOne(BitWidth, 0);
1589 computeKnownBits(&I, KnownZero, KnownOne, 0, &I);
1590 if ((IntVal | KnownZero).isAllOnesValue()) {
1591 return BinaryOperator::CreateXor(Op1, C);
1592 }
1593 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001594 }
1595
David Majnemer72a643d2014-11-03 05:53:55 +00001596 {
Suyog Sardacba4b1d2014-10-08 08:37:49 +00001597 Value *Y;
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001598 // X-(X+Y) == -Y X-(Y+X) == -Y
1599 if (match(Op1, m_Add(m_Specific(Op0), m_Value(Y))) ||
1600 match(Op1, m_Add(m_Value(Y), m_Specific(Op0))))
1601 return BinaryOperator::CreateNeg(Y);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001602
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001603 // (X-Y)-X == -Y
1604 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
1605 return BinaryOperator::CreateNeg(Y);
1606 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001607
David Majnemer312c3e52014-10-19 08:32:32 +00001608 // (sub (or A, B) (xor A, B)) --> (and A, B)
1609 {
1610 Value *A = nullptr, *B = nullptr;
1611 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
1612 (match(Op0, m_Or(m_Specific(A), m_Specific(B))) ||
1613 match(Op0, m_Or(m_Specific(B), m_Specific(A)))))
1614 return BinaryOperator::CreateAnd(A, B);
1615 }
1616
David Majnemer72a643d2014-11-03 05:53:55 +00001617 if (Op0->hasOneUse()) {
1618 Value *Y = nullptr;
1619 // ((X | Y) - X) --> (~X & Y)
1620 if (match(Op0, m_Or(m_Value(Y), m_Specific(Op1))) ||
1621 match(Op0, m_Or(m_Specific(Op1), m_Value(Y))))
1622 return BinaryOperator::CreateAnd(
1623 Y, Builder->CreateNot(Op1, Op1->getName() + ".not"));
1624 }
1625
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001626 if (Op1->hasOneUse()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001627 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
1628 Constant *C = nullptr;
1629 Constant *CI = nullptr;
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001630
1631 // (X - (Y - Z)) --> (X + (Z - Y)).
1632 if (match(Op1, m_Sub(m_Value(Y), m_Value(Z))))
1633 return BinaryOperator::CreateAdd(Op0,
1634 Builder->CreateSub(Z, Y, Op1->getName()));
1635
1636 // (X - (X & Y)) --> (X & ~Y)
1637 //
1638 if (match(Op1, m_And(m_Value(Y), m_Specific(Op0))) ||
1639 match(Op1, m_And(m_Specific(Op0), m_Value(Y))))
1640 return BinaryOperator::CreateAnd(Op0,
1641 Builder->CreateNot(Y, Y->getName() + ".not"));
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001642
David Majnemerbdeef602014-07-02 06:07:09 +00001643 // 0 - (X sdiv C) -> (X sdiv -C) provided the negation doesn't overflow.
1644 if (match(Op1, m_SDiv(m_Value(X), m_Constant(C))) && match(Op0, m_Zero()) &&
David Majnemer0e6c9862014-08-22 16:41:23 +00001645 C->isNotMinSignedValue() && !C->isOneValue())
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001646 return BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(C));
1647
1648 // 0 - (X << Y) -> (-X << Y) when X is freely negatable.
1649 if (match(Op1, m_Shl(m_Value(X), m_Value(Y))) && match(Op0, m_Zero()))
1650 if (Value *XNeg = dyn_castNegVal(X))
1651 return BinaryOperator::CreateShl(XNeg, Y);
1652
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001653 // X - A*-B -> X + A*B
1654 // X - -A*B -> X + A*B
1655 Value *A, *B;
1656 if (match(Op1, m_Mul(m_Value(A), m_Neg(m_Value(B)))) ||
1657 match(Op1, m_Mul(m_Neg(m_Value(A)), m_Value(B))))
1658 return BinaryOperator::CreateAdd(Op0, Builder->CreateMul(A, B));
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001659
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001660 // X - A*CI -> X + A*-CI
1661 // X - CI*A -> X + A*-CI
Benjamin Kramer72196f32014-01-19 15:24:22 +00001662 if (match(Op1, m_Mul(m_Value(A), m_Constant(CI))) ||
1663 match(Op1, m_Mul(m_Constant(CI), m_Value(A)))) {
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001664 Value *NewMul = Builder->CreateMul(A, ConstantExpr::getNeg(CI));
1665 return BinaryOperator::CreateAdd(Op0, NewMul);
Chris Lattner82aa8882010-01-05 07:18:46 +00001666 }
1667 }
1668
Chris Lattner82aa8882010-01-05 07:18:46 +00001669 // Optimize pointer differences into the same array into a size. Consider:
1670 // &A[10] - &A[0]: we should compile this to "10".
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001671 Value *LHSOp, *RHSOp;
1672 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
1673 match(Op1, m_PtrToInt(m_Value(RHSOp))))
1674 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001675 return replaceInstUsesWith(I, Res);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001676
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001677 // trunc(p)-trunc(q) -> trunc(p-q)
1678 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
1679 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
1680 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001681 return replaceInstUsesWith(I, Res);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001682
David Majnemer57d5bc82014-08-19 23:36:30 +00001683 bool Changed = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001684 if (!I.hasNoSignedWrap() && WillNotOverflowSignedSub(Op0, Op1, I)) {
David Majnemer57d5bc82014-08-19 23:36:30 +00001685 Changed = true;
1686 I.setHasNoSignedWrap(true);
1687 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001688 if (!I.hasNoUnsignedWrap() && WillNotOverflowUnsignedSub(Op0, Op1, I)) {
David Majnemer42158f32014-08-20 07:17:31 +00001689 Changed = true;
1690 I.setHasNoUnsignedWrap(true);
1691 }
David Majnemer57d5bc82014-08-19 23:36:30 +00001692
1693 return Changed ? &I : nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001694}
1695
1696Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
1697 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1698
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001699 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001700 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001701
Chandler Carruth66b31302015-01-04 12:03:27 +00001702 if (Value *V =
1703 SimplifyFSubInst(Op0, Op1, I.getFastMathFlags(), DL, TLI, DT, AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001704 return replaceInstUsesWith(I, V);
Michael Ilsemand5787be2012-12-12 00:28:32 +00001705
Sanjay Patele68f7152014-12-31 22:14:05 +00001706 // fsub nsz 0, X ==> fsub nsz -0.0, X
1707 if (I.getFastMathFlags().noSignedZeros() && match(Op0, m_Zero())) {
1708 // Subtraction from -0.0 is the canonical form of fneg.
1709 Instruction *NewI = BinaryOperator::CreateFNeg(Op1);
1710 NewI->copyFastMathFlags(&I);
1711 return NewI;
1712 }
1713
Stephen Lina9b57f62013-07-20 07:13:13 +00001714 if (isa<Constant>(Op0))
1715 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1716 if (Instruction *NV = FoldOpIntoSelect(I, SI))
1717 return NV;
1718
Owen Andersone37c2e42013-07-26 21:40:29 +00001719 // If this is a 'B = x-(-A)', change to B = x+A, potentially looking
1720 // through FP extensions/truncations along the way.
Owen Andersonc7be5192013-07-30 23:53:17 +00001721 if (Value *V = dyn_castFNegVal(Op1)) {
1722 Instruction *NewI = BinaryOperator::CreateFAdd(Op0, V);
1723 NewI->copyFastMathFlags(&I);
1724 return NewI;
1725 }
Owen Andersone37c2e42013-07-26 21:40:29 +00001726 if (FPTruncInst *FPTI = dyn_cast<FPTruncInst>(Op1)) {
1727 if (Value *V = dyn_castFNegVal(FPTI->getOperand(0))) {
1728 Value *NewTrunc = Builder->CreateFPTrunc(V, I.getType());
Owen Andersonc7be5192013-07-30 23:53:17 +00001729 Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewTrunc);
1730 NewI->copyFastMathFlags(&I);
1731 return NewI;
Owen Andersone37c2e42013-07-26 21:40:29 +00001732 }
1733 } else if (FPExtInst *FPEI = dyn_cast<FPExtInst>(Op1)) {
1734 if (Value *V = dyn_castFNegVal(FPEI->getOperand(0))) {
Owen Andersond6d4da02013-07-26 22:06:21 +00001735 Value *NewExt = Builder->CreateFPExt(V, I.getType());
Owen Andersonc7be5192013-07-30 23:53:17 +00001736 Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewExt);
1737 NewI->copyFastMathFlags(&I);
1738 return NewI;
Owen Andersone37c2e42013-07-26 21:40:29 +00001739 }
1740 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001741
Shuxin Yang37a1efe2012-12-18 23:10:12 +00001742 if (I.hasUnsafeAlgebra()) {
1743 if (Value *V = FAddCombine(Builder).simplify(&I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001744 return replaceInstUsesWith(I, V);
Shuxin Yang37a1efe2012-12-18 23:10:12 +00001745 }
1746
Craig Topperf40110f2014-04-25 05:29:35 +00001747 return nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001748}