blob: be31f984db737c228c43bf4702370fce7ad25aaf [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
126 void set(short Coefficient, Value *V) { Coeff.set(Coefficient), Val = V; }
127 void set(const APFloat& Coefficient, Value *V)
128 { Coeff.set(Coefficient); Val = V; }
129 void set(const ConstantFP* Coefficient, Value *V)
130 { Coeff.set(Coefficient->getValueAPF()); Val = V; }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000131
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000132 void negate() { Coeff.negate(); }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000133
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000134 /// Drill down the U-D chain one step to find the definition of V, and
135 /// try to break the definition into one or two addends.
136 static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000137
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000138 /// Similar to FAddend::drillDownOneStep() except that the value being
139 /// splitted is the addend itself.
140 unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000141
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000142 void operator+=(const FAddend &T) {
143 assert((Val == T.Val) && "Symbolic-values disagree");
144 Coeff += T.Coeff;
145 }
146
147 private:
148 void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000149
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000150 // This addend has the value of "Coeff * Val".
151 Value *Val;
152 FAddendCoef Coeff;
153 };
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000154
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000155 /// FAddCombine is the class for optimizing an unsafe fadd/fsub along
156 /// with its neighboring at most two instructions.
157 ///
158 class FAddCombine {
159 public:
Craig Topperf40110f2014-04-25 05:29:35 +0000160 FAddCombine(InstCombiner::BuilderTy *B) : Builder(B), Instr(nullptr) {}
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000161 Value *simplify(Instruction *FAdd);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000162
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000163 private:
164 typedef SmallVector<const FAddend*, 4> AddendVect;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000165
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000166 Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000167
168 Value *performFactorization(Instruction *I);
169
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000170 /// Convert given addend to a Value
171 Value *createAddendVal(const FAddend &A, bool& NeedNeg);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000172
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000173 /// Return the number of instructions needed to emit the N-ary addition.
174 unsigned calcInstrNumber(const AddendVect& Vect);
175 Value *createFSub(Value *Opnd0, Value *Opnd1);
176 Value *createFAdd(Value *Opnd0, Value *Opnd1);
177 Value *createFMul(Value *Opnd0, Value *Opnd1);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000178 Value *createFDiv(Value *Opnd0, Value *Opnd1);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000179 Value *createFNeg(Value *V);
180 Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
Owen Anderson1664dc82014-01-20 07:44:53 +0000181 void createInstPostProc(Instruction *NewInst, bool NoNumber = false);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000182
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000183 InstCombiner::BuilderTy *Builder;
184 Instruction *Instr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000185
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000186 // 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 };
Eugene Zelenkoffec81c2015-11-04 22:32:32 +0000196
197} // anonymous namespace
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000198
199//===----------------------------------------------------------------------===//
200//
201// Implementation of
202// {FAddendCoef, FAddend, FAddition, FAddCombine}.
203//
204//===----------------------------------------------------------------------===//
205FAddendCoef::~FAddendCoef() {
206 if (BufHasFpVal)
207 getFpValPtr()->~APFloat();
208}
209
210void FAddendCoef::set(const APFloat& C) {
211 APFloat *P = getFpValPtr();
212
213 if (isInt()) {
214 // As the buffer is meanless byte stream, we cannot call
215 // APFloat::operator=().
216 new(P) APFloat(C);
217 } else
218 *P = C;
219
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000220 IsFp = BufHasFpVal = true;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000221}
222
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000223void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
224 if (!isInt())
225 return;
226
227 APFloat *P = getFpValPtr();
228 if (IntVal > 0)
229 new(P) APFloat(Sem, IntVal);
230 else {
231 new(P) APFloat(Sem, 0 - IntVal);
232 P->changeSign();
233 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000234 IsFp = BufHasFpVal = true;
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000235}
236
237APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
238 if (Val >= 0)
239 return APFloat(Sem, Val);
240
241 APFloat T(Sem, 0 - Val);
242 T.changeSign();
243
244 return T;
245}
246
247void FAddendCoef::operator=(const FAddendCoef &That) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000248 if (That.isInt())
249 set(That.IntVal);
250 else
251 set(That.getFpVal());
252}
253
254void FAddendCoef::operator+=(const FAddendCoef &That) {
255 enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
256 if (isInt() == That.isInt()) {
257 if (isInt())
258 IntVal += That.IntVal;
259 else
260 getFpVal().add(That.getFpVal(), RndMode);
261 return;
262 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000263
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000264 if (isInt()) {
265 const APFloat &T = That.getFpVal();
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000266 convertToFpType(T.getSemantics());
267 getFpVal().add(T, RndMode);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000268 return;
269 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000270
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000271 APFloat &T = getFpVal();
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000272 T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000273}
274
275void FAddendCoef::operator-=(const FAddendCoef &That) {
276 enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
277 if (isInt() == That.isInt()) {
278 if (isInt())
279 IntVal -= That.IntVal;
280 else
281 getFpVal().subtract(That.getFpVal(), RndMode);
282 return;
283 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000284
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000285 if (isInt()) {
286 const APFloat &T = That.getFpVal();
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000287 convertToFpType(T.getSemantics());
288 getFpVal().subtract(T, RndMode);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000289 return;
290 }
291
292 APFloat &T = getFpVal();
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000293 T.subtract(createAPFloatFromInt(T.getSemantics(), IntVal), RndMode);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000294}
295
296void FAddendCoef::operator*=(const FAddendCoef &That) {
297 if (That.isOne())
298 return;
299
300 if (That.isMinusOne()) {
301 negate();
302 return;
303 }
304
305 if (isInt() && That.isInt()) {
306 int Res = IntVal * (int)That.IntVal;
307 assert(!insaneIntVal(Res) && "Insane int value");
308 IntVal = Res;
309 return;
310 }
311
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000312 const fltSemantics &Semantic =
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000313 isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
314
315 if (isInt())
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000316 convertToFpType(Semantic);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000317 APFloat &F0 = getFpVal();
318
319 if (That.isInt())
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000320 F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
321 APFloat::rmNearestTiesToEven);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000322 else
323 F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven);
324
325 return;
326}
327
328void FAddendCoef::negate() {
329 if (isInt())
330 IntVal = 0 - IntVal;
331 else
332 getFpVal().changeSign();
333}
334
335Value *FAddendCoef::getValue(Type *Ty) const {
336 return isInt() ?
337 ConstantFP::get(Ty, float(IntVal)) :
338 ConstantFP::get(Ty->getContext(), getFpVal());
339}
340
341// The definition of <Val> Addends
342// =========================================
343// A + B <1, A>, <1,B>
344// A - B <1, A>, <1,B>
345// 0 - B <-1, B>
346// C * A, <C, A>
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000347// A + C <1, A> <C, NULL>
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000348// 0 +/- 0 <0, NULL> (corner case)
349//
350// Legend: A and B are not constant, C is constant
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000351//
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000352unsigned FAddend::drillValueDownOneStep
353 (Value *Val, FAddend &Addend0, FAddend &Addend1) {
Craig Topperf40110f2014-04-25 05:29:35 +0000354 Instruction *I = nullptr;
355 if (!Val || !(I = dyn_cast<Instruction>(Val)))
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000356 return 0;
357
358 unsigned Opcode = I->getOpcode();
359
360 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
361 ConstantFP *C0, *C1;
362 Value *Opnd0 = I->getOperand(0);
363 Value *Opnd1 = I->getOperand(1);
364 if ((C0 = dyn_cast<ConstantFP>(Opnd0)) && C0->isZero())
Craig Topperf40110f2014-04-25 05:29:35 +0000365 Opnd0 = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000366
367 if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
Craig Topperf40110f2014-04-25 05:29:35 +0000368 Opnd1 = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000369
370 if (Opnd0) {
371 if (!C0)
372 Addend0.set(1, Opnd0);
373 else
Craig Topperf40110f2014-04-25 05:29:35 +0000374 Addend0.set(C0, nullptr);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000375 }
376
377 if (Opnd1) {
378 FAddend &Addend = Opnd0 ? Addend1 : Addend0;
379 if (!C1)
380 Addend.set(1, Opnd1);
381 else
Craig Topperf40110f2014-04-25 05:29:35 +0000382 Addend.set(C1, nullptr);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000383 if (Opcode == Instruction::FSub)
384 Addend.negate();
385 }
386
387 if (Opnd0 || Opnd1)
388 return Opnd0 && Opnd1 ? 2 : 1;
389
390 // Both operands are zero. Weird!
Craig Topperf40110f2014-04-25 05:29:35 +0000391 Addend0.set(APFloat(C0->getValueAPF().getSemantics()), nullptr);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000392 return 1;
393 }
394
395 if (I->getOpcode() == Instruction::FMul) {
396 Value *V0 = I->getOperand(0);
397 Value *V1 = I->getOperand(1);
398 if (ConstantFP *C = dyn_cast<ConstantFP>(V0)) {
399 Addend0.set(C, V1);
400 return 1;
401 }
402
403 if (ConstantFP *C = dyn_cast<ConstantFP>(V1)) {
404 Addend0.set(C, V0);
405 return 1;
406 }
407 }
408
409 return 0;
410}
411
412// Try to break *this* addend into two addends. e.g. Suppose this addend is
413// <2.3, V>, and V = X + Y, by calling this function, we obtain two addends,
414// i.e. <2.3, X> and <2.3, Y>.
415//
416unsigned FAddend::drillAddendDownOneStep
417 (FAddend &Addend0, FAddend &Addend1) const {
418 if (isConstant())
419 return 0;
420
421 unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000422 if (!BreakNum || Coeff.isOne())
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000423 return BreakNum;
424
425 Addend0.Scale(Coeff);
426
427 if (BreakNum == 2)
428 Addend1.Scale(Coeff);
429
430 return BreakNum;
431}
432
Shuxin Yang2eca6022013-03-14 18:08:26 +0000433// Try to perform following optimization on the input instruction I. Return the
434// simplified expression if was successful; otherwise, return 0.
435//
436// Instruction "I" is Simplified into
437// -------------------------------------------------------
438// (x * y) +/- (x * z) x * (y +/- z)
439// (y / x) +/- (z / x) (y +/- z) / x
440//
441Value *FAddCombine::performFactorization(Instruction *I) {
442 assert((I->getOpcode() == Instruction::FAdd ||
443 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000444
Shuxin Yang2eca6022013-03-14 18:08:26 +0000445 Instruction *I0 = dyn_cast<Instruction>(I->getOperand(0));
446 Instruction *I1 = dyn_cast<Instruction>(I->getOperand(1));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000447
Shuxin Yang2eca6022013-03-14 18:08:26 +0000448 if (!I0 || !I1 || I0->getOpcode() != I1->getOpcode())
Craig Topperf40110f2014-04-25 05:29:35 +0000449 return nullptr;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000450
451 bool isMpy = false;
452 if (I0->getOpcode() == Instruction::FMul)
453 isMpy = true;
454 else if (I0->getOpcode() != Instruction::FDiv)
Craig Topperf40110f2014-04-25 05:29:35 +0000455 return nullptr;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000456
457 Value *Opnd0_0 = I0->getOperand(0);
458 Value *Opnd0_1 = I0->getOperand(1);
459 Value *Opnd1_0 = I1->getOperand(0);
460 Value *Opnd1_1 = I1->getOperand(1);
461
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000462 // Input Instr I Factor AddSub0 AddSub1
Shuxin Yang2eca6022013-03-14 18:08:26 +0000463 // ----------------------------------------------
464 // (x*y) +/- (x*z) x y z
465 // (y/x) +/- (z/x) x y z
466 //
Craig Topperf40110f2014-04-25 05:29:35 +0000467 Value *Factor = nullptr;
468 Value *AddSub0 = nullptr, *AddSub1 = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000469
Shuxin Yang2eca6022013-03-14 18:08:26 +0000470 if (isMpy) {
471 if (Opnd0_0 == Opnd1_0 || Opnd0_0 == Opnd1_1)
472 Factor = Opnd0_0;
473 else if (Opnd0_1 == Opnd1_0 || Opnd0_1 == Opnd1_1)
474 Factor = Opnd0_1;
475
476 if (Factor) {
477 AddSub0 = (Factor == Opnd0_0) ? Opnd0_1 : Opnd0_0;
478 AddSub1 = (Factor == Opnd1_0) ? Opnd1_1 : Opnd1_0;
479 }
480 } else if (Opnd0_1 == Opnd1_1) {
481 Factor = Opnd0_1;
482 AddSub0 = Opnd0_0;
483 AddSub1 = Opnd1_0;
484 }
485
486 if (!Factor)
Craig Topperf40110f2014-04-25 05:29:35 +0000487 return nullptr;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000488
Owen Anderson1664dc82014-01-20 07:44:53 +0000489 FastMathFlags Flags;
490 Flags.setUnsafeAlgebra();
491 if (I0) Flags &= I->getFastMathFlags();
492 if (I1) Flags &= I->getFastMathFlags();
493
Shuxin Yang2eca6022013-03-14 18:08:26 +0000494 // Create expression "NewAddSub = AddSub0 +/- AddsSub1"
495 Value *NewAddSub = (I->getOpcode() == Instruction::FAdd) ?
496 createFAdd(AddSub0, AddSub1) :
497 createFSub(AddSub0, AddSub1);
498 if (ConstantFP *CFP = dyn_cast<ConstantFP>(NewAddSub)) {
499 const APFloat &F = CFP->getValueAPF();
Michael Gottesmanc2af8d62013-06-26 23:17:31 +0000500 if (!F.isNormal())
Craig Topperf40110f2014-04-25 05:29:35 +0000501 return nullptr;
Owen Anderson1664dc82014-01-20 07:44:53 +0000502 } else if (Instruction *II = dyn_cast<Instruction>(NewAddSub))
503 II->setFastMathFlags(Flags);
504
505 if (isMpy) {
506 Value *RI = createFMul(Factor, NewAddSub);
507 if (Instruction *II = dyn_cast<Instruction>(RI))
508 II->setFastMathFlags(Flags);
509 return RI;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000510 }
511
Owen Anderson1664dc82014-01-20 07:44:53 +0000512 Value *RI = createFDiv(NewAddSub, Factor);
513 if (Instruction *II = dyn_cast<Instruction>(RI))
514 II->setFastMathFlags(Flags);
515 return RI;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000516}
517
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000518Value *FAddCombine::simplify(Instruction *I) {
519 assert(I->hasUnsafeAlgebra() && "Should be in unsafe mode");
520
521 // Currently we are not able to handle vector type.
522 if (I->getType()->isVectorTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000523 return nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000524
525 assert((I->getOpcode() == Instruction::FAdd ||
526 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
527
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000528 // Save the instruction before calling other member-functions.
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000529 Instr = I;
530
531 FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
532
533 unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
534
535 // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
536 unsigned Opnd0_ExpNum = 0;
537 unsigned Opnd1_ExpNum = 0;
538
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000539 if (!Opnd0.isConstant())
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000540 Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
541
542 // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
543 if (OpndNum == 2 && !Opnd1.isConstant())
544 Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
545
546 // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
547 if (Opnd0_ExpNum && Opnd1_ExpNum) {
548 AddendVect AllOpnds;
549 AllOpnds.push_back(&Opnd0_0);
550 AllOpnds.push_back(&Opnd1_0);
551 if (Opnd0_ExpNum == 2)
552 AllOpnds.push_back(&Opnd0_1);
553 if (Opnd1_ExpNum == 2)
554 AllOpnds.push_back(&Opnd1_1);
555
556 // Compute instruction quota. We should save at least one instruction.
557 unsigned InstQuota = 0;
558
559 Value *V0 = I->getOperand(0);
560 Value *V1 = I->getOperand(1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000561 InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000562 (!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
563
564 if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
565 return R;
566 }
567
568 if (OpndNum != 2) {
569 // The input instruction is : "I=0.0 +/- V". If the "V" were able to be
570 // splitted into two addends, say "V = X - Y", the instruction would have
571 // been optimized into "I = Y - X" in the previous steps.
572 //
573 const FAddendCoef &CE = Opnd0.getCoef();
Craig Topperf40110f2014-04-25 05:29:35 +0000574 return CE.isOne() ? Opnd0.getSymVal() : nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000575 }
576
577 // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
578 if (Opnd1_ExpNum) {
579 AddendVect AllOpnds;
580 AllOpnds.push_back(&Opnd0);
581 AllOpnds.push_back(&Opnd1_0);
582 if (Opnd1_ExpNum == 2)
583 AllOpnds.push_back(&Opnd1_1);
584
585 if (Value *R = simplifyFAdd(AllOpnds, 1))
586 return R;
587 }
588
589 // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
590 if (Opnd0_ExpNum) {
591 AddendVect AllOpnds;
592 AllOpnds.push_back(&Opnd1);
593 AllOpnds.push_back(&Opnd0_0);
594 if (Opnd0_ExpNum == 2)
595 AllOpnds.push_back(&Opnd0_1);
596
597 if (Value *R = simplifyFAdd(AllOpnds, 1))
598 return R;
599 }
600
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000601 // step 6: Try factorization as the last resort,
Shuxin Yang2eca6022013-03-14 18:08:26 +0000602 return performFactorization(I);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000603}
604
605Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000606 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
Sanjay Patelc242dbb2014-12-18 21:11:09 +0000754Value *FAddCombine::createFSub(Value *Opnd0, Value *Opnd1) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000755 Value *V = Builder->CreateFSub(Opnd0, Opnd1);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000756 if (Instruction *I = dyn_cast<Instruction>(V))
757 createInstPostProc(I);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000758 return V;
759}
760
761Value *FAddCombine::createFNeg(Value *V) {
Sanjay Patelea3c8022014-12-19 16:44:08 +0000762 Value *Zero = cast<Value>(ConstantFP::getZeroValueForNegation(V->getType()));
Owen Anderson1664dc82014-01-20 07:44:53 +0000763 Value *NewV = createFSub(Zero, V);
764 if (Instruction *I = dyn_cast<Instruction>(NewV))
765 createInstPostProc(I, true); // fneg's don't receive instruction numbers.
766 return NewV;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000767}
768
Sanjay Patelc242dbb2014-12-18 21:11:09 +0000769Value *FAddCombine::createFAdd(Value *Opnd0, Value *Opnd1) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000770 Value *V = Builder->CreateFAdd(Opnd0, Opnd1);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000771 if (Instruction *I = dyn_cast<Instruction>(V))
772 createInstPostProc(I);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000773 return V;
774}
775
776Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
777 Value *V = Builder->CreateFMul(Opnd0, Opnd1);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000778 if (Instruction *I = dyn_cast<Instruction>(V))
779 createInstPostProc(I);
780 return V;
781}
782
783Value *FAddCombine::createFDiv(Value *Opnd0, Value *Opnd1) {
784 Value *V = Builder->CreateFDiv(Opnd0, Opnd1);
785 if (Instruction *I = dyn_cast<Instruction>(V))
786 createInstPostProc(I);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000787 return V;
788}
789
Sanjay Patelc242dbb2014-12-18 21:11:09 +0000790void FAddCombine::createInstPostProc(Instruction *NewInstr, bool NoNumber) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000791 NewInstr->setDebugLoc(Instr->getDebugLoc());
792
793 // Keep track of the number of instruction created.
Owen Anderson1664dc82014-01-20 07:44:53 +0000794 if (!NoNumber)
795 incCreateInstNum();
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000796
797 // Propagate fast-math flags
798 NewInstr->setFastMathFlags(Instr->getFastMathFlags());
799}
800
801// Return the number of instruction needed to emit the N-ary addition.
802// NOTE: Keep this function in sync with createAddendVal().
803unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
804 unsigned OpndNum = Opnds.size();
805 unsigned InstrNeeded = OpndNum - 1;
806
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000807 // The number of addends in the form of "(-1)*x".
808 unsigned NegOpndNum = 0;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000809
810 // Adjust the number of instructions needed to emit the N-ary add.
811 for (AddendVect::const_iterator I = Opnds.begin(), E = Opnds.end();
812 I != E; I++) {
813 const FAddend *Opnd = *I;
814 if (Opnd->isConstant())
815 continue;
816
817 const FAddendCoef &CE = Opnd->getCoef();
818 if (CE.isMinusOne() || CE.isMinusTwo())
819 NegOpndNum++;
820
821 // Let the addend be "c * x". If "c == +/-1", the value of the addend
822 // is immediately available; otherwise, it needs exactly one instruction
823 // to evaluate the value.
824 if (!CE.isMinusOne() && !CE.isOne())
825 InstrNeeded++;
826 }
827 if (NegOpndNum == OpndNum)
828 InstrNeeded++;
829 return InstrNeeded;
830}
831
832// Input Addend Value NeedNeg(output)
833// ================================================================
834// Constant C C false
835// <+/-1, V> V coefficient is -1
836// <2/-2, V> "fadd V, V" coefficient is -2
837// <C, V> "fmul V, C" false
838//
839// NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
Sanjay Patelc242dbb2014-12-18 21:11:09 +0000840Value *FAddCombine::createAddendVal(const FAddend &Opnd, bool &NeedNeg) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000841 const FAddendCoef &Coeff = Opnd.getCoef();
842
843 if (Opnd.isConstant()) {
844 NeedNeg = false;
845 return Coeff.getValue(Instr->getType());
846 }
847
848 Value *OpndVal = Opnd.getSymVal();
849
850 if (Coeff.isMinusOne() || Coeff.isOne()) {
851 NeedNeg = Coeff.isMinusOne();
852 return OpndVal;
853 }
854
855 if (Coeff.isTwo() || Coeff.isMinusTwo()) {
856 NeedNeg = Coeff.isMinusTwo();
857 return createFAdd(OpndVal, OpndVal);
858 }
859
860 NeedNeg = false;
861 return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
862}
863
Rafael Espindola04c22582014-06-04 15:39:14 +0000864// If one of the operands only has one non-zero bit, and if the other
865// operand has a known-zero bit in a more significant place than it (not
866// including the sign bit) the ripple may go up to and fill the zero, but
867// won't change the sign. For example, (X & ~4) + 1.
868static bool checkRippleForAdd(const APInt &Op0KnownZero,
869 const APInt &Op1KnownZero) {
870 APInt Op1MaybeOne = ~Op1KnownZero;
871 // Make sure that one of the operand has at most one bit set to 1.
872 if (Op1MaybeOne.countPopulation() != 1)
873 return false;
874
875 // Find the most significant known 0 other than the sign bit.
876 int BitWidth = Op0KnownZero.getBitWidth();
877 APInt Op0KnownZeroTemp(Op0KnownZero);
878 Op0KnownZeroTemp.clearBit(BitWidth - 1);
879 int Op0ZeroPosition = BitWidth - Op0KnownZeroTemp.countLeadingZeros() - 1;
880
881 int Op1OnePosition = BitWidth - Op1MaybeOne.countLeadingZeros() - 1;
882 assert(Op1OnePosition >= 0);
883
884 // This also covers the case of no known zero, since in that case
885 // Op0ZeroPosition is -1.
886 return Op0ZeroPosition >= Op1OnePosition;
887}
Chris Lattner82aa8882010-01-05 07:18:46 +0000888
Sanjay Patel6eccf482015-09-09 15:24:36 +0000889/// Return true if we can prove that:
Chris Lattner82aa8882010-01-05 07:18:46 +0000890/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
891/// This basically requires proving that the add in the original type would not
892/// overflow to change the sign bit or have a carry out.
Hal Finkel60db0582014-09-07 18:57:58 +0000893bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000894 Instruction &CxtI) {
Chris Lattner82aa8882010-01-05 07:18:46 +0000895 // There are different heuristics we can use for this. Here are some simple
896 // ones.
Michael Ilseman9fc0f252012-12-12 20:57:53 +0000897
Rafael Espindolad1a2c2d2014-06-02 22:01:04 +0000898 // If LHS and RHS each have at least two sign bits, the addition will look
899 // like
900 //
901 // XX..... +
902 // YY.....
903 //
904 // If the carry into the most significant position is 0, X and Y can't both
905 // be 1 and therefore the carry out of the addition is also 0.
906 //
907 // If the carry into the most significant position is 1, X and Y can't both
908 // be 0 and therefore the carry out of the addition is also 1.
909 //
910 // Since the carry into the most significant position is always equal to
911 // the carry out of the addition, there is no signed overflow.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000912 if (ComputeNumSignBits(LHS, 0, &CxtI) > 1 &&
913 ComputeNumSignBits(RHS, 0, &CxtI) > 1)
Chris Lattner82aa8882010-01-05 07:18:46 +0000914 return true;
Michael Ilseman9fc0f252012-12-12 20:57:53 +0000915
David Majnemer54c2ca22014-12-26 09:10:14 +0000916 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
917 APInt LHSKnownZero(BitWidth, 0);
918 APInt LHSKnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000919 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, 0, &CxtI);
Michael Ilseman9fc0f252012-12-12 20:57:53 +0000920
David Majnemer54c2ca22014-12-26 09:10:14 +0000921 APInt RHSKnownZero(BitWidth, 0);
922 APInt RHSKnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000923 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, 0, &CxtI);
Michael Ilseman9fc0f252012-12-12 20:57:53 +0000924
David Majnemer54c2ca22014-12-26 09:10:14 +0000925 // Addition of two 2's compliment numbers having opposite signs will never
926 // overflow.
927 if ((LHSKnownOne[BitWidth - 1] && RHSKnownZero[BitWidth - 1]) ||
928 (LHSKnownZero[BitWidth - 1] && RHSKnownOne[BitWidth - 1]))
929 return true;
Michael Ilseman9fc0f252012-12-12 20:57:53 +0000930
David Majnemer54c2ca22014-12-26 09:10:14 +0000931 // Check if carry bit of addition will not cause overflow.
932 if (checkRippleForAdd(LHSKnownZero, RHSKnownZero))
933 return true;
934 if (checkRippleForAdd(RHSKnownZero, LHSKnownZero))
935 return true;
936
Chris Lattner82aa8882010-01-05 07:18:46 +0000937 return false;
938}
939
David Majnemer57d5bc82014-08-19 23:36:30 +0000940/// \brief Return true if we can prove that:
941/// (sub LHS, RHS) === (sub nsw LHS, RHS)
942/// This basically requires proving that the add in the original type would not
943/// overflow to change the sign bit or have a carry out.
944/// TODO: Handle this for Vectors.
Hal Finkel60db0582014-09-07 18:57:58 +0000945bool InstCombiner::WillNotOverflowSignedSub(Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000946 Instruction &CxtI) {
David Majnemer57d5bc82014-08-19 23:36:30 +0000947 // If LHS and RHS each have at least two sign bits, the subtraction
948 // cannot overflow.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000949 if (ComputeNumSignBits(LHS, 0, &CxtI) > 1 &&
950 ComputeNumSignBits(RHS, 0, &CxtI) > 1)
David Majnemer57d5bc82014-08-19 23:36:30 +0000951 return true;
952
David Majnemer54c2ca22014-12-26 09:10:14 +0000953 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
954 APInt LHSKnownZero(BitWidth, 0);
955 APInt LHSKnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000956 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, 0, &CxtI);
David Majnemer57d5bc82014-08-19 23:36:30 +0000957
David Majnemer54c2ca22014-12-26 09:10:14 +0000958 APInt RHSKnownZero(BitWidth, 0);
959 APInt RHSKnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000960 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, 0, &CxtI);
David Majnemer57d5bc82014-08-19 23:36:30 +0000961
David Majnemer54c2ca22014-12-26 09:10:14 +0000962 // Subtraction of two 2's compliment numbers having identical signs will
963 // never overflow.
964 if ((LHSKnownOne[BitWidth - 1] && RHSKnownOne[BitWidth - 1]) ||
965 (LHSKnownZero[BitWidth - 1] && RHSKnownZero[BitWidth - 1]))
966 return true;
David Majnemer57d5bc82014-08-19 23:36:30 +0000967
David Majnemer54c2ca22014-12-26 09:10:14 +0000968 // TODO: implement logic similar to checkRippleForAdd
David Majnemer57d5bc82014-08-19 23:36:30 +0000969 return false;
970}
971
David Majnemer42158f32014-08-20 07:17:31 +0000972/// \brief Return true if we can prove that:
973/// (sub LHS, RHS) === (sub nuw LHS, RHS)
Hal Finkel60db0582014-09-07 18:57:58 +0000974bool InstCombiner::WillNotOverflowUnsignedSub(Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000975 Instruction &CxtI) {
David Majnemer42158f32014-08-20 07:17:31 +0000976 // If the LHS is negative and the RHS is non-negative, no unsigned wrap.
977 bool LHSKnownNonNegative, LHSKnownNegative;
978 bool RHSKnownNonNegative, RHSKnownNegative;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000979 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, /*Depth=*/0,
980 &CxtI);
981 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, /*Depth=*/0,
982 &CxtI);
David Majnemer42158f32014-08-20 07:17:31 +0000983 if (LHSKnownNegative && RHSKnownNonNegative)
984 return true;
985
986 return false;
987}
988
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000989// Checks if any operand is negative and we can convert add to sub.
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000990// This function checks for following negative patterns
991// ADD(XOR(OR(Z, NOT(C)), C)), 1) == NEG(AND(Z, C))
992// ADD(XOR(AND(Z, C), C), 1) == NEG(OR(Z, ~C))
993// XOR(AND(Z, C), (C + 1)) == NEG(OR(Z, ~C)) if C is even
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000994static Value *checkForNegativeOperand(BinaryOperator &I,
995 InstCombiner::BuilderTy *Builder) {
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000996 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000997
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000998 // This function creates 2 instructions to replace ADD, we need at least one
999 // of LHS or RHS to have one use to ensure benefit in transform.
1000 if (!LHS->hasOneUse() && !RHS->hasOneUse())
1001 return nullptr;
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001002
Dinesh Dwivediadc07732014-06-27 07:47:35 +00001003 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
1004 const APInt *C1 = nullptr, *C2 = nullptr;
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001005
Dinesh Dwivediadc07732014-06-27 07:47:35 +00001006 // if ONE is on other side, swap
1007 if (match(RHS, m_Add(m_Value(X), m_One())))
1008 std::swap(LHS, RHS);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001009
Dinesh Dwivediadc07732014-06-27 07:47:35 +00001010 if (match(LHS, m_Add(m_Value(X), m_One()))) {
1011 // if XOR on other side, swap
1012 if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
1013 std::swap(X, RHS);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001014
Dinesh Dwivediadc07732014-06-27 07:47:35 +00001015 if (match(X, m_Xor(m_Value(Y), m_APInt(C1)))) {
1016 // X = XOR(Y, C1), Y = OR(Z, C2), C2 = NOT(C1) ==> X == NOT(AND(Z, C1))
1017 // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, AND(Z, C1))
1018 if (match(Y, m_Or(m_Value(Z), m_APInt(C2))) && (*C2 == ~(*C1))) {
1019 Value *NewAnd = Builder->CreateAnd(Z, *C1);
1020 return Builder->CreateSub(RHS, NewAnd, "sub");
1021 } else if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && (*C1 == *C2)) {
1022 // X = XOR(Y, C1), Y = AND(Z, C2), C2 == C1 ==> X == NOT(OR(Z, ~C1))
1023 // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, OR(Z, ~C1))
1024 Value *NewOr = Builder->CreateOr(Z, ~(*C1));
1025 return Builder->CreateSub(RHS, NewOr, "sub");
1026 }
1027 }
1028 }
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001029
Dinesh Dwivediadc07732014-06-27 07:47:35 +00001030 // Restore LHS and RHS
1031 LHS = I.getOperand(0);
1032 RHS = I.getOperand(1);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001033
Dinesh Dwivediadc07732014-06-27 07:47:35 +00001034 // if XOR is on other side, swap
1035 if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
1036 std::swap(LHS, RHS);
1037
1038 // C2 is ODD
1039 // LHS = XOR(Y, C1), Y = AND(Z, C2), C1 == (C2 + 1) => LHS == NEG(OR(Z, ~C2))
1040 // ADD(LHS, RHS) == SUB(RHS, OR(Z, ~C2))
1041 if (match(LHS, m_Xor(m_Value(Y), m_APInt(C1))))
1042 if (C1->countTrailingZeros() == 0)
1043 if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && *C1 == (*C2 + 1)) {
1044 Value *NewOr = Builder->CreateOr(Z, ~(*C2));
1045 return Builder->CreateSub(RHS, NewOr, "sub");
1046 }
1047 return nullptr;
1048}
1049
1050Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001051 bool Changed = SimplifyAssociativeOrCommutative(I);
1052 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Jingyue Wu33bd53d2014-06-17 00:42:07 +00001053
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001054 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001055 return replaceInstUsesWith(I, V);
Chris Lattner82aa8882010-01-05 07:18:46 +00001056
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001057 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
1058 I.hasNoUnsignedWrap(), DL, TLI, DT, AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001059 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001060
Dinesh Dwivedia71617352014-06-26 05:40:22 +00001061 // (A*B)+(A*C) -> A*(B+C) etc
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001062 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001063 return replaceInstUsesWith(I, V);
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001064
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001065 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1066 // X + (signbit) --> X ^ signbit
1067 const APInt &Val = CI->getValue();
1068 if (Val.isSignBit())
1069 return BinaryOperator::CreateXor(LHS, RHS);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001070
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001071 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1072 // (X & 254)+1 -> (X&254)|1
1073 if (SimplifyDemandedInstructionBits(I))
1074 return &I;
1075
1076 // zext(bool) + C -> bool ? C + 1 : C
1077 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
1078 if (ZI->getSrcTy()->isIntegerTy(1))
1079 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001080
Craig Topperf40110f2014-04-25 05:29:35 +00001081 Value *XorLHS = nullptr; ConstantInt *XorRHS = nullptr;
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001082 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001083 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001084 const APInt &RHSVal = CI->getValue();
Eli Friedmana2cc2872010-01-31 04:29:12 +00001085 unsigned ExtendAmt = 0;
1086 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1087 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1088 if (XorRHS->getValue() == -RHSVal) {
1089 if (RHSVal.isPowerOf2())
1090 ExtendAmt = TySizeBits - RHSVal.logBase2() - 1;
1091 else if (XorRHS->getValue().isPowerOf2())
1092 ExtendAmt = TySizeBits - XorRHS->getValue().logBase2() - 1;
Chris Lattner82aa8882010-01-05 07:18:46 +00001093 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001094
Eli Friedmana2cc2872010-01-31 04:29:12 +00001095 if (ExtendAmt) {
1096 APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt);
Hal Finkel60db0582014-09-07 18:57:58 +00001097 if (!MaskedValueIsZero(XorLHS, Mask, 0, &I))
Eli Friedmana2cc2872010-01-31 04:29:12 +00001098 ExtendAmt = 0;
1099 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001100
Eli Friedmana2cc2872010-01-31 04:29:12 +00001101 if (ExtendAmt) {
1102 Constant *ShAmt = ConstantInt::get(I.getType(), ExtendAmt);
1103 Value *NewShl = Builder->CreateShl(XorLHS, ShAmt, "sext");
1104 return BinaryOperator::CreateAShr(NewShl, ShAmt);
Chris Lattner82aa8882010-01-05 07:18:46 +00001105 }
Benjamin Kramerb16bd772011-12-24 17:31:53 +00001106
1107 // If this is a xor that was canonicalized from a sub, turn it back into
1108 // a sub and fuse this add with it.
1109 if (LHS->hasOneUse() && (XorRHS->getValue()+1).isPowerOf2()) {
1110 IntegerType *IT = cast<IntegerType>(I.getType());
Benjamin Kramerb16bd772011-12-24 17:31:53 +00001111 APInt LHSKnownOne(IT->getBitWidth(), 0);
1112 APInt LHSKnownZero(IT->getBitWidth(), 0);
Hal Finkel60db0582014-09-07 18:57:58 +00001113 computeKnownBits(XorLHS, LHSKnownZero, LHSKnownOne, 0, &I);
Benjamin Kramerb16bd772011-12-24 17:31:53 +00001114 if ((XorRHS->getValue() | LHSKnownZero).isAllOnesValue())
1115 return BinaryOperator::CreateSub(ConstantExpr::getAdd(XorRHS, CI),
1116 XorLHS);
1117 }
David Majnemer70f286d2013-05-06 21:21:31 +00001118 // (X + signbit) + C could have gotten canonicalized to (X ^ signbit) + C,
1119 // transform them into (X + (signbit ^ C))
1120 if (XorRHS->getValue().isSignBit())
Craig Toppereafbd572015-12-21 01:02:28 +00001121 return BinaryOperator::CreateAdd(XorLHS,
1122 ConstantExpr::getXor(XorRHS, CI));
Chris Lattner82aa8882010-01-05 07:18:46 +00001123 }
1124 }
1125
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001126 if (isa<Constant>(RHS) && isa<PHINode>(LHS))
1127 if (Instruction *NV = FoldOpIntoPhi(I))
1128 return NV;
1129
Benjamin Kramer72196f32014-01-19 15:24:22 +00001130 if (I.getType()->getScalarType()->isIntegerTy(1))
Chris Lattner82aa8882010-01-05 07:18:46 +00001131 return BinaryOperator::CreateXor(LHS, RHS);
1132
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001133 // X + X --> X << 1
Chris Lattnerd4067642011-02-17 20:55:29 +00001134 if (LHS == RHS) {
Chris Lattner55920712011-02-17 02:23:02 +00001135 BinaryOperator *New =
1136 BinaryOperator::CreateShl(LHS, ConstantInt::get(I.getType(), 1));
1137 New->setHasNoSignedWrap(I.hasNoSignedWrap());
1138 New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1139 return New;
1140 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001141
1142 // -A + B --> B - A
1143 // -A + -B --> -(A + B)
1144 if (Value *LHSV = dyn_castNegVal(LHS)) {
Nuno Lopes2710f1b2012-06-08 22:30:05 +00001145 if (!isa<Constant>(RHS))
1146 if (Value *RHSV = dyn_castNegVal(RHS)) {
1147 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
1148 return BinaryOperator::CreateNeg(NewAdd);
1149 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001150
Chris Lattner82aa8882010-01-05 07:18:46 +00001151 return BinaryOperator::CreateSub(RHS, LHSV);
1152 }
1153
1154 // A + -B --> A - B
1155 if (!isa<Constant>(RHS))
1156 if (Value *V = dyn_castNegVal(RHS))
1157 return BinaryOperator::CreateSub(LHS, V);
1158
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001159 if (Value *V = checkForNegativeOperand(I, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001160 return replaceInstUsesWith(I, V);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001161
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001162 // A+B --> A|B iff A and B have no bits set in common.
Jingyue Wuca321902015-05-14 23:53:19 +00001163 if (haveNoCommonBitsSet(LHS, RHS, DL, AC, &I, DT))
1164 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner82aa8882010-01-05 07:18:46 +00001165
Benjamin Kramer72196f32014-01-19 15:24:22 +00001166 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
1167 Value *X;
1168 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Chris Lattner82aa8882010-01-05 07:18:46 +00001169 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Benjamin Kramer72196f32014-01-19 15:24:22 +00001170 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001171
Benjamin Kramer72196f32014-01-19 15:24:22 +00001172 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001173 // (X & FF00) + xx00 -> (X+xx00) & FF00
Benjamin Kramer72196f32014-01-19 15:24:22 +00001174 Value *X;
1175 ConstantInt *C2;
Chris Lattner82aa8882010-01-05 07:18:46 +00001176 if (LHS->hasOneUse() &&
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001177 match(LHS, m_And(m_Value(X), m_ConstantInt(C2))) &&
1178 CRHS->getValue() == (CRHS->getValue() & C2->getValue())) {
1179 // See if all bits from the first bit set in the Add RHS up are included
1180 // in the mask. First, get the rightmost bit.
1181 const APInt &AddRHSV = CRHS->getValue();
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001182
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001183 // Form a mask of all bits from the lowest bit added through the top.
1184 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattner82aa8882010-01-05 07:18:46 +00001185
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001186 // See if the and mask includes all of these bits.
1187 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Chris Lattner82aa8882010-01-05 07:18:46 +00001188
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001189 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1190 // Okay, the xform is safe. Insert the new add pronto.
1191 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
1192 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattner82aa8882010-01-05 07:18:46 +00001193 }
1194 }
1195
1196 // Try to fold constant add into select arguments.
1197 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1198 if (Instruction *R = FoldOpIntoSelect(I, SI))
1199 return R;
1200 }
1201
1202 // add (select X 0 (sub n A)) A --> select X A n
1203 {
1204 SelectInst *SI = dyn_cast<SelectInst>(LHS);
1205 Value *A = RHS;
1206 if (!SI) {
1207 SI = dyn_cast<SelectInst>(RHS);
1208 A = LHS;
1209 }
1210 if (SI && SI->hasOneUse()) {
1211 Value *TV = SI->getTrueValue();
1212 Value *FV = SI->getFalseValue();
1213 Value *N;
1214
1215 // Can we fold the add into the argument of the select?
1216 // We check both true and false select arguments for a matching subtract.
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001217 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner82aa8882010-01-05 07:18:46 +00001218 // Fold the add into the true select value.
1219 return SelectInst::Create(SI->getCondition(), N, A);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001220
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001221 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner82aa8882010-01-05 07:18:46 +00001222 // Fold the add into the false select value.
1223 return SelectInst::Create(SI->getCondition(), A, N);
1224 }
1225 }
1226
1227 // Check for (add (sext x), y), see if we can merge this into an
1228 // integer add followed by a sext.
1229 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
1230 // (add (sext x), cst) --> (sext (add x, cst'))
1231 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001232 Constant *CI =
Chris Lattner82aa8882010-01-05 07:18:46 +00001233 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
1234 if (LHSConv->hasOneUse() &&
1235 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001236 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI, I)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001237 // Insert the new, smaller add.
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001238 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner82aa8882010-01-05 07:18:46 +00001239 CI, "addconv");
1240 return new SExtInst(NewAdd, I.getType());
1241 }
1242 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001243
Chris Lattner82aa8882010-01-05 07:18:46 +00001244 // (add (sext x), (sext y)) --> (sext (add int x, y))
1245 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
1246 // Only do this if x/y have the same type, if at last one of them has a
1247 // single use (so we don't increase the number of sexts), and if the
1248 // integer add will not overflow.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001249 if (LHSConv->getOperand(0)->getType() ==
1250 RHSConv->getOperand(0)->getType() &&
Chris Lattner82aa8882010-01-05 07:18:46 +00001251 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1252 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001253 RHSConv->getOperand(0), I)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001254 // Insert the new integer add.
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001255 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattnerdec68472010-01-05 20:56:24 +00001256 RHSConv->getOperand(0), "addconv");
Chris Lattner82aa8882010-01-05 07:18:46 +00001257 return new SExtInst(NewAdd, I.getType());
1258 }
1259 }
1260 }
1261
David Majnemerab07f002014-08-11 22:32:02 +00001262 // (add (xor A, B) (and A, B)) --> (or A, B)
Chad Rosier7813dce2012-04-26 23:29:14 +00001263 {
Craig Topperf40110f2014-04-25 05:29:35 +00001264 Value *A = nullptr, *B = nullptr;
Chad Rosier7813dce2012-04-26 23:29:14 +00001265 if (match(RHS, m_Xor(m_Value(A), m_Value(B))) &&
1266 (match(LHS, m_And(m_Specific(A), m_Specific(B))) ||
1267 match(LHS, m_And(m_Specific(B), m_Specific(A)))))
1268 return BinaryOperator::CreateOr(A, B);
1269
1270 if (match(LHS, m_Xor(m_Value(A), m_Value(B))) &&
1271 (match(RHS, m_And(m_Specific(A), m_Specific(B))) ||
1272 match(RHS, m_And(m_Specific(B), m_Specific(A)))))
1273 return BinaryOperator::CreateOr(A, B);
1274 }
1275
David Majnemerab07f002014-08-11 22:32:02 +00001276 // (add (or A, B) (and A, B)) --> (add A, B)
1277 {
1278 Value *A = nullptr, *B = nullptr;
1279 if (match(RHS, m_Or(m_Value(A), m_Value(B))) &&
1280 (match(LHS, m_And(m_Specific(A), m_Specific(B))) ||
1281 match(LHS, m_And(m_Specific(B), m_Specific(A))))) {
1282 auto *New = BinaryOperator::CreateAdd(A, B);
1283 New->setHasNoSignedWrap(I.hasNoSignedWrap());
1284 New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1285 return New;
1286 }
1287
1288 if (match(LHS, m_Or(m_Value(A), m_Value(B))) &&
1289 (match(RHS, m_And(m_Specific(A), m_Specific(B))) ||
1290 match(RHS, m_And(m_Specific(B), m_Specific(A))))) {
1291 auto *New = BinaryOperator::CreateAdd(A, B);
1292 New->setHasNoSignedWrap(I.hasNoSignedWrap());
1293 New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1294 return New;
1295 }
1296 }
1297
Jingyue Wu33bd53d2014-06-17 00:42:07 +00001298 // TODO(jingyue): Consider WillNotOverflowSignedAdd and
1299 // WillNotOverflowUnsignedAdd to reduce the number of invocations of
1300 // computeKnownBits.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001301 if (!I.hasNoSignedWrap() && WillNotOverflowSignedAdd(LHS, RHS, I)) {
Rafael Espindolad1a2c2d2014-06-02 22:01:04 +00001302 Changed = true;
1303 I.setHasNoSignedWrap(true);
1304 }
David Majnemer5310c1e2015-01-07 00:39:50 +00001305 if (!I.hasNoUnsignedWrap() &&
1306 computeOverflowForUnsignedAdd(LHS, RHS, &I) ==
1307 OverflowResult::NeverOverflows) {
Jingyue Wu33bd53d2014-06-17 00:42:07 +00001308 Changed = true;
1309 I.setHasNoUnsignedWrap(true);
1310 }
Rafael Espindolad1a2c2d2014-06-02 22:01:04 +00001311
Craig Topperf40110f2014-04-25 05:29:35 +00001312 return Changed ? &I : nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001313}
1314
1315Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001316 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner82aa8882010-01-05 07:18:46 +00001317 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1318
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001319 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001320 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001321
Chandler Carruth66b31302015-01-04 12:03:27 +00001322 if (Value *V =
1323 SimplifyFAddInst(LHS, RHS, I.getFastMathFlags(), DL, TLI, DT, AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001324 return replaceInstUsesWith(I, V);
Chris Lattner82aa8882010-01-05 07:18:46 +00001325
Stephen Lina9b57f62013-07-20 07:13:13 +00001326 if (isa<Constant>(RHS)) {
1327 if (isa<PHINode>(LHS))
1328 if (Instruction *NV = FoldOpIntoPhi(I))
1329 return NV;
1330
1331 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1332 if (Instruction *NV = FoldOpIntoSelect(I, SI))
1333 return NV;
1334 }
Michael Ilsemane2754dc2012-12-14 22:08:26 +00001335
Chris Lattner82aa8882010-01-05 07:18:46 +00001336 // -A + B --> B - A
1337 // -A + -B --> -(A + B)
Owen Andersone7321662014-01-16 21:26:02 +00001338 if (Value *LHSV = dyn_castFNegVal(LHS)) {
1339 Instruction *RI = BinaryOperator::CreateFSub(RHS, LHSV);
1340 RI->copyFastMathFlags(&I);
1341 return RI;
1342 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001343
1344 // A + -B --> A - B
1345 if (!isa<Constant>(RHS))
Owen Andersone7321662014-01-16 21:26:02 +00001346 if (Value *V = dyn_castFNegVal(RHS)) {
1347 Instruction *RI = BinaryOperator::CreateFSub(LHS, V);
1348 RI->copyFastMathFlags(&I);
1349 return RI;
1350 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001351
Dan Gohman6f34abd2010-03-02 01:11:08 +00001352 // Check for (fadd double (sitofp x), y), see if we can merge this into an
Chris Lattner82aa8882010-01-05 07:18:46 +00001353 // integer add followed by a promotion.
1354 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
Dan Gohman6f34abd2010-03-02 01:11:08 +00001355 // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
Chris Lattner82aa8882010-01-05 07:18:46 +00001356 // ... if the constant fits in the integer value. This is useful for things
1357 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
1358 // requires a constant pool load, and generally allows the add to be better
1359 // instcombined.
1360 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001361 Constant *CI =
Chris Lattner82aa8882010-01-05 07:18:46 +00001362 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
1363 if (LHSConv->hasOneUse() &&
1364 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001365 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI, I)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001366 // Insert the new integer add.
1367 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1368 CI, "addconv");
1369 return new SIToFPInst(NewAdd, I.getType());
1370 }
1371 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001372
Dan Gohman6f34abd2010-03-02 01:11:08 +00001373 // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
Chris Lattner82aa8882010-01-05 07:18:46 +00001374 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
1375 // Only do this if x/y have the same type, if at last one of them has a
1376 // single use (so we don't increase the number of int->fp conversions),
1377 // and if the integer add will not overflow.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001378 if (LHSConv->getOperand(0)->getType() ==
1379 RHSConv->getOperand(0)->getType() &&
Chris Lattner82aa8882010-01-05 07:18:46 +00001380 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1381 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001382 RHSConv->getOperand(0), I)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001383 // Insert the new integer add.
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001384 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner82aa8882010-01-05 07:18:46 +00001385 RHSConv->getOperand(0),"addconv");
1386 return new SIToFPInst(NewAdd, I.getType());
1387 }
1388 }
1389 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001390
Jean-Luc Duprat3e4fc3e2013-05-06 16:55:50 +00001391 // select C, 0, B + select C, A, 0 -> select C, A, B
1392 {
1393 Value *A1, *B1, *C1, *A2, *B2, *C2;
1394 if (match(LHS, m_Select(m_Value(C1), m_Value(A1), m_Value(B1))) &&
1395 match(RHS, m_Select(m_Value(C2), m_Value(A2), m_Value(B2)))) {
1396 if (C1 == C2) {
Craig Topperf40110f2014-04-25 05:29:35 +00001397 Constant *Z1=nullptr, *Z2=nullptr;
Jean-Luc Duprat3e4fc3e2013-05-06 16:55:50 +00001398 Value *A, *B, *C=C1;
1399 if (match(A1, m_AnyZero()) && match(B2, m_AnyZero())) {
1400 Z1 = dyn_cast<Constant>(A1); A = A2;
1401 Z2 = dyn_cast<Constant>(B2); B = B1;
1402 } else if (match(B1, m_AnyZero()) && match(A2, m_AnyZero())) {
1403 Z1 = dyn_cast<Constant>(B1); B = B2;
David Majnemer72a643d2014-11-03 05:53:55 +00001404 Z2 = dyn_cast<Constant>(A2); A = A1;
Jean-Luc Duprat3e4fc3e2013-05-06 16:55:50 +00001405 }
David Majnemer72a643d2014-11-03 05:53:55 +00001406
1407 if (Z1 && Z2 &&
1408 (I.hasNoSignedZeros() ||
Jean-Luc Duprat3e4fc3e2013-05-06 16:55:50 +00001409 (Z1->isNegativeZeroValue() && Z2->isNegativeZeroValue()))) {
1410 return SelectInst::Create(C, A, B);
1411 }
1412 }
1413 }
1414 }
1415
Shuxin Yang37a1efe2012-12-18 23:10:12 +00001416 if (I.hasUnsafeAlgebra()) {
1417 if (Value *V = FAddCombine(Builder).simplify(&I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001418 return replaceInstUsesWith(I, V);
Shuxin Yang37a1efe2012-12-18 23:10:12 +00001419 }
1420
Craig Topperf40110f2014-04-25 05:29:35 +00001421 return Changed ? &I : nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001422}
1423
Chris Lattner82aa8882010-01-05 07:18:46 +00001424/// Optimize pointer differences into the same array into a size. Consider:
1425/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
1426/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
1427///
1428Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
Chris Lattner229907c2011-07-18 04:54:35 +00001429 Type *Ty) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001430 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
1431 // this.
1432 bool Swapped = false;
Craig Topperf40110f2014-04-25 05:29:35 +00001433 GEPOperator *GEP1 = nullptr, *GEP2 = nullptr;
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001434
Chris Lattner82aa8882010-01-05 07:18:46 +00001435 // For now we require one side to be the base pointer "A" or a constant
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001436 // GEP derived from it.
1437 if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001438 // (gep X, ...) - X
1439 if (LHSGEP->getOperand(0) == RHS) {
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001440 GEP1 = LHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001441 Swapped = false;
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001442 } else if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1443 // (gep X, ...) - (gep X, ...)
1444 if (LHSGEP->getOperand(0)->stripPointerCasts() ==
1445 RHSGEP->getOperand(0)->stripPointerCasts()) {
1446 GEP2 = RHSGEP;
1447 GEP1 = LHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001448 Swapped = false;
1449 }
1450 }
1451 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001452
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001453 if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001454 // X - (gep X, ...)
1455 if (RHSGEP->getOperand(0) == LHS) {
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001456 GEP1 = RHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001457 Swapped = true;
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001458 } else if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1459 // (gep X, ...) - (gep X, ...)
1460 if (RHSGEP->getOperand(0)->stripPointerCasts() ==
1461 LHSGEP->getOperand(0)->stripPointerCasts()) {
1462 GEP2 = LHSGEP;
1463 GEP1 = RHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001464 Swapped = true;
1465 }
1466 }
1467 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001468
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001469 // Avoid duplicating the arithmetic if GEP2 has non-constant indices and
1470 // multiple users.
Craig Topperf40110f2014-04-25 05:29:35 +00001471 if (!GEP1 ||
1472 (GEP2 && !GEP2->hasAllConstantIndices() && !GEP2->hasOneUse()))
1473 return nullptr;
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001474
Chris Lattner82aa8882010-01-05 07:18:46 +00001475 // Emit the offset of the GEP and an intptr_t.
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001476 Value *Result = EmitGEPOffset(GEP1);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001477
Chris Lattner82aa8882010-01-05 07:18:46 +00001478 // If we had a constant expression GEP on the other side offsetting the
1479 // pointer, subtract it from the offset we have.
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001480 if (GEP2) {
1481 Value *Offset = EmitGEPOffset(GEP2);
1482 Result = Builder->CreateSub(Result, Offset);
Chris Lattner82aa8882010-01-05 07:18:46 +00001483 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001484
1485 // If we have p - gep(p, ...) then we have to negate the result.
1486 if (Swapped)
1487 Result = Builder->CreateNeg(Result, "diff.neg");
1488
1489 return Builder->CreateIntCast(Result, Ty, true);
1490}
1491
Chris Lattner82aa8882010-01-05 07:18:46 +00001492Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1493 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1494
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001495 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001496 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001497
Duncan Sands0a2c41682010-12-15 14:07:39 +00001498 if (Value *V = SimplifySubInst(Op0, Op1, I.hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00001499 I.hasNoUnsignedWrap(), DL, TLI, DT, AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001500 return replaceInstUsesWith(I, V);
Chris Lattner82aa8882010-01-05 07:18:46 +00001501
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001502 // (A*B)-(A*C) -> A*(B-C) etc
1503 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001504 return replaceInstUsesWith(I, V);
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001505
David Majnemera92687d2014-07-31 04:49:29 +00001506 // If this is a 'B = x-(-A)', change to B = x+A.
Chris Lattner82aa8882010-01-05 07:18:46 +00001507 if (Value *V = dyn_castNegVal(Op1)) {
1508 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
David Majnemera92687d2014-07-31 04:49:29 +00001509
1510 if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
1511 assert(BO->getOpcode() == Instruction::Sub &&
1512 "Expected a subtraction operator!");
1513 if (BO->hasNoSignedWrap() && I.hasNoSignedWrap())
1514 Res->setHasNoSignedWrap(true);
David Majnemer0e6c9862014-08-22 16:41:23 +00001515 } else {
1516 if (cast<Constant>(Op1)->isNotMinSignedValue() && I.hasNoSignedWrap())
1517 Res->setHasNoSignedWrap(true);
David Majnemera92687d2014-07-31 04:49:29 +00001518 }
1519
Chris Lattner82aa8882010-01-05 07:18:46 +00001520 return Res;
1521 }
1522
Duncan Sands9dff9be2010-02-15 16:12:20 +00001523 if (I.getType()->isIntegerTy(1))
Chris Lattner82aa8882010-01-05 07:18:46 +00001524 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001525
1526 // Replace (-1 - A) with (~A).
1527 if (match(Op0, m_AllOnes()))
1528 return BinaryOperator::CreateNot(Op1);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001529
Benjamin Kramer72196f32014-01-19 15:24:22 +00001530 if (Constant *C = dyn_cast<Constant>(Op0)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001531 // C - ~X == X + (1+C)
Craig Topperf40110f2014-04-25 05:29:35 +00001532 Value *X = nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001533 if (match(Op1, m_Not(m_Value(X))))
1534 return BinaryOperator::CreateAdd(X, AddOne(C));
1535
Benjamin Kramer72196f32014-01-19 15:24:22 +00001536 // Try to fold constant sub into select arguments.
1537 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1538 if (Instruction *R = FoldOpIntoSelect(I, SI))
1539 return R;
1540
1541 // C-(X+C2) --> (C-C2)-X
1542 Constant *C2;
1543 if (match(Op1, m_Add(m_Value(X), m_Constant(C2))))
1544 return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
1545
1546 if (SimplifyDemandedInstructionBits(I))
1547 return &I;
1548
1549 // Fold (sub 0, (zext bool to B)) --> (sext bool to B)
1550 if (C->isNullValue() && match(Op1, m_ZExt(m_Value(X))))
1551 if (X->getType()->getScalarType()->isIntegerTy(1))
1552 return CastInst::CreateSExtOrBitCast(X, Op1->getType());
1553
1554 // Fold (sub 0, (sext bool to B)) --> (zext bool to B)
1555 if (C->isNullValue() && match(Op1, m_SExt(m_Value(X))))
1556 if (X->getType()->getScalarType()->isIntegerTy(1))
1557 return CastInst::CreateZExtOrBitCast(X, Op1->getType());
1558 }
1559
1560 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001561 // -(X >>u 31) -> (X >>s 31)
1562 // -(X >>s 31) -> (X >>u 31)
1563 if (C->isZero()) {
David Majnemer72a643d2014-11-03 05:53:55 +00001564 Value *X;
Suyog Sardacba4b1d2014-10-08 08:37:49 +00001565 ConstantInt *CI;
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001566 if (match(Op1, m_LShr(m_Value(X), m_ConstantInt(CI))) &&
1567 // Verify we are shifting out everything but the sign bit.
Suyog Sardacba4b1d2014-10-08 08:37:49 +00001568 CI->getValue() == I.getType()->getPrimitiveSizeInBits() - 1)
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001569 return BinaryOperator::CreateAShr(X, CI);
1570
1571 if (match(Op1, m_AShr(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::CreateLShr(X, CI);
Chris Lattner82aa8882010-01-05 07:18:46 +00001575 }
Matthias Braunec683342015-04-30 22:04:26 +00001576
1577 // Turn this into a xor if LHS is 2^n-1 and the remaining bits are known
1578 // zero.
1579 APInt IntVal = C->getValue();
1580 if ((IntVal + 1).isPowerOf2()) {
1581 unsigned BitWidth = I.getType()->getScalarSizeInBits();
1582 APInt KnownZero(BitWidth, 0);
1583 APInt KnownOne(BitWidth, 0);
1584 computeKnownBits(&I, KnownZero, KnownOne, 0, &I);
1585 if ((IntVal | KnownZero).isAllOnesValue()) {
1586 return BinaryOperator::CreateXor(Op1, C);
1587 }
1588 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001589 }
1590
David Majnemer72a643d2014-11-03 05:53:55 +00001591 {
Suyog Sardacba4b1d2014-10-08 08:37:49 +00001592 Value *Y;
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001593 // X-(X+Y) == -Y X-(Y+X) == -Y
1594 if (match(Op1, m_Add(m_Specific(Op0), m_Value(Y))) ||
1595 match(Op1, m_Add(m_Value(Y), m_Specific(Op0))))
1596 return BinaryOperator::CreateNeg(Y);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001597
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001598 // (X-Y)-X == -Y
1599 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
1600 return BinaryOperator::CreateNeg(Y);
1601 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001602
David Majnemer312c3e52014-10-19 08:32:32 +00001603 // (sub (or A, B) (xor A, B)) --> (and A, B)
1604 {
1605 Value *A = nullptr, *B = nullptr;
1606 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
1607 (match(Op0, m_Or(m_Specific(A), m_Specific(B))) ||
1608 match(Op0, m_Or(m_Specific(B), m_Specific(A)))))
1609 return BinaryOperator::CreateAnd(A, B);
1610 }
1611
David Majnemer72a643d2014-11-03 05:53:55 +00001612 if (Op0->hasOneUse()) {
1613 Value *Y = nullptr;
1614 // ((X | Y) - X) --> (~X & Y)
1615 if (match(Op0, m_Or(m_Value(Y), m_Specific(Op1))) ||
1616 match(Op0, m_Or(m_Specific(Op1), m_Value(Y))))
1617 return BinaryOperator::CreateAnd(
1618 Y, Builder->CreateNot(Op1, Op1->getName() + ".not"));
1619 }
1620
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001621 if (Op1->hasOneUse()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001622 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
1623 Constant *C = nullptr;
1624 Constant *CI = nullptr;
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001625
1626 // (X - (Y - Z)) --> (X + (Z - Y)).
1627 if (match(Op1, m_Sub(m_Value(Y), m_Value(Z))))
1628 return BinaryOperator::CreateAdd(Op0,
1629 Builder->CreateSub(Z, Y, Op1->getName()));
1630
1631 // (X - (X & Y)) --> (X & ~Y)
1632 //
1633 if (match(Op1, m_And(m_Value(Y), m_Specific(Op0))) ||
1634 match(Op1, m_And(m_Specific(Op0), m_Value(Y))))
1635 return BinaryOperator::CreateAnd(Op0,
1636 Builder->CreateNot(Y, Y->getName() + ".not"));
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001637
David Majnemerbdeef602014-07-02 06:07:09 +00001638 // 0 - (X sdiv C) -> (X sdiv -C) provided the negation doesn't overflow.
1639 if (match(Op1, m_SDiv(m_Value(X), m_Constant(C))) && match(Op0, m_Zero()) &&
David Majnemer0e6c9862014-08-22 16:41:23 +00001640 C->isNotMinSignedValue() && !C->isOneValue())
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001641 return BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(C));
1642
1643 // 0 - (X << Y) -> (-X << Y) when X is freely negatable.
1644 if (match(Op1, m_Shl(m_Value(X), m_Value(Y))) && match(Op0, m_Zero()))
1645 if (Value *XNeg = dyn_castNegVal(X))
1646 return BinaryOperator::CreateShl(XNeg, Y);
1647
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001648 // X - A*-B -> X + A*B
1649 // X - -A*B -> X + A*B
1650 Value *A, *B;
1651 if (match(Op1, m_Mul(m_Value(A), m_Neg(m_Value(B)))) ||
1652 match(Op1, m_Mul(m_Neg(m_Value(A)), m_Value(B))))
1653 return BinaryOperator::CreateAdd(Op0, Builder->CreateMul(A, B));
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001654
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001655 // X - A*CI -> X + A*-CI
1656 // X - CI*A -> X + A*-CI
Benjamin Kramer72196f32014-01-19 15:24:22 +00001657 if (match(Op1, m_Mul(m_Value(A), m_Constant(CI))) ||
1658 match(Op1, m_Mul(m_Constant(CI), m_Value(A)))) {
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001659 Value *NewMul = Builder->CreateMul(A, ConstantExpr::getNeg(CI));
1660 return BinaryOperator::CreateAdd(Op0, NewMul);
Chris Lattner82aa8882010-01-05 07:18:46 +00001661 }
1662 }
1663
Chris Lattner82aa8882010-01-05 07:18:46 +00001664 // Optimize pointer differences into the same array into a size. Consider:
1665 // &A[10] - &A[0]: we should compile this to "10".
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001666 Value *LHSOp, *RHSOp;
1667 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
1668 match(Op1, m_PtrToInt(m_Value(RHSOp))))
1669 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001670 return replaceInstUsesWith(I, Res);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001671
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001672 // trunc(p)-trunc(q) -> trunc(p-q)
1673 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
1674 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
1675 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
Sanjay Patel4b198802016-02-01 22:23:39 +00001676 return replaceInstUsesWith(I, Res);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001677
David Majnemer57d5bc82014-08-19 23:36:30 +00001678 bool Changed = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001679 if (!I.hasNoSignedWrap() && WillNotOverflowSignedSub(Op0, Op1, I)) {
David Majnemer57d5bc82014-08-19 23:36:30 +00001680 Changed = true;
1681 I.setHasNoSignedWrap(true);
1682 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001683 if (!I.hasNoUnsignedWrap() && WillNotOverflowUnsignedSub(Op0, Op1, I)) {
David Majnemer42158f32014-08-20 07:17:31 +00001684 Changed = true;
1685 I.setHasNoUnsignedWrap(true);
1686 }
David Majnemer57d5bc82014-08-19 23:36:30 +00001687
1688 return Changed ? &I : nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001689}
1690
1691Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
1692 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1693
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001694 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001695 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001696
Chandler Carruth66b31302015-01-04 12:03:27 +00001697 if (Value *V =
1698 SimplifyFSubInst(Op0, Op1, I.getFastMathFlags(), DL, TLI, DT, AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001699 return replaceInstUsesWith(I, V);
Michael Ilsemand5787be2012-12-12 00:28:32 +00001700
Sanjay Patele68f7152014-12-31 22:14:05 +00001701 // fsub nsz 0, X ==> fsub nsz -0.0, X
1702 if (I.getFastMathFlags().noSignedZeros() && match(Op0, m_Zero())) {
1703 // Subtraction from -0.0 is the canonical form of fneg.
1704 Instruction *NewI = BinaryOperator::CreateFNeg(Op1);
1705 NewI->copyFastMathFlags(&I);
1706 return NewI;
1707 }
1708
Stephen Lina9b57f62013-07-20 07:13:13 +00001709 if (isa<Constant>(Op0))
1710 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1711 if (Instruction *NV = FoldOpIntoSelect(I, SI))
1712 return NV;
1713
Owen Andersone37c2e42013-07-26 21:40:29 +00001714 // If this is a 'B = x-(-A)', change to B = x+A, potentially looking
1715 // through FP extensions/truncations along the way.
Owen Andersonc7be5192013-07-30 23:53:17 +00001716 if (Value *V = dyn_castFNegVal(Op1)) {
1717 Instruction *NewI = BinaryOperator::CreateFAdd(Op0, V);
1718 NewI->copyFastMathFlags(&I);
1719 return NewI;
1720 }
Owen Andersone37c2e42013-07-26 21:40:29 +00001721 if (FPTruncInst *FPTI = dyn_cast<FPTruncInst>(Op1)) {
1722 if (Value *V = dyn_castFNegVal(FPTI->getOperand(0))) {
1723 Value *NewTrunc = Builder->CreateFPTrunc(V, I.getType());
Owen Andersonc7be5192013-07-30 23:53:17 +00001724 Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewTrunc);
1725 NewI->copyFastMathFlags(&I);
1726 return NewI;
Owen Andersone37c2e42013-07-26 21:40:29 +00001727 }
1728 } else if (FPExtInst *FPEI = dyn_cast<FPExtInst>(Op1)) {
1729 if (Value *V = dyn_castFNegVal(FPEI->getOperand(0))) {
Owen Andersond6d4da02013-07-26 22:06:21 +00001730 Value *NewExt = Builder->CreateFPExt(V, I.getType());
Owen Andersonc7be5192013-07-30 23:53:17 +00001731 Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewExt);
1732 NewI->copyFastMathFlags(&I);
1733 return NewI;
Owen Andersone37c2e42013-07-26 21:40:29 +00001734 }
1735 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001736
Shuxin Yang37a1efe2012-12-18 23:10:12 +00001737 if (I.hasUnsafeAlgebra()) {
1738 if (Value *V = FAddCombine(Builder).simplify(&I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001739 return replaceInstUsesWith(I, V);
Shuxin Yang37a1efe2012-12-18 23:10:12 +00001740 }
1741
Craig Topperf40110f2014-04-25 05:29:35 +00001742 return nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001743}