1f4a2713aSLionel Sambuc //===- InstCombineAddSub.cpp ----------------------------------------------===//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc //                     The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc //
10f4a2713aSLionel Sambuc // This file implements the visit functions for add, fadd, sub, and fsub.
11f4a2713aSLionel Sambuc //
12f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
13f4a2713aSLionel Sambuc 
14f4a2713aSLionel Sambuc #include "InstCombine.h"
15f4a2713aSLionel Sambuc #include "llvm/ADT/STLExtras.h"
16f4a2713aSLionel Sambuc #include "llvm/Analysis/InstructionSimplify.h"
17f4a2713aSLionel Sambuc #include "llvm/IR/DataLayout.h"
18*0a6a1f1dSLionel Sambuc #include "llvm/IR/GetElementPtrTypeIterator.h"
19*0a6a1f1dSLionel Sambuc #include "llvm/IR/PatternMatch.h"
20f4a2713aSLionel Sambuc using namespace llvm;
21f4a2713aSLionel Sambuc using namespace PatternMatch;
22f4a2713aSLionel Sambuc 
23*0a6a1f1dSLionel Sambuc #define DEBUG_TYPE "instcombine"
24*0a6a1f1dSLionel Sambuc 
25f4a2713aSLionel Sambuc namespace {
26f4a2713aSLionel Sambuc 
27f4a2713aSLionel Sambuc   /// Class representing coefficient of floating-point addend.
28f4a2713aSLionel Sambuc   /// This class needs to be highly efficient, which is especially true for
29f4a2713aSLionel Sambuc   /// the constructor. As of I write this comment, the cost of the default
30f4a2713aSLionel Sambuc   /// constructor is merely 4-byte-store-zero (Assuming compiler is able to
31f4a2713aSLionel Sambuc   /// perform write-merging).
32f4a2713aSLionel Sambuc   ///
33f4a2713aSLionel Sambuc   class FAddendCoef {
34f4a2713aSLionel Sambuc   public:
35*0a6a1f1dSLionel Sambuc     // The constructor has to initialize a APFloat, which is unnecessary for
36f4a2713aSLionel Sambuc     // most addends which have coefficient either 1 or -1. So, the constructor
37f4a2713aSLionel Sambuc     // is expensive. In order to avoid the cost of the constructor, we should
38f4a2713aSLionel Sambuc     // reuse some instances whenever possible. The pre-created instances
39f4a2713aSLionel Sambuc     // FAddCombine::Add[0-5] embodies this idea.
40f4a2713aSLionel Sambuc     //
FAddendCoef()41f4a2713aSLionel Sambuc     FAddendCoef() : IsFp(false), BufHasFpVal(false), IntVal(0) {}
42f4a2713aSLionel Sambuc     ~FAddendCoef();
43f4a2713aSLionel Sambuc 
set(short C)44f4a2713aSLionel Sambuc     void set(short C) {
45f4a2713aSLionel Sambuc       assert(!insaneIntVal(C) && "Insane coefficient");
46f4a2713aSLionel Sambuc       IsFp = false; IntVal = C;
47f4a2713aSLionel Sambuc     }
48f4a2713aSLionel Sambuc 
49f4a2713aSLionel Sambuc     void set(const APFloat& C);
50f4a2713aSLionel Sambuc 
51f4a2713aSLionel Sambuc     void negate();
52f4a2713aSLionel Sambuc 
isZero() const53f4a2713aSLionel Sambuc     bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); }
54f4a2713aSLionel Sambuc     Value *getValue(Type *) const;
55f4a2713aSLionel Sambuc 
56f4a2713aSLionel Sambuc     // If possible, don't define operator+/operator- etc because these
57f4a2713aSLionel Sambuc     // operators inevitably call FAddendCoef's constructor which is not cheap.
58f4a2713aSLionel Sambuc     void operator=(const FAddendCoef &A);
59f4a2713aSLionel Sambuc     void operator+=(const FAddendCoef &A);
60f4a2713aSLionel Sambuc     void operator-=(const FAddendCoef &A);
61f4a2713aSLionel Sambuc     void operator*=(const FAddendCoef &S);
62f4a2713aSLionel Sambuc 
isOne() const63f4a2713aSLionel Sambuc     bool isOne() const { return isInt() && IntVal == 1; }
isTwo() const64f4a2713aSLionel Sambuc     bool isTwo() const { return isInt() && IntVal == 2; }
isMinusOne() const65f4a2713aSLionel Sambuc     bool isMinusOne() const { return isInt() && IntVal == -1; }
isMinusTwo() const66f4a2713aSLionel Sambuc     bool isMinusTwo() const { return isInt() && IntVal == -2; }
67f4a2713aSLionel Sambuc 
68f4a2713aSLionel Sambuc   private:
insaneIntVal(int V)69f4a2713aSLionel Sambuc     bool insaneIntVal(int V) { return V > 4 || V < -4; }
getFpValPtr(void)70f4a2713aSLionel Sambuc     APFloat *getFpValPtr(void)
71f4a2713aSLionel Sambuc       { return reinterpret_cast<APFloat*>(&FpValBuf.buffer[0]); }
getFpValPtr(void) const72f4a2713aSLionel Sambuc     const APFloat *getFpValPtr(void) const
73f4a2713aSLionel Sambuc       { return reinterpret_cast<const APFloat*>(&FpValBuf.buffer[0]); }
74f4a2713aSLionel Sambuc 
getFpVal(void) const75f4a2713aSLionel Sambuc     const APFloat &getFpVal(void) const {
76f4a2713aSLionel Sambuc       assert(IsFp && BufHasFpVal && "Incorret state");
77f4a2713aSLionel Sambuc       return *getFpValPtr();
78f4a2713aSLionel Sambuc     }
79f4a2713aSLionel Sambuc 
getFpVal(void)80f4a2713aSLionel Sambuc     APFloat &getFpVal(void) {
81f4a2713aSLionel Sambuc       assert(IsFp && BufHasFpVal && "Incorret state");
82f4a2713aSLionel Sambuc       return *getFpValPtr();
83f4a2713aSLionel Sambuc     }
84f4a2713aSLionel Sambuc 
isInt() const85f4a2713aSLionel Sambuc     bool isInt() const { return !IsFp; }
86f4a2713aSLionel Sambuc 
87f4a2713aSLionel Sambuc     // If the coefficient is represented by an integer, promote it to a
88f4a2713aSLionel Sambuc     // floating point.
89f4a2713aSLionel Sambuc     void convertToFpType(const fltSemantics &Sem);
90f4a2713aSLionel Sambuc 
91f4a2713aSLionel Sambuc     // Construct an APFloat from a signed integer.
92f4a2713aSLionel Sambuc     // TODO: We should get rid of this function when APFloat can be constructed
93f4a2713aSLionel Sambuc     //       from an *SIGNED* integer.
94f4a2713aSLionel Sambuc     APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val);
95f4a2713aSLionel Sambuc   private:
96f4a2713aSLionel Sambuc 
97f4a2713aSLionel Sambuc     bool IsFp;
98f4a2713aSLionel Sambuc 
99f4a2713aSLionel Sambuc     // True iff FpValBuf contains an instance of APFloat.
100f4a2713aSLionel Sambuc     bool BufHasFpVal;
101f4a2713aSLionel Sambuc 
102f4a2713aSLionel Sambuc     // The integer coefficient of an individual addend is either 1 or -1,
103f4a2713aSLionel Sambuc     // and we try to simplify at most 4 addends from neighboring at most
104f4a2713aSLionel Sambuc     // two instructions. So the range of <IntVal> falls in [-4, 4]. APInt
105f4a2713aSLionel Sambuc     // is overkill of this end.
106f4a2713aSLionel Sambuc     short IntVal;
107f4a2713aSLionel Sambuc 
108f4a2713aSLionel Sambuc     AlignedCharArrayUnion<APFloat> FpValBuf;
109f4a2713aSLionel Sambuc   };
110f4a2713aSLionel Sambuc 
111f4a2713aSLionel Sambuc   /// FAddend is used to represent floating-point addend. An addend is
112f4a2713aSLionel Sambuc   /// represented as <C, V>, where the V is a symbolic value, and C is a
113f4a2713aSLionel Sambuc   /// constant coefficient. A constant addend is represented as <C, 0>.
114f4a2713aSLionel Sambuc   ///
115f4a2713aSLionel Sambuc   class FAddend {
116f4a2713aSLionel Sambuc   public:
FAddend()117*0a6a1f1dSLionel Sambuc     FAddend() { Val = nullptr; }
118f4a2713aSLionel Sambuc 
getSymVal(void) const119f4a2713aSLionel Sambuc     Value *getSymVal (void) const { return Val; }
getCoef(void) const120f4a2713aSLionel Sambuc     const FAddendCoef &getCoef(void) const { return Coeff; }
121f4a2713aSLionel Sambuc 
isConstant() const122*0a6a1f1dSLionel Sambuc     bool isConstant() const { return Val == nullptr; }
isZero() const123f4a2713aSLionel Sambuc     bool isZero() const { return Coeff.isZero(); }
124f4a2713aSLionel Sambuc 
set(short Coefficient,Value * V)125f4a2713aSLionel Sambuc     void set(short Coefficient, Value *V) { Coeff.set(Coefficient), Val = V; }
set(const APFloat & Coefficient,Value * V)126f4a2713aSLionel Sambuc     void set(const APFloat& Coefficient, Value *V)
127f4a2713aSLionel Sambuc       { Coeff.set(Coefficient); Val = V; }
set(const ConstantFP * Coefficient,Value * V)128f4a2713aSLionel Sambuc     void set(const ConstantFP* Coefficient, Value *V)
129f4a2713aSLionel Sambuc       { Coeff.set(Coefficient->getValueAPF()); Val = V; }
130f4a2713aSLionel Sambuc 
negate()131f4a2713aSLionel Sambuc     void negate() { Coeff.negate(); }
132f4a2713aSLionel Sambuc 
133f4a2713aSLionel Sambuc     /// Drill down the U-D chain one step to find the definition of V, and
134f4a2713aSLionel Sambuc     /// try to break the definition into one or two addends.
135f4a2713aSLionel Sambuc     static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
136f4a2713aSLionel Sambuc 
137f4a2713aSLionel Sambuc     /// Similar to FAddend::drillDownOneStep() except that the value being
138f4a2713aSLionel Sambuc     /// splitted is the addend itself.
139f4a2713aSLionel Sambuc     unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
140f4a2713aSLionel Sambuc 
operator +=(const FAddend & T)141f4a2713aSLionel Sambuc     void operator+=(const FAddend &T) {
142f4a2713aSLionel Sambuc       assert((Val == T.Val) && "Symbolic-values disagree");
143f4a2713aSLionel Sambuc       Coeff += T.Coeff;
144f4a2713aSLionel Sambuc     }
145f4a2713aSLionel Sambuc 
146f4a2713aSLionel Sambuc   private:
Scale(const FAddendCoef & ScaleAmt)147f4a2713aSLionel Sambuc     void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
148f4a2713aSLionel Sambuc 
149f4a2713aSLionel Sambuc     // This addend has the value of "Coeff * Val".
150f4a2713aSLionel Sambuc     Value *Val;
151f4a2713aSLionel Sambuc     FAddendCoef Coeff;
152f4a2713aSLionel Sambuc   };
153f4a2713aSLionel Sambuc 
154f4a2713aSLionel Sambuc   /// FAddCombine is the class for optimizing an unsafe fadd/fsub along
155f4a2713aSLionel Sambuc   /// with its neighboring at most two instructions.
156f4a2713aSLionel Sambuc   ///
157f4a2713aSLionel Sambuc   class FAddCombine {
158f4a2713aSLionel Sambuc   public:
FAddCombine(InstCombiner::BuilderTy * B)159*0a6a1f1dSLionel Sambuc     FAddCombine(InstCombiner::BuilderTy *B) : Builder(B), Instr(nullptr) {}
160f4a2713aSLionel Sambuc     Value *simplify(Instruction *FAdd);
161f4a2713aSLionel Sambuc 
162f4a2713aSLionel Sambuc   private:
163f4a2713aSLionel Sambuc     typedef SmallVector<const FAddend*, 4> AddendVect;
164f4a2713aSLionel Sambuc 
165f4a2713aSLionel Sambuc     Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
166f4a2713aSLionel Sambuc 
167f4a2713aSLionel Sambuc     Value *performFactorization(Instruction *I);
168f4a2713aSLionel Sambuc 
169f4a2713aSLionel Sambuc     /// Convert given addend to a Value
170f4a2713aSLionel Sambuc     Value *createAddendVal(const FAddend &A, bool& NeedNeg);
171f4a2713aSLionel Sambuc 
172f4a2713aSLionel Sambuc     /// Return the number of instructions needed to emit the N-ary addition.
173f4a2713aSLionel Sambuc     unsigned calcInstrNumber(const AddendVect& Vect);
174f4a2713aSLionel Sambuc     Value *createFSub(Value *Opnd0, Value *Opnd1);
175f4a2713aSLionel Sambuc     Value *createFAdd(Value *Opnd0, Value *Opnd1);
176f4a2713aSLionel Sambuc     Value *createFMul(Value *Opnd0, Value *Opnd1);
177f4a2713aSLionel Sambuc     Value *createFDiv(Value *Opnd0, Value *Opnd1);
178f4a2713aSLionel Sambuc     Value *createFNeg(Value *V);
179f4a2713aSLionel Sambuc     Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
180*0a6a1f1dSLionel Sambuc     void createInstPostProc(Instruction *NewInst, bool NoNumber = false);
181f4a2713aSLionel Sambuc 
182f4a2713aSLionel Sambuc     InstCombiner::BuilderTy *Builder;
183f4a2713aSLionel Sambuc     Instruction *Instr;
184f4a2713aSLionel Sambuc 
185f4a2713aSLionel Sambuc   private:
186f4a2713aSLionel Sambuc      // Debugging stuff are clustered here.
187f4a2713aSLionel Sambuc     #ifndef NDEBUG
188f4a2713aSLionel Sambuc       unsigned CreateInstrNum;
initCreateInstNum()189f4a2713aSLionel Sambuc       void initCreateInstNum() { CreateInstrNum = 0; }
incCreateInstNum()190f4a2713aSLionel Sambuc       void incCreateInstNum() { CreateInstrNum++; }
191f4a2713aSLionel Sambuc     #else
192f4a2713aSLionel Sambuc       void initCreateInstNum() {}
193f4a2713aSLionel Sambuc       void incCreateInstNum() {}
194f4a2713aSLionel Sambuc     #endif
195f4a2713aSLionel Sambuc   };
196f4a2713aSLionel Sambuc }
197f4a2713aSLionel Sambuc 
198f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
199f4a2713aSLionel Sambuc //
200f4a2713aSLionel Sambuc // Implementation of
201f4a2713aSLionel Sambuc //    {FAddendCoef, FAddend, FAddition, FAddCombine}.
202f4a2713aSLionel Sambuc //
203f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
~FAddendCoef()204f4a2713aSLionel Sambuc FAddendCoef::~FAddendCoef() {
205f4a2713aSLionel Sambuc   if (BufHasFpVal)
206f4a2713aSLionel Sambuc     getFpValPtr()->~APFloat();
207f4a2713aSLionel Sambuc }
208f4a2713aSLionel Sambuc 
set(const APFloat & C)209f4a2713aSLionel Sambuc void FAddendCoef::set(const APFloat& C) {
210f4a2713aSLionel Sambuc   APFloat *P = getFpValPtr();
211f4a2713aSLionel Sambuc 
212f4a2713aSLionel Sambuc   if (isInt()) {
213f4a2713aSLionel Sambuc     // As the buffer is meanless byte stream, we cannot call
214f4a2713aSLionel Sambuc     // APFloat::operator=().
215f4a2713aSLionel Sambuc     new(P) APFloat(C);
216f4a2713aSLionel Sambuc   } else
217f4a2713aSLionel Sambuc     *P = C;
218f4a2713aSLionel Sambuc 
219f4a2713aSLionel Sambuc   IsFp = BufHasFpVal = true;
220f4a2713aSLionel Sambuc }
221f4a2713aSLionel Sambuc 
convertToFpType(const fltSemantics & Sem)222f4a2713aSLionel Sambuc void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
223f4a2713aSLionel Sambuc   if (!isInt())
224f4a2713aSLionel Sambuc     return;
225f4a2713aSLionel Sambuc 
226f4a2713aSLionel Sambuc   APFloat *P = getFpValPtr();
227f4a2713aSLionel Sambuc   if (IntVal > 0)
228f4a2713aSLionel Sambuc     new(P) APFloat(Sem, IntVal);
229f4a2713aSLionel Sambuc   else {
230f4a2713aSLionel Sambuc     new(P) APFloat(Sem, 0 - IntVal);
231f4a2713aSLionel Sambuc     P->changeSign();
232f4a2713aSLionel Sambuc   }
233f4a2713aSLionel Sambuc   IsFp = BufHasFpVal = true;
234f4a2713aSLionel Sambuc }
235f4a2713aSLionel Sambuc 
createAPFloatFromInt(const fltSemantics & Sem,int Val)236f4a2713aSLionel Sambuc APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
237f4a2713aSLionel Sambuc   if (Val >= 0)
238f4a2713aSLionel Sambuc     return APFloat(Sem, Val);
239f4a2713aSLionel Sambuc 
240f4a2713aSLionel Sambuc   APFloat T(Sem, 0 - Val);
241f4a2713aSLionel Sambuc   T.changeSign();
242f4a2713aSLionel Sambuc 
243f4a2713aSLionel Sambuc   return T;
244f4a2713aSLionel Sambuc }
245f4a2713aSLionel Sambuc 
operator =(const FAddendCoef & That)246f4a2713aSLionel Sambuc void FAddendCoef::operator=(const FAddendCoef &That) {
247f4a2713aSLionel Sambuc   if (That.isInt())
248f4a2713aSLionel Sambuc     set(That.IntVal);
249f4a2713aSLionel Sambuc   else
250f4a2713aSLionel Sambuc     set(That.getFpVal());
251f4a2713aSLionel Sambuc }
252f4a2713aSLionel Sambuc 
operator +=(const FAddendCoef & That)253f4a2713aSLionel Sambuc void FAddendCoef::operator+=(const FAddendCoef &That) {
254f4a2713aSLionel Sambuc   enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
255f4a2713aSLionel Sambuc   if (isInt() == That.isInt()) {
256f4a2713aSLionel Sambuc     if (isInt())
257f4a2713aSLionel Sambuc       IntVal += That.IntVal;
258f4a2713aSLionel Sambuc     else
259f4a2713aSLionel Sambuc       getFpVal().add(That.getFpVal(), RndMode);
260f4a2713aSLionel Sambuc     return;
261f4a2713aSLionel Sambuc   }
262f4a2713aSLionel Sambuc 
263f4a2713aSLionel Sambuc   if (isInt()) {
264f4a2713aSLionel Sambuc     const APFloat &T = That.getFpVal();
265f4a2713aSLionel Sambuc     convertToFpType(T.getSemantics());
266f4a2713aSLionel Sambuc     getFpVal().add(T, RndMode);
267f4a2713aSLionel Sambuc     return;
268f4a2713aSLionel Sambuc   }
269f4a2713aSLionel Sambuc 
270f4a2713aSLionel Sambuc   APFloat &T = getFpVal();
271f4a2713aSLionel Sambuc   T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
272f4a2713aSLionel Sambuc }
273f4a2713aSLionel Sambuc 
operator -=(const FAddendCoef & That)274f4a2713aSLionel Sambuc void FAddendCoef::operator-=(const FAddendCoef &That) {
275f4a2713aSLionel Sambuc   enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
276f4a2713aSLionel Sambuc   if (isInt() == That.isInt()) {
277f4a2713aSLionel Sambuc     if (isInt())
278f4a2713aSLionel Sambuc       IntVal -= That.IntVal;
279f4a2713aSLionel Sambuc     else
280f4a2713aSLionel Sambuc       getFpVal().subtract(That.getFpVal(), RndMode);
281f4a2713aSLionel Sambuc     return;
282f4a2713aSLionel Sambuc   }
283f4a2713aSLionel Sambuc 
284f4a2713aSLionel Sambuc   if (isInt()) {
285f4a2713aSLionel Sambuc     const APFloat &T = That.getFpVal();
286f4a2713aSLionel Sambuc     convertToFpType(T.getSemantics());
287f4a2713aSLionel Sambuc     getFpVal().subtract(T, RndMode);
288f4a2713aSLionel Sambuc     return;
289f4a2713aSLionel Sambuc   }
290f4a2713aSLionel Sambuc 
291f4a2713aSLionel Sambuc   APFloat &T = getFpVal();
292f4a2713aSLionel Sambuc   T.subtract(createAPFloatFromInt(T.getSemantics(), IntVal), RndMode);
293f4a2713aSLionel Sambuc }
294f4a2713aSLionel Sambuc 
operator *=(const FAddendCoef & That)295f4a2713aSLionel Sambuc void FAddendCoef::operator*=(const FAddendCoef &That) {
296f4a2713aSLionel Sambuc   if (That.isOne())
297f4a2713aSLionel Sambuc     return;
298f4a2713aSLionel Sambuc 
299f4a2713aSLionel Sambuc   if (That.isMinusOne()) {
300f4a2713aSLionel Sambuc     negate();
301f4a2713aSLionel Sambuc     return;
302f4a2713aSLionel Sambuc   }
303f4a2713aSLionel Sambuc 
304f4a2713aSLionel Sambuc   if (isInt() && That.isInt()) {
305f4a2713aSLionel Sambuc     int Res = IntVal * (int)That.IntVal;
306f4a2713aSLionel Sambuc     assert(!insaneIntVal(Res) && "Insane int value");
307f4a2713aSLionel Sambuc     IntVal = Res;
308f4a2713aSLionel Sambuc     return;
309f4a2713aSLionel Sambuc   }
310f4a2713aSLionel Sambuc 
311f4a2713aSLionel Sambuc   const fltSemantics &Semantic =
312f4a2713aSLionel Sambuc     isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
313f4a2713aSLionel Sambuc 
314f4a2713aSLionel Sambuc   if (isInt())
315f4a2713aSLionel Sambuc     convertToFpType(Semantic);
316f4a2713aSLionel Sambuc   APFloat &F0 = getFpVal();
317f4a2713aSLionel Sambuc 
318f4a2713aSLionel Sambuc   if (That.isInt())
319f4a2713aSLionel Sambuc     F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
320f4a2713aSLionel Sambuc                 APFloat::rmNearestTiesToEven);
321f4a2713aSLionel Sambuc   else
322f4a2713aSLionel Sambuc     F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven);
323f4a2713aSLionel Sambuc 
324f4a2713aSLionel Sambuc   return;
325f4a2713aSLionel Sambuc }
326f4a2713aSLionel Sambuc 
negate()327f4a2713aSLionel Sambuc void FAddendCoef::negate() {
328f4a2713aSLionel Sambuc   if (isInt())
329f4a2713aSLionel Sambuc     IntVal = 0 - IntVal;
330f4a2713aSLionel Sambuc   else
331f4a2713aSLionel Sambuc     getFpVal().changeSign();
332f4a2713aSLionel Sambuc }
333f4a2713aSLionel Sambuc 
getValue(Type * Ty) const334f4a2713aSLionel Sambuc Value *FAddendCoef::getValue(Type *Ty) const {
335f4a2713aSLionel Sambuc   return isInt() ?
336f4a2713aSLionel Sambuc     ConstantFP::get(Ty, float(IntVal)) :
337f4a2713aSLionel Sambuc     ConstantFP::get(Ty->getContext(), getFpVal());
338f4a2713aSLionel Sambuc }
339f4a2713aSLionel Sambuc 
340f4a2713aSLionel Sambuc // The definition of <Val>     Addends
341f4a2713aSLionel Sambuc // =========================================
342f4a2713aSLionel Sambuc //  A + B                     <1, A>, <1,B>
343f4a2713aSLionel Sambuc //  A - B                     <1, A>, <1,B>
344f4a2713aSLionel Sambuc //  0 - B                     <-1, B>
345f4a2713aSLionel Sambuc //  C * A,                    <C, A>
346f4a2713aSLionel Sambuc //  A + C                     <1, A> <C, NULL>
347f4a2713aSLionel Sambuc //  0 +/- 0                   <0, NULL> (corner case)
348f4a2713aSLionel Sambuc //
349f4a2713aSLionel Sambuc // Legend: A and B are not constant, C is constant
350f4a2713aSLionel Sambuc //
drillValueDownOneStep(Value * Val,FAddend & Addend0,FAddend & Addend1)351f4a2713aSLionel Sambuc unsigned FAddend::drillValueDownOneStep
352f4a2713aSLionel Sambuc   (Value *Val, FAddend &Addend0, FAddend &Addend1) {
353*0a6a1f1dSLionel Sambuc   Instruction *I = nullptr;
354*0a6a1f1dSLionel Sambuc   if (!Val || !(I = dyn_cast<Instruction>(Val)))
355f4a2713aSLionel Sambuc     return 0;
356f4a2713aSLionel Sambuc 
357f4a2713aSLionel Sambuc   unsigned Opcode = I->getOpcode();
358f4a2713aSLionel Sambuc 
359f4a2713aSLionel Sambuc   if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
360f4a2713aSLionel Sambuc     ConstantFP *C0, *C1;
361f4a2713aSLionel Sambuc     Value *Opnd0 = I->getOperand(0);
362f4a2713aSLionel Sambuc     Value *Opnd1 = I->getOperand(1);
363f4a2713aSLionel Sambuc     if ((C0 = dyn_cast<ConstantFP>(Opnd0)) && C0->isZero())
364*0a6a1f1dSLionel Sambuc       Opnd0 = nullptr;
365f4a2713aSLionel Sambuc 
366f4a2713aSLionel Sambuc     if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
367*0a6a1f1dSLionel Sambuc       Opnd1 = nullptr;
368f4a2713aSLionel Sambuc 
369f4a2713aSLionel Sambuc     if (Opnd0) {
370f4a2713aSLionel Sambuc       if (!C0)
371f4a2713aSLionel Sambuc         Addend0.set(1, Opnd0);
372f4a2713aSLionel Sambuc       else
373*0a6a1f1dSLionel Sambuc         Addend0.set(C0, nullptr);
374f4a2713aSLionel Sambuc     }
375f4a2713aSLionel Sambuc 
376f4a2713aSLionel Sambuc     if (Opnd1) {
377f4a2713aSLionel Sambuc       FAddend &Addend = Opnd0 ? Addend1 : Addend0;
378f4a2713aSLionel Sambuc       if (!C1)
379f4a2713aSLionel Sambuc         Addend.set(1, Opnd1);
380f4a2713aSLionel Sambuc       else
381*0a6a1f1dSLionel Sambuc         Addend.set(C1, nullptr);
382f4a2713aSLionel Sambuc       if (Opcode == Instruction::FSub)
383f4a2713aSLionel Sambuc         Addend.negate();
384f4a2713aSLionel Sambuc     }
385f4a2713aSLionel Sambuc 
386f4a2713aSLionel Sambuc     if (Opnd0 || Opnd1)
387f4a2713aSLionel Sambuc       return Opnd0 && Opnd1 ? 2 : 1;
388f4a2713aSLionel Sambuc 
389f4a2713aSLionel Sambuc     // Both operands are zero. Weird!
390*0a6a1f1dSLionel Sambuc     Addend0.set(APFloat(C0->getValueAPF().getSemantics()), nullptr);
391f4a2713aSLionel Sambuc     return 1;
392f4a2713aSLionel Sambuc   }
393f4a2713aSLionel Sambuc 
394f4a2713aSLionel Sambuc   if (I->getOpcode() == Instruction::FMul) {
395f4a2713aSLionel Sambuc     Value *V0 = I->getOperand(0);
396f4a2713aSLionel Sambuc     Value *V1 = I->getOperand(1);
397f4a2713aSLionel Sambuc     if (ConstantFP *C = dyn_cast<ConstantFP>(V0)) {
398f4a2713aSLionel Sambuc       Addend0.set(C, V1);
399f4a2713aSLionel Sambuc       return 1;
400f4a2713aSLionel Sambuc     }
401f4a2713aSLionel Sambuc 
402f4a2713aSLionel Sambuc     if (ConstantFP *C = dyn_cast<ConstantFP>(V1)) {
403f4a2713aSLionel Sambuc       Addend0.set(C, V0);
404f4a2713aSLionel Sambuc       return 1;
405f4a2713aSLionel Sambuc     }
406f4a2713aSLionel Sambuc   }
407f4a2713aSLionel Sambuc 
408f4a2713aSLionel Sambuc   return 0;
409f4a2713aSLionel Sambuc }
410f4a2713aSLionel Sambuc 
411f4a2713aSLionel Sambuc // Try to break *this* addend into two addends. e.g. Suppose this addend is
412f4a2713aSLionel Sambuc // <2.3, V>, and V = X + Y, by calling this function, we obtain two addends,
413f4a2713aSLionel Sambuc // i.e. <2.3, X> and <2.3, Y>.
414f4a2713aSLionel Sambuc //
drillAddendDownOneStep(FAddend & Addend0,FAddend & Addend1) const415f4a2713aSLionel Sambuc unsigned FAddend::drillAddendDownOneStep
416f4a2713aSLionel Sambuc   (FAddend &Addend0, FAddend &Addend1) const {
417f4a2713aSLionel Sambuc   if (isConstant())
418f4a2713aSLionel Sambuc     return 0;
419f4a2713aSLionel Sambuc 
420f4a2713aSLionel Sambuc   unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1);
421f4a2713aSLionel Sambuc   if (!BreakNum || Coeff.isOne())
422f4a2713aSLionel Sambuc     return BreakNum;
423f4a2713aSLionel Sambuc 
424f4a2713aSLionel Sambuc   Addend0.Scale(Coeff);
425f4a2713aSLionel Sambuc 
426f4a2713aSLionel Sambuc   if (BreakNum == 2)
427f4a2713aSLionel Sambuc     Addend1.Scale(Coeff);
428f4a2713aSLionel Sambuc 
429f4a2713aSLionel Sambuc   return BreakNum;
430f4a2713aSLionel Sambuc }
431f4a2713aSLionel Sambuc 
432f4a2713aSLionel Sambuc // Try to perform following optimization on the input instruction I. Return the
433f4a2713aSLionel Sambuc // simplified expression if was successful; otherwise, return 0.
434f4a2713aSLionel Sambuc //
435f4a2713aSLionel Sambuc //   Instruction "I" is                Simplified into
436f4a2713aSLionel Sambuc // -------------------------------------------------------
437f4a2713aSLionel Sambuc //   (x * y) +/- (x * z)               x * (y +/- z)
438f4a2713aSLionel Sambuc //   (y / x) +/- (z / x)               (y +/- z) / x
439f4a2713aSLionel Sambuc //
performFactorization(Instruction * I)440f4a2713aSLionel Sambuc Value *FAddCombine::performFactorization(Instruction *I) {
441f4a2713aSLionel Sambuc   assert((I->getOpcode() == Instruction::FAdd ||
442f4a2713aSLionel Sambuc           I->getOpcode() == Instruction::FSub) && "Expect add/sub");
443f4a2713aSLionel Sambuc 
444f4a2713aSLionel Sambuc   Instruction *I0 = dyn_cast<Instruction>(I->getOperand(0));
445f4a2713aSLionel Sambuc   Instruction *I1 = dyn_cast<Instruction>(I->getOperand(1));
446f4a2713aSLionel Sambuc 
447f4a2713aSLionel Sambuc   if (!I0 || !I1 || I0->getOpcode() != I1->getOpcode())
448*0a6a1f1dSLionel Sambuc     return nullptr;
449f4a2713aSLionel Sambuc 
450f4a2713aSLionel Sambuc   bool isMpy = false;
451f4a2713aSLionel Sambuc   if (I0->getOpcode() == Instruction::FMul)
452f4a2713aSLionel Sambuc     isMpy = true;
453f4a2713aSLionel Sambuc   else if (I0->getOpcode() != Instruction::FDiv)
454*0a6a1f1dSLionel Sambuc     return nullptr;
455f4a2713aSLionel Sambuc 
456f4a2713aSLionel Sambuc   Value *Opnd0_0 = I0->getOperand(0);
457f4a2713aSLionel Sambuc   Value *Opnd0_1 = I0->getOperand(1);
458f4a2713aSLionel Sambuc   Value *Opnd1_0 = I1->getOperand(0);
459f4a2713aSLionel Sambuc   Value *Opnd1_1 = I1->getOperand(1);
460f4a2713aSLionel Sambuc 
461f4a2713aSLionel Sambuc   //  Input Instr I       Factor   AddSub0  AddSub1
462f4a2713aSLionel Sambuc   //  ----------------------------------------------
463f4a2713aSLionel Sambuc   // (x*y) +/- (x*z)        x        y         z
464f4a2713aSLionel Sambuc   // (y/x) +/- (z/x)        x        y         z
465f4a2713aSLionel Sambuc   //
466*0a6a1f1dSLionel Sambuc   Value *Factor = nullptr;
467*0a6a1f1dSLionel Sambuc   Value *AddSub0 = nullptr, *AddSub1 = nullptr;
468f4a2713aSLionel Sambuc 
469f4a2713aSLionel Sambuc   if (isMpy) {
470f4a2713aSLionel Sambuc     if (Opnd0_0 == Opnd1_0 || Opnd0_0 == Opnd1_1)
471f4a2713aSLionel Sambuc       Factor = Opnd0_0;
472f4a2713aSLionel Sambuc     else if (Opnd0_1 == Opnd1_0 || Opnd0_1 == Opnd1_1)
473f4a2713aSLionel Sambuc       Factor = Opnd0_1;
474f4a2713aSLionel Sambuc 
475f4a2713aSLionel Sambuc     if (Factor) {
476f4a2713aSLionel Sambuc       AddSub0 = (Factor == Opnd0_0) ? Opnd0_1 : Opnd0_0;
477f4a2713aSLionel Sambuc       AddSub1 = (Factor == Opnd1_0) ? Opnd1_1 : Opnd1_0;
478f4a2713aSLionel Sambuc     }
479f4a2713aSLionel Sambuc   } else if (Opnd0_1 == Opnd1_1) {
480f4a2713aSLionel Sambuc     Factor = Opnd0_1;
481f4a2713aSLionel Sambuc     AddSub0 = Opnd0_0;
482f4a2713aSLionel Sambuc     AddSub1 = Opnd1_0;
483f4a2713aSLionel Sambuc   }
484f4a2713aSLionel Sambuc 
485f4a2713aSLionel Sambuc   if (!Factor)
486*0a6a1f1dSLionel Sambuc     return nullptr;
487*0a6a1f1dSLionel Sambuc 
488*0a6a1f1dSLionel Sambuc   FastMathFlags Flags;
489*0a6a1f1dSLionel Sambuc   Flags.setUnsafeAlgebra();
490*0a6a1f1dSLionel Sambuc   if (I0) Flags &= I->getFastMathFlags();
491*0a6a1f1dSLionel Sambuc   if (I1) Flags &= I->getFastMathFlags();
492f4a2713aSLionel Sambuc 
493f4a2713aSLionel Sambuc   // Create expression "NewAddSub = AddSub0 +/- AddsSub1"
494f4a2713aSLionel Sambuc   Value *NewAddSub = (I->getOpcode() == Instruction::FAdd) ?
495f4a2713aSLionel Sambuc                       createFAdd(AddSub0, AddSub1) :
496f4a2713aSLionel Sambuc                       createFSub(AddSub0, AddSub1);
497f4a2713aSLionel Sambuc   if (ConstantFP *CFP = dyn_cast<ConstantFP>(NewAddSub)) {
498f4a2713aSLionel Sambuc     const APFloat &F = CFP->getValueAPF();
499f4a2713aSLionel Sambuc     if (!F.isNormal())
500*0a6a1f1dSLionel Sambuc       return nullptr;
501*0a6a1f1dSLionel Sambuc   } else if (Instruction *II = dyn_cast<Instruction>(NewAddSub))
502*0a6a1f1dSLionel Sambuc     II->setFastMathFlags(Flags);
503*0a6a1f1dSLionel Sambuc 
504*0a6a1f1dSLionel Sambuc   if (isMpy) {
505*0a6a1f1dSLionel Sambuc     Value *RI = createFMul(Factor, NewAddSub);
506*0a6a1f1dSLionel Sambuc     if (Instruction *II = dyn_cast<Instruction>(RI))
507*0a6a1f1dSLionel Sambuc       II->setFastMathFlags(Flags);
508*0a6a1f1dSLionel Sambuc     return RI;
509f4a2713aSLionel Sambuc   }
510f4a2713aSLionel Sambuc 
511*0a6a1f1dSLionel Sambuc   Value *RI = createFDiv(NewAddSub, Factor);
512*0a6a1f1dSLionel Sambuc   if (Instruction *II = dyn_cast<Instruction>(RI))
513*0a6a1f1dSLionel Sambuc     II->setFastMathFlags(Flags);
514*0a6a1f1dSLionel Sambuc   return RI;
515f4a2713aSLionel Sambuc }
516f4a2713aSLionel Sambuc 
simplify(Instruction * I)517f4a2713aSLionel Sambuc Value *FAddCombine::simplify(Instruction *I) {
518f4a2713aSLionel Sambuc   assert(I->hasUnsafeAlgebra() && "Should be in unsafe mode");
519f4a2713aSLionel Sambuc 
520f4a2713aSLionel Sambuc   // Currently we are not able to handle vector type.
521f4a2713aSLionel Sambuc   if (I->getType()->isVectorTy())
522*0a6a1f1dSLionel Sambuc     return nullptr;
523f4a2713aSLionel Sambuc 
524f4a2713aSLionel Sambuc   assert((I->getOpcode() == Instruction::FAdd ||
525f4a2713aSLionel Sambuc           I->getOpcode() == Instruction::FSub) && "Expect add/sub");
526f4a2713aSLionel Sambuc 
527f4a2713aSLionel Sambuc   // Save the instruction before calling other member-functions.
528f4a2713aSLionel Sambuc   Instr = I;
529f4a2713aSLionel Sambuc 
530f4a2713aSLionel Sambuc   FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
531f4a2713aSLionel Sambuc 
532f4a2713aSLionel Sambuc   unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
533f4a2713aSLionel Sambuc 
534f4a2713aSLionel Sambuc   // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
535f4a2713aSLionel Sambuc   unsigned Opnd0_ExpNum = 0;
536f4a2713aSLionel Sambuc   unsigned Opnd1_ExpNum = 0;
537f4a2713aSLionel Sambuc 
538f4a2713aSLionel Sambuc   if (!Opnd0.isConstant())
539f4a2713aSLionel Sambuc     Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
540f4a2713aSLionel Sambuc 
541f4a2713aSLionel Sambuc   // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
542f4a2713aSLionel Sambuc   if (OpndNum == 2 && !Opnd1.isConstant())
543f4a2713aSLionel Sambuc     Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
544f4a2713aSLionel Sambuc 
545f4a2713aSLionel Sambuc   // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
546f4a2713aSLionel Sambuc   if (Opnd0_ExpNum && Opnd1_ExpNum) {
547f4a2713aSLionel Sambuc     AddendVect AllOpnds;
548f4a2713aSLionel Sambuc     AllOpnds.push_back(&Opnd0_0);
549f4a2713aSLionel Sambuc     AllOpnds.push_back(&Opnd1_0);
550f4a2713aSLionel Sambuc     if (Opnd0_ExpNum == 2)
551f4a2713aSLionel Sambuc       AllOpnds.push_back(&Opnd0_1);
552f4a2713aSLionel Sambuc     if (Opnd1_ExpNum == 2)
553f4a2713aSLionel Sambuc       AllOpnds.push_back(&Opnd1_1);
554f4a2713aSLionel Sambuc 
555f4a2713aSLionel Sambuc     // Compute instruction quota. We should save at least one instruction.
556f4a2713aSLionel Sambuc     unsigned InstQuota = 0;
557f4a2713aSLionel Sambuc 
558f4a2713aSLionel Sambuc     Value *V0 = I->getOperand(0);
559f4a2713aSLionel Sambuc     Value *V1 = I->getOperand(1);
560f4a2713aSLionel Sambuc     InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
561f4a2713aSLionel Sambuc                  (!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
562f4a2713aSLionel Sambuc 
563f4a2713aSLionel Sambuc     if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
564f4a2713aSLionel Sambuc       return R;
565f4a2713aSLionel Sambuc   }
566f4a2713aSLionel Sambuc 
567f4a2713aSLionel Sambuc   if (OpndNum != 2) {
568f4a2713aSLionel Sambuc     // The input instruction is : "I=0.0 +/- V". If the "V" were able to be
569f4a2713aSLionel Sambuc     // splitted into two addends, say "V = X - Y", the instruction would have
570f4a2713aSLionel Sambuc     // been optimized into "I = Y - X" in the previous steps.
571f4a2713aSLionel Sambuc     //
572f4a2713aSLionel Sambuc     const FAddendCoef &CE = Opnd0.getCoef();
573*0a6a1f1dSLionel Sambuc     return CE.isOne() ? Opnd0.getSymVal() : nullptr;
574f4a2713aSLionel Sambuc   }
575f4a2713aSLionel Sambuc 
576f4a2713aSLionel Sambuc   // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
577f4a2713aSLionel Sambuc   if (Opnd1_ExpNum) {
578f4a2713aSLionel Sambuc     AddendVect AllOpnds;
579f4a2713aSLionel Sambuc     AllOpnds.push_back(&Opnd0);
580f4a2713aSLionel Sambuc     AllOpnds.push_back(&Opnd1_0);
581f4a2713aSLionel Sambuc     if (Opnd1_ExpNum == 2)
582f4a2713aSLionel Sambuc       AllOpnds.push_back(&Opnd1_1);
583f4a2713aSLionel Sambuc 
584f4a2713aSLionel Sambuc     if (Value *R = simplifyFAdd(AllOpnds, 1))
585f4a2713aSLionel Sambuc       return R;
586f4a2713aSLionel Sambuc   }
587f4a2713aSLionel Sambuc 
588f4a2713aSLionel Sambuc   // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
589f4a2713aSLionel Sambuc   if (Opnd0_ExpNum) {
590f4a2713aSLionel Sambuc     AddendVect AllOpnds;
591f4a2713aSLionel Sambuc     AllOpnds.push_back(&Opnd1);
592f4a2713aSLionel Sambuc     AllOpnds.push_back(&Opnd0_0);
593f4a2713aSLionel Sambuc     if (Opnd0_ExpNum == 2)
594f4a2713aSLionel Sambuc       AllOpnds.push_back(&Opnd0_1);
595f4a2713aSLionel Sambuc 
596f4a2713aSLionel Sambuc     if (Value *R = simplifyFAdd(AllOpnds, 1))
597f4a2713aSLionel Sambuc       return R;
598f4a2713aSLionel Sambuc   }
599f4a2713aSLionel Sambuc 
600f4a2713aSLionel Sambuc   // step 6: Try factorization as the last resort,
601f4a2713aSLionel Sambuc   return performFactorization(I);
602f4a2713aSLionel Sambuc }
603f4a2713aSLionel Sambuc 
simplifyFAdd(AddendVect & Addends,unsigned InstrQuota)604f4a2713aSLionel Sambuc Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
605f4a2713aSLionel Sambuc 
606f4a2713aSLionel Sambuc   unsigned AddendNum = Addends.size();
607f4a2713aSLionel Sambuc   assert(AddendNum <= 4 && "Too many addends");
608f4a2713aSLionel Sambuc 
609f4a2713aSLionel Sambuc   // For saving intermediate results;
610f4a2713aSLionel Sambuc   unsigned NextTmpIdx = 0;
611f4a2713aSLionel Sambuc   FAddend TmpResult[3];
612f4a2713aSLionel Sambuc 
613f4a2713aSLionel Sambuc   // Points to the constant addend of the resulting simplified expression.
614f4a2713aSLionel Sambuc   // If the resulting expr has constant-addend, this constant-addend is
615f4a2713aSLionel Sambuc   // desirable to reside at the top of the resulting expression tree. Placing
616f4a2713aSLionel Sambuc   // constant close to supper-expr(s) will potentially reveal some optimization
617f4a2713aSLionel Sambuc   // opportunities in super-expr(s).
618f4a2713aSLionel Sambuc   //
619*0a6a1f1dSLionel Sambuc   const FAddend *ConstAdd = nullptr;
620f4a2713aSLionel Sambuc 
621f4a2713aSLionel Sambuc   // Simplified addends are placed <SimpVect>.
622f4a2713aSLionel Sambuc   AddendVect SimpVect;
623f4a2713aSLionel Sambuc 
624f4a2713aSLionel Sambuc   // The outer loop works on one symbolic-value at a time. Suppose the input
625f4a2713aSLionel Sambuc   // addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
626f4a2713aSLionel Sambuc   // The symbolic-values will be processed in this order: x, y, z.
627f4a2713aSLionel Sambuc   //
628f4a2713aSLionel Sambuc   for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
629f4a2713aSLionel Sambuc 
630f4a2713aSLionel Sambuc     const FAddend *ThisAddend = Addends[SymIdx];
631f4a2713aSLionel Sambuc     if (!ThisAddend) {
632f4a2713aSLionel Sambuc       // This addend was processed before.
633f4a2713aSLionel Sambuc       continue;
634f4a2713aSLionel Sambuc     }
635f4a2713aSLionel Sambuc 
636f4a2713aSLionel Sambuc     Value *Val = ThisAddend->getSymVal();
637f4a2713aSLionel Sambuc     unsigned StartIdx = SimpVect.size();
638f4a2713aSLionel Sambuc     SimpVect.push_back(ThisAddend);
639f4a2713aSLionel Sambuc 
640f4a2713aSLionel Sambuc     // The inner loop collects addends sharing same symbolic-value, and these
641f4a2713aSLionel Sambuc     // addends will be later on folded into a single addend. Following above
642f4a2713aSLionel Sambuc     // example, if the symbolic value "y" is being processed, the inner loop
643f4a2713aSLionel Sambuc     // will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
644f4a2713aSLionel Sambuc     // be later on folded into "<b1+b2, y>".
645f4a2713aSLionel Sambuc     //
646f4a2713aSLionel Sambuc     for (unsigned SameSymIdx = SymIdx + 1;
647f4a2713aSLionel Sambuc          SameSymIdx < AddendNum; SameSymIdx++) {
648f4a2713aSLionel Sambuc       const FAddend *T = Addends[SameSymIdx];
649f4a2713aSLionel Sambuc       if (T && T->getSymVal() == Val) {
650f4a2713aSLionel Sambuc         // Set null such that next iteration of the outer loop will not process
651f4a2713aSLionel Sambuc         // this addend again.
652*0a6a1f1dSLionel Sambuc         Addends[SameSymIdx] = nullptr;
653f4a2713aSLionel Sambuc         SimpVect.push_back(T);
654f4a2713aSLionel Sambuc       }
655f4a2713aSLionel Sambuc     }
656f4a2713aSLionel Sambuc 
657f4a2713aSLionel Sambuc     // If multiple addends share same symbolic value, fold them together.
658f4a2713aSLionel Sambuc     if (StartIdx + 1 != SimpVect.size()) {
659f4a2713aSLionel Sambuc       FAddend &R = TmpResult[NextTmpIdx ++];
660f4a2713aSLionel Sambuc       R = *SimpVect[StartIdx];
661f4a2713aSLionel Sambuc       for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
662f4a2713aSLionel Sambuc         R += *SimpVect[Idx];
663f4a2713aSLionel Sambuc 
664f4a2713aSLionel Sambuc       // Pop all addends being folded and push the resulting folded addend.
665f4a2713aSLionel Sambuc       SimpVect.resize(StartIdx);
666*0a6a1f1dSLionel Sambuc       if (Val) {
667f4a2713aSLionel Sambuc         if (!R.isZero()) {
668f4a2713aSLionel Sambuc           SimpVect.push_back(&R);
669f4a2713aSLionel Sambuc         }
670f4a2713aSLionel Sambuc       } else {
671f4a2713aSLionel Sambuc         // Don't push constant addend at this time. It will be the last element
672f4a2713aSLionel Sambuc         // of <SimpVect>.
673f4a2713aSLionel Sambuc         ConstAdd = &R;
674f4a2713aSLionel Sambuc       }
675f4a2713aSLionel Sambuc     }
676f4a2713aSLionel Sambuc   }
677f4a2713aSLionel Sambuc 
678f4a2713aSLionel Sambuc   assert((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&
679f4a2713aSLionel Sambuc          "out-of-bound access");
680f4a2713aSLionel Sambuc 
681f4a2713aSLionel Sambuc   if (ConstAdd)
682f4a2713aSLionel Sambuc     SimpVect.push_back(ConstAdd);
683f4a2713aSLionel Sambuc 
684f4a2713aSLionel Sambuc   Value *Result;
685f4a2713aSLionel Sambuc   if (!SimpVect.empty())
686f4a2713aSLionel Sambuc     Result = createNaryFAdd(SimpVect, InstrQuota);
687f4a2713aSLionel Sambuc   else {
688f4a2713aSLionel Sambuc     // The addition is folded to 0.0.
689f4a2713aSLionel Sambuc     Result = ConstantFP::get(Instr->getType(), 0.0);
690f4a2713aSLionel Sambuc   }
691f4a2713aSLionel Sambuc 
692f4a2713aSLionel Sambuc   return Result;
693f4a2713aSLionel Sambuc }
694f4a2713aSLionel Sambuc 
createNaryFAdd(const AddendVect & Opnds,unsigned InstrQuota)695f4a2713aSLionel Sambuc Value *FAddCombine::createNaryFAdd
696f4a2713aSLionel Sambuc   (const AddendVect &Opnds, unsigned InstrQuota) {
697f4a2713aSLionel Sambuc   assert(!Opnds.empty() && "Expect at least one addend");
698f4a2713aSLionel Sambuc 
699f4a2713aSLionel Sambuc   // Step 1: Check if the # of instructions needed exceeds the quota.
700f4a2713aSLionel Sambuc   //
701f4a2713aSLionel Sambuc   unsigned InstrNeeded = calcInstrNumber(Opnds);
702f4a2713aSLionel Sambuc   if (InstrNeeded > InstrQuota)
703*0a6a1f1dSLionel Sambuc     return nullptr;
704f4a2713aSLionel Sambuc 
705f4a2713aSLionel Sambuc   initCreateInstNum();
706f4a2713aSLionel Sambuc 
707f4a2713aSLionel Sambuc   // step 2: Emit the N-ary addition.
708f4a2713aSLionel Sambuc   // Note that at most three instructions are involved in Fadd-InstCombine: the
709f4a2713aSLionel Sambuc   // addition in question, and at most two neighboring instructions.
710f4a2713aSLionel Sambuc   // The resulting optimized addition should have at least one less instruction
711f4a2713aSLionel Sambuc   // than the original addition expression tree. This implies that the resulting
712f4a2713aSLionel Sambuc   // N-ary addition has at most two instructions, and we don't need to worry
713f4a2713aSLionel Sambuc   // about tree-height when constructing the N-ary addition.
714f4a2713aSLionel Sambuc 
715*0a6a1f1dSLionel Sambuc   Value *LastVal = nullptr;
716f4a2713aSLionel Sambuc   bool LastValNeedNeg = false;
717f4a2713aSLionel Sambuc 
718f4a2713aSLionel Sambuc   // Iterate the addends, creating fadd/fsub using adjacent two addends.
719f4a2713aSLionel Sambuc   for (AddendVect::const_iterator I = Opnds.begin(), E = Opnds.end();
720f4a2713aSLionel Sambuc        I != E; I++) {
721f4a2713aSLionel Sambuc     bool NeedNeg;
722f4a2713aSLionel Sambuc     Value *V = createAddendVal(**I, NeedNeg);
723f4a2713aSLionel Sambuc     if (!LastVal) {
724f4a2713aSLionel Sambuc       LastVal = V;
725f4a2713aSLionel Sambuc       LastValNeedNeg = NeedNeg;
726f4a2713aSLionel Sambuc       continue;
727f4a2713aSLionel Sambuc     }
728f4a2713aSLionel Sambuc 
729f4a2713aSLionel Sambuc     if (LastValNeedNeg == NeedNeg) {
730f4a2713aSLionel Sambuc       LastVal = createFAdd(LastVal, V);
731f4a2713aSLionel Sambuc       continue;
732f4a2713aSLionel Sambuc     }
733f4a2713aSLionel Sambuc 
734f4a2713aSLionel Sambuc     if (LastValNeedNeg)
735f4a2713aSLionel Sambuc       LastVal = createFSub(V, LastVal);
736f4a2713aSLionel Sambuc     else
737f4a2713aSLionel Sambuc       LastVal = createFSub(LastVal, V);
738f4a2713aSLionel Sambuc 
739f4a2713aSLionel Sambuc     LastValNeedNeg = false;
740f4a2713aSLionel Sambuc   }
741f4a2713aSLionel Sambuc 
742f4a2713aSLionel Sambuc   if (LastValNeedNeg) {
743f4a2713aSLionel Sambuc     LastVal = createFNeg(LastVal);
744f4a2713aSLionel Sambuc   }
745f4a2713aSLionel Sambuc 
746f4a2713aSLionel Sambuc   #ifndef NDEBUG
747f4a2713aSLionel Sambuc     assert(CreateInstrNum == InstrNeeded &&
748f4a2713aSLionel Sambuc            "Inconsistent in instruction numbers");
749f4a2713aSLionel Sambuc   #endif
750f4a2713aSLionel Sambuc 
751f4a2713aSLionel Sambuc   return LastVal;
752f4a2713aSLionel Sambuc }
753f4a2713aSLionel Sambuc 
createFSub(Value * Opnd0,Value * Opnd1)754*0a6a1f1dSLionel Sambuc Value *FAddCombine::createFSub(Value *Opnd0, Value *Opnd1) {
755f4a2713aSLionel Sambuc   Value *V = Builder->CreateFSub(Opnd0, Opnd1);
756f4a2713aSLionel Sambuc   if (Instruction *I = dyn_cast<Instruction>(V))
757f4a2713aSLionel Sambuc     createInstPostProc(I);
758f4a2713aSLionel Sambuc   return V;
759f4a2713aSLionel Sambuc }
760f4a2713aSLionel Sambuc 
createFNeg(Value * V)761f4a2713aSLionel Sambuc Value *FAddCombine::createFNeg(Value *V) {
762*0a6a1f1dSLionel Sambuc   Value *Zero = cast<Value>(ConstantFP::getZeroValueForNegation(V->getType()));
763*0a6a1f1dSLionel Sambuc   Value *NewV = createFSub(Zero, V);
764*0a6a1f1dSLionel Sambuc   if (Instruction *I = dyn_cast<Instruction>(NewV))
765*0a6a1f1dSLionel Sambuc     createInstPostProc(I, true); // fneg's don't receive instruction numbers.
766*0a6a1f1dSLionel Sambuc   return NewV;
767f4a2713aSLionel Sambuc }
768f4a2713aSLionel Sambuc 
createFAdd(Value * Opnd0,Value * Opnd1)769*0a6a1f1dSLionel Sambuc Value *FAddCombine::createFAdd(Value *Opnd0, Value *Opnd1) {
770f4a2713aSLionel Sambuc   Value *V = Builder->CreateFAdd(Opnd0, Opnd1);
771f4a2713aSLionel Sambuc   if (Instruction *I = dyn_cast<Instruction>(V))
772f4a2713aSLionel Sambuc     createInstPostProc(I);
773f4a2713aSLionel Sambuc   return V;
774f4a2713aSLionel Sambuc }
775f4a2713aSLionel Sambuc 
createFMul(Value * Opnd0,Value * Opnd1)776f4a2713aSLionel Sambuc Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
777f4a2713aSLionel Sambuc   Value *V = Builder->CreateFMul(Opnd0, Opnd1);
778f4a2713aSLionel Sambuc   if (Instruction *I = dyn_cast<Instruction>(V))
779f4a2713aSLionel Sambuc     createInstPostProc(I);
780f4a2713aSLionel Sambuc   return V;
781f4a2713aSLionel Sambuc }
782f4a2713aSLionel Sambuc 
createFDiv(Value * Opnd0,Value * Opnd1)783f4a2713aSLionel Sambuc Value *FAddCombine::createFDiv(Value *Opnd0, Value *Opnd1) {
784f4a2713aSLionel Sambuc   Value *V = Builder->CreateFDiv(Opnd0, Opnd1);
785f4a2713aSLionel Sambuc   if (Instruction *I = dyn_cast<Instruction>(V))
786f4a2713aSLionel Sambuc     createInstPostProc(I);
787f4a2713aSLionel Sambuc   return V;
788f4a2713aSLionel Sambuc }
789f4a2713aSLionel Sambuc 
createInstPostProc(Instruction * NewInstr,bool NoNumber)790*0a6a1f1dSLionel Sambuc void FAddCombine::createInstPostProc(Instruction *NewInstr, bool NoNumber) {
791f4a2713aSLionel Sambuc   NewInstr->setDebugLoc(Instr->getDebugLoc());
792f4a2713aSLionel Sambuc 
793f4a2713aSLionel Sambuc   // Keep track of the number of instruction created.
794*0a6a1f1dSLionel Sambuc   if (!NoNumber)
795f4a2713aSLionel Sambuc     incCreateInstNum();
796f4a2713aSLionel Sambuc 
797f4a2713aSLionel Sambuc   // Propagate fast-math flags
798f4a2713aSLionel Sambuc   NewInstr->setFastMathFlags(Instr->getFastMathFlags());
799f4a2713aSLionel Sambuc }
800f4a2713aSLionel Sambuc 
801f4a2713aSLionel Sambuc // Return the number of instruction needed to emit the N-ary addition.
802f4a2713aSLionel Sambuc // NOTE: Keep this function in sync with createAddendVal().
calcInstrNumber(const AddendVect & Opnds)803f4a2713aSLionel Sambuc unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
804f4a2713aSLionel Sambuc   unsigned OpndNum = Opnds.size();
805f4a2713aSLionel Sambuc   unsigned InstrNeeded = OpndNum - 1;
806f4a2713aSLionel Sambuc 
807f4a2713aSLionel Sambuc   // The number of addends in the form of "(-1)*x".
808f4a2713aSLionel Sambuc   unsigned NegOpndNum = 0;
809f4a2713aSLionel Sambuc 
810f4a2713aSLionel Sambuc   // Adjust the number of instructions needed to emit the N-ary add.
811f4a2713aSLionel Sambuc   for (AddendVect::const_iterator I = Opnds.begin(), E = Opnds.end();
812f4a2713aSLionel Sambuc        I != E; I++) {
813f4a2713aSLionel Sambuc     const FAddend *Opnd = *I;
814f4a2713aSLionel Sambuc     if (Opnd->isConstant())
815f4a2713aSLionel Sambuc       continue;
816f4a2713aSLionel Sambuc 
817f4a2713aSLionel Sambuc     const FAddendCoef &CE = Opnd->getCoef();
818f4a2713aSLionel Sambuc     if (CE.isMinusOne() || CE.isMinusTwo())
819f4a2713aSLionel Sambuc       NegOpndNum++;
820f4a2713aSLionel Sambuc 
821f4a2713aSLionel Sambuc     // Let the addend be "c * x". If "c == +/-1", the value of the addend
822f4a2713aSLionel Sambuc     // is immediately available; otherwise, it needs exactly one instruction
823f4a2713aSLionel Sambuc     // to evaluate the value.
824f4a2713aSLionel Sambuc     if (!CE.isMinusOne() && !CE.isOne())
825f4a2713aSLionel Sambuc       InstrNeeded++;
826f4a2713aSLionel Sambuc   }
827f4a2713aSLionel Sambuc   if (NegOpndNum == OpndNum)
828f4a2713aSLionel Sambuc     InstrNeeded++;
829f4a2713aSLionel Sambuc   return InstrNeeded;
830f4a2713aSLionel Sambuc }
831f4a2713aSLionel Sambuc 
832f4a2713aSLionel Sambuc // Input Addend        Value           NeedNeg(output)
833f4a2713aSLionel Sambuc // ================================================================
834f4a2713aSLionel Sambuc // Constant C          C               false
835f4a2713aSLionel Sambuc // <+/-1, V>           V               coefficient is -1
836f4a2713aSLionel Sambuc // <2/-2, V>          "fadd V, V"      coefficient is -2
837f4a2713aSLionel Sambuc // <C, V>             "fmul V, C"      false
838f4a2713aSLionel Sambuc //
839f4a2713aSLionel Sambuc // NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
createAddendVal(const FAddend & Opnd,bool & NeedNeg)840*0a6a1f1dSLionel Sambuc Value *FAddCombine::createAddendVal(const FAddend &Opnd, bool &NeedNeg) {
841f4a2713aSLionel Sambuc   const FAddendCoef &Coeff = Opnd.getCoef();
842f4a2713aSLionel Sambuc 
843f4a2713aSLionel Sambuc   if (Opnd.isConstant()) {
844f4a2713aSLionel Sambuc     NeedNeg = false;
845f4a2713aSLionel Sambuc     return Coeff.getValue(Instr->getType());
846f4a2713aSLionel Sambuc   }
847f4a2713aSLionel Sambuc 
848f4a2713aSLionel Sambuc   Value *OpndVal = Opnd.getSymVal();
849f4a2713aSLionel Sambuc 
850f4a2713aSLionel Sambuc   if (Coeff.isMinusOne() || Coeff.isOne()) {
851f4a2713aSLionel Sambuc     NeedNeg = Coeff.isMinusOne();
852f4a2713aSLionel Sambuc     return OpndVal;
853f4a2713aSLionel Sambuc   }
854f4a2713aSLionel Sambuc 
855f4a2713aSLionel Sambuc   if (Coeff.isTwo() || Coeff.isMinusTwo()) {
856f4a2713aSLionel Sambuc     NeedNeg = Coeff.isMinusTwo();
857f4a2713aSLionel Sambuc     return createFAdd(OpndVal, OpndVal);
858f4a2713aSLionel Sambuc   }
859f4a2713aSLionel Sambuc 
860f4a2713aSLionel Sambuc   NeedNeg = false;
861f4a2713aSLionel Sambuc   return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
862f4a2713aSLionel Sambuc }
863f4a2713aSLionel Sambuc 
864*0a6a1f1dSLionel Sambuc // If one of the operands only has one non-zero bit, and if the other
865*0a6a1f1dSLionel Sambuc // operand has a known-zero bit in a more significant place than it (not
866*0a6a1f1dSLionel Sambuc // including the sign bit) the ripple may go up to and fill the zero, but
867*0a6a1f1dSLionel Sambuc // won't change the sign. For example, (X & ~4) + 1.
checkRippleForAdd(const APInt & Op0KnownZero,const APInt & Op1KnownZero)868*0a6a1f1dSLionel Sambuc static bool checkRippleForAdd(const APInt &Op0KnownZero,
869*0a6a1f1dSLionel Sambuc                               const APInt &Op1KnownZero) {
870*0a6a1f1dSLionel Sambuc   APInt Op1MaybeOne = ~Op1KnownZero;
871*0a6a1f1dSLionel Sambuc   // Make sure that one of the operand has at most one bit set to 1.
872*0a6a1f1dSLionel Sambuc   if (Op1MaybeOne.countPopulation() != 1)
873*0a6a1f1dSLionel Sambuc     return false;
874*0a6a1f1dSLionel Sambuc 
875*0a6a1f1dSLionel Sambuc   // Find the most significant known 0 other than the sign bit.
876*0a6a1f1dSLionel Sambuc   int BitWidth = Op0KnownZero.getBitWidth();
877*0a6a1f1dSLionel Sambuc   APInt Op0KnownZeroTemp(Op0KnownZero);
878*0a6a1f1dSLionel Sambuc   Op0KnownZeroTemp.clearBit(BitWidth - 1);
879*0a6a1f1dSLionel Sambuc   int Op0ZeroPosition = BitWidth - Op0KnownZeroTemp.countLeadingZeros() - 1;
880*0a6a1f1dSLionel Sambuc 
881*0a6a1f1dSLionel Sambuc   int Op1OnePosition = BitWidth - Op1MaybeOne.countLeadingZeros() - 1;
882*0a6a1f1dSLionel Sambuc   assert(Op1OnePosition >= 0);
883*0a6a1f1dSLionel Sambuc 
884*0a6a1f1dSLionel Sambuc   // This also covers the case of no known zero, since in that case
885*0a6a1f1dSLionel Sambuc   // Op0ZeroPosition is -1.
886*0a6a1f1dSLionel Sambuc   return Op0ZeroPosition >= Op1OnePosition;
887f4a2713aSLionel Sambuc }
888f4a2713aSLionel Sambuc 
889f4a2713aSLionel Sambuc /// WillNotOverflowSignedAdd - Return true if we can prove that:
890f4a2713aSLionel Sambuc ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
891f4a2713aSLionel Sambuc /// This basically requires proving that the add in the original type would not
892f4a2713aSLionel Sambuc /// overflow to change the sign bit or have a carry out.
WillNotOverflowSignedAdd(Value * LHS,Value * RHS,Instruction * CxtI)893*0a6a1f1dSLionel Sambuc bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS,
894*0a6a1f1dSLionel Sambuc                                             Instruction *CxtI) {
895f4a2713aSLionel Sambuc   // There are different heuristics we can use for this.  Here are some simple
896f4a2713aSLionel Sambuc   // ones.
897f4a2713aSLionel Sambuc 
898*0a6a1f1dSLionel Sambuc   // If LHS and RHS each have at least two sign bits, the addition will look
899*0a6a1f1dSLionel Sambuc   // like
900*0a6a1f1dSLionel Sambuc   //
901*0a6a1f1dSLionel Sambuc   // XX..... +
902*0a6a1f1dSLionel Sambuc   // YY.....
903*0a6a1f1dSLionel Sambuc   //
904*0a6a1f1dSLionel Sambuc   // If the carry into the most significant position is 0, X and Y can't both
905*0a6a1f1dSLionel Sambuc   // be 1 and therefore the carry out of the addition is also 0.
906*0a6a1f1dSLionel Sambuc   //
907*0a6a1f1dSLionel Sambuc   // If the carry into the most significant position is 1, X and Y can't both
908*0a6a1f1dSLionel Sambuc   // be 0 and therefore the carry out of the addition is also 1.
909*0a6a1f1dSLionel Sambuc   //
910*0a6a1f1dSLionel Sambuc   // Since the carry into the most significant position is always equal to
911*0a6a1f1dSLionel Sambuc   // the carry out of the addition, there is no signed overflow.
912*0a6a1f1dSLionel Sambuc   if (ComputeNumSignBits(LHS, 0, CxtI) > 1 &&
913*0a6a1f1dSLionel Sambuc       ComputeNumSignBits(RHS, 0, CxtI) > 1)
914f4a2713aSLionel Sambuc     return true;
915f4a2713aSLionel Sambuc 
916*0a6a1f1dSLionel Sambuc   unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
917*0a6a1f1dSLionel Sambuc   APInt LHSKnownZero(BitWidth, 0);
918*0a6a1f1dSLionel Sambuc   APInt LHSKnownOne(BitWidth, 0);
919*0a6a1f1dSLionel Sambuc   computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, 0, CxtI);
920f4a2713aSLionel Sambuc 
921*0a6a1f1dSLionel Sambuc   APInt RHSKnownZero(BitWidth, 0);
922*0a6a1f1dSLionel Sambuc   APInt RHSKnownOne(BitWidth, 0);
923*0a6a1f1dSLionel Sambuc   computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, 0, CxtI);
924f4a2713aSLionel Sambuc 
925*0a6a1f1dSLionel Sambuc   // Addition of two 2's compliment numbers having opposite signs will never
926*0a6a1f1dSLionel Sambuc   // overflow.
927*0a6a1f1dSLionel Sambuc   if ((LHSKnownOne[BitWidth - 1] && RHSKnownZero[BitWidth - 1]) ||
928*0a6a1f1dSLionel Sambuc       (LHSKnownZero[BitWidth - 1] && RHSKnownOne[BitWidth - 1]))
929*0a6a1f1dSLionel Sambuc     return true;
930*0a6a1f1dSLionel Sambuc 
931*0a6a1f1dSLionel Sambuc   // Check if carry bit of addition will not cause overflow.
932*0a6a1f1dSLionel Sambuc   if (checkRippleForAdd(LHSKnownZero, RHSKnownZero))
933*0a6a1f1dSLionel Sambuc     return true;
934*0a6a1f1dSLionel Sambuc   if (checkRippleForAdd(RHSKnownZero, LHSKnownZero))
935*0a6a1f1dSLionel Sambuc     return true;
936f4a2713aSLionel Sambuc 
937f4a2713aSLionel Sambuc   return false;
938f4a2713aSLionel Sambuc }
939f4a2713aSLionel Sambuc 
940*0a6a1f1dSLionel Sambuc /// \brief Return true if we can prove that:
941*0a6a1f1dSLionel Sambuc ///    (sub LHS, RHS)  === (sub nsw LHS, RHS)
942*0a6a1f1dSLionel Sambuc /// This basically requires proving that the add in the original type would not
943*0a6a1f1dSLionel Sambuc /// overflow to change the sign bit or have a carry out.
944*0a6a1f1dSLionel Sambuc /// TODO: Handle this for Vectors.
WillNotOverflowSignedSub(Value * LHS,Value * RHS,Instruction * CxtI)945*0a6a1f1dSLionel Sambuc bool InstCombiner::WillNotOverflowSignedSub(Value *LHS, Value *RHS,
946*0a6a1f1dSLionel Sambuc                                             Instruction *CxtI) {
947*0a6a1f1dSLionel Sambuc   // If LHS and RHS each have at least two sign bits, the subtraction
948*0a6a1f1dSLionel Sambuc   // cannot overflow.
949*0a6a1f1dSLionel Sambuc   if (ComputeNumSignBits(LHS, 0, CxtI) > 1 &&
950*0a6a1f1dSLionel Sambuc       ComputeNumSignBits(RHS, 0, CxtI) > 1)
951*0a6a1f1dSLionel Sambuc     return true;
952*0a6a1f1dSLionel Sambuc 
953*0a6a1f1dSLionel Sambuc   unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
954*0a6a1f1dSLionel Sambuc   APInt LHSKnownZero(BitWidth, 0);
955*0a6a1f1dSLionel Sambuc   APInt LHSKnownOne(BitWidth, 0);
956*0a6a1f1dSLionel Sambuc   computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, 0, CxtI);
957*0a6a1f1dSLionel Sambuc 
958*0a6a1f1dSLionel Sambuc   APInt RHSKnownZero(BitWidth, 0);
959*0a6a1f1dSLionel Sambuc   APInt RHSKnownOne(BitWidth, 0);
960*0a6a1f1dSLionel Sambuc   computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, 0, CxtI);
961*0a6a1f1dSLionel Sambuc 
962*0a6a1f1dSLionel Sambuc   // Subtraction of two 2's compliment numbers having identical signs will
963*0a6a1f1dSLionel Sambuc   // never overflow.
964*0a6a1f1dSLionel Sambuc   if ((LHSKnownOne[BitWidth - 1] && RHSKnownOne[BitWidth - 1]) ||
965*0a6a1f1dSLionel Sambuc       (LHSKnownZero[BitWidth - 1] && RHSKnownZero[BitWidth - 1]))
966*0a6a1f1dSLionel Sambuc     return true;
967*0a6a1f1dSLionel Sambuc 
968*0a6a1f1dSLionel Sambuc   // TODO: implement logic similar to checkRippleForAdd
969*0a6a1f1dSLionel Sambuc   return false;
970*0a6a1f1dSLionel Sambuc }
971*0a6a1f1dSLionel Sambuc 
972*0a6a1f1dSLionel Sambuc /// \brief Return true if we can prove that:
973*0a6a1f1dSLionel Sambuc ///    (sub LHS, RHS)  === (sub nuw LHS, RHS)
WillNotOverflowUnsignedSub(Value * LHS,Value * RHS,Instruction * CxtI)974*0a6a1f1dSLionel Sambuc bool InstCombiner::WillNotOverflowUnsignedSub(Value *LHS, Value *RHS,
975*0a6a1f1dSLionel Sambuc                                               Instruction *CxtI) {
976*0a6a1f1dSLionel Sambuc   // If the LHS is negative and the RHS is non-negative, no unsigned wrap.
977*0a6a1f1dSLionel Sambuc   bool LHSKnownNonNegative, LHSKnownNegative;
978*0a6a1f1dSLionel Sambuc   bool RHSKnownNonNegative, RHSKnownNegative;
979*0a6a1f1dSLionel Sambuc   ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, /*Depth=*/0, CxtI);
980*0a6a1f1dSLionel Sambuc   ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, /*Depth=*/0, CxtI);
981*0a6a1f1dSLionel Sambuc   if (LHSKnownNegative && RHSKnownNonNegative)
982*0a6a1f1dSLionel Sambuc     return true;
983*0a6a1f1dSLionel Sambuc 
984*0a6a1f1dSLionel Sambuc   return false;
985*0a6a1f1dSLionel Sambuc }
986*0a6a1f1dSLionel Sambuc 
987*0a6a1f1dSLionel Sambuc // Checks if any operand is negative and we can convert add to sub.
988*0a6a1f1dSLionel Sambuc // This function checks for following negative patterns
989*0a6a1f1dSLionel Sambuc //   ADD(XOR(OR(Z, NOT(C)), C)), 1) == NEG(AND(Z, C))
990*0a6a1f1dSLionel Sambuc //   ADD(XOR(AND(Z, C), C), 1) == NEG(OR(Z, ~C))
991*0a6a1f1dSLionel Sambuc //   XOR(AND(Z, C), (C + 1)) == NEG(OR(Z, ~C)) if C is even
checkForNegativeOperand(BinaryOperator & I,InstCombiner::BuilderTy * Builder)992*0a6a1f1dSLionel Sambuc static Value *checkForNegativeOperand(BinaryOperator &I,
993*0a6a1f1dSLionel Sambuc                                       InstCombiner::BuilderTy *Builder) {
994*0a6a1f1dSLionel Sambuc   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
995*0a6a1f1dSLionel Sambuc 
996*0a6a1f1dSLionel Sambuc   // This function creates 2 instructions to replace ADD, we need at least one
997*0a6a1f1dSLionel Sambuc   // of LHS or RHS to have one use to ensure benefit in transform.
998*0a6a1f1dSLionel Sambuc   if (!LHS->hasOneUse() && !RHS->hasOneUse())
999*0a6a1f1dSLionel Sambuc     return nullptr;
1000*0a6a1f1dSLionel Sambuc 
1001*0a6a1f1dSLionel Sambuc   Value *X = nullptr, *Y = nullptr, *Z = nullptr;
1002*0a6a1f1dSLionel Sambuc   const APInt *C1 = nullptr, *C2 = nullptr;
1003*0a6a1f1dSLionel Sambuc 
1004*0a6a1f1dSLionel Sambuc   // if ONE is on other side, swap
1005*0a6a1f1dSLionel Sambuc   if (match(RHS, m_Add(m_Value(X), m_One())))
1006*0a6a1f1dSLionel Sambuc     std::swap(LHS, RHS);
1007*0a6a1f1dSLionel Sambuc 
1008*0a6a1f1dSLionel Sambuc   if (match(LHS, m_Add(m_Value(X), m_One()))) {
1009*0a6a1f1dSLionel Sambuc     // if XOR on other side, swap
1010*0a6a1f1dSLionel Sambuc     if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
1011*0a6a1f1dSLionel Sambuc       std::swap(X, RHS);
1012*0a6a1f1dSLionel Sambuc 
1013*0a6a1f1dSLionel Sambuc     if (match(X, m_Xor(m_Value(Y), m_APInt(C1)))) {
1014*0a6a1f1dSLionel Sambuc       // X = XOR(Y, C1), Y = OR(Z, C2), C2 = NOT(C1) ==> X == NOT(AND(Z, C1))
1015*0a6a1f1dSLionel Sambuc       // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, AND(Z, C1))
1016*0a6a1f1dSLionel Sambuc       if (match(Y, m_Or(m_Value(Z), m_APInt(C2))) && (*C2 == ~(*C1))) {
1017*0a6a1f1dSLionel Sambuc         Value *NewAnd = Builder->CreateAnd(Z, *C1);
1018*0a6a1f1dSLionel Sambuc         return Builder->CreateSub(RHS, NewAnd, "sub");
1019*0a6a1f1dSLionel Sambuc       } else if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && (*C1 == *C2)) {
1020*0a6a1f1dSLionel Sambuc         // X = XOR(Y, C1), Y = AND(Z, C2), C2 == C1 ==> X == NOT(OR(Z, ~C1))
1021*0a6a1f1dSLionel Sambuc         // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, OR(Z, ~C1))
1022*0a6a1f1dSLionel Sambuc         Value *NewOr = Builder->CreateOr(Z, ~(*C1));
1023*0a6a1f1dSLionel Sambuc         return Builder->CreateSub(RHS, NewOr, "sub");
1024*0a6a1f1dSLionel Sambuc       }
1025*0a6a1f1dSLionel Sambuc     }
1026*0a6a1f1dSLionel Sambuc   }
1027*0a6a1f1dSLionel Sambuc 
1028*0a6a1f1dSLionel Sambuc   // Restore LHS and RHS
1029*0a6a1f1dSLionel Sambuc   LHS = I.getOperand(0);
1030*0a6a1f1dSLionel Sambuc   RHS = I.getOperand(1);
1031*0a6a1f1dSLionel Sambuc 
1032*0a6a1f1dSLionel Sambuc   // if XOR is on other side, swap
1033*0a6a1f1dSLionel Sambuc   if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1))))
1034*0a6a1f1dSLionel Sambuc     std::swap(LHS, RHS);
1035*0a6a1f1dSLionel Sambuc 
1036*0a6a1f1dSLionel Sambuc   // C2 is ODD
1037*0a6a1f1dSLionel Sambuc   // LHS = XOR(Y, C1), Y = AND(Z, C2), C1 == (C2 + 1) => LHS == NEG(OR(Z, ~C2))
1038*0a6a1f1dSLionel Sambuc   // ADD(LHS, RHS) == SUB(RHS, OR(Z, ~C2))
1039*0a6a1f1dSLionel Sambuc   if (match(LHS, m_Xor(m_Value(Y), m_APInt(C1))))
1040*0a6a1f1dSLionel Sambuc     if (C1->countTrailingZeros() == 0)
1041*0a6a1f1dSLionel Sambuc       if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && *C1 == (*C2 + 1)) {
1042*0a6a1f1dSLionel Sambuc         Value *NewOr = Builder->CreateOr(Z, ~(*C2));
1043*0a6a1f1dSLionel Sambuc         return Builder->CreateSub(RHS, NewOr, "sub");
1044*0a6a1f1dSLionel Sambuc       }
1045*0a6a1f1dSLionel Sambuc   return nullptr;
1046*0a6a1f1dSLionel Sambuc }
1047*0a6a1f1dSLionel Sambuc 
visitAdd(BinaryOperator & I)1048f4a2713aSLionel Sambuc Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1049f4a2713aSLionel Sambuc    bool Changed = SimplifyAssociativeOrCommutative(I);
1050f4a2713aSLionel Sambuc    Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1051f4a2713aSLionel Sambuc 
1052*0a6a1f1dSLionel Sambuc    if (Value *V = SimplifyVectorOp(I))
1053*0a6a1f1dSLionel Sambuc      return ReplaceInstUsesWith(I, V);
1054*0a6a1f1dSLionel Sambuc 
1055f4a2713aSLionel Sambuc    if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
1056*0a6a1f1dSLionel Sambuc                                   I.hasNoUnsignedWrap(), DL, TLI, DT, AC))
1057f4a2713aSLionel Sambuc      return ReplaceInstUsesWith(I, V);
1058f4a2713aSLionel Sambuc 
1059f4a2713aSLionel Sambuc    // (A*B)+(A*C) -> A*(B+C) etc
1060f4a2713aSLionel Sambuc   if (Value *V = SimplifyUsingDistributiveLaws(I))
1061f4a2713aSLionel Sambuc     return ReplaceInstUsesWith(I, V);
1062f4a2713aSLionel Sambuc 
1063f4a2713aSLionel Sambuc   if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1064f4a2713aSLionel Sambuc     // X + (signbit) --> X ^ signbit
1065f4a2713aSLionel Sambuc     const APInt &Val = CI->getValue();
1066f4a2713aSLionel Sambuc     if (Val.isSignBit())
1067f4a2713aSLionel Sambuc       return BinaryOperator::CreateXor(LHS, RHS);
1068f4a2713aSLionel Sambuc 
1069f4a2713aSLionel Sambuc     // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1070f4a2713aSLionel Sambuc     // (X & 254)+1 -> (X&254)|1
1071f4a2713aSLionel Sambuc     if (SimplifyDemandedInstructionBits(I))
1072f4a2713aSLionel Sambuc       return &I;
1073f4a2713aSLionel Sambuc 
1074f4a2713aSLionel Sambuc     // zext(bool) + C -> bool ? C + 1 : C
1075f4a2713aSLionel Sambuc     if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
1076f4a2713aSLionel Sambuc       if (ZI->getSrcTy()->isIntegerTy(1))
1077f4a2713aSLionel Sambuc         return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
1078f4a2713aSLionel Sambuc 
1079*0a6a1f1dSLionel Sambuc     Value *XorLHS = nullptr; ConstantInt *XorRHS = nullptr;
1080f4a2713aSLionel Sambuc     if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1081f4a2713aSLionel Sambuc       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
1082f4a2713aSLionel Sambuc       const APInt &RHSVal = CI->getValue();
1083f4a2713aSLionel Sambuc       unsigned ExtendAmt = 0;
1084f4a2713aSLionel Sambuc       // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1085f4a2713aSLionel Sambuc       // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1086f4a2713aSLionel Sambuc       if (XorRHS->getValue() == -RHSVal) {
1087f4a2713aSLionel Sambuc         if (RHSVal.isPowerOf2())
1088f4a2713aSLionel Sambuc           ExtendAmt = TySizeBits - RHSVal.logBase2() - 1;
1089f4a2713aSLionel Sambuc         else if (XorRHS->getValue().isPowerOf2())
1090f4a2713aSLionel Sambuc           ExtendAmt = TySizeBits - XorRHS->getValue().logBase2() - 1;
1091f4a2713aSLionel Sambuc       }
1092f4a2713aSLionel Sambuc 
1093f4a2713aSLionel Sambuc       if (ExtendAmt) {
1094f4a2713aSLionel Sambuc         APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt);
1095*0a6a1f1dSLionel Sambuc         if (!MaskedValueIsZero(XorLHS, Mask, 0, &I))
1096f4a2713aSLionel Sambuc           ExtendAmt = 0;
1097f4a2713aSLionel Sambuc       }
1098f4a2713aSLionel Sambuc 
1099f4a2713aSLionel Sambuc       if (ExtendAmt) {
1100f4a2713aSLionel Sambuc         Constant *ShAmt = ConstantInt::get(I.getType(), ExtendAmt);
1101f4a2713aSLionel Sambuc         Value *NewShl = Builder->CreateShl(XorLHS, ShAmt, "sext");
1102f4a2713aSLionel Sambuc         return BinaryOperator::CreateAShr(NewShl, ShAmt);
1103f4a2713aSLionel Sambuc       }
1104f4a2713aSLionel Sambuc 
1105f4a2713aSLionel Sambuc       // If this is a xor that was canonicalized from a sub, turn it back into
1106f4a2713aSLionel Sambuc       // a sub and fuse this add with it.
1107f4a2713aSLionel Sambuc       if (LHS->hasOneUse() && (XorRHS->getValue()+1).isPowerOf2()) {
1108f4a2713aSLionel Sambuc         IntegerType *IT = cast<IntegerType>(I.getType());
1109f4a2713aSLionel Sambuc         APInt LHSKnownOne(IT->getBitWidth(), 0);
1110f4a2713aSLionel Sambuc         APInt LHSKnownZero(IT->getBitWidth(), 0);
1111*0a6a1f1dSLionel Sambuc         computeKnownBits(XorLHS, LHSKnownZero, LHSKnownOne, 0, &I);
1112f4a2713aSLionel Sambuc         if ((XorRHS->getValue() | LHSKnownZero).isAllOnesValue())
1113f4a2713aSLionel Sambuc           return BinaryOperator::CreateSub(ConstantExpr::getAdd(XorRHS, CI),
1114f4a2713aSLionel Sambuc                                            XorLHS);
1115f4a2713aSLionel Sambuc       }
1116f4a2713aSLionel Sambuc       // (X + signbit) + C could have gotten canonicalized to (X ^ signbit) + C,
1117f4a2713aSLionel Sambuc       // transform them into (X + (signbit ^ C))
1118f4a2713aSLionel Sambuc       if (XorRHS->getValue().isSignBit())
1119f4a2713aSLionel Sambuc           return BinaryOperator::CreateAdd(XorLHS,
1120f4a2713aSLionel Sambuc                                            ConstantExpr::getXor(XorRHS, CI));
1121f4a2713aSLionel Sambuc     }
1122f4a2713aSLionel Sambuc   }
1123f4a2713aSLionel Sambuc 
1124f4a2713aSLionel Sambuc   if (isa<Constant>(RHS) && isa<PHINode>(LHS))
1125f4a2713aSLionel Sambuc     if (Instruction *NV = FoldOpIntoPhi(I))
1126f4a2713aSLionel Sambuc       return NV;
1127f4a2713aSLionel Sambuc 
1128*0a6a1f1dSLionel Sambuc   if (I.getType()->getScalarType()->isIntegerTy(1))
1129f4a2713aSLionel Sambuc     return BinaryOperator::CreateXor(LHS, RHS);
1130f4a2713aSLionel Sambuc 
1131f4a2713aSLionel Sambuc   // X + X --> X << 1
1132f4a2713aSLionel Sambuc   if (LHS == RHS) {
1133f4a2713aSLionel Sambuc     BinaryOperator *New =
1134f4a2713aSLionel Sambuc       BinaryOperator::CreateShl(LHS, ConstantInt::get(I.getType(), 1));
1135f4a2713aSLionel Sambuc     New->setHasNoSignedWrap(I.hasNoSignedWrap());
1136f4a2713aSLionel Sambuc     New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1137f4a2713aSLionel Sambuc     return New;
1138f4a2713aSLionel Sambuc   }
1139f4a2713aSLionel Sambuc 
1140f4a2713aSLionel Sambuc   // -A + B  -->  B - A
1141f4a2713aSLionel Sambuc   // -A + -B  -->  -(A + B)
1142f4a2713aSLionel Sambuc   if (Value *LHSV = dyn_castNegVal(LHS)) {
1143f4a2713aSLionel Sambuc     if (!isa<Constant>(RHS))
1144f4a2713aSLionel Sambuc       if (Value *RHSV = dyn_castNegVal(RHS)) {
1145f4a2713aSLionel Sambuc         Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
1146f4a2713aSLionel Sambuc         return BinaryOperator::CreateNeg(NewAdd);
1147f4a2713aSLionel Sambuc       }
1148f4a2713aSLionel Sambuc 
1149f4a2713aSLionel Sambuc     return BinaryOperator::CreateSub(RHS, LHSV);
1150f4a2713aSLionel Sambuc   }
1151f4a2713aSLionel Sambuc 
1152f4a2713aSLionel Sambuc   // A + -B  -->  A - B
1153f4a2713aSLionel Sambuc   if (!isa<Constant>(RHS))
1154f4a2713aSLionel Sambuc     if (Value *V = dyn_castNegVal(RHS))
1155f4a2713aSLionel Sambuc       return BinaryOperator::CreateSub(LHS, V);
1156f4a2713aSLionel Sambuc 
1157*0a6a1f1dSLionel Sambuc   if (Value *V = checkForNegativeOperand(I, Builder))
1158*0a6a1f1dSLionel Sambuc     return ReplaceInstUsesWith(I, V);
1159f4a2713aSLionel Sambuc 
1160f4a2713aSLionel Sambuc   // A+B --> A|B iff A and B have no bits set in common.
1161f4a2713aSLionel Sambuc   if (IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
1162f4a2713aSLionel Sambuc     APInt LHSKnownOne(IT->getBitWidth(), 0);
1163f4a2713aSLionel Sambuc     APInt LHSKnownZero(IT->getBitWidth(), 0);
1164*0a6a1f1dSLionel Sambuc     computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, 0, &I);
1165f4a2713aSLionel Sambuc     if (LHSKnownZero != 0) {
1166f4a2713aSLionel Sambuc       APInt RHSKnownOne(IT->getBitWidth(), 0);
1167f4a2713aSLionel Sambuc       APInt RHSKnownZero(IT->getBitWidth(), 0);
1168*0a6a1f1dSLionel Sambuc       computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, 0, &I);
1169f4a2713aSLionel Sambuc 
1170f4a2713aSLionel Sambuc       // No bits in common -> bitwise or.
1171f4a2713aSLionel Sambuc       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
1172f4a2713aSLionel Sambuc         return BinaryOperator::CreateOr(LHS, RHS);
1173f4a2713aSLionel Sambuc     }
1174f4a2713aSLionel Sambuc   }
1175f4a2713aSLionel Sambuc 
1176*0a6a1f1dSLionel Sambuc   if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
1177*0a6a1f1dSLionel Sambuc     Value *X;
1178*0a6a1f1dSLionel Sambuc     if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
1179*0a6a1f1dSLionel Sambuc       return BinaryOperator::CreateSub(SubOne(CRHS), X);
1180f4a2713aSLionel Sambuc   }
1181f4a2713aSLionel Sambuc 
1182f4a2713aSLionel Sambuc   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1183f4a2713aSLionel Sambuc     // (X & FF00) + xx00  -> (X+xx00) & FF00
1184*0a6a1f1dSLionel Sambuc     Value *X;
1185*0a6a1f1dSLionel Sambuc     ConstantInt *C2;
1186f4a2713aSLionel Sambuc     if (LHS->hasOneUse() &&
1187f4a2713aSLionel Sambuc         match(LHS, m_And(m_Value(X), m_ConstantInt(C2))) &&
1188f4a2713aSLionel Sambuc         CRHS->getValue() == (CRHS->getValue() & C2->getValue())) {
1189f4a2713aSLionel Sambuc       // See if all bits from the first bit set in the Add RHS up are included
1190f4a2713aSLionel Sambuc       // in the mask.  First, get the rightmost bit.
1191f4a2713aSLionel Sambuc       const APInt &AddRHSV = CRHS->getValue();
1192f4a2713aSLionel Sambuc 
1193f4a2713aSLionel Sambuc       // Form a mask of all bits from the lowest bit added through the top.
1194f4a2713aSLionel Sambuc       APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
1195f4a2713aSLionel Sambuc 
1196f4a2713aSLionel Sambuc       // See if the and mask includes all of these bits.
1197f4a2713aSLionel Sambuc       APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
1198f4a2713aSLionel Sambuc 
1199f4a2713aSLionel Sambuc       if (AddRHSHighBits == AddRHSHighBitsAnd) {
1200f4a2713aSLionel Sambuc         // Okay, the xform is safe.  Insert the new add pronto.
1201f4a2713aSLionel Sambuc         Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
1202f4a2713aSLionel Sambuc         return BinaryOperator::CreateAnd(NewAdd, C2);
1203f4a2713aSLionel Sambuc       }
1204f4a2713aSLionel Sambuc     }
1205f4a2713aSLionel Sambuc 
1206f4a2713aSLionel Sambuc     // Try to fold constant add into select arguments.
1207f4a2713aSLionel Sambuc     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1208f4a2713aSLionel Sambuc       if (Instruction *R = FoldOpIntoSelect(I, SI))
1209f4a2713aSLionel Sambuc         return R;
1210f4a2713aSLionel Sambuc   }
1211f4a2713aSLionel Sambuc 
1212f4a2713aSLionel Sambuc   // add (select X 0 (sub n A)) A  -->  select X A n
1213f4a2713aSLionel Sambuc   {
1214f4a2713aSLionel Sambuc     SelectInst *SI = dyn_cast<SelectInst>(LHS);
1215f4a2713aSLionel Sambuc     Value *A = RHS;
1216f4a2713aSLionel Sambuc     if (!SI) {
1217f4a2713aSLionel Sambuc       SI = dyn_cast<SelectInst>(RHS);
1218f4a2713aSLionel Sambuc       A = LHS;
1219f4a2713aSLionel Sambuc     }
1220f4a2713aSLionel Sambuc     if (SI && SI->hasOneUse()) {
1221f4a2713aSLionel Sambuc       Value *TV = SI->getTrueValue();
1222f4a2713aSLionel Sambuc       Value *FV = SI->getFalseValue();
1223f4a2713aSLionel Sambuc       Value *N;
1224f4a2713aSLionel Sambuc 
1225f4a2713aSLionel Sambuc       // Can we fold the add into the argument of the select?
1226f4a2713aSLionel Sambuc       // We check both true and false select arguments for a matching subtract.
1227f4a2713aSLionel Sambuc       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
1228f4a2713aSLionel Sambuc         // Fold the add into the true select value.
1229f4a2713aSLionel Sambuc         return SelectInst::Create(SI->getCondition(), N, A);
1230f4a2713aSLionel Sambuc 
1231f4a2713aSLionel Sambuc       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
1232f4a2713aSLionel Sambuc         // Fold the add into the false select value.
1233f4a2713aSLionel Sambuc         return SelectInst::Create(SI->getCondition(), A, N);
1234f4a2713aSLionel Sambuc     }
1235f4a2713aSLionel Sambuc   }
1236f4a2713aSLionel Sambuc 
1237f4a2713aSLionel Sambuc   // Check for (add (sext x), y), see if we can merge this into an
1238f4a2713aSLionel Sambuc   // integer add followed by a sext.
1239f4a2713aSLionel Sambuc   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
1240f4a2713aSLionel Sambuc     // (add (sext x), cst) --> (sext (add x, cst'))
1241f4a2713aSLionel Sambuc     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
1242f4a2713aSLionel Sambuc       Constant *CI =
1243f4a2713aSLionel Sambuc         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
1244f4a2713aSLionel Sambuc       if (LHSConv->hasOneUse() &&
1245f4a2713aSLionel Sambuc           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
1246*0a6a1f1dSLionel Sambuc           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI, &I)) {
1247f4a2713aSLionel Sambuc         // Insert the new, smaller add.
1248f4a2713aSLionel Sambuc         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1249f4a2713aSLionel Sambuc                                               CI, "addconv");
1250f4a2713aSLionel Sambuc         return new SExtInst(NewAdd, I.getType());
1251f4a2713aSLionel Sambuc       }
1252f4a2713aSLionel Sambuc     }
1253f4a2713aSLionel Sambuc 
1254f4a2713aSLionel Sambuc     // (add (sext x), (sext y)) --> (sext (add int x, y))
1255f4a2713aSLionel Sambuc     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
1256f4a2713aSLionel Sambuc       // Only do this if x/y have the same type, if at last one of them has a
1257f4a2713aSLionel Sambuc       // single use (so we don't increase the number of sexts), and if the
1258f4a2713aSLionel Sambuc       // integer add will not overflow.
1259f4a2713aSLionel Sambuc       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
1260f4a2713aSLionel Sambuc           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1261f4a2713aSLionel Sambuc           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
1262*0a6a1f1dSLionel Sambuc                                    RHSConv->getOperand(0), &I)) {
1263f4a2713aSLionel Sambuc         // Insert the new integer add.
1264f4a2713aSLionel Sambuc         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1265f4a2713aSLionel Sambuc                                              RHSConv->getOperand(0), "addconv");
1266f4a2713aSLionel Sambuc         return new SExtInst(NewAdd, I.getType());
1267f4a2713aSLionel Sambuc       }
1268f4a2713aSLionel Sambuc     }
1269f4a2713aSLionel Sambuc   }
1270f4a2713aSLionel Sambuc 
1271*0a6a1f1dSLionel Sambuc   // (add (xor A, B) (and A, B)) --> (or A, B)
1272f4a2713aSLionel Sambuc   {
1273*0a6a1f1dSLionel Sambuc     Value *A = nullptr, *B = nullptr;
1274f4a2713aSLionel Sambuc     if (match(RHS, m_Xor(m_Value(A), m_Value(B))) &&
1275f4a2713aSLionel Sambuc         (match(LHS, m_And(m_Specific(A), m_Specific(B))) ||
1276f4a2713aSLionel Sambuc          match(LHS, m_And(m_Specific(B), m_Specific(A)))))
1277f4a2713aSLionel Sambuc       return BinaryOperator::CreateOr(A, B);
1278f4a2713aSLionel Sambuc 
1279f4a2713aSLionel Sambuc     if (match(LHS, m_Xor(m_Value(A), m_Value(B))) &&
1280f4a2713aSLionel Sambuc         (match(RHS, m_And(m_Specific(A), m_Specific(B))) ||
1281f4a2713aSLionel Sambuc          match(RHS, m_And(m_Specific(B), m_Specific(A)))))
1282f4a2713aSLionel Sambuc       return BinaryOperator::CreateOr(A, B);
1283f4a2713aSLionel Sambuc   }
1284f4a2713aSLionel Sambuc 
1285*0a6a1f1dSLionel Sambuc   // (add (or A, B) (and A, B)) --> (add A, B)
1286*0a6a1f1dSLionel Sambuc   {
1287*0a6a1f1dSLionel Sambuc     Value *A = nullptr, *B = nullptr;
1288*0a6a1f1dSLionel Sambuc     if (match(RHS, m_Or(m_Value(A), m_Value(B))) &&
1289*0a6a1f1dSLionel Sambuc         (match(LHS, m_And(m_Specific(A), m_Specific(B))) ||
1290*0a6a1f1dSLionel Sambuc          match(LHS, m_And(m_Specific(B), m_Specific(A))))) {
1291*0a6a1f1dSLionel Sambuc       auto *New = BinaryOperator::CreateAdd(A, B);
1292*0a6a1f1dSLionel Sambuc       New->setHasNoSignedWrap(I.hasNoSignedWrap());
1293*0a6a1f1dSLionel Sambuc       New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1294*0a6a1f1dSLionel Sambuc       return New;
1295*0a6a1f1dSLionel Sambuc     }
1296*0a6a1f1dSLionel Sambuc 
1297*0a6a1f1dSLionel Sambuc     if (match(LHS, m_Or(m_Value(A), m_Value(B))) &&
1298*0a6a1f1dSLionel Sambuc         (match(RHS, m_And(m_Specific(A), m_Specific(B))) ||
1299*0a6a1f1dSLionel Sambuc          match(RHS, m_And(m_Specific(B), m_Specific(A))))) {
1300*0a6a1f1dSLionel Sambuc       auto *New = BinaryOperator::CreateAdd(A, B);
1301*0a6a1f1dSLionel Sambuc       New->setHasNoSignedWrap(I.hasNoSignedWrap());
1302*0a6a1f1dSLionel Sambuc       New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
1303*0a6a1f1dSLionel Sambuc       return New;
1304*0a6a1f1dSLionel Sambuc     }
1305*0a6a1f1dSLionel Sambuc   }
1306*0a6a1f1dSLionel Sambuc 
1307*0a6a1f1dSLionel Sambuc   // TODO(jingyue): Consider WillNotOverflowSignedAdd and
1308*0a6a1f1dSLionel Sambuc   // WillNotOverflowUnsignedAdd to reduce the number of invocations of
1309*0a6a1f1dSLionel Sambuc   // computeKnownBits.
1310*0a6a1f1dSLionel Sambuc   if (!I.hasNoSignedWrap() && WillNotOverflowSignedAdd(LHS, RHS, &I)) {
1311*0a6a1f1dSLionel Sambuc     Changed = true;
1312*0a6a1f1dSLionel Sambuc     I.setHasNoSignedWrap(true);
1313*0a6a1f1dSLionel Sambuc   }
1314*0a6a1f1dSLionel Sambuc   if (!I.hasNoUnsignedWrap() &&
1315*0a6a1f1dSLionel Sambuc       computeOverflowForUnsignedAdd(LHS, RHS, &I) ==
1316*0a6a1f1dSLionel Sambuc           OverflowResult::NeverOverflows) {
1317*0a6a1f1dSLionel Sambuc     Changed = true;
1318*0a6a1f1dSLionel Sambuc     I.setHasNoUnsignedWrap(true);
1319*0a6a1f1dSLionel Sambuc   }
1320*0a6a1f1dSLionel Sambuc 
1321*0a6a1f1dSLionel Sambuc   return Changed ? &I : nullptr;
1322f4a2713aSLionel Sambuc }
1323f4a2713aSLionel Sambuc 
visitFAdd(BinaryOperator & I)1324f4a2713aSLionel Sambuc Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
1325f4a2713aSLionel Sambuc   bool Changed = SimplifyAssociativeOrCommutative(I);
1326f4a2713aSLionel Sambuc   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1327f4a2713aSLionel Sambuc 
1328*0a6a1f1dSLionel Sambuc   if (Value *V = SimplifyVectorOp(I))
1329*0a6a1f1dSLionel Sambuc     return ReplaceInstUsesWith(I, V);
1330*0a6a1f1dSLionel Sambuc 
1331*0a6a1f1dSLionel Sambuc   if (Value *V =
1332*0a6a1f1dSLionel Sambuc           SimplifyFAddInst(LHS, RHS, I.getFastMathFlags(), DL, TLI, DT, AC))
1333f4a2713aSLionel Sambuc     return ReplaceInstUsesWith(I, V);
1334f4a2713aSLionel Sambuc 
1335f4a2713aSLionel Sambuc   if (isa<Constant>(RHS)) {
1336f4a2713aSLionel Sambuc     if (isa<PHINode>(LHS))
1337f4a2713aSLionel Sambuc       if (Instruction *NV = FoldOpIntoPhi(I))
1338f4a2713aSLionel Sambuc         return NV;
1339f4a2713aSLionel Sambuc 
1340f4a2713aSLionel Sambuc     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1341f4a2713aSLionel Sambuc       if (Instruction *NV = FoldOpIntoSelect(I, SI))
1342f4a2713aSLionel Sambuc         return NV;
1343f4a2713aSLionel Sambuc   }
1344f4a2713aSLionel Sambuc 
1345f4a2713aSLionel Sambuc   // -A + B  -->  B - A
1346f4a2713aSLionel Sambuc   // -A + -B  -->  -(A + B)
1347*0a6a1f1dSLionel Sambuc   if (Value *LHSV = dyn_castFNegVal(LHS)) {
1348*0a6a1f1dSLionel Sambuc     Instruction *RI = BinaryOperator::CreateFSub(RHS, LHSV);
1349*0a6a1f1dSLionel Sambuc     RI->copyFastMathFlags(&I);
1350*0a6a1f1dSLionel Sambuc     return RI;
1351*0a6a1f1dSLionel Sambuc   }
1352f4a2713aSLionel Sambuc 
1353f4a2713aSLionel Sambuc   // A + -B  -->  A - B
1354f4a2713aSLionel Sambuc   if (!isa<Constant>(RHS))
1355*0a6a1f1dSLionel Sambuc     if (Value *V = dyn_castFNegVal(RHS)) {
1356*0a6a1f1dSLionel Sambuc       Instruction *RI = BinaryOperator::CreateFSub(LHS, V);
1357*0a6a1f1dSLionel Sambuc       RI->copyFastMathFlags(&I);
1358*0a6a1f1dSLionel Sambuc       return RI;
1359*0a6a1f1dSLionel Sambuc     }
1360f4a2713aSLionel Sambuc 
1361f4a2713aSLionel Sambuc   // Check for (fadd double (sitofp x), y), see if we can merge this into an
1362f4a2713aSLionel Sambuc   // integer add followed by a promotion.
1363f4a2713aSLionel Sambuc   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
1364f4a2713aSLionel Sambuc     // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
1365f4a2713aSLionel Sambuc     // ... if the constant fits in the integer value.  This is useful for things
1366f4a2713aSLionel Sambuc     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
1367f4a2713aSLionel Sambuc     // requires a constant pool load, and generally allows the add to be better
1368f4a2713aSLionel Sambuc     // instcombined.
1369f4a2713aSLionel Sambuc     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
1370f4a2713aSLionel Sambuc       Constant *CI =
1371f4a2713aSLionel Sambuc       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
1372f4a2713aSLionel Sambuc       if (LHSConv->hasOneUse() &&
1373f4a2713aSLionel Sambuc           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
1374*0a6a1f1dSLionel Sambuc           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI, &I)) {
1375f4a2713aSLionel Sambuc         // Insert the new integer add.
1376f4a2713aSLionel Sambuc         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1377f4a2713aSLionel Sambuc                                               CI, "addconv");
1378f4a2713aSLionel Sambuc         return new SIToFPInst(NewAdd, I.getType());
1379f4a2713aSLionel Sambuc       }
1380f4a2713aSLionel Sambuc     }
1381f4a2713aSLionel Sambuc 
1382f4a2713aSLionel Sambuc     // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
1383f4a2713aSLionel Sambuc     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
1384f4a2713aSLionel Sambuc       // Only do this if x/y have the same type, if at last one of them has a
1385f4a2713aSLionel Sambuc       // single use (so we don't increase the number of int->fp conversions),
1386f4a2713aSLionel Sambuc       // and if the integer add will not overflow.
1387f4a2713aSLionel Sambuc       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
1388f4a2713aSLionel Sambuc           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
1389f4a2713aSLionel Sambuc           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
1390*0a6a1f1dSLionel Sambuc                                    RHSConv->getOperand(0), &I)) {
1391f4a2713aSLionel Sambuc         // Insert the new integer add.
1392f4a2713aSLionel Sambuc         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
1393f4a2713aSLionel Sambuc                                               RHSConv->getOperand(0),"addconv");
1394f4a2713aSLionel Sambuc         return new SIToFPInst(NewAdd, I.getType());
1395f4a2713aSLionel Sambuc       }
1396f4a2713aSLionel Sambuc     }
1397f4a2713aSLionel Sambuc   }
1398f4a2713aSLionel Sambuc 
1399f4a2713aSLionel Sambuc   // select C, 0, B + select C, A, 0 -> select C, A, B
1400f4a2713aSLionel Sambuc   {
1401f4a2713aSLionel Sambuc     Value *A1, *B1, *C1, *A2, *B2, *C2;
1402f4a2713aSLionel Sambuc     if (match(LHS, m_Select(m_Value(C1), m_Value(A1), m_Value(B1))) &&
1403f4a2713aSLionel Sambuc         match(RHS, m_Select(m_Value(C2), m_Value(A2), m_Value(B2)))) {
1404f4a2713aSLionel Sambuc       if (C1 == C2) {
1405*0a6a1f1dSLionel Sambuc         Constant *Z1=nullptr, *Z2=nullptr;
1406f4a2713aSLionel Sambuc         Value *A, *B, *C=C1;
1407f4a2713aSLionel Sambuc         if (match(A1, m_AnyZero()) && match(B2, m_AnyZero())) {
1408f4a2713aSLionel Sambuc             Z1 = dyn_cast<Constant>(A1); A = A2;
1409f4a2713aSLionel Sambuc             Z2 = dyn_cast<Constant>(B2); B = B1;
1410f4a2713aSLionel Sambuc         } else if (match(B1, m_AnyZero()) && match(A2, m_AnyZero())) {
1411f4a2713aSLionel Sambuc             Z1 = dyn_cast<Constant>(B1); B = B2;
1412f4a2713aSLionel Sambuc             Z2 = dyn_cast<Constant>(A2); A = A1;
1413f4a2713aSLionel Sambuc         }
1414f4a2713aSLionel Sambuc 
1415f4a2713aSLionel Sambuc         if (Z1 && Z2 &&
1416f4a2713aSLionel Sambuc             (I.hasNoSignedZeros() ||
1417f4a2713aSLionel Sambuc              (Z1->isNegativeZeroValue() && Z2->isNegativeZeroValue()))) {
1418f4a2713aSLionel Sambuc           return SelectInst::Create(C, A, B);
1419f4a2713aSLionel Sambuc         }
1420f4a2713aSLionel Sambuc       }
1421f4a2713aSLionel Sambuc     }
1422f4a2713aSLionel Sambuc   }
1423f4a2713aSLionel Sambuc 
1424f4a2713aSLionel Sambuc   if (I.hasUnsafeAlgebra()) {
1425f4a2713aSLionel Sambuc     if (Value *V = FAddCombine(Builder).simplify(&I))
1426f4a2713aSLionel Sambuc       return ReplaceInstUsesWith(I, V);
1427f4a2713aSLionel Sambuc   }
1428f4a2713aSLionel Sambuc 
1429*0a6a1f1dSLionel Sambuc   return Changed ? &I : nullptr;
1430f4a2713aSLionel Sambuc }
1431f4a2713aSLionel Sambuc 
1432f4a2713aSLionel Sambuc 
1433f4a2713aSLionel Sambuc /// Optimize pointer differences into the same array into a size.  Consider:
1434f4a2713aSLionel Sambuc ///  &A[10] - &A[0]: we should compile this to "10".  LHS/RHS are the pointer
1435f4a2713aSLionel Sambuc /// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
1436f4a2713aSLionel Sambuc ///
OptimizePointerDifference(Value * LHS,Value * RHS,Type * Ty)1437f4a2713aSLionel Sambuc Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
1438f4a2713aSLionel Sambuc                                                Type *Ty) {
1439*0a6a1f1dSLionel Sambuc   assert(DL && "Must have target data info for this");
1440f4a2713aSLionel Sambuc 
1441f4a2713aSLionel Sambuc   // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
1442f4a2713aSLionel Sambuc   // this.
1443f4a2713aSLionel Sambuc   bool Swapped = false;
1444*0a6a1f1dSLionel Sambuc   GEPOperator *GEP1 = nullptr, *GEP2 = nullptr;
1445f4a2713aSLionel Sambuc 
1446f4a2713aSLionel Sambuc   // For now we require one side to be the base pointer "A" or a constant
1447f4a2713aSLionel Sambuc   // GEP derived from it.
1448f4a2713aSLionel Sambuc   if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1449f4a2713aSLionel Sambuc     // (gep X, ...) - X
1450f4a2713aSLionel Sambuc     if (LHSGEP->getOperand(0) == RHS) {
1451f4a2713aSLionel Sambuc       GEP1 = LHSGEP;
1452f4a2713aSLionel Sambuc       Swapped = false;
1453f4a2713aSLionel Sambuc     } else if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1454f4a2713aSLionel Sambuc       // (gep X, ...) - (gep X, ...)
1455f4a2713aSLionel Sambuc       if (LHSGEP->getOperand(0)->stripPointerCasts() ==
1456f4a2713aSLionel Sambuc             RHSGEP->getOperand(0)->stripPointerCasts()) {
1457f4a2713aSLionel Sambuc         GEP2 = RHSGEP;
1458f4a2713aSLionel Sambuc         GEP1 = LHSGEP;
1459f4a2713aSLionel Sambuc         Swapped = false;
1460f4a2713aSLionel Sambuc       }
1461f4a2713aSLionel Sambuc     }
1462f4a2713aSLionel Sambuc   }
1463f4a2713aSLionel Sambuc 
1464f4a2713aSLionel Sambuc   if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
1465f4a2713aSLionel Sambuc     // X - (gep X, ...)
1466f4a2713aSLionel Sambuc     if (RHSGEP->getOperand(0) == LHS) {
1467f4a2713aSLionel Sambuc       GEP1 = RHSGEP;
1468f4a2713aSLionel Sambuc       Swapped = true;
1469f4a2713aSLionel Sambuc     } else if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
1470f4a2713aSLionel Sambuc       // (gep X, ...) - (gep X, ...)
1471f4a2713aSLionel Sambuc       if (RHSGEP->getOperand(0)->stripPointerCasts() ==
1472f4a2713aSLionel Sambuc             LHSGEP->getOperand(0)->stripPointerCasts()) {
1473f4a2713aSLionel Sambuc         GEP2 = LHSGEP;
1474f4a2713aSLionel Sambuc         GEP1 = RHSGEP;
1475f4a2713aSLionel Sambuc         Swapped = true;
1476f4a2713aSLionel Sambuc       }
1477f4a2713aSLionel Sambuc     }
1478f4a2713aSLionel Sambuc   }
1479f4a2713aSLionel Sambuc 
1480f4a2713aSLionel Sambuc   // Avoid duplicating the arithmetic if GEP2 has non-constant indices and
1481f4a2713aSLionel Sambuc   // multiple users.
1482*0a6a1f1dSLionel Sambuc   if (!GEP1 ||
1483*0a6a1f1dSLionel Sambuc       (GEP2 && !GEP2->hasAllConstantIndices() && !GEP2->hasOneUse()))
1484*0a6a1f1dSLionel Sambuc     return nullptr;
1485f4a2713aSLionel Sambuc 
1486f4a2713aSLionel Sambuc   // Emit the offset of the GEP and an intptr_t.
1487f4a2713aSLionel Sambuc   Value *Result = EmitGEPOffset(GEP1);
1488f4a2713aSLionel Sambuc 
1489f4a2713aSLionel Sambuc   // If we had a constant expression GEP on the other side offsetting the
1490f4a2713aSLionel Sambuc   // pointer, subtract it from the offset we have.
1491f4a2713aSLionel Sambuc   if (GEP2) {
1492f4a2713aSLionel Sambuc     Value *Offset = EmitGEPOffset(GEP2);
1493f4a2713aSLionel Sambuc     Result = Builder->CreateSub(Result, Offset);
1494f4a2713aSLionel Sambuc   }
1495f4a2713aSLionel Sambuc 
1496f4a2713aSLionel Sambuc   // If we have p - gep(p, ...)  then we have to negate the result.
1497f4a2713aSLionel Sambuc   if (Swapped)
1498f4a2713aSLionel Sambuc     Result = Builder->CreateNeg(Result, "diff.neg");
1499f4a2713aSLionel Sambuc 
1500f4a2713aSLionel Sambuc   return Builder->CreateIntCast(Result, Ty, true);
1501f4a2713aSLionel Sambuc }
1502f4a2713aSLionel Sambuc 
visitSub(BinaryOperator & I)1503f4a2713aSLionel Sambuc Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1504f4a2713aSLionel Sambuc   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1505f4a2713aSLionel Sambuc 
1506*0a6a1f1dSLionel Sambuc   if (Value *V = SimplifyVectorOp(I))
1507*0a6a1f1dSLionel Sambuc     return ReplaceInstUsesWith(I, V);
1508*0a6a1f1dSLionel Sambuc 
1509f4a2713aSLionel Sambuc   if (Value *V = SimplifySubInst(Op0, Op1, I.hasNoSignedWrap(),
1510*0a6a1f1dSLionel Sambuc                                  I.hasNoUnsignedWrap(), DL, TLI, DT, AC))
1511f4a2713aSLionel Sambuc     return ReplaceInstUsesWith(I, V);
1512f4a2713aSLionel Sambuc 
1513f4a2713aSLionel Sambuc   // (A*B)-(A*C) -> A*(B-C) etc
1514f4a2713aSLionel Sambuc   if (Value *V = SimplifyUsingDistributiveLaws(I))
1515f4a2713aSLionel Sambuc     return ReplaceInstUsesWith(I, V);
1516f4a2713aSLionel Sambuc 
1517*0a6a1f1dSLionel Sambuc   // If this is a 'B = x-(-A)', change to B = x+A.
1518f4a2713aSLionel Sambuc   if (Value *V = dyn_castNegVal(Op1)) {
1519f4a2713aSLionel Sambuc     BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
1520*0a6a1f1dSLionel Sambuc 
1521*0a6a1f1dSLionel Sambuc     if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
1522*0a6a1f1dSLionel Sambuc       assert(BO->getOpcode() == Instruction::Sub &&
1523*0a6a1f1dSLionel Sambuc              "Expected a subtraction operator!");
1524*0a6a1f1dSLionel Sambuc       if (BO->hasNoSignedWrap() && I.hasNoSignedWrap())
1525*0a6a1f1dSLionel Sambuc         Res->setHasNoSignedWrap(true);
1526*0a6a1f1dSLionel Sambuc     } else {
1527*0a6a1f1dSLionel Sambuc       if (cast<Constant>(Op1)->isNotMinSignedValue() && I.hasNoSignedWrap())
1528*0a6a1f1dSLionel Sambuc         Res->setHasNoSignedWrap(true);
1529*0a6a1f1dSLionel Sambuc     }
1530*0a6a1f1dSLionel Sambuc 
1531f4a2713aSLionel Sambuc     return Res;
1532f4a2713aSLionel Sambuc   }
1533f4a2713aSLionel Sambuc 
1534f4a2713aSLionel Sambuc   if (I.getType()->isIntegerTy(1))
1535f4a2713aSLionel Sambuc     return BinaryOperator::CreateXor(Op0, Op1);
1536f4a2713aSLionel Sambuc 
1537f4a2713aSLionel Sambuc   // Replace (-1 - A) with (~A).
1538f4a2713aSLionel Sambuc   if (match(Op0, m_AllOnes()))
1539f4a2713aSLionel Sambuc     return BinaryOperator::CreateNot(Op1);
1540f4a2713aSLionel Sambuc 
1541*0a6a1f1dSLionel Sambuc   if (Constant *C = dyn_cast<Constant>(Op0)) {
1542f4a2713aSLionel Sambuc     // C - ~X == X + (1+C)
1543*0a6a1f1dSLionel Sambuc     Value *X = nullptr;
1544f4a2713aSLionel Sambuc     if (match(Op1, m_Not(m_Value(X))))
1545f4a2713aSLionel Sambuc       return BinaryOperator::CreateAdd(X, AddOne(C));
1546f4a2713aSLionel Sambuc 
1547*0a6a1f1dSLionel Sambuc     // Try to fold constant sub into select arguments.
1548*0a6a1f1dSLionel Sambuc     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1549*0a6a1f1dSLionel Sambuc       if (Instruction *R = FoldOpIntoSelect(I, SI))
1550*0a6a1f1dSLionel Sambuc         return R;
1551*0a6a1f1dSLionel Sambuc 
1552*0a6a1f1dSLionel Sambuc     // C-(X+C2) --> (C-C2)-X
1553*0a6a1f1dSLionel Sambuc     Constant *C2;
1554*0a6a1f1dSLionel Sambuc     if (match(Op1, m_Add(m_Value(X), m_Constant(C2))))
1555*0a6a1f1dSLionel Sambuc       return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
1556*0a6a1f1dSLionel Sambuc 
1557*0a6a1f1dSLionel Sambuc     if (SimplifyDemandedInstructionBits(I))
1558*0a6a1f1dSLionel Sambuc       return &I;
1559*0a6a1f1dSLionel Sambuc 
1560*0a6a1f1dSLionel Sambuc     // Fold (sub 0, (zext bool to B)) --> (sext bool to B)
1561*0a6a1f1dSLionel Sambuc     if (C->isNullValue() && match(Op1, m_ZExt(m_Value(X))))
1562*0a6a1f1dSLionel Sambuc       if (X->getType()->getScalarType()->isIntegerTy(1))
1563*0a6a1f1dSLionel Sambuc         return CastInst::CreateSExtOrBitCast(X, Op1->getType());
1564*0a6a1f1dSLionel Sambuc 
1565*0a6a1f1dSLionel Sambuc     // Fold (sub 0, (sext bool to B)) --> (zext bool to B)
1566*0a6a1f1dSLionel Sambuc     if (C->isNullValue() && match(Op1, m_SExt(m_Value(X))))
1567*0a6a1f1dSLionel Sambuc       if (X->getType()->getScalarType()->isIntegerTy(1))
1568*0a6a1f1dSLionel Sambuc         return CastInst::CreateZExtOrBitCast(X, Op1->getType());
1569*0a6a1f1dSLionel Sambuc   }
1570*0a6a1f1dSLionel Sambuc 
1571*0a6a1f1dSLionel Sambuc   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1572f4a2713aSLionel Sambuc     // -(X >>u 31) -> (X >>s 31)
1573f4a2713aSLionel Sambuc     // -(X >>s 31) -> (X >>u 31)
1574f4a2713aSLionel Sambuc     if (C->isZero()) {
1575*0a6a1f1dSLionel Sambuc       Value *X;
1576*0a6a1f1dSLionel Sambuc       ConstantInt *CI;
1577f4a2713aSLionel Sambuc       if (match(Op1, m_LShr(m_Value(X), m_ConstantInt(CI))) &&
1578f4a2713aSLionel Sambuc           // Verify we are shifting out everything but the sign bit.
1579f4a2713aSLionel Sambuc           CI->getValue() == I.getType()->getPrimitiveSizeInBits() - 1)
1580f4a2713aSLionel Sambuc         return BinaryOperator::CreateAShr(X, CI);
1581f4a2713aSLionel Sambuc 
1582f4a2713aSLionel Sambuc       if (match(Op1, m_AShr(m_Value(X), m_ConstantInt(CI))) &&
1583f4a2713aSLionel Sambuc           // Verify we are shifting out everything but the sign bit.
1584f4a2713aSLionel Sambuc           CI->getValue() == I.getType()->getPrimitiveSizeInBits() - 1)
1585f4a2713aSLionel Sambuc         return BinaryOperator::CreateLShr(X, CI);
1586f4a2713aSLionel Sambuc     }
1587f4a2713aSLionel Sambuc   }
1588f4a2713aSLionel Sambuc 
1589f4a2713aSLionel Sambuc 
1590*0a6a1f1dSLionel Sambuc   {
1591*0a6a1f1dSLionel Sambuc     Value *Y;
1592f4a2713aSLionel Sambuc     // X-(X+Y) == -Y    X-(Y+X) == -Y
1593f4a2713aSLionel Sambuc     if (match(Op1, m_Add(m_Specific(Op0), m_Value(Y))) ||
1594f4a2713aSLionel Sambuc         match(Op1, m_Add(m_Value(Y), m_Specific(Op0))))
1595f4a2713aSLionel Sambuc       return BinaryOperator::CreateNeg(Y);
1596f4a2713aSLionel Sambuc 
1597f4a2713aSLionel Sambuc     // (X-Y)-X == -Y
1598f4a2713aSLionel Sambuc     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
1599f4a2713aSLionel Sambuc       return BinaryOperator::CreateNeg(Y);
1600f4a2713aSLionel Sambuc   }
1601f4a2713aSLionel Sambuc 
1602*0a6a1f1dSLionel Sambuc   // (sub (or A, B) (xor A, B)) --> (and A, B)
1603*0a6a1f1dSLionel Sambuc   {
1604*0a6a1f1dSLionel Sambuc     Value *A = nullptr, *B = nullptr;
1605*0a6a1f1dSLionel Sambuc     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
1606*0a6a1f1dSLionel Sambuc         (match(Op0, m_Or(m_Specific(A), m_Specific(B))) ||
1607*0a6a1f1dSLionel Sambuc          match(Op0, m_Or(m_Specific(B), m_Specific(A)))))
1608*0a6a1f1dSLionel Sambuc       return BinaryOperator::CreateAnd(A, B);
1609*0a6a1f1dSLionel Sambuc   }
1610*0a6a1f1dSLionel Sambuc 
1611*0a6a1f1dSLionel Sambuc   if (Op0->hasOneUse()) {
1612*0a6a1f1dSLionel Sambuc     Value *Y = nullptr;
1613*0a6a1f1dSLionel Sambuc     // ((X | Y) - X) --> (~X & Y)
1614*0a6a1f1dSLionel Sambuc     if (match(Op0, m_Or(m_Value(Y), m_Specific(Op1))) ||
1615*0a6a1f1dSLionel Sambuc         match(Op0, m_Or(m_Specific(Op1), m_Value(Y))))
1616*0a6a1f1dSLionel Sambuc       return BinaryOperator::CreateAnd(
1617*0a6a1f1dSLionel Sambuc           Y, Builder->CreateNot(Op1, Op1->getName() + ".not"));
1618*0a6a1f1dSLionel Sambuc   }
1619*0a6a1f1dSLionel Sambuc 
1620f4a2713aSLionel Sambuc   if (Op1->hasOneUse()) {
1621*0a6a1f1dSLionel Sambuc     Value *X = nullptr, *Y = nullptr, *Z = nullptr;
1622*0a6a1f1dSLionel Sambuc     Constant *C = nullptr;
1623*0a6a1f1dSLionel Sambuc     Constant *CI = nullptr;
1624f4a2713aSLionel Sambuc 
1625f4a2713aSLionel Sambuc     // (X - (Y - Z))  -->  (X + (Z - Y)).
1626f4a2713aSLionel Sambuc     if (match(Op1, m_Sub(m_Value(Y), m_Value(Z))))
1627f4a2713aSLionel Sambuc       return BinaryOperator::CreateAdd(Op0,
1628f4a2713aSLionel Sambuc                                       Builder->CreateSub(Z, Y, Op1->getName()));
1629f4a2713aSLionel Sambuc 
1630f4a2713aSLionel Sambuc     // (X - (X & Y))   -->   (X & ~Y)
1631f4a2713aSLionel Sambuc     //
1632f4a2713aSLionel Sambuc     if (match(Op1, m_And(m_Value(Y), m_Specific(Op0))) ||
1633f4a2713aSLionel Sambuc         match(Op1, m_And(m_Specific(Op0), m_Value(Y))))
1634f4a2713aSLionel Sambuc       return BinaryOperator::CreateAnd(Op0,
1635f4a2713aSLionel Sambuc                                   Builder->CreateNot(Y, Y->getName() + ".not"));
1636f4a2713aSLionel Sambuc 
1637*0a6a1f1dSLionel Sambuc     // 0 - (X sdiv C)  -> (X sdiv -C)  provided the negation doesn't overflow.
1638*0a6a1f1dSLionel Sambuc     if (match(Op1, m_SDiv(m_Value(X), m_Constant(C))) && match(Op0, m_Zero()) &&
1639*0a6a1f1dSLionel Sambuc         C->isNotMinSignedValue() && !C->isOneValue())
1640f4a2713aSLionel Sambuc       return BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(C));
1641f4a2713aSLionel Sambuc 
1642f4a2713aSLionel Sambuc     // 0 - (X << Y)  -> (-X << Y)   when X is freely negatable.
1643f4a2713aSLionel Sambuc     if (match(Op1, m_Shl(m_Value(X), m_Value(Y))) && match(Op0, m_Zero()))
1644f4a2713aSLionel Sambuc       if (Value *XNeg = dyn_castNegVal(X))
1645f4a2713aSLionel Sambuc         return BinaryOperator::CreateShl(XNeg, Y);
1646f4a2713aSLionel Sambuc 
1647f4a2713aSLionel Sambuc     // X - A*-B -> X + A*B
1648f4a2713aSLionel Sambuc     // X - -A*B -> X + A*B
1649f4a2713aSLionel Sambuc     Value *A, *B;
1650f4a2713aSLionel Sambuc     if (match(Op1, m_Mul(m_Value(A), m_Neg(m_Value(B)))) ||
1651f4a2713aSLionel Sambuc         match(Op1, m_Mul(m_Neg(m_Value(A)), m_Value(B))))
1652f4a2713aSLionel Sambuc       return BinaryOperator::CreateAdd(Op0, Builder->CreateMul(A, B));
1653f4a2713aSLionel Sambuc 
1654f4a2713aSLionel Sambuc     // X - A*CI -> X + A*-CI
1655f4a2713aSLionel Sambuc     // X - CI*A -> X + A*-CI
1656*0a6a1f1dSLionel Sambuc     if (match(Op1, m_Mul(m_Value(A), m_Constant(CI))) ||
1657*0a6a1f1dSLionel Sambuc         match(Op1, m_Mul(m_Constant(CI), m_Value(A)))) {
1658f4a2713aSLionel Sambuc       Value *NewMul = Builder->CreateMul(A, ConstantExpr::getNeg(CI));
1659f4a2713aSLionel Sambuc       return BinaryOperator::CreateAdd(Op0, NewMul);
1660f4a2713aSLionel Sambuc     }
1661f4a2713aSLionel Sambuc   }
1662f4a2713aSLionel Sambuc 
1663f4a2713aSLionel Sambuc   // Optimize pointer differences into the same array into a size.  Consider:
1664f4a2713aSLionel Sambuc   //  &A[10] - &A[0]: we should compile this to "10".
1665*0a6a1f1dSLionel Sambuc   if (DL) {
1666f4a2713aSLionel Sambuc     Value *LHSOp, *RHSOp;
1667f4a2713aSLionel Sambuc     if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
1668f4a2713aSLionel Sambuc         match(Op1, m_PtrToInt(m_Value(RHSOp))))
1669f4a2713aSLionel Sambuc       if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1670f4a2713aSLionel Sambuc         return ReplaceInstUsesWith(I, Res);
1671f4a2713aSLionel Sambuc 
1672f4a2713aSLionel Sambuc     // trunc(p)-trunc(q) -> trunc(p-q)
1673f4a2713aSLionel Sambuc     if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
1674f4a2713aSLionel Sambuc         match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
1675f4a2713aSLionel Sambuc       if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
1676f4a2713aSLionel Sambuc         return ReplaceInstUsesWith(I, Res);
1677f4a2713aSLionel Sambuc       }
1678f4a2713aSLionel Sambuc 
1679*0a6a1f1dSLionel Sambuc   bool Changed = false;
1680*0a6a1f1dSLionel Sambuc   if (!I.hasNoSignedWrap() && WillNotOverflowSignedSub(Op0, Op1, &I)) {
1681*0a6a1f1dSLionel Sambuc     Changed = true;
1682*0a6a1f1dSLionel Sambuc     I.setHasNoSignedWrap(true);
1683*0a6a1f1dSLionel Sambuc   }
1684*0a6a1f1dSLionel Sambuc   if (!I.hasNoUnsignedWrap() && WillNotOverflowUnsignedSub(Op0, Op1, &I)) {
1685*0a6a1f1dSLionel Sambuc     Changed = true;
1686*0a6a1f1dSLionel Sambuc     I.setHasNoUnsignedWrap(true);
1687*0a6a1f1dSLionel Sambuc   }
1688*0a6a1f1dSLionel Sambuc 
1689*0a6a1f1dSLionel Sambuc   return Changed ? &I : nullptr;
1690f4a2713aSLionel Sambuc }
1691f4a2713aSLionel Sambuc 
visitFSub(BinaryOperator & I)1692f4a2713aSLionel Sambuc Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
1693f4a2713aSLionel Sambuc   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1694f4a2713aSLionel Sambuc 
1695*0a6a1f1dSLionel Sambuc   if (Value *V = SimplifyVectorOp(I))
1696f4a2713aSLionel Sambuc     return ReplaceInstUsesWith(I, V);
1697f4a2713aSLionel Sambuc 
1698*0a6a1f1dSLionel Sambuc   if (Value *V =
1699*0a6a1f1dSLionel Sambuc           SimplifyFSubInst(Op0, Op1, I.getFastMathFlags(), DL, TLI, DT, AC))
1700*0a6a1f1dSLionel Sambuc     return ReplaceInstUsesWith(I, V);
1701*0a6a1f1dSLionel Sambuc 
1702*0a6a1f1dSLionel Sambuc   // fsub nsz 0, X ==> fsub nsz -0.0, X
1703*0a6a1f1dSLionel Sambuc   if (I.getFastMathFlags().noSignedZeros() && match(Op0, m_Zero())) {
1704*0a6a1f1dSLionel Sambuc     // Subtraction from -0.0 is the canonical form of fneg.
1705*0a6a1f1dSLionel Sambuc     Instruction *NewI = BinaryOperator::CreateFNeg(Op1);
1706*0a6a1f1dSLionel Sambuc     NewI->copyFastMathFlags(&I);
1707*0a6a1f1dSLionel Sambuc     return NewI;
1708*0a6a1f1dSLionel Sambuc   }
1709*0a6a1f1dSLionel Sambuc 
1710f4a2713aSLionel Sambuc   if (isa<Constant>(Op0))
1711f4a2713aSLionel Sambuc     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1712f4a2713aSLionel Sambuc       if (Instruction *NV = FoldOpIntoSelect(I, SI))
1713f4a2713aSLionel Sambuc         return NV;
1714f4a2713aSLionel Sambuc 
1715f4a2713aSLionel Sambuc   // If this is a 'B = x-(-A)', change to B = x+A, potentially looking
1716f4a2713aSLionel Sambuc   // through FP extensions/truncations along the way.
1717f4a2713aSLionel Sambuc   if (Value *V = dyn_castFNegVal(Op1)) {
1718f4a2713aSLionel Sambuc     Instruction *NewI = BinaryOperator::CreateFAdd(Op0, V);
1719f4a2713aSLionel Sambuc     NewI->copyFastMathFlags(&I);
1720f4a2713aSLionel Sambuc     return NewI;
1721f4a2713aSLionel Sambuc   }
1722f4a2713aSLionel Sambuc   if (FPTruncInst *FPTI = dyn_cast<FPTruncInst>(Op1)) {
1723f4a2713aSLionel Sambuc     if (Value *V = dyn_castFNegVal(FPTI->getOperand(0))) {
1724f4a2713aSLionel Sambuc       Value *NewTrunc = Builder->CreateFPTrunc(V, I.getType());
1725f4a2713aSLionel Sambuc       Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewTrunc);
1726f4a2713aSLionel Sambuc       NewI->copyFastMathFlags(&I);
1727f4a2713aSLionel Sambuc       return NewI;
1728f4a2713aSLionel Sambuc     }
1729f4a2713aSLionel Sambuc   } else if (FPExtInst *FPEI = dyn_cast<FPExtInst>(Op1)) {
1730f4a2713aSLionel Sambuc     if (Value *V = dyn_castFNegVal(FPEI->getOperand(0))) {
1731f4a2713aSLionel Sambuc       Value *NewExt = Builder->CreateFPExt(V, I.getType());
1732f4a2713aSLionel Sambuc       Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewExt);
1733f4a2713aSLionel Sambuc       NewI->copyFastMathFlags(&I);
1734f4a2713aSLionel Sambuc       return NewI;
1735f4a2713aSLionel Sambuc     }
1736f4a2713aSLionel Sambuc   }
1737f4a2713aSLionel Sambuc 
1738f4a2713aSLionel Sambuc   if (I.hasUnsafeAlgebra()) {
1739f4a2713aSLionel Sambuc     if (Value *V = FAddCombine(Builder).simplify(&I))
1740f4a2713aSLionel Sambuc       return ReplaceInstUsesWith(I, V);
1741f4a2713aSLionel Sambuc   }
1742f4a2713aSLionel Sambuc 
1743*0a6a1f1dSLionel Sambuc   return nullptr;
1744f4a2713aSLionel Sambuc }
1745