blob: 1f04a8b3a3a8f00bed51637f4b302b55703ba57b [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"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000015#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APInt.h"
Craig Topper58713212013-07-15 04:27:47 +000017#include "llvm/ADT/STLExtras.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000018#include "llvm/ADT/SmallVector.h"
Chris Lattner82aa8882010-01-05 07:18:46 +000019#include "llvm/Analysis/InstructionSimplify.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000020#include "llvm/Analysis/ValueTracking.h"
21#include "llvm/IR/Constant.h"
22#include "llvm/IR/Constants.h"
23#include "llvm/IR/InstrTypes.h"
24#include "llvm/IR/Instruction.h"
25#include "llvm/IR/Instructions.h"
26#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000027#include "llvm/IR/PatternMatch.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000028#include "llvm/IR/Type.h"
29#include "llvm/IR/Value.h"
30#include "llvm/Support/AlignOf.h"
31#include "llvm/Support/Casting.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000032#include "llvm/Support/KnownBits.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000033#include <cassert>
34#include <utility>
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000035
Chris Lattner82aa8882010-01-05 07:18:46 +000036using namespace llvm;
37using namespace PatternMatch;
38
Chandler Carruth964daaa2014-04-22 02:55:47 +000039#define DEBUG_TYPE "instcombine"
40
Shuxin Yang37a1efe2012-12-18 23:10:12 +000041namespace {
42
43 /// Class representing coefficient of floating-point addend.
44 /// This class needs to be highly efficient, which is especially true for
45 /// the constructor. As of I write this comment, the cost of the default
Jim Grosbachbdbd7342013-04-05 21:20:12 +000046 /// constructor is merely 4-byte-store-zero (Assuming compiler is able to
Shuxin Yang37a1efe2012-12-18 23:10:12 +000047 /// perform write-merging).
Jim Grosbachbdbd7342013-04-05 21:20:12 +000048 ///
Shuxin Yang37a1efe2012-12-18 23:10:12 +000049 class FAddendCoef {
50 public:
Suyog Sardade409fd2014-07-17 06:09:34 +000051 // The constructor has to initialize a APFloat, which is unnecessary for
Shuxin Yang37a1efe2012-12-18 23:10:12 +000052 // most addends which have coefficient either 1 or -1. So, the constructor
53 // is expensive. In order to avoid the cost of the constructor, we should
54 // reuse some instances whenever possible. The pre-created instances
55 // FAddCombine::Add[0-5] embodies this idea.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000056 FAddendCoef() = default;
Shuxin Yang37a1efe2012-12-18 23:10:12 +000057 ~FAddendCoef();
Jim Grosbachbdbd7342013-04-05 21:20:12 +000058
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000059 // If possible, don't define operator+/operator- etc because these
60 // operators inevitably call FAddendCoef's constructor which is not cheap.
61 void operator=(const FAddendCoef &A);
62 void operator+=(const FAddendCoef &A);
63 void operator*=(const FAddendCoef &S);
64
Shuxin Yang37a1efe2012-12-18 23:10:12 +000065 void set(short C) {
66 assert(!insaneIntVal(C) && "Insane coefficient");
67 IsFp = false; IntVal = C;
68 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000069
Shuxin Yang37a1efe2012-12-18 23:10:12 +000070 void set(const APFloat& C);
Shuxin Yang389ed4b2013-03-25 20:43:41 +000071
Shuxin Yang37a1efe2012-12-18 23:10:12 +000072 void negate();
Jim Grosbachbdbd7342013-04-05 21:20:12 +000073
Shuxin Yang37a1efe2012-12-18 23:10:12 +000074 bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); }
75 Value *getValue(Type *) const;
Jim Grosbachbdbd7342013-04-05 21:20:12 +000076
Shuxin Yang37a1efe2012-12-18 23:10:12 +000077 bool isOne() const { return isInt() && IntVal == 1; }
78 bool isTwo() const { return isInt() && IntVal == 2; }
79 bool isMinusOne() const { return isInt() && IntVal == -1; }
80 bool isMinusTwo() const { return isInt() && IntVal == -2; }
Jim Grosbachbdbd7342013-04-05 21:20:12 +000081
Shuxin Yang37a1efe2012-12-18 23:10:12 +000082 private:
83 bool insaneIntVal(int V) { return V > 4 || V < -4; }
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000084
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000085 APFloat *getFpValPtr()
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000086 { return reinterpret_cast<APFloat *>(&FpValBuf.buffer[0]); }
87
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000088 const APFloat *getFpValPtr() const
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000089 { return reinterpret_cast<const APFloat *>(&FpValBuf.buffer[0]); }
Shuxin Yang37a1efe2012-12-18 23:10:12 +000090
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000091 const APFloat &getFpVal() const {
Shuxin Yang37a1efe2012-12-18 23:10:12 +000092 assert(IsFp && BufHasFpVal && "Incorret state");
David Greene530430b2013-01-14 21:04:40 +000093 return *getFpValPtr();
Shuxin Yang37a1efe2012-12-18 23:10:12 +000094 }
95
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000096 APFloat &getFpVal() {
Jim Grosbachbdbd7342013-04-05 21:20:12 +000097 assert(IsFp && BufHasFpVal && "Incorret state");
98 return *getFpValPtr();
99 }
100
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000101 bool isInt() const { return !IsFp; }
102
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000103 // If the coefficient is represented by an integer, promote it to a
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000104 // floating point.
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000105 void convertToFpType(const fltSemantics &Sem);
106
107 // Construct an APFloat from a signed integer.
108 // TODO: We should get rid of this function when APFloat can be constructed
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000109 // from an *SIGNED* integer.
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000110 APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val);
Shuxin Yang5b841c42012-12-19 01:10:17 +0000111
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000112 bool IsFp = false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000113
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000114 // True iff FpValBuf contains an instance of APFloat.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000115 bool BufHasFpVal = false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000116
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000117 // The integer coefficient of an individual addend is either 1 or -1,
118 // and we try to simplify at most 4 addends from neighboring at most
119 // two instructions. So the range of <IntVal> falls in [-4, 4]. APInt
120 // is overkill of this end.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000121 short IntVal = 0;
Shuxin Yang5b841c42012-12-19 01:10:17 +0000122
123 AlignedCharArrayUnion<APFloat> FpValBuf;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000124 };
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000125
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000126 /// FAddend is used to represent floating-point addend. An addend is
127 /// represented as <C, V>, where the V is a symbolic value, and C is a
128 /// constant coefficient. A constant addend is represented as <C, 0>.
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000129 class FAddend {
130 public:
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000131 FAddend() = default;
132
133 void operator+=(const FAddend &T) {
134 assert((Val == T.Val) && "Symbolic-values disagree");
135 Coeff += T.Coeff;
136 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000137
Eugene Zelenkoffec81c2015-11-04 22:32:32 +0000138 Value *getSymVal() const { return Val; }
139 const FAddendCoef &getCoef() const { return Coeff; }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000140
Craig Topperf40110f2014-04-25 05:29:35 +0000141 bool isConstant() const { return Val == nullptr; }
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000142 bool isZero() const { return Coeff.isZero(); }
143
Richard Trieu7a083812016-02-18 22:09:30 +0000144 void set(short Coefficient, Value *V) {
145 Coeff.set(Coefficient);
146 Val = V;
147 }
148 void set(const APFloat &Coefficient, Value *V) {
149 Coeff.set(Coefficient);
150 Val = V;
151 }
152 void set(const ConstantFP *Coefficient, Value *V) {
153 Coeff.set(Coefficient->getValueAPF());
154 Val = V;
155 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000156
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000157 void negate() { Coeff.negate(); }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000158
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000159 /// Drill down the U-D chain one step to find the definition of V, and
160 /// try to break the definition into one or two addends.
161 static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000162
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000163 /// Similar to FAddend::drillDownOneStep() except that the value being
164 /// splitted is the addend itself.
165 unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000166
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000167 private:
168 void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000169
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000170 // This addend has the value of "Coeff * Val".
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000171 Value *Val = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000172 FAddendCoef Coeff;
173 };
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000174
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000175 /// FAddCombine is the class for optimizing an unsafe fadd/fsub along
176 /// with its neighboring at most two instructions.
177 ///
178 class FAddCombine {
179 public:
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000180 FAddCombine(InstCombiner::BuilderTy &B) : Builder(B) {}
181
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000182 Value *simplify(Instruction *FAdd);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000183
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000184 private:
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000185 using AddendVect = SmallVector<const FAddend *, 4>;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000186
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000187 Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000188
189 Value *performFactorization(Instruction *I);
190
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000191 /// Convert given addend to a Value
192 Value *createAddendVal(const FAddend &A, bool& NeedNeg);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000193
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000194 /// Return the number of instructions needed to emit the N-ary addition.
195 unsigned calcInstrNumber(const AddendVect& Vect);
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000196
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000197 Value *createFSub(Value *Opnd0, Value *Opnd1);
198 Value *createFAdd(Value *Opnd0, Value *Opnd1);
199 Value *createFMul(Value *Opnd0, Value *Opnd1);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000200 Value *createFDiv(Value *Opnd0, Value *Opnd1);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000201 Value *createFNeg(Value *V);
202 Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
Owen Anderson1664dc82014-01-20 07:44:53 +0000203 void createInstPostProc(Instruction *NewInst, bool NoNumber = false);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000204
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000205 // Debugging stuff are clustered here.
206 #ifndef NDEBUG
207 unsigned CreateInstrNum;
208 void initCreateInstNum() { CreateInstrNum = 0; }
209 void incCreateInstNum() { CreateInstrNum++; }
210 #else
211 void initCreateInstNum() {}
212 void incCreateInstNum() {}
213 #endif
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000214
215 InstCombiner::BuilderTy &Builder;
216 Instruction *Instr = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000217 };
Eugene Zelenkoffec81c2015-11-04 22:32:32 +0000218
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000219} // end anonymous namespace
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000220
221//===----------------------------------------------------------------------===//
222//
223// Implementation of
224// {FAddendCoef, FAddend, FAddition, FAddCombine}.
225//
226//===----------------------------------------------------------------------===//
227FAddendCoef::~FAddendCoef() {
228 if (BufHasFpVal)
229 getFpValPtr()->~APFloat();
230}
231
232void FAddendCoef::set(const APFloat& C) {
233 APFloat *P = getFpValPtr();
234
235 if (isInt()) {
236 // As the buffer is meanless byte stream, we cannot call
237 // APFloat::operator=().
238 new(P) APFloat(C);
239 } else
240 *P = C;
241
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000242 IsFp = BufHasFpVal = true;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000243}
244
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000245void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
246 if (!isInt())
247 return;
248
249 APFloat *P = getFpValPtr();
250 if (IntVal > 0)
251 new(P) APFloat(Sem, IntVal);
252 else {
253 new(P) APFloat(Sem, 0 - IntVal);
254 P->changeSign();
255 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000256 IsFp = BufHasFpVal = true;
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000257}
258
259APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
260 if (Val >= 0)
261 return APFloat(Sem, Val);
262
263 APFloat T(Sem, 0 - Val);
264 T.changeSign();
265
266 return T;
267}
268
269void FAddendCoef::operator=(const FAddendCoef &That) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000270 if (That.isInt())
271 set(That.IntVal);
272 else
273 set(That.getFpVal());
274}
275
276void FAddendCoef::operator+=(const FAddendCoef &That) {
277 enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
278 if (isInt() == That.isInt()) {
279 if (isInt())
280 IntVal += That.IntVal;
281 else
282 getFpVal().add(That.getFpVal(), RndMode);
283 return;
284 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000285
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000286 if (isInt()) {
287 const APFloat &T = That.getFpVal();
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000288 convertToFpType(T.getSemantics());
289 getFpVal().add(T, RndMode);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000290 return;
291 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000292
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000293 APFloat &T = getFpVal();
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000294 T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000295}
296
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000297void FAddendCoef::operator*=(const FAddendCoef &That) {
298 if (That.isOne())
299 return;
300
301 if (That.isMinusOne()) {
302 negate();
303 return;
304 }
305
306 if (isInt() && That.isInt()) {
307 int Res = IntVal * (int)That.IntVal;
308 assert(!insaneIntVal(Res) && "Insane int value");
309 IntVal = Res;
310 return;
311 }
312
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000313 const fltSemantics &Semantic =
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000314 isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
315
316 if (isInt())
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000317 convertToFpType(Semantic);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000318 APFloat &F0 = getFpVal();
319
320 if (That.isInt())
Shuxin Yang389ed4b2013-03-25 20:43:41 +0000321 F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
322 APFloat::rmNearestTiesToEven);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000323 else
324 F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000325}
326
327void FAddendCoef::negate() {
328 if (isInt())
329 IntVal = 0 - IntVal;
330 else
331 getFpVal().changeSign();
332}
333
334Value *FAddendCoef::getValue(Type *Ty) const {
335 return isInt() ?
336 ConstantFP::get(Ty, float(IntVal)) :
337 ConstantFP::get(Ty->getContext(), getFpVal());
338}
339
340// The definition of <Val> Addends
341// =========================================
342// A + B <1, A>, <1,B>
343// A - B <1, A>, <1,B>
344// 0 - B <-1, B>
345// C * A, <C, A>
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000346// A + C <1, A> <C, NULL>
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000347// 0 +/- 0 <0, NULL> (corner case)
348//
349// Legend: A and B are not constant, C is constant
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000350unsigned FAddend::drillValueDownOneStep
351 (Value *Val, FAddend &Addend0, FAddend &Addend1) {
Craig Topperf40110f2014-04-25 05:29:35 +0000352 Instruction *I = nullptr;
353 if (!Val || !(I = dyn_cast<Instruction>(Val)))
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000354 return 0;
355
356 unsigned Opcode = I->getOpcode();
357
358 if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
359 ConstantFP *C0, *C1;
360 Value *Opnd0 = I->getOperand(0);
361 Value *Opnd1 = I->getOperand(1);
362 if ((C0 = dyn_cast<ConstantFP>(Opnd0)) && C0->isZero())
Craig Topperf40110f2014-04-25 05:29:35 +0000363 Opnd0 = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000364
365 if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
Craig Topperf40110f2014-04-25 05:29:35 +0000366 Opnd1 = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000367
368 if (Opnd0) {
369 if (!C0)
370 Addend0.set(1, Opnd0);
371 else
Craig Topperf40110f2014-04-25 05:29:35 +0000372 Addend0.set(C0, nullptr);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000373 }
374
375 if (Opnd1) {
376 FAddend &Addend = Opnd0 ? Addend1 : Addend0;
377 if (!C1)
378 Addend.set(1, Opnd1);
379 else
Craig Topperf40110f2014-04-25 05:29:35 +0000380 Addend.set(C1, nullptr);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000381 if (Opcode == Instruction::FSub)
382 Addend.negate();
383 }
384
385 if (Opnd0 || Opnd1)
386 return Opnd0 && Opnd1 ? 2 : 1;
387
388 // Both operands are zero. Weird!
Craig Topperf40110f2014-04-25 05:29:35 +0000389 Addend0.set(APFloat(C0->getValueAPF().getSemantics()), nullptr);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000390 return 1;
391 }
392
393 if (I->getOpcode() == Instruction::FMul) {
394 Value *V0 = I->getOperand(0);
395 Value *V1 = I->getOperand(1);
396 if (ConstantFP *C = dyn_cast<ConstantFP>(V0)) {
397 Addend0.set(C, V1);
398 return 1;
399 }
400
401 if (ConstantFP *C = dyn_cast<ConstantFP>(V1)) {
402 Addend0.set(C, V0);
403 return 1;
404 }
405 }
406
407 return 0;
408}
409
410// Try to break *this* addend into two addends. e.g. Suppose this addend is
411// <2.3, V>, and V = X + Y, by calling this function, we obtain two addends,
412// i.e. <2.3, X> and <2.3, Y>.
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000413unsigned FAddend::drillAddendDownOneStep
414 (FAddend &Addend0, FAddend &Addend1) const {
415 if (isConstant())
416 return 0;
417
418 unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000419 if (!BreakNum || Coeff.isOne())
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000420 return BreakNum;
421
422 Addend0.Scale(Coeff);
423
424 if (BreakNum == 2)
425 Addend1.Scale(Coeff);
426
427 return BreakNum;
428}
429
Shuxin Yang2eca6022013-03-14 18:08:26 +0000430// Try to perform following optimization on the input instruction I. Return the
431// simplified expression if was successful; otherwise, return 0.
432//
433// Instruction "I" is Simplified into
434// -------------------------------------------------------
435// (x * y) +/- (x * z) x * (y +/- z)
436// (y / x) +/- (z / x) (y +/- z) / x
Shuxin Yang2eca6022013-03-14 18:08:26 +0000437Value *FAddCombine::performFactorization(Instruction *I) {
438 assert((I->getOpcode() == Instruction::FAdd ||
439 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000440
Shuxin Yang2eca6022013-03-14 18:08:26 +0000441 Instruction *I0 = dyn_cast<Instruction>(I->getOperand(0));
442 Instruction *I1 = dyn_cast<Instruction>(I->getOperand(1));
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000443
Shuxin Yang2eca6022013-03-14 18:08:26 +0000444 if (!I0 || !I1 || I0->getOpcode() != I1->getOpcode())
Craig Topperf40110f2014-04-25 05:29:35 +0000445 return nullptr;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000446
447 bool isMpy = false;
448 if (I0->getOpcode() == Instruction::FMul)
449 isMpy = true;
450 else if (I0->getOpcode() != Instruction::FDiv)
Craig Topperf40110f2014-04-25 05:29:35 +0000451 return nullptr;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000452
453 Value *Opnd0_0 = I0->getOperand(0);
454 Value *Opnd0_1 = I0->getOperand(1);
455 Value *Opnd1_0 = I1->getOperand(0);
456 Value *Opnd1_1 = I1->getOperand(1);
457
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000458 // Input Instr I Factor AddSub0 AddSub1
Shuxin Yang2eca6022013-03-14 18:08:26 +0000459 // ----------------------------------------------
460 // (x*y) +/- (x*z) x y z
461 // (y/x) +/- (z/x) x y z
Craig Topperf40110f2014-04-25 05:29:35 +0000462 Value *Factor = nullptr;
463 Value *AddSub0 = nullptr, *AddSub1 = nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000464
Shuxin Yang2eca6022013-03-14 18:08:26 +0000465 if (isMpy) {
466 if (Opnd0_0 == Opnd1_0 || Opnd0_0 == Opnd1_1)
467 Factor = Opnd0_0;
468 else if (Opnd0_1 == Opnd1_0 || Opnd0_1 == Opnd1_1)
469 Factor = Opnd0_1;
470
471 if (Factor) {
472 AddSub0 = (Factor == Opnd0_0) ? Opnd0_1 : Opnd0_0;
473 AddSub1 = (Factor == Opnd1_0) ? Opnd1_1 : Opnd1_0;
474 }
475 } else if (Opnd0_1 == Opnd1_1) {
476 Factor = Opnd0_1;
477 AddSub0 = Opnd0_0;
478 AddSub1 = Opnd1_0;
479 }
480
481 if (!Factor)
Craig Topperf40110f2014-04-25 05:29:35 +0000482 return nullptr;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000483
Owen Anderson1664dc82014-01-20 07:44:53 +0000484 FastMathFlags Flags;
Sanjay Patel629c4112017-11-06 16:27:15 +0000485 Flags.setFast();
Owen Anderson1664dc82014-01-20 07:44:53 +0000486 if (I0) Flags &= I->getFastMathFlags();
487 if (I1) Flags &= I->getFastMathFlags();
488
Shuxin Yang2eca6022013-03-14 18:08:26 +0000489 // Create expression "NewAddSub = AddSub0 +/- AddsSub1"
490 Value *NewAddSub = (I->getOpcode() == Instruction::FAdd) ?
491 createFAdd(AddSub0, AddSub1) :
492 createFSub(AddSub0, AddSub1);
493 if (ConstantFP *CFP = dyn_cast<ConstantFP>(NewAddSub)) {
494 const APFloat &F = CFP->getValueAPF();
Michael Gottesmanc2af8d62013-06-26 23:17:31 +0000495 if (!F.isNormal())
Craig Topperf40110f2014-04-25 05:29:35 +0000496 return nullptr;
Owen Anderson1664dc82014-01-20 07:44:53 +0000497 } else if (Instruction *II = dyn_cast<Instruction>(NewAddSub))
498 II->setFastMathFlags(Flags);
499
500 if (isMpy) {
501 Value *RI = createFMul(Factor, NewAddSub);
502 if (Instruction *II = dyn_cast<Instruction>(RI))
503 II->setFastMathFlags(Flags);
504 return RI;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000505 }
506
Owen Anderson1664dc82014-01-20 07:44:53 +0000507 Value *RI = createFDiv(NewAddSub, Factor);
508 if (Instruction *II = dyn_cast<Instruction>(RI))
509 II->setFastMathFlags(Flags);
510 return RI;
Shuxin Yang2eca6022013-03-14 18:08:26 +0000511}
512
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000513Value *FAddCombine::simplify(Instruction *I) {
Sanjay Patel629c4112017-11-06 16:27:15 +0000514 assert(I->isFast() && "Expected 'fast' instruction");
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000515
516 // Currently we are not able to handle vector type.
517 if (I->getType()->isVectorTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000518 return nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000519
520 assert((I->getOpcode() == Instruction::FAdd ||
521 I->getOpcode() == Instruction::FSub) && "Expect add/sub");
522
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000523 // Save the instruction before calling other member-functions.
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000524 Instr = I;
525
526 FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
527
528 unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
529
530 // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
531 unsigned Opnd0_ExpNum = 0;
532 unsigned Opnd1_ExpNum = 0;
533
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000534 if (!Opnd0.isConstant())
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000535 Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
536
537 // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
538 if (OpndNum == 2 && !Opnd1.isConstant())
539 Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
540
541 // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
542 if (Opnd0_ExpNum && Opnd1_ExpNum) {
543 AddendVect AllOpnds;
544 AllOpnds.push_back(&Opnd0_0);
545 AllOpnds.push_back(&Opnd1_0);
546 if (Opnd0_ExpNum == 2)
547 AllOpnds.push_back(&Opnd0_1);
548 if (Opnd1_ExpNum == 2)
549 AllOpnds.push_back(&Opnd1_1);
550
551 // Compute instruction quota. We should save at least one instruction.
552 unsigned InstQuota = 0;
553
554 Value *V0 = I->getOperand(0);
555 Value *V1 = I->getOperand(1);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000556 InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000557 (!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
558
559 if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
560 return R;
561 }
562
563 if (OpndNum != 2) {
564 // The input instruction is : "I=0.0 +/- V". If the "V" were able to be
565 // splitted into two addends, say "V = X - Y", the instruction would have
566 // been optimized into "I = Y - X" in the previous steps.
567 //
568 const FAddendCoef &CE = Opnd0.getCoef();
Craig Topperf40110f2014-04-25 05:29:35 +0000569 return CE.isOne() ? Opnd0.getSymVal() : nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000570 }
571
572 // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
573 if (Opnd1_ExpNum) {
574 AddendVect AllOpnds;
575 AllOpnds.push_back(&Opnd0);
576 AllOpnds.push_back(&Opnd1_0);
577 if (Opnd1_ExpNum == 2)
578 AllOpnds.push_back(&Opnd1_1);
579
580 if (Value *R = simplifyFAdd(AllOpnds, 1))
581 return R;
582 }
583
584 // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
585 if (Opnd0_ExpNum) {
586 AddendVect AllOpnds;
587 AllOpnds.push_back(&Opnd1);
588 AllOpnds.push_back(&Opnd0_0);
589 if (Opnd0_ExpNum == 2)
590 AllOpnds.push_back(&Opnd0_1);
591
592 if (Value *R = simplifyFAdd(AllOpnds, 1))
593 return R;
594 }
595
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000596 // step 6: Try factorization as the last resort,
Shuxin Yang2eca6022013-03-14 18:08:26 +0000597 return performFactorization(I);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000598}
599
600Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000601 unsigned AddendNum = Addends.size();
602 assert(AddendNum <= 4 && "Too many addends");
603
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000604 // For saving intermediate results;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000605 unsigned NextTmpIdx = 0;
606 FAddend TmpResult[3];
607
608 // Points to the constant addend of the resulting simplified expression.
609 // If the resulting expr has constant-addend, this constant-addend is
610 // desirable to reside at the top of the resulting expression tree. Placing
611 // constant close to supper-expr(s) will potentially reveal some optimization
612 // opportunities in super-expr(s).
Craig Topperf40110f2014-04-25 05:29:35 +0000613 const FAddend *ConstAdd = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000614
615 // Simplified addends are placed <SimpVect>.
616 AddendVect SimpVect;
617
618 // The outer loop works on one symbolic-value at a time. Suppose the input
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000619 // addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000620 // The symbolic-values will be processed in this order: x, y, z.
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000621 for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
622
623 const FAddend *ThisAddend = Addends[SymIdx];
624 if (!ThisAddend) {
625 // This addend was processed before.
626 continue;
627 }
628
629 Value *Val = ThisAddend->getSymVal();
630 unsigned StartIdx = SimpVect.size();
631 SimpVect.push_back(ThisAddend);
632
633 // The inner loop collects addends sharing same symbolic-value, and these
634 // addends will be later on folded into a single addend. Following above
635 // example, if the symbolic value "y" is being processed, the inner loop
636 // will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
637 // be later on folded into "<b1+b2, y>".
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000638 for (unsigned SameSymIdx = SymIdx + 1;
639 SameSymIdx < AddendNum; SameSymIdx++) {
640 const FAddend *T = Addends[SameSymIdx];
641 if (T && T->getSymVal() == Val) {
642 // Set null such that next iteration of the outer loop will not process
643 // this addend again.
Craig Topperf40110f2014-04-25 05:29:35 +0000644 Addends[SameSymIdx] = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000645 SimpVect.push_back(T);
646 }
647 }
648
649 // If multiple addends share same symbolic value, fold them together.
650 if (StartIdx + 1 != SimpVect.size()) {
651 FAddend &R = TmpResult[NextTmpIdx ++];
652 R = *SimpVect[StartIdx];
653 for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
654 R += *SimpVect[Idx];
655
656 // Pop all addends being folded and push the resulting folded addend.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000657 SimpVect.resize(StartIdx);
Craig Topperf40110f2014-04-25 05:29:35 +0000658 if (Val) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000659 if (!R.isZero()) {
660 SimpVect.push_back(&R);
661 }
662 } else {
663 // Don't push constant addend at this time. It will be the last element
664 // of <SimpVect>.
665 ConstAdd = &R;
666 }
667 }
668 }
669
Craig Topper58713212013-07-15 04:27:47 +0000670 assert((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000671 "out-of-bound access");
672
673 if (ConstAdd)
674 SimpVect.push_back(ConstAdd);
675
676 Value *Result;
677 if (!SimpVect.empty())
678 Result = createNaryFAdd(SimpVect, InstrQuota);
679 else {
680 // The addition is folded to 0.0.
681 Result = ConstantFP::get(Instr->getType(), 0.0);
682 }
683
684 return Result;
685}
686
687Value *FAddCombine::createNaryFAdd
688 (const AddendVect &Opnds, unsigned InstrQuota) {
689 assert(!Opnds.empty() && "Expect at least one addend");
690
691 // Step 1: Check if the # of instructions needed exceeds the quota.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000692
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000693 unsigned InstrNeeded = calcInstrNumber(Opnds);
694 if (InstrNeeded > InstrQuota)
Craig Topperf40110f2014-04-25 05:29:35 +0000695 return nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000696
697 initCreateInstNum();
698
699 // step 2: Emit the N-ary addition.
700 // Note that at most three instructions are involved in Fadd-InstCombine: the
701 // addition in question, and at most two neighboring instructions.
702 // The resulting optimized addition should have at least one less instruction
703 // than the original addition expression tree. This implies that the resulting
704 // N-ary addition has at most two instructions, and we don't need to worry
705 // about tree-height when constructing the N-ary addition.
706
Craig Topperf40110f2014-04-25 05:29:35 +0000707 Value *LastVal = nullptr;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000708 bool LastValNeedNeg = false;
709
710 // Iterate the addends, creating fadd/fsub using adjacent two addends.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000711 for (const FAddend *Opnd : Opnds) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000712 bool NeedNeg;
Benjamin Kramer135f7352016-06-26 12:28:59 +0000713 Value *V = createAddendVal(*Opnd, NeedNeg);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000714 if (!LastVal) {
715 LastVal = V;
716 LastValNeedNeg = NeedNeg;
717 continue;
718 }
719
720 if (LastValNeedNeg == NeedNeg) {
721 LastVal = createFAdd(LastVal, V);
722 continue;
723 }
724
725 if (LastValNeedNeg)
726 LastVal = createFSub(V, LastVal);
727 else
728 LastVal = createFSub(LastVal, V);
729
730 LastValNeedNeg = false;
731 }
732
733 if (LastValNeedNeg) {
734 LastVal = createFNeg(LastVal);
735 }
736
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000737#ifndef NDEBUG
738 assert(CreateInstrNum == InstrNeeded &&
739 "Inconsistent in instruction numbers");
740#endif
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000741
742 return LastVal;
743}
744
Sanjay Patelc242dbb2014-12-18 21:11:09 +0000745Value *FAddCombine::createFSub(Value *Opnd0, Value *Opnd1) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000746 Value *V = Builder.CreateFSub(Opnd0, Opnd1);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000747 if (Instruction *I = dyn_cast<Instruction>(V))
748 createInstPostProc(I);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000749 return V;
750}
751
752Value *FAddCombine::createFNeg(Value *V) {
Sanjay Patelea3c8022014-12-19 16:44:08 +0000753 Value *Zero = cast<Value>(ConstantFP::getZeroValueForNegation(V->getType()));
Owen Anderson1664dc82014-01-20 07:44:53 +0000754 Value *NewV = createFSub(Zero, V);
755 if (Instruction *I = dyn_cast<Instruction>(NewV))
756 createInstPostProc(I, true); // fneg's don't receive instruction numbers.
757 return NewV;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000758}
759
Sanjay Patelc242dbb2014-12-18 21:11:09 +0000760Value *FAddCombine::createFAdd(Value *Opnd0, Value *Opnd1) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000761 Value *V = Builder.CreateFAdd(Opnd0, Opnd1);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000762 if (Instruction *I = dyn_cast<Instruction>(V))
763 createInstPostProc(I);
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000764 return V;
765}
766
767Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000768 Value *V = Builder.CreateFMul(Opnd0, Opnd1);
Shuxin Yang2eca6022013-03-14 18:08:26 +0000769 if (Instruction *I = dyn_cast<Instruction>(V))
770 createInstPostProc(I);
771 return V;
772}
773
774Value *FAddCombine::createFDiv(Value *Opnd0, Value *Opnd1) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000775 Value *V = Builder.CreateFDiv(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
Sanjay Patelc242dbb2014-12-18 21:11:09 +0000781void FAddCombine::createInstPostProc(Instruction *NewInstr, bool NoNumber) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000782 NewInstr->setDebugLoc(Instr->getDebugLoc());
783
784 // Keep track of the number of instruction created.
Owen Anderson1664dc82014-01-20 07:44:53 +0000785 if (!NoNumber)
786 incCreateInstNum();
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000787
788 // Propagate fast-math flags
789 NewInstr->setFastMathFlags(Instr->getFastMathFlags());
790}
791
792// Return the number of instruction needed to emit the N-ary addition.
793// NOTE: Keep this function in sync with createAddendVal().
794unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
795 unsigned OpndNum = Opnds.size();
796 unsigned InstrNeeded = OpndNum - 1;
797
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000798 // The number of addends in the form of "(-1)*x".
799 unsigned NegOpndNum = 0;
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000800
801 // Adjust the number of instructions needed to emit the N-ary add.
Benjamin Kramer135f7352016-06-26 12:28:59 +0000802 for (const FAddend *Opnd : Opnds) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000803 if (Opnd->isConstant())
804 continue;
805
Matt Arsenault02907f32017-04-24 17:24:37 +0000806 // The constant check above is really for a few special constant
807 // coefficients.
808 if (isa<UndefValue>(Opnd->getSymVal()))
809 continue;
810
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000811 const FAddendCoef &CE = Opnd->getCoef();
812 if (CE.isMinusOne() || CE.isMinusTwo())
813 NegOpndNum++;
814
815 // Let the addend be "c * x". If "c == +/-1", the value of the addend
816 // is immediately available; otherwise, it needs exactly one instruction
817 // to evaluate the value.
818 if (!CE.isMinusOne() && !CE.isOne())
819 InstrNeeded++;
820 }
821 if (NegOpndNum == OpndNum)
822 InstrNeeded++;
823 return InstrNeeded;
824}
825
826// Input Addend Value NeedNeg(output)
827// ================================================================
828// Constant C C false
829// <+/-1, V> V coefficient is -1
830// <2/-2, V> "fadd V, V" coefficient is -2
831// <C, V> "fmul V, C" false
832//
833// NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
Sanjay Patelc242dbb2014-12-18 21:11:09 +0000834Value *FAddCombine::createAddendVal(const FAddend &Opnd, bool &NeedNeg) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +0000835 const FAddendCoef &Coeff = Opnd.getCoef();
836
837 if (Opnd.isConstant()) {
838 NeedNeg = false;
839 return Coeff.getValue(Instr->getType());
840 }
841
842 Value *OpndVal = Opnd.getSymVal();
843
844 if (Coeff.isMinusOne() || Coeff.isOne()) {
845 NeedNeg = Coeff.isMinusOne();
846 return OpndVal;
847 }
848
849 if (Coeff.isTwo() || Coeff.isMinusTwo()) {
850 NeedNeg = Coeff.isMinusTwo();
851 return createFAdd(OpndVal, OpndVal);
852 }
853
854 NeedNeg = false;
855 return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
856}
857
David Majnemer57d5bc82014-08-19 23:36:30 +0000858/// \brief Return true if we can prove that:
859/// (sub LHS, RHS) === (sub nsw LHS, RHS)
860/// This basically requires proving that the add in the original type would not
861/// overflow to change the sign bit or have a carry out.
862/// TODO: Handle this for Vectors.
Craig Topper2b1fc322017-05-22 06:25:31 +0000863bool InstCombiner::willNotOverflowSignedSub(const Value *LHS,
864 const Value *RHS,
865 const Instruction &CxtI) const {
David Majnemer57d5bc82014-08-19 23:36:30 +0000866 // If LHS and RHS each have at least two sign bits, the subtraction
867 // cannot overflow.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000868 if (ComputeNumSignBits(LHS, 0, &CxtI) > 1 &&
869 ComputeNumSignBits(RHS, 0, &CxtI) > 1)
David Majnemer57d5bc82014-08-19 23:36:30 +0000870 return true;
871
Craig Topper8205a1a2017-05-24 16:53:07 +0000872 KnownBits LHSKnown = computeKnownBits(LHS, 0, &CxtI);
David Majnemer57d5bc82014-08-19 23:36:30 +0000873
Craig Topper8205a1a2017-05-24 16:53:07 +0000874 KnownBits RHSKnown = computeKnownBits(RHS, 0, &CxtI);
David Majnemer57d5bc82014-08-19 23:36:30 +0000875
Craig Topper957a94c2017-04-11 18:47:58 +0000876 // Subtraction of two 2's complement numbers having identical signs will
David Majnemer54c2ca22014-12-26 09:10:14 +0000877 // never overflow.
Craig Topperaaef41f2017-05-22 00:49:33 +0000878 if ((LHSKnown.isNegative() && RHSKnown.isNegative()) ||
879 (LHSKnown.isNonNegative() && RHSKnown.isNonNegative()))
David Majnemer54c2ca22014-12-26 09:10:14 +0000880 return true;
David Majnemer57d5bc82014-08-19 23:36:30 +0000881
David Majnemer54c2ca22014-12-26 09:10:14 +0000882 // TODO: implement logic similar to checkRippleForAdd
David Majnemer57d5bc82014-08-19 23:36:30 +0000883 return false;
884}
885
David Majnemer42158f32014-08-20 07:17:31 +0000886/// \brief Return true if we can prove that:
887/// (sub LHS, RHS) === (sub nuw LHS, RHS)
Craig Topper2b1fc322017-05-22 06:25:31 +0000888bool InstCombiner::willNotOverflowUnsignedSub(const Value *LHS,
889 const Value *RHS,
890 const Instruction &CxtI) const {
David Majnemer42158f32014-08-20 07:17:31 +0000891 // If the LHS is negative and the RHS is non-negative, no unsigned wrap.
Craig Topper1a36b7d2017-05-15 06:39:41 +0000892 KnownBits LHSKnown = computeKnownBits(LHS, /*Depth=*/0, &CxtI);
893 KnownBits RHSKnown = computeKnownBits(RHS, /*Depth=*/0, &CxtI);
894 if (LHSKnown.isNegative() && RHSKnown.isNonNegative())
David Majnemer42158f32014-08-20 07:17:31 +0000895 return true;
896
897 return false;
898}
899
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000900// Checks if any operand is negative and we can convert add to sub.
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000901// This function checks for following negative patterns
902// ADD(XOR(OR(Z, NOT(C)), C)), 1) == NEG(AND(Z, C))
903// ADD(XOR(AND(Z, C), C), 1) == NEG(OR(Z, ~C))
904// XOR(AND(Z, C), (C + 1)) == NEG(OR(Z, ~C)) if C is even
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000905static Value *checkForNegativeOperand(BinaryOperator &I,
Craig Topperbb4069e2017-07-07 23:16:26 +0000906 InstCombiner::BuilderTy &Builder) {
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000907 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000908
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000909 // This function creates 2 instructions to replace ADD, we need at least one
910 // of LHS or RHS to have one use to ensure benefit in transform.
911 if (!LHS->hasOneUse() && !RHS->hasOneUse())
912 return nullptr;
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000913
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000914 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
915 const APInt *C1 = nullptr, *C2 = nullptr;
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000916
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000917 // if ONE is on other side, swap
918 if (match(RHS, m_Add(m_Value(X), m_One())))
919 std::swap(LHS, RHS);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000920
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000921 if (match(LHS, m_Add(m_Value(X), m_One()))) {
922 // if XOR on other side, swap
923 if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
924 std::swap(X, RHS);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000925
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000926 if (match(X, m_Xor(m_Value(Y), m_APInt(C1)))) {
927 // X = XOR(Y, C1), Y = OR(Z, C2), C2 = NOT(C1) ==> X == NOT(AND(Z, C1))
928 // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, AND(Z, C1))
929 if (match(Y, m_Or(m_Value(Z), m_APInt(C2))) && (*C2 == ~(*C1))) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000930 Value *NewAnd = Builder.CreateAnd(Z, *C1);
931 return Builder.CreateSub(RHS, NewAnd, "sub");
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000932 } else if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && (*C1 == *C2)) {
933 // X = XOR(Y, C1), Y = AND(Z, C2), C2 == C1 ==> X == NOT(OR(Z, ~C1))
934 // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, OR(Z, ~C1))
Craig Topperbb4069e2017-07-07 23:16:26 +0000935 Value *NewOr = Builder.CreateOr(Z, ~(*C1));
936 return Builder.CreateSub(RHS, NewOr, "sub");
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000937 }
938 }
939 }
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000940
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000941 // Restore LHS and RHS
942 LHS = I.getOperand(0);
943 RHS = I.getOperand(1);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +0000944
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000945 // if XOR is on other side, swap
946 if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
947 std::swap(LHS, RHS);
948
949 // C2 is ODD
950 // LHS = XOR(Y, C1), Y = AND(Z, C2), C1 == (C2 + 1) => LHS == NEG(OR(Z, ~C2))
951 // ADD(LHS, RHS) == SUB(RHS, OR(Z, ~C2))
952 if (match(LHS, m_Xor(m_Value(Y), m_APInt(C1))))
953 if (C1->countTrailingZeros() == 0)
954 if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && *C1 == (*C2 + 1)) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000955 Value *NewOr = Builder.CreateOr(Z, ~(*C2));
956 return Builder.CreateSub(RHS, NewOr, "sub");
Dinesh Dwivediadc07732014-06-27 07:47:35 +0000957 }
958 return nullptr;
959}
960
Sanjay Patel8d810fe2017-10-13 16:43:58 +0000961Instruction *InstCombiner::foldAddWithConstant(BinaryOperator &Add) {
Sanjay Patel4133d4a2017-05-10 00:07:16 +0000962 Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1);
Sanjay Patel21506512017-10-13 16:29:38 +0000963 Constant *Op1C;
964 if (!match(Op1, m_Constant(Op1C)))
965 return nullptr;
966
Sanjay Patel8fdd87f2018-02-28 16:36:24 +0000967 if (Instruction *NV = foldBinOpIntoSelectOrPhi(Add))
Sanjay Patel8d810fe2017-10-13 16:43:58 +0000968 return NV;
969
Sanjay Patel21506512017-10-13 16:29:38 +0000970 Value *X;
Sanjay Patelf0242de2017-10-13 20:29:11 +0000971 // zext(bool) + C -> bool ? C + 1 : C
972 if (match(Op0, m_ZExt(m_Value(X))) &&
973 X->getType()->getScalarSizeInBits() == 1)
Sanjay Patel76ed9ea2017-10-13 17:00:47 +0000974 return SelectInst::Create(X, AddOne(Op1C), Op1);
Sanjay Patel21506512017-10-13 16:29:38 +0000975
Sanjay Patelf0242de2017-10-13 20:29:11 +0000976 // ~X + C --> (C-1) - X
977 if (match(Op0, m_Not(m_Value(X))))
978 return BinaryOperator::CreateSub(SubOne(Op1C), X);
979
Sanjay Patel4133d4a2017-05-10 00:07:16 +0000980 const APInt *C;
981 if (!match(Op1, m_APInt(C)))
982 return nullptr;
983
984 if (C->isSignMask()) {
985 // If wrapping is not allowed, then the addition must set the sign bit:
986 // X + (signmask) --> X | signmask
987 if (Add.hasNoSignedWrap() || Add.hasNoUnsignedWrap())
988 return BinaryOperator::CreateOr(Op0, Op1);
989
990 // If wrapping is allowed, then the addition flips the sign bit of LHS:
991 // X + (signmask) --> X ^ signmask
992 return BinaryOperator::CreateXor(Op0, Op1);
993 }
994
Sanjay Patel4133d4a2017-05-10 00:07:16 +0000995 // Is this add the last step in a convoluted sext?
996 // add(zext(xor i16 X, -32768), -32768) --> sext X
Sanjay Patel76ed9ea2017-10-13 17:00:47 +0000997 Type *Ty = Add.getType();
Sanjay Patel21506512017-10-13 16:29:38 +0000998 const APInt *C2;
Sanjay Patel4133d4a2017-05-10 00:07:16 +0000999 if (match(Op0, m_ZExt(m_Xor(m_Value(X), m_APInt(C2)))) &&
1000 C2->isMinSignedValue() && C2->sext(Ty->getScalarSizeInBits()) == *C)
1001 return CastInst::Create(Instruction::SExt, X, Ty);
1002
1003 // (add (zext (add nuw X, C2)), C) --> (zext (add nuw X, C2 + C))
Sanjay Patelc419c9f2017-10-13 17:47:25 +00001004 if (match(Op0, m_OneUse(m_ZExt(m_NUWAdd(m_Value(X), m_APInt(C2))))) &&
1005 C->isNegative() && C->sge(-C2->sext(C->getBitWidth()))) {
Sanjay Patel4133d4a2017-05-10 00:07:16 +00001006 Constant *NewC =
1007 ConstantInt::get(X->getType(), *C2 + C->trunc(C2->getBitWidth()));
1008 return new ZExtInst(Builder.CreateNUWAdd(X, NewC), Ty);
1009 }
1010
Sanjay Patel2f3ead72017-06-25 14:15:28 +00001011 if (C->isOneValue() && Op0->hasOneUse()) {
1012 // add (sext i1 X), 1 --> zext (not X)
1013 // TODO: The smallest IR representation is (select X, 0, 1), and that would
1014 // not require the one-use check. But we need to remove a transform in
1015 // visitSelect and make sure that IR value tracking for select is equal or
1016 // better than for these ops.
1017 if (match(Op0, m_SExt(m_Value(X))) &&
1018 X->getType()->getScalarSizeInBits() == 1)
1019 return new ZExtInst(Builder.CreateNot(X), Ty);
1020
1021 // Shifts and add used to flip and mask off the low bit:
1022 // add (ashr (shl i32 X, 31), 31), 1 --> and (not X), 1
1023 const APInt *C3;
1024 if (match(Op0, m_AShr(m_Shl(m_Value(X), m_APInt(C2)), m_APInt(C3))) &&
1025 C2 == C3 && *C2 == Ty->getScalarSizeInBits() - 1) {
1026 Value *NotX = Builder.CreateNot(X);
1027 return BinaryOperator::CreateAnd(NotX, ConstantInt::get(Ty, 1));
1028 }
Sanjay Patel2e069f22017-05-10 13:56:52 +00001029 }
1030
Sanjay Patel4133d4a2017-05-10 00:07:16 +00001031 return nullptr;
1032}
1033
Dinesh Dwivediadc07732014-06-27 07:47:35 +00001034Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001035 bool Changed = SimplifyAssociativeOrCommutative(I);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001036 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001037 return replaceInstUsesWith(I, V);
Chris Lattner82aa8882010-01-05 07:18:46 +00001038
Sanjay Patel21189522017-10-13 18:32:53 +00001039 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Craig Toppera4205622017-06-09 03:21:29 +00001040 if (Value *V =
1041 SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
1042 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001043 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001044
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001045 // (A*B)+(A*C) -> A*(B+C) etc
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001046 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001047 return replaceInstUsesWith(I, V);
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001048
Sanjay Patel8d810fe2017-10-13 16:43:58 +00001049 if (Instruction *X = foldAddWithConstant(I))
Sanjay Patel4133d4a2017-05-10 00:07:16 +00001050 return X;
Sanjay Patel53c5c3d2017-02-18 22:20:09 +00001051
Sanjay Patel4133d4a2017-05-10 00:07:16 +00001052 // FIXME: This should be moved into the above helper function to allow these
Sanjay Patel21506512017-10-13 16:29:38 +00001053 // transforms for general constant or constant splat vectors.
Sanjay Patel21189522017-10-13 18:32:53 +00001054 Type *Ty = I.getType();
Sanjay Patel79acd2a2016-07-16 18:29:26 +00001055 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001056 Value *XorLHS = nullptr; ConstantInt *XorRHS = nullptr;
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001057 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Sanjay Patel21189522017-10-13 18:32:53 +00001058 unsigned TySizeBits = Ty->getScalarSizeInBits();
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001059 const APInt &RHSVal = CI->getValue();
Eli Friedmana2cc2872010-01-31 04:29:12 +00001060 unsigned ExtendAmt = 0;
1061 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1062 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1063 if (XorRHS->getValue() == -RHSVal) {
1064 if (RHSVal.isPowerOf2())
1065 ExtendAmt = TySizeBits - RHSVal.logBase2() - 1;
1066 else if (XorRHS->getValue().isPowerOf2())
1067 ExtendAmt = TySizeBits - XorRHS->getValue().logBase2() - 1;
Chris Lattner82aa8882010-01-05 07:18:46 +00001068 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001069
Eli Friedmana2cc2872010-01-31 04:29:12 +00001070 if (ExtendAmt) {
1071 APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt);
Hal Finkel60db0582014-09-07 18:57:58 +00001072 if (!MaskedValueIsZero(XorLHS, Mask, 0, &I))
Eli Friedmana2cc2872010-01-31 04:29:12 +00001073 ExtendAmt = 0;
1074 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001075
Eli Friedmana2cc2872010-01-31 04:29:12 +00001076 if (ExtendAmt) {
Sanjay Patel21189522017-10-13 18:32:53 +00001077 Constant *ShAmt = ConstantInt::get(Ty, ExtendAmt);
Craig Topperbb4069e2017-07-07 23:16:26 +00001078 Value *NewShl = Builder.CreateShl(XorLHS, ShAmt, "sext");
Eli Friedmana2cc2872010-01-31 04:29:12 +00001079 return BinaryOperator::CreateAShr(NewShl, ShAmt);
Chris Lattner82aa8882010-01-05 07:18:46 +00001080 }
Benjamin Kramerb16bd772011-12-24 17:31:53 +00001081
1082 // If this is a xor that was canonicalized from a sub, turn it back into
1083 // a sub and fuse this add with it.
1084 if (LHS->hasOneUse() && (XorRHS->getValue()+1).isPowerOf2()) {
Craig Topper8205a1a2017-05-24 16:53:07 +00001085 KnownBits LHSKnown = computeKnownBits(XorLHS, 0, &I);
Craig Topperb45eabc2017-04-26 16:39:58 +00001086 if ((XorRHS->getValue() | LHSKnown.Zero).isAllOnesValue())
Benjamin Kramerb16bd772011-12-24 17:31:53 +00001087 return BinaryOperator::CreateSub(ConstantExpr::getAdd(XorRHS, CI),
1088 XorLHS);
1089 }
Craig Topperbcfd2d12017-04-20 16:56:25 +00001090 // (X + signmask) + C could have gotten canonicalized to (X^signmask) + C,
1091 // transform them into (X + (signmask ^ C))
1092 if (XorRHS->getValue().isSignMask())
Craig Toppereafbd572015-12-21 01:02:28 +00001093 return BinaryOperator::CreateAdd(XorLHS,
1094 ConstantExpr::getXor(XorRHS, CI));
Chris Lattner82aa8882010-01-05 07:18:46 +00001095 }
1096 }
1097
Sanjay Patel21189522017-10-13 18:32:53 +00001098 if (Ty->isIntOrIntVectorTy(1))
Chris Lattner82aa8882010-01-05 07:18:46 +00001099 return BinaryOperator::CreateXor(LHS, RHS);
1100
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001101 // X + X --> X << 1
Chris Lattnerd4067642011-02-17 20:55:29 +00001102 if (LHS == RHS) {
Sanjay Patel21189522017-10-13 18:32:53 +00001103 auto *Shl = BinaryOperator::CreateShl(LHS, ConstantInt::get(Ty, 1));
1104 Shl->setHasNoSignedWrap(I.hasNoSignedWrap());
1105 Shl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1106 return Shl;
Chris Lattner55920712011-02-17 02:23:02 +00001107 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001108
Sanjay Patelb869f762017-10-13 21:28:50 +00001109 Value *A, *B;
1110 if (match(LHS, m_Neg(m_Value(A)))) {
1111 // -A + -B --> -(A + B)
1112 if (match(RHS, m_Neg(m_Value(B))))
1113 return BinaryOperator::CreateNeg(Builder.CreateAdd(A, B));
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001114
Sanjay Patelb869f762017-10-13 21:28:50 +00001115 // -A + B --> B - A
1116 return BinaryOperator::CreateSub(RHS, A);
Chris Lattner82aa8882010-01-05 07:18:46 +00001117 }
1118
1119 // A + -B --> A - B
Sanjay Patelb869f762017-10-13 21:28:50 +00001120 if (match(RHS, m_Neg(m_Value(B))))
1121 return BinaryOperator::CreateSub(LHS, B);
Chris Lattner82aa8882010-01-05 07:18:46 +00001122
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001123 if (Value *V = checkForNegativeOperand(I, Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001124 return replaceInstUsesWith(I, V);
Dinesh Dwivedi562fd752014-06-19 10:36:52 +00001125
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001126 // A+B --> A|B iff A and B have no bits set in common.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001127 if (haveNoCommonBitsSet(LHS, RHS, DL, &AC, &I, &DT))
Jingyue Wuca321902015-05-14 23:53:19 +00001128 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner82aa8882010-01-05 07:18:46 +00001129
Sanjay Patel79acd2a2016-07-16 18:29:26 +00001130 // FIXME: We already did a check for ConstantInt RHS above this.
1131 // FIXME: Is this pattern covered by another fold? No regression tests fail on
1132 // removal.
Benjamin Kramer72196f32014-01-19 15:24:22 +00001133 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001134 // (X & FF00) + xx00 -> (X+xx00) & FF00
Benjamin Kramer72196f32014-01-19 15:24:22 +00001135 Value *X;
1136 ConstantInt *C2;
Chris Lattner82aa8882010-01-05 07:18:46 +00001137 if (LHS->hasOneUse() &&
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001138 match(LHS, m_And(m_Value(X), m_ConstantInt(C2))) &&
1139 CRHS->getValue() == (CRHS->getValue() & C2->getValue())) {
1140 // See if all bits from the first bit set in the Add RHS up are included
1141 // in the mask. First, get the rightmost bit.
1142 const APInt &AddRHSV = CRHS->getValue();
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001143
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001144 // Form a mask of all bits from the lowest bit added through the top.
1145 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattner82aa8882010-01-05 07:18:46 +00001146
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001147 // See if the and mask includes all of these bits.
1148 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Chris Lattner82aa8882010-01-05 07:18:46 +00001149
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001150 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1151 // Okay, the xform is safe. Insert the new add pronto.
Craig Topperbb4069e2017-07-07 23:16:26 +00001152 Value *NewAdd = Builder.CreateAdd(X, CRHS, LHS->getName());
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001153 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattner82aa8882010-01-05 07:18:46 +00001154 }
1155 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001156 }
1157
1158 // add (select X 0 (sub n A)) A --> select X A n
1159 {
1160 SelectInst *SI = dyn_cast<SelectInst>(LHS);
1161 Value *A = RHS;
1162 if (!SI) {
1163 SI = dyn_cast<SelectInst>(RHS);
1164 A = LHS;
1165 }
1166 if (SI && SI->hasOneUse()) {
1167 Value *TV = SI->getTrueValue();
1168 Value *FV = SI->getFalseValue();
1169 Value *N;
1170
1171 // Can we fold the add into the argument of the select?
1172 // We check both true and false select arguments for a matching subtract.
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001173 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner82aa8882010-01-05 07:18:46 +00001174 // Fold the add into the true select value.
1175 return SelectInst::Create(SI->getCondition(), N, A);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001176
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001177 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner82aa8882010-01-05 07:18:46 +00001178 // Fold the add into the false select value.
1179 return SelectInst::Create(SI->getCondition(), A, N);
1180 }
1181 }
1182
1183 // Check for (add (sext x), y), see if we can merge this into an
1184 // integer add followed by a sext.
1185 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
1186 // (add (sext x), cst) --> (sext (add x, cst'))
1187 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +00001188 if (LHSConv->hasOneUse()) {
1189 Constant *CI =
1190 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Sanjay Patel21189522017-10-13 18:32:53 +00001191 if (ConstantExpr::getSExt(CI, Ty) == RHSC &&
Craig Topper2b1fc322017-05-22 06:25:31 +00001192 willNotOverflowSignedAdd(LHSConv->getOperand(0), CI, I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +00001193 // Insert the new, smaller add.
1194 Value *NewAdd =
Craig Topperbb4069e2017-07-07 23:16:26 +00001195 Builder.CreateNSWAdd(LHSConv->getOperand(0), CI, "addconv");
Sanjay Patel21189522017-10-13 18:32:53 +00001196 return new SExtInst(NewAdd, Ty);
David Majnemera1cfd7c2016-12-30 00:28:58 +00001197 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001198 }
1199 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001200
Chris Lattner82aa8882010-01-05 07:18:46 +00001201 // (add (sext x), (sext y)) --> (sext (add int x, y))
1202 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
Craig Topper79e5bc52017-03-30 22:28:55 +00001203 // Only do this if x/y have the same type, if at least one of them has a
Chris Lattner82aa8882010-01-05 07:18:46 +00001204 // single use (so we don't increase the number of sexts), and if the
1205 // integer add will not overflow.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001206 if (LHSConv->getOperand(0)->getType() ==
1207 RHSConv->getOperand(0)->getType() &&
Chris Lattner82aa8882010-01-05 07:18:46 +00001208 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
Craig Topper2b1fc322017-05-22 06:25:31 +00001209 willNotOverflowSignedAdd(LHSConv->getOperand(0),
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001210 RHSConv->getOperand(0), I)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001211 // Insert the new integer add.
Craig Topperbb4069e2017-07-07 23:16:26 +00001212 Value *NewAdd = Builder.CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattnerdec68472010-01-05 20:56:24 +00001213 RHSConv->getOperand(0), "addconv");
Sanjay Patel21189522017-10-13 18:32:53 +00001214 return new SExtInst(NewAdd, Ty);
Chris Lattner82aa8882010-01-05 07:18:46 +00001215 }
1216 }
1217 }
1218
David Majnemera1cfd7c2016-12-30 00:28:58 +00001219 // Check for (add (zext x), y), see if we can merge this into an
1220 // integer add followed by a zext.
1221 if (auto *LHSConv = dyn_cast<ZExtInst>(LHS)) {
1222 // (add (zext x), cst) --> (zext (add x, cst'))
1223 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
1224 if (LHSConv->hasOneUse()) {
1225 Constant *CI =
1226 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Sanjay Patel21189522017-10-13 18:32:53 +00001227 if (ConstantExpr::getZExt(CI, Ty) == RHSC &&
Craig Topperbb973722017-05-15 02:44:08 +00001228 willNotOverflowUnsignedAdd(LHSConv->getOperand(0), CI, I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +00001229 // Insert the new, smaller add.
1230 Value *NewAdd =
Craig Topperbb4069e2017-07-07 23:16:26 +00001231 Builder.CreateNUWAdd(LHSConv->getOperand(0), CI, "addconv");
Sanjay Patel21189522017-10-13 18:32:53 +00001232 return new ZExtInst(NewAdd, Ty);
David Majnemera1cfd7c2016-12-30 00:28:58 +00001233 }
1234 }
1235 }
1236
1237 // (add (zext x), (zext y)) --> (zext (add int x, y))
1238 if (auto *RHSConv = dyn_cast<ZExtInst>(RHS)) {
Craig Topper79e5bc52017-03-30 22:28:55 +00001239 // Only do this if x/y have the same type, if at least one of them has a
David Majnemera1cfd7c2016-12-30 00:28:58 +00001240 // single use (so we don't increase the number of zexts), and if the
1241 // integer add will not overflow.
1242 if (LHSConv->getOperand(0)->getType() ==
1243 RHSConv->getOperand(0)->getType() &&
1244 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
Craig Topperbb973722017-05-15 02:44:08 +00001245 willNotOverflowUnsignedAdd(LHSConv->getOperand(0),
1246 RHSConv->getOperand(0), I)) {
David Majnemera1cfd7c2016-12-30 00:28:58 +00001247 // Insert the new integer add.
Craig Topperbb4069e2017-07-07 23:16:26 +00001248 Value *NewAdd = Builder.CreateNUWAdd(
David Majnemera1cfd7c2016-12-30 00:28:58 +00001249 LHSConv->getOperand(0), RHSConv->getOperand(0), "addconv");
Sanjay Patel21189522017-10-13 18:32:53 +00001250 return new ZExtInst(NewAdd, Ty);
David Majnemera1cfd7c2016-12-30 00:28:58 +00001251 }
1252 }
1253 }
1254
David Majnemerab07f002014-08-11 22:32:02 +00001255 // (add (xor A, B) (and A, B)) --> (or A, B)
Sanjay Patel28b3aa32017-10-13 20:12:21 +00001256 if (match(LHS, m_Xor(m_Value(A), m_Value(B))) &&
1257 match(RHS, m_c_And(m_Specific(A), m_Specific(B))))
1258 return BinaryOperator::CreateOr(A, B);
Chad Rosier7813dce2012-04-26 23:29:14 +00001259
Sanjay Patel28b3aa32017-10-13 20:12:21 +00001260 // (add (and A, B) (xor A, B)) --> (or A, B)
1261 if (match(RHS, m_Xor(m_Value(A), m_Value(B))) &&
1262 match(LHS, m_c_And(m_Specific(A), m_Specific(B))))
1263 return BinaryOperator::CreateOr(A, B);
Chad Rosier7813dce2012-04-26 23:29:14 +00001264
David Majnemerab07f002014-08-11 22:32:02 +00001265 // (add (or A, B) (and A, B)) --> (add A, B)
Sanjay Patel28b3aa32017-10-13 20:12:21 +00001266 if (match(LHS, m_Or(m_Value(A), m_Value(B))) &&
1267 match(RHS, m_c_And(m_Specific(A), m_Specific(B)))) {
1268 I.setOperand(0, A);
1269 I.setOperand(1, B);
1270 return &I;
1271 }
David Majnemerab07f002014-08-11 22:32:02 +00001272
Sanjay Patel28b3aa32017-10-13 20:12:21 +00001273 // (add (and A, B) (or A, B)) --> (add A, B)
1274 if (match(RHS, m_Or(m_Value(A), m_Value(B))) &&
1275 match(LHS, m_c_And(m_Specific(A), m_Specific(B)))) {
1276 I.setOperand(0, A);
1277 I.setOperand(1, B);
1278 return &I;
David Majnemerab07f002014-08-11 22:32:02 +00001279 }
1280
Craig Topper2b1fc322017-05-22 06:25:31 +00001281 // TODO(jingyue): Consider willNotOverflowSignedAdd and
Craig Topperbb973722017-05-15 02:44:08 +00001282 // willNotOverflowUnsignedAdd to reduce the number of invocations of
Jingyue Wu33bd53d2014-06-17 00:42:07 +00001283 // computeKnownBits.
Craig Topper2b1fc322017-05-22 06:25:31 +00001284 if (!I.hasNoSignedWrap() && willNotOverflowSignedAdd(LHS, RHS, I)) {
Rafael Espindolad1a2c2d2014-06-02 22:01:04 +00001285 Changed = true;
1286 I.setHasNoSignedWrap(true);
1287 }
Craig Topperbb973722017-05-15 02:44:08 +00001288 if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedAdd(LHS, RHS, I)) {
Jingyue Wu33bd53d2014-06-17 00:42:07 +00001289 Changed = true;
1290 I.setHasNoUnsignedWrap(true);
1291 }
Rafael Espindolad1a2c2d2014-06-02 22:01:04 +00001292
Craig Topperf40110f2014-04-25 05:29:35 +00001293 return Changed ? &I : nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001294}
1295
1296Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
Duncan Sands641baf12010-11-13 15:10:37 +00001297 bool Changed = SimplifyAssociativeOrCommutative(I);
Chris Lattner82aa8882010-01-05 07:18:46 +00001298 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1299
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001300 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001301 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001302
Craig Toppera4205622017-06-09 03:21:29 +00001303 if (Value *V = SimplifyFAddInst(LHS, RHS, I.getFastMathFlags(),
1304 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001305 return replaceInstUsesWith(I, V);
Chris Lattner82aa8882010-01-05 07:18:46 +00001306
Sanjay Patel8fdd87f2018-02-28 16:36:24 +00001307 if (Instruction *FoldedFAdd = foldBinOpIntoSelectOrPhi(I))
1308 return FoldedFAdd;
Michael Ilsemane2754dc2012-12-14 22:08:26 +00001309
Chris Lattner82aa8882010-01-05 07:18:46 +00001310 // -A + B --> B - A
Sanjay Patel4a9116e2018-02-23 17:07:29 +00001311 if (Value *LHSV = dyn_castFNegVal(LHS))
1312 return BinaryOperator::CreateFSubFMF(RHS, LHSV, &I);
Chris Lattner82aa8882010-01-05 07:18:46 +00001313
1314 // A + -B --> A - B
1315 if (!isa<Constant>(RHS))
Sanjay Patel4a9116e2018-02-23 17:07:29 +00001316 if (Value *V = dyn_castFNegVal(RHS))
1317 return BinaryOperator::CreateFSubFMF(LHS, V, &I);
Chris Lattner82aa8882010-01-05 07:18:46 +00001318
Dan Gohman6f34abd2010-03-02 01:11:08 +00001319 // Check for (fadd double (sitofp x), y), see if we can merge this into an
Chris Lattner82aa8882010-01-05 07:18:46 +00001320 // integer add followed by a promotion.
1321 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
Artur Pilipenko4cc61302017-03-21 11:32:15 +00001322 Value *LHSIntVal = LHSConv->getOperand(0);
Artur Pilipenko134d94f2017-04-21 18:45:25 +00001323 Type *FPType = LHSConv->getType();
1324
1325 // TODO: This check is overly conservative. In many cases known bits
1326 // analysis can tell us that the result of the addition has less significant
1327 // bits than the integer type can hold.
1328 auto IsValidPromotion = [](Type *FTy, Type *ITy) {
Artur Pilipenko0632bdc2017-04-22 07:24:52 +00001329 Type *FScalarTy = FTy->getScalarType();
1330 Type *IScalarTy = ITy->getScalarType();
1331
Artur Pilipenko134d94f2017-04-21 18:45:25 +00001332 // Do we have enough bits in the significand to represent the result of
1333 // the integer addition?
1334 unsigned MaxRepresentableBits =
Artur Pilipenko0632bdc2017-04-22 07:24:52 +00001335 APFloat::semanticsPrecision(FScalarTy->getFltSemantics());
1336 return IScalarTy->getIntegerBitWidth() <= MaxRepresentableBits;
Artur Pilipenko134d94f2017-04-21 18:45:25 +00001337 };
Artur Pilipenko4cc61302017-03-21 11:32:15 +00001338
Dan Gohman6f34abd2010-03-02 01:11:08 +00001339 // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
Chris Lattner82aa8882010-01-05 07:18:46 +00001340 // ... if the constant fits in the integer value. This is useful for things
1341 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
1342 // requires a constant pool load, and generally allows the add to be better
1343 // instcombined.
Artur Pilipenko134d94f2017-04-21 18:45:25 +00001344 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
1345 if (IsValidPromotion(FPType, LHSIntVal->getType())) {
1346 Constant *CI =
1347 ConstantExpr::getFPToSI(CFP, LHSIntVal->getType());
1348 if (LHSConv->hasOneUse() &&
1349 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Craig Topper2b1fc322017-05-22 06:25:31 +00001350 willNotOverflowSignedAdd(LHSIntVal, CI, I)) {
Artur Pilipenko134d94f2017-04-21 18:45:25 +00001351 // Insert the new integer add.
Craig Topperbb4069e2017-07-07 23:16:26 +00001352 Value *NewAdd = Builder.CreateNSWAdd(LHSIntVal, CI, "addconv");
Artur Pilipenko134d94f2017-04-21 18:45:25 +00001353 return new SIToFPInst(NewAdd, I.getType());
1354 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001355 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001356
Dan Gohman6f34abd2010-03-02 01:11:08 +00001357 // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
Chris Lattner82aa8882010-01-05 07:18:46 +00001358 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
Artur Pilipenko4cc61302017-03-21 11:32:15 +00001359 Value *RHSIntVal = RHSConv->getOperand(0);
Artur Pilipenko134d94f2017-04-21 18:45:25 +00001360 // It's enough to check LHS types only because we require int types to
1361 // be the same for this transform.
1362 if (IsValidPromotion(FPType, LHSIntVal->getType())) {
1363 // Only do this if x/y have the same type, if at least one of them has a
1364 // single use (so we don't increase the number of int->fp conversions),
1365 // and if the integer add will not overflow.
1366 if (LHSIntVal->getType() == RHSIntVal->getType() &&
1367 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
Craig Topper2b1fc322017-05-22 06:25:31 +00001368 willNotOverflowSignedAdd(LHSIntVal, RHSIntVal, I)) {
Artur Pilipenko134d94f2017-04-21 18:45:25 +00001369 // Insert the new integer add.
Craig Topperbb4069e2017-07-07 23:16:26 +00001370 Value *NewAdd = Builder.CreateNSWAdd(LHSIntVal, RHSIntVal, "addconv");
Artur Pilipenko134d94f2017-04-21 18:45:25 +00001371 return new SIToFPInst(NewAdd, I.getType());
1372 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001373 }
1374 }
1375 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001376
Quentin Colombetaa103b32017-09-20 17:32:16 +00001377 // Handle specials cases for FAdd with selects feeding the operation
1378 if (Value *V = SimplifySelectsFeedingBinaryOp(I, LHS, RHS))
1379 return replaceInstUsesWith(I, V);
Jean-Luc Duprat3e4fc3e2013-05-06 16:55:50 +00001380
Sanjay Patel629c4112017-11-06 16:27:15 +00001381 if (I.isFast()) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +00001382 if (Value *V = FAddCombine(Builder).simplify(&I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001383 return replaceInstUsesWith(I, V);
Shuxin Yang37a1efe2012-12-18 23:10:12 +00001384 }
1385
Craig Topperf40110f2014-04-25 05:29:35 +00001386 return Changed ? &I : nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001387}
1388
Chris Lattner82aa8882010-01-05 07:18:46 +00001389/// Optimize pointer differences into the same array into a size. Consider:
1390/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
1391/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
Chris Lattner82aa8882010-01-05 07:18:46 +00001392Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
Chris Lattner229907c2011-07-18 04:54:35 +00001393 Type *Ty) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001394 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
1395 // this.
1396 bool Swapped = false;
Craig Topperf40110f2014-04-25 05:29:35 +00001397 GEPOperator *GEP1 = nullptr, *GEP2 = nullptr;
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001398
Chris Lattner82aa8882010-01-05 07:18:46 +00001399 // For now we require one side to be the base pointer "A" or a constant
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001400 // GEP derived from it.
1401 if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001402 // (gep X, ...) - X
1403 if (LHSGEP->getOperand(0) == RHS) {
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001404 GEP1 = LHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001405 Swapped = false;
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001406 } else if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1407 // (gep X, ...) - (gep X, ...)
1408 if (LHSGEP->getOperand(0)->stripPointerCasts() ==
1409 RHSGEP->getOperand(0)->stripPointerCasts()) {
1410 GEP2 = RHSGEP;
1411 GEP1 = LHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001412 Swapped = false;
1413 }
1414 }
1415 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001416
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001417 if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
Chris Lattner82aa8882010-01-05 07:18:46 +00001418 // X - (gep X, ...)
1419 if (RHSGEP->getOperand(0) == LHS) {
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001420 GEP1 = RHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001421 Swapped = true;
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001422 } else if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1423 // (gep X, ...) - (gep X, ...)
1424 if (RHSGEP->getOperand(0)->stripPointerCasts() ==
1425 LHSGEP->getOperand(0)->stripPointerCasts()) {
1426 GEP2 = LHSGEP;
1427 GEP1 = RHSGEP;
Chris Lattner82aa8882010-01-05 07:18:46 +00001428 Swapped = true;
1429 }
1430 }
1431 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001432
Hiroshi Yamauchi60855212017-07-27 18:27:11 +00001433 if (!GEP1)
1434 // No GEP found.
Craig Topperf40110f2014-04-25 05:29:35 +00001435 return nullptr;
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001436
Hiroshi Yamauchi60855212017-07-27 18:27:11 +00001437 if (GEP2) {
1438 // (gep X, ...) - (gep X, ...)
1439 //
1440 // Avoid duplicating the arithmetic if there are more than one non-constant
1441 // indices between the two GEPs and either GEP has a non-constant index and
1442 // multiple users. If zero non-constant index, the result is a constant and
1443 // there is no duplication. If one non-constant index, the result is an add
1444 // or sub with a constant, which is no larger than the original code, and
1445 // there's no duplicated arithmetic, even if either GEP has multiple
1446 // users. If more than one non-constant indices combined, as long as the GEP
1447 // with at least one non-constant index doesn't have multiple users, there
1448 // is no duplication.
1449 unsigned NumNonConstantIndices1 = GEP1->countNonConstantIndices();
1450 unsigned NumNonConstantIndices2 = GEP2->countNonConstantIndices();
1451 if (NumNonConstantIndices1 + NumNonConstantIndices2 > 1 &&
1452 ((NumNonConstantIndices1 > 0 && !GEP1->hasOneUse()) ||
1453 (NumNonConstantIndices2 > 0 && !GEP2->hasOneUse()))) {
1454 return nullptr;
1455 }
1456 }
1457
Chris Lattner82aa8882010-01-05 07:18:46 +00001458 // Emit the offset of the GEP and an intptr_t.
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001459 Value *Result = EmitGEPOffset(GEP1);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001460
Chris Lattner82aa8882010-01-05 07:18:46 +00001461 // If we had a constant expression GEP on the other side offsetting the
1462 // pointer, subtract it from the offset we have.
Benjamin Kramer7746eb62012-02-20 14:34:57 +00001463 if (GEP2) {
1464 Value *Offset = EmitGEPOffset(GEP2);
Craig Topperbb4069e2017-07-07 23:16:26 +00001465 Result = Builder.CreateSub(Result, Offset);
Chris Lattner82aa8882010-01-05 07:18:46 +00001466 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001467
1468 // If we have p - gep(p, ...) then we have to negate the result.
1469 if (Swapped)
Craig Topperbb4069e2017-07-07 23:16:26 +00001470 Result = Builder.CreateNeg(Result, "diff.neg");
Chris Lattner82aa8882010-01-05 07:18:46 +00001471
Craig Topperbb4069e2017-07-07 23:16:26 +00001472 return Builder.CreateIntCast(Result, Ty, true);
Chris Lattner82aa8882010-01-05 07:18:46 +00001473}
1474
Chris Lattner82aa8882010-01-05 07:18:46 +00001475Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1476 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1477
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001478 if (Value *V = SimplifyVectorOp(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001479 return replaceInstUsesWith(I, V);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001480
Craig Toppera4205622017-06-09 03:21:29 +00001481 if (Value *V =
1482 SimplifySubInst(Op0, Op1, I.hasNoSignedWrap(), I.hasNoUnsignedWrap(),
1483 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001484 return replaceInstUsesWith(I, V);
Chris Lattner82aa8882010-01-05 07:18:46 +00001485
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001486 // (A*B)-(A*C) -> A*(B-C) etc
1487 if (Value *V = SimplifyUsingDistributiveLaws(I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001488 return replaceInstUsesWith(I, V);
Duncan Sandsfbb9ac32010-12-22 13:36:08 +00001489
David Majnemera92687d2014-07-31 04:49:29 +00001490 // If this is a 'B = x-(-A)', change to B = x+A.
Chris Lattner82aa8882010-01-05 07:18:46 +00001491 if (Value *V = dyn_castNegVal(Op1)) {
1492 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
David Majnemera92687d2014-07-31 04:49:29 +00001493
1494 if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
1495 assert(BO->getOpcode() == Instruction::Sub &&
1496 "Expected a subtraction operator!");
1497 if (BO->hasNoSignedWrap() && I.hasNoSignedWrap())
1498 Res->setHasNoSignedWrap(true);
David Majnemer0e6c9862014-08-22 16:41:23 +00001499 } else {
1500 if (cast<Constant>(Op1)->isNotMinSignedValue() && I.hasNoSignedWrap())
1501 Res->setHasNoSignedWrap(true);
David Majnemera92687d2014-07-31 04:49:29 +00001502 }
1503
Chris Lattner82aa8882010-01-05 07:18:46 +00001504 return Res;
1505 }
1506
Craig Topperfde47232017-07-09 07:04:03 +00001507 if (I.getType()->isIntOrIntVectorTy(1))
Chris Lattner82aa8882010-01-05 07:18:46 +00001508 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001509
1510 // Replace (-1 - A) with (~A).
1511 if (match(Op0, m_AllOnes()))
1512 return BinaryOperator::CreateNot(Op1);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001513
Sanjay Patel1a8d5c32018-03-03 17:53:25 +00001514 // (~X) - (~Y) --> Y - X
1515 Value *X, *Y;
1516 if (match(Op0, m_Not(m_Value(X))) && match(Op1, m_Not(m_Value(Y))))
1517 return BinaryOperator::CreateSub(Y, X);
1518
Benjamin Kramer72196f32014-01-19 15:24:22 +00001519 if (Constant *C = dyn_cast<Constant>(Op0)) {
Sanjay Patelb6404a82017-12-06 21:22:57 +00001520 Value *X;
1521 // C - zext(bool) -> bool ? C - 1 : C
1522 if (match(Op1, m_ZExt(m_Value(X))) &&
1523 X->getType()->getScalarSizeInBits() == 1)
1524 return SelectInst::Create(X, SubOne(C), C);
1525
Chris Lattner82aa8882010-01-05 07:18:46 +00001526 // C - ~X == X + (1+C)
Chris Lattner82aa8882010-01-05 07:18:46 +00001527 if (match(Op1, m_Not(m_Value(X))))
1528 return BinaryOperator::CreateAdd(X, AddOne(C));
1529
Benjamin Kramer72196f32014-01-19 15:24:22 +00001530 // Try to fold constant sub into select arguments.
1531 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1532 if (Instruction *R = FoldOpIntoSelect(I, SI))
1533 return R;
1534
Craig Topperfb71b7d2017-04-14 19:20:12 +00001535 // Try to fold constant sub into PHI values.
1536 if (PHINode *PN = dyn_cast<PHINode>(Op1))
1537 if (Instruction *R = foldOpIntoPhi(I, PN))
1538 return R;
1539
Benjamin Kramer72196f32014-01-19 15:24:22 +00001540 // C-(X+C2) --> (C-C2)-X
1541 Constant *C2;
1542 if (match(Op1, m_Add(m_Value(X), m_Constant(C2))))
1543 return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
1544
Benjamin Kramer72196f32014-01-19 15:24:22 +00001545 // Fold (sub 0, (zext bool to B)) --> (sext bool to B)
1546 if (C->isNullValue() && match(Op1, m_ZExt(m_Value(X))))
Craig Topperfde47232017-07-09 07:04:03 +00001547 if (X->getType()->isIntOrIntVectorTy(1))
Benjamin Kramer72196f32014-01-19 15:24:22 +00001548 return CastInst::CreateSExtOrBitCast(X, Op1->getType());
1549
1550 // Fold (sub 0, (sext bool to B)) --> (zext bool to B)
1551 if (C->isNullValue() && match(Op1, m_SExt(m_Value(X))))
Craig Topperfde47232017-07-09 07:04:03 +00001552 if (X->getType()->isIntOrIntVectorTy(1))
Benjamin Kramer72196f32014-01-19 15:24:22 +00001553 return CastInst::CreateZExtOrBitCast(X, Op1->getType());
1554 }
1555
Sanjay Patel6d6eca52016-10-14 16:31:54 +00001556 const APInt *Op0C;
1557 if (match(Op0, m_APInt(Op0C))) {
1558 unsigned BitWidth = I.getType()->getScalarSizeInBits();
1559
Chris Lattner82aa8882010-01-05 07:18:46 +00001560 // -(X >>u 31) -> (X >>s 31)
1561 // -(X >>s 31) -> (X >>u 31)
Craig Topper73ba1c82017-06-07 07:40:37 +00001562 if (Op0C->isNullValue()) {
David Majnemer72a643d2014-11-03 05:53:55 +00001563 Value *X;
Sanjay Patel6d6eca52016-10-14 16:31:54 +00001564 const APInt *ShAmt;
1565 if (match(Op1, m_LShr(m_Value(X), m_APInt(ShAmt))) &&
1566 *ShAmt == BitWidth - 1) {
1567 Value *ShAmtOp = cast<Instruction>(Op1)->getOperand(1);
1568 return BinaryOperator::CreateAShr(X, ShAmtOp);
1569 }
1570 if (match(Op1, m_AShr(m_Value(X), m_APInt(ShAmt))) &&
1571 *ShAmt == BitWidth - 1) {
1572 Value *ShAmtOp = cast<Instruction>(Op1)->getOperand(1);
1573 return BinaryOperator::CreateLShr(X, ShAmtOp);
1574 }
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.
Craig Topperb4da6842017-04-06 21:06:03 +00001579 if (Op0C->isMask()) {
Craig Topper8205a1a2017-05-24 16:53:07 +00001580 KnownBits RHSKnown = computeKnownBits(Op1, 0, &I);
Craig Topperb45eabc2017-04-26 16:39:58 +00001581 if ((*Op0C | RHSKnown.Zero).isAllOnesValue())
Sanjay Patel6d6eca52016-10-14 16:31:54 +00001582 return BinaryOperator::CreateXor(Op1, Op0);
Matthias Braunec683342015-04-30 22:04:26 +00001583 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001584 }
1585
David Majnemer72a643d2014-11-03 05:53:55 +00001586 {
Suyog Sardacba4b1d2014-10-08 08:37:49 +00001587 Value *Y;
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001588 // X-(X+Y) == -Y X-(Y+X) == -Y
Craig Topper98851ad2017-04-10 16:59:40 +00001589 if (match(Op1, m_c_Add(m_Specific(Op0), m_Value(Y))))
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001590 return BinaryOperator::CreateNeg(Y);
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001591
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001592 // (X-Y)-X == -Y
1593 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
1594 return BinaryOperator::CreateNeg(Y);
1595 }
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001596
Hiroshi Yamauchi0445e312017-07-26 21:54:43 +00001597 // (sub (or A, B), (xor A, B)) --> (and A, B)
David Majnemer312c3e52014-10-19 08:32:32 +00001598 {
Craig Topper0d830ff2017-04-10 18:09:25 +00001599 Value *A, *B;
David Majnemer312c3e52014-10-19 08:32:32 +00001600 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Craig Topper0d830ff2017-04-10 18:09:25 +00001601 match(Op0, m_c_Or(m_Specific(A), m_Specific(B))))
David Majnemer312c3e52014-10-19 08:32:32 +00001602 return BinaryOperator::CreateAnd(A, B);
1603 }
1604
Craig Topper0d830ff2017-04-10 18:09:25 +00001605 {
1606 Value *Y;
David Majnemer72a643d2014-11-03 05:53:55 +00001607 // ((X | Y) - X) --> (~X & Y)
Craig Topper0d830ff2017-04-10 18:09:25 +00001608 if (match(Op0, m_OneUse(m_c_Or(m_Value(Y), m_Specific(Op1)))))
David Majnemer72a643d2014-11-03 05:53:55 +00001609 return BinaryOperator::CreateAnd(
Craig Topperbb4069e2017-07-07 23:16:26 +00001610 Y, Builder.CreateNot(Op1, Op1->getName() + ".not"));
David Majnemer72a643d2014-11-03 05:53:55 +00001611 }
1612
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001613 if (Op1->hasOneUse()) {
Craig Topperf40110f2014-04-25 05:29:35 +00001614 Value *X = nullptr, *Y = nullptr, *Z = nullptr;
1615 Constant *C = nullptr;
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001616
1617 // (X - (Y - Z)) --> (X + (Z - Y)).
1618 if (match(Op1, m_Sub(m_Value(Y), m_Value(Z))))
1619 return BinaryOperator::CreateAdd(Op0,
Craig Topperbb4069e2017-07-07 23:16:26 +00001620 Builder.CreateSub(Z, Y, Op1->getName()));
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001621
1622 // (X - (X & Y)) --> (X & ~Y)
Craig Topper0d830ff2017-04-10 18:09:25 +00001623 if (match(Op1, m_c_And(m_Value(Y), m_Specific(Op0))))
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001624 return BinaryOperator::CreateAnd(Op0,
Craig Topperbb4069e2017-07-07 23:16:26 +00001625 Builder.CreateNot(Y, Y->getName() + ".not"));
Michael Ilseman9fc0f252012-12-12 20:57:53 +00001626
David Majnemerbdeef602014-07-02 06:07:09 +00001627 // 0 - (X sdiv C) -> (X sdiv -C) provided the negation doesn't overflow.
1628 if (match(Op1, m_SDiv(m_Value(X), m_Constant(C))) && match(Op0, m_Zero()) &&
David Majnemer0e6c9862014-08-22 16:41:23 +00001629 C->isNotMinSignedValue() && !C->isOneValue())
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001630 return BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(C));
1631
1632 // 0 - (X << Y) -> (-X << Y) when X is freely negatable.
1633 if (match(Op1, m_Shl(m_Value(X), m_Value(Y))) && match(Op0, m_Zero()))
1634 if (Value *XNeg = dyn_castNegVal(X))
1635 return BinaryOperator::CreateShl(XNeg, Y);
1636
Sanjay Patelc6c59652016-10-14 15:24:31 +00001637 // Subtracting -1/0 is the same as adding 1/0:
1638 // sub [nsw] Op0, sext(bool Y) -> add [nsw] Op0, zext(bool Y)
1639 // 'nuw' is dropped in favor of the canonical form.
1640 if (match(Op1, m_SExt(m_Value(Y))) &&
1641 Y->getType()->getScalarSizeInBits() == 1) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001642 Value *Zext = Builder.CreateZExt(Y, I.getType());
Sanjay Patelc6c59652016-10-14 15:24:31 +00001643 BinaryOperator *Add = BinaryOperator::CreateAdd(Op0, Zext);
1644 Add->setHasNoSignedWrap(I.hasNoSignedWrap());
1645 return Add;
1646 }
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;
Craig Topper0d830ff2017-04-10 18:09:25 +00001651 Constant *CI;
1652 if (match(Op1, m_c_Mul(m_Value(A), m_Neg(m_Value(B)))))
Craig Topperbb4069e2017-07-07 23:16:26 +00001653 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
Craig Topper0d830ff2017-04-10 18:09:25 +00001656 // No need to handle commuted multiply because multiply handling will
1657 // ensure constant will be move to the right hand side.
1658 if (match(Op1, m_Mul(m_Value(A), m_Constant(CI)))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001659 Value *NewMul = Builder.CreateMul(A, ConstantExpr::getNeg(CI));
Chris Lattner7d0e43f2011-02-10 05:14:58 +00001660 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;
Craig Topper2b1fc322017-05-22 06:25:31 +00001679 if (!I.hasNoSignedWrap() && willNotOverflowSignedSub(Op0, Op1, I)) {
David Majnemer57d5bc82014-08-19 23:36:30 +00001680 Changed = true;
1681 I.setHasNoSignedWrap(true);
1682 }
Craig Topper2b1fc322017-05-22 06:25:31 +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
Craig Toppera4205622017-06-09 03:21:29 +00001697 if (Value *V = SimplifyFSubInst(Op0, Op1, I.getFastMathFlags(),
1698 SQ.getWithInstruction(&I)))
Sanjay Patel4b198802016-02-01 22:23:39 +00001699 return replaceInstUsesWith(I, V);
Michael Ilsemand5787be2012-12-12 00:28:32 +00001700
Sanjay Patel4a9116e2018-02-23 17:07:29 +00001701 // Subtraction from -0.0 is the canonical form of fneg.
Sanjay Patele68f7152014-12-31 22:14:05 +00001702 // fsub nsz 0, X ==> fsub nsz -0.0, X
Sanjay Patel93e64dd2018-03-25 21:16:33 +00001703 if (I.getFastMathFlags().noSignedZeros() && match(Op0, m_PosZeroFP()))
Sanjay Patel4a9116e2018-02-23 17:07:29 +00001704 return BinaryOperator::CreateFNegFMF(Op1, &I);
Sanjay Patele68f7152014-12-31 22:14:05 +00001705
Stephen Lina9b57f62013-07-20 07:13:13 +00001706 if (isa<Constant>(Op0))
1707 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1708 if (Instruction *NV = FoldOpIntoSelect(I, SI))
1709 return NV;
1710
Owen Andersone37c2e42013-07-26 21:40:29 +00001711 // If this is a 'B = x-(-A)', change to B = x+A, potentially looking
1712 // through FP extensions/truncations along the way.
Sanjay Patel4a9116e2018-02-23 17:07:29 +00001713 if (Value *V = dyn_castFNegVal(Op1))
1714 return BinaryOperator::CreateFAddFMF(Op0, V, &I);
1715
Owen Andersone37c2e42013-07-26 21:40:29 +00001716 if (FPTruncInst *FPTI = dyn_cast<FPTruncInst>(Op1)) {
1717 if (Value *V = dyn_castFNegVal(FPTI->getOperand(0))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001718 Value *NewTrunc = Builder.CreateFPTrunc(V, I.getType());
Sanjay Patel4a9116e2018-02-23 17:07:29 +00001719 return BinaryOperator::CreateFAddFMF(Op0, NewTrunc, &I);
Owen Andersone37c2e42013-07-26 21:40:29 +00001720 }
1721 } else if (FPExtInst *FPEI = dyn_cast<FPExtInst>(Op1)) {
1722 if (Value *V = dyn_castFNegVal(FPEI->getOperand(0))) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001723 Value *NewExt = Builder.CreateFPExt(V, I.getType());
Sanjay Patel4a9116e2018-02-23 17:07:29 +00001724 return BinaryOperator::CreateFAddFMF(Op0, NewExt, &I);
Owen Andersone37c2e42013-07-26 21:40:29 +00001725 }
1726 }
Chris Lattner82aa8882010-01-05 07:18:46 +00001727
Quentin Colombetaa103b32017-09-20 17:32:16 +00001728 // Handle specials cases for FSub with selects feeding the operation
1729 if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1))
1730 return replaceInstUsesWith(I, V);
1731
Sanjay Patel629c4112017-11-06 16:27:15 +00001732 if (I.isFast()) {
Shuxin Yang37a1efe2012-12-18 23:10:12 +00001733 if (Value *V = FAddCombine(Builder).simplify(&I))
Sanjay Patel4b198802016-02-01 22:23:39 +00001734 return replaceInstUsesWith(I, V);
Shuxin Yang37a1efe2012-12-18 23:10:12 +00001735 }
1736
Craig Topperf40110f2014-04-25 05:29:35 +00001737 return nullptr;
Chris Lattner82aa8882010-01-05 07:18:46 +00001738}