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