LLVM API Documentation

InstCombineAddSub.cpp
Go to the documentation of this file.
00001 //===- InstCombineAddSub.cpp ----------------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the visit functions for add, fadd, sub, and fsub.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "InstCombine.h"
00015 #include "llvm/ADT/STLExtras.h"
00016 #include "llvm/Analysis/InstructionSimplify.h"
00017 #include "llvm/IR/DataLayout.h"
00018 #include "llvm/IR/GetElementPtrTypeIterator.h"
00019 #include "llvm/IR/PatternMatch.h"
00020 using namespace llvm;
00021 using namespace PatternMatch;
00022 
00023 namespace {
00024 
00025   /// Class representing coefficient of floating-point addend.
00026   /// This class needs to be highly efficient, which is especially true for
00027   /// the constructor. As of I write this comment, the cost of the default
00028   /// constructor is merely 4-byte-store-zero (Assuming compiler is able to
00029   /// perform write-merging).
00030   ///
00031   class FAddendCoef {
00032   public:
00033     // The constructor has to initialize a APFloat, which is uncessary for
00034     // most addends which have coefficient either 1 or -1. So, the constructor
00035     // is expensive. In order to avoid the cost of the constructor, we should
00036     // reuse some instances whenever possible. The pre-created instances
00037     // FAddCombine::Add[0-5] embodies this idea.
00038     //
00039     FAddendCoef() : IsFp(false), BufHasFpVal(false), IntVal(0) {}
00040     ~FAddendCoef();
00041 
00042     void set(short C) {
00043       assert(!insaneIntVal(C) && "Insane coefficient");
00044       IsFp = false; IntVal = C;
00045     }
00046 
00047     void set(const APFloat& C);
00048 
00049     void negate();
00050 
00051     bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); }
00052     Value *getValue(Type *) const;
00053 
00054     // If possible, don't define operator+/operator- etc because these
00055     // operators inevitably call FAddendCoef's constructor which is not cheap.
00056     void operator=(const FAddendCoef &A);
00057     void operator+=(const FAddendCoef &A);
00058     void operator-=(const FAddendCoef &A);
00059     void operator*=(const FAddendCoef &S);
00060 
00061     bool isOne() const { return isInt() && IntVal == 1; }
00062     bool isTwo() const { return isInt() && IntVal == 2; }
00063     bool isMinusOne() const { return isInt() && IntVal == -1; }
00064     bool isMinusTwo() const { return isInt() && IntVal == -2; }
00065 
00066   private:
00067     bool insaneIntVal(int V) { return V > 4 || V < -4; }
00068     APFloat *getFpValPtr(void)
00069       { return reinterpret_cast<APFloat*>(&FpValBuf.buffer[0]); }
00070     const APFloat *getFpValPtr(void) const
00071       { return reinterpret_cast<const APFloat*>(&FpValBuf.buffer[0]); }
00072 
00073     const APFloat &getFpVal(void) const {
00074       assert(IsFp && BufHasFpVal && "Incorret state");
00075       return *getFpValPtr();
00076     }
00077 
00078     APFloat &getFpVal(void) {
00079       assert(IsFp && BufHasFpVal && "Incorret state");
00080       return *getFpValPtr();
00081     }
00082 
00083     bool isInt() const { return !IsFp; }
00084 
00085     // If the coefficient is represented by an integer, promote it to a
00086     // floating point.
00087     void convertToFpType(const fltSemantics &Sem);
00088 
00089     // Construct an APFloat from a signed integer.
00090     // TODO: We should get rid of this function when APFloat can be constructed
00091     //       from an *SIGNED* integer.
00092     APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val);
00093   private:
00094 
00095     bool IsFp;
00096 
00097     // True iff FpValBuf contains an instance of APFloat.
00098     bool BufHasFpVal;
00099 
00100     // The integer coefficient of an individual addend is either 1 or -1,
00101     // and we try to simplify at most 4 addends from neighboring at most
00102     // two instructions. So the range of <IntVal> falls in [-4, 4]. APInt
00103     // is overkill of this end.
00104     short IntVal;
00105 
00106     AlignedCharArrayUnion<APFloat> FpValBuf;
00107   };
00108 
00109   /// FAddend is used to represent floating-point addend. An addend is
00110   /// represented as <C, V>, where the V is a symbolic value, and C is a
00111   /// constant coefficient. A constant addend is represented as <C, 0>.
00112   ///
00113   class FAddend {
00114   public:
00115     FAddend() { Val = 0; }
00116 
00117     Value *getSymVal (void) const { return Val; }
00118     const FAddendCoef &getCoef(void) const { return Coeff; }
00119 
00120     bool isConstant() const { return Val == 0; }
00121     bool isZero() const { return Coeff.isZero(); }
00122 
00123     void set(short Coefficient, Value *V) { Coeff.set(Coefficient), Val = V; }
00124     void set(const APFloat& Coefficient, Value *V)
00125       { Coeff.set(Coefficient); Val = V; }
00126     void set(const ConstantFP* Coefficient, Value *V)
00127       { Coeff.set(Coefficient->getValueAPF()); Val = V; }
00128 
00129     void negate() { Coeff.negate(); }
00130 
00131     /// Drill down the U-D chain one step to find the definition of V, and
00132     /// try to break the definition into one or two addends.
00133     static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1);
00134 
00135     /// Similar to FAddend::drillDownOneStep() except that the value being
00136     /// splitted is the addend itself.
00137     unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const;
00138 
00139     void operator+=(const FAddend &T) {
00140       assert((Val == T.Val) && "Symbolic-values disagree");
00141       Coeff += T.Coeff;
00142     }
00143 
00144   private:
00145     void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; }
00146 
00147     // This addend has the value of "Coeff * Val".
00148     Value *Val;
00149     FAddendCoef Coeff;
00150   };
00151 
00152   /// FAddCombine is the class for optimizing an unsafe fadd/fsub along
00153   /// with its neighboring at most two instructions.
00154   ///
00155   class FAddCombine {
00156   public:
00157     FAddCombine(InstCombiner::BuilderTy *B) : Builder(B), Instr(0) {}
00158     Value *simplify(Instruction *FAdd);
00159 
00160   private:
00161     typedef SmallVector<const FAddend*, 4> AddendVect;
00162 
00163     Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota);
00164 
00165     Value *performFactorization(Instruction *I);
00166 
00167     /// Convert given addend to a Value
00168     Value *createAddendVal(const FAddend &A, bool& NeedNeg);
00169 
00170     /// Return the number of instructions needed to emit the N-ary addition.
00171     unsigned calcInstrNumber(const AddendVect& Vect);
00172     Value *createFSub(Value *Opnd0, Value *Opnd1);
00173     Value *createFAdd(Value *Opnd0, Value *Opnd1);
00174     Value *createFMul(Value *Opnd0, Value *Opnd1);
00175     Value *createFDiv(Value *Opnd0, Value *Opnd1);
00176     Value *createFNeg(Value *V);
00177     Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota);
00178     void createInstPostProc(Instruction *NewInst, bool NoNumber = false);
00179 
00180     InstCombiner::BuilderTy *Builder;
00181     Instruction *Instr;
00182 
00183   private:
00184      // Debugging stuff are clustered here.
00185     #ifndef NDEBUG
00186       unsigned CreateInstrNum;
00187       void initCreateInstNum() { CreateInstrNum = 0; }
00188       void incCreateInstNum() { CreateInstrNum++; }
00189     #else
00190       void initCreateInstNum() {}
00191       void incCreateInstNum() {}
00192     #endif
00193   };
00194 }
00195 
00196 //===----------------------------------------------------------------------===//
00197 //
00198 // Implementation of
00199 //    {FAddendCoef, FAddend, FAddition, FAddCombine}.
00200 //
00201 //===----------------------------------------------------------------------===//
00202 FAddendCoef::~FAddendCoef() {
00203   if (BufHasFpVal)
00204     getFpValPtr()->~APFloat();
00205 }
00206 
00207 void FAddendCoef::set(const APFloat& C) {
00208   APFloat *P = getFpValPtr();
00209 
00210   if (isInt()) {
00211     // As the buffer is meanless byte stream, we cannot call
00212     // APFloat::operator=().
00213     new(P) APFloat(C);
00214   } else
00215     *P = C;
00216 
00217   IsFp = BufHasFpVal = true;
00218 }
00219 
00220 void FAddendCoef::convertToFpType(const fltSemantics &Sem) {
00221   if (!isInt())
00222     return;
00223 
00224   APFloat *P = getFpValPtr();
00225   if (IntVal > 0)
00226     new(P) APFloat(Sem, IntVal);
00227   else {
00228     new(P) APFloat(Sem, 0 - IntVal);
00229     P->changeSign();
00230   }
00231   IsFp = BufHasFpVal = true;
00232 }
00233 
00234 APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) {
00235   if (Val >= 0)
00236     return APFloat(Sem, Val);
00237 
00238   APFloat T(Sem, 0 - Val);
00239   T.changeSign();
00240 
00241   return T;
00242 }
00243 
00244 void FAddendCoef::operator=(const FAddendCoef &That) {
00245   if (That.isInt())
00246     set(That.IntVal);
00247   else
00248     set(That.getFpVal());
00249 }
00250 
00251 void FAddendCoef::operator+=(const FAddendCoef &That) {
00252   enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
00253   if (isInt() == That.isInt()) {
00254     if (isInt())
00255       IntVal += That.IntVal;
00256     else
00257       getFpVal().add(That.getFpVal(), RndMode);
00258     return;
00259   }
00260 
00261   if (isInt()) {
00262     const APFloat &T = That.getFpVal();
00263     convertToFpType(T.getSemantics());
00264     getFpVal().add(T, RndMode);
00265     return;
00266   }
00267 
00268   APFloat &T = getFpVal();
00269   T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode);
00270 }
00271 
00272 void FAddendCoef::operator-=(const FAddendCoef &That) {
00273   enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven;
00274   if (isInt() == That.isInt()) {
00275     if (isInt())
00276       IntVal -= That.IntVal;
00277     else
00278       getFpVal().subtract(That.getFpVal(), RndMode);
00279     return;
00280   }
00281 
00282   if (isInt()) {
00283     const APFloat &T = That.getFpVal();
00284     convertToFpType(T.getSemantics());
00285     getFpVal().subtract(T, RndMode);
00286     return;
00287   }
00288 
00289   APFloat &T = getFpVal();
00290   T.subtract(createAPFloatFromInt(T.getSemantics(), IntVal), RndMode);
00291 }
00292 
00293 void FAddendCoef::operator*=(const FAddendCoef &That) {
00294   if (That.isOne())
00295     return;
00296 
00297   if (That.isMinusOne()) {
00298     negate();
00299     return;
00300   }
00301 
00302   if (isInt() && That.isInt()) {
00303     int Res = IntVal * (int)That.IntVal;
00304     assert(!insaneIntVal(Res) && "Insane int value");
00305     IntVal = Res;
00306     return;
00307   }
00308 
00309   const fltSemantics &Semantic =
00310     isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics();
00311 
00312   if (isInt())
00313     convertToFpType(Semantic);
00314   APFloat &F0 = getFpVal();
00315 
00316   if (That.isInt())
00317     F0.multiply(createAPFloatFromInt(Semantic, That.IntVal),
00318                 APFloat::rmNearestTiesToEven);
00319   else
00320     F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven);
00321 
00322   return;
00323 }
00324 
00325 void FAddendCoef::negate() {
00326   if (isInt())
00327     IntVal = 0 - IntVal;
00328   else
00329     getFpVal().changeSign();
00330 }
00331 
00332 Value *FAddendCoef::getValue(Type *Ty) const {
00333   return isInt() ?
00334     ConstantFP::get(Ty, float(IntVal)) :
00335     ConstantFP::get(Ty->getContext(), getFpVal());
00336 }
00337 
00338 // The definition of <Val>     Addends
00339 // =========================================
00340 //  A + B                     <1, A>, <1,B>
00341 //  A - B                     <1, A>, <1,B>
00342 //  0 - B                     <-1, B>
00343 //  C * A,                    <C, A>
00344 //  A + C                     <1, A> <C, NULL>
00345 //  0 +/- 0                   <0, NULL> (corner case)
00346 //
00347 // Legend: A and B are not constant, C is constant
00348 //
00349 unsigned FAddend::drillValueDownOneStep
00350   (Value *Val, FAddend &Addend0, FAddend &Addend1) {
00351   Instruction *I = 0;
00352   if (Val == 0 || !(I = dyn_cast<Instruction>(Val)))
00353     return 0;
00354 
00355   unsigned Opcode = I->getOpcode();
00356 
00357   if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) {
00358     ConstantFP *C0, *C1;
00359     Value *Opnd0 = I->getOperand(0);
00360     Value *Opnd1 = I->getOperand(1);
00361     if ((C0 = dyn_cast<ConstantFP>(Opnd0)) && C0->isZero())
00362       Opnd0 = 0;
00363 
00364     if ((C1 = dyn_cast<ConstantFP>(Opnd1)) && C1->isZero())
00365       Opnd1 = 0;
00366 
00367     if (Opnd0) {
00368       if (!C0)
00369         Addend0.set(1, Opnd0);
00370       else
00371         Addend0.set(C0, 0);
00372     }
00373 
00374     if (Opnd1) {
00375       FAddend &Addend = Opnd0 ? Addend1 : Addend0;
00376       if (!C1)
00377         Addend.set(1, Opnd1);
00378       else
00379         Addend.set(C1, 0);
00380       if (Opcode == Instruction::FSub)
00381         Addend.negate();
00382     }
00383 
00384     if (Opnd0 || Opnd1)
00385       return Opnd0 && Opnd1 ? 2 : 1;
00386 
00387     // Both operands are zero. Weird!
00388     Addend0.set(APFloat(C0->getValueAPF().getSemantics()), 0);
00389     return 1;
00390   }
00391 
00392   if (I->getOpcode() == Instruction::FMul) {
00393     Value *V0 = I->getOperand(0);
00394     Value *V1 = I->getOperand(1);
00395     if (ConstantFP *C = dyn_cast<ConstantFP>(V0)) {
00396       Addend0.set(C, V1);
00397       return 1;
00398     }
00399 
00400     if (ConstantFP *C = dyn_cast<ConstantFP>(V1)) {
00401       Addend0.set(C, V0);
00402       return 1;
00403     }
00404   }
00405 
00406   return 0;
00407 }
00408 
00409 // Try to break *this* addend into two addends. e.g. Suppose this addend is
00410 // <2.3, V>, and V = X + Y, by calling this function, we obtain two addends,
00411 // i.e. <2.3, X> and <2.3, Y>.
00412 //
00413 unsigned FAddend::drillAddendDownOneStep
00414   (FAddend &Addend0, FAddend &Addend1) const {
00415   if (isConstant())
00416     return 0;
00417 
00418   unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1);
00419   if (!BreakNum || Coeff.isOne())
00420     return BreakNum;
00421 
00422   Addend0.Scale(Coeff);
00423 
00424   if (BreakNum == 2)
00425     Addend1.Scale(Coeff);
00426 
00427   return BreakNum;
00428 }
00429 
00430 // Try to perform following optimization on the input instruction I. Return the
00431 // simplified expression if was successful; otherwise, return 0.
00432 //
00433 //   Instruction "I" is                Simplified into
00434 // -------------------------------------------------------
00435 //   (x * y) +/- (x * z)               x * (y +/- z)
00436 //   (y / x) +/- (z / x)               (y +/- z) / x
00437 //
00438 Value *FAddCombine::performFactorization(Instruction *I) {
00439   assert((I->getOpcode() == Instruction::FAdd ||
00440           I->getOpcode() == Instruction::FSub) && "Expect add/sub");
00441 
00442   Instruction *I0 = dyn_cast<Instruction>(I->getOperand(0));
00443   Instruction *I1 = dyn_cast<Instruction>(I->getOperand(1));
00444 
00445   if (!I0 || !I1 || I0->getOpcode() != I1->getOpcode())
00446     return 0;
00447 
00448   bool isMpy = false;
00449   if (I0->getOpcode() == Instruction::FMul)
00450     isMpy = true;
00451   else if (I0->getOpcode() != Instruction::FDiv)
00452     return 0;
00453 
00454   Value *Opnd0_0 = I0->getOperand(0);
00455   Value *Opnd0_1 = I0->getOperand(1);
00456   Value *Opnd1_0 = I1->getOperand(0);
00457   Value *Opnd1_1 = I1->getOperand(1);
00458 
00459   //  Input Instr I       Factor   AddSub0  AddSub1
00460   //  ----------------------------------------------
00461   // (x*y) +/- (x*z)        x        y         z
00462   // (y/x) +/- (z/x)        x        y         z
00463   //
00464   Value *Factor = 0;
00465   Value *AddSub0 = 0, *AddSub1 = 0;
00466 
00467   if (isMpy) {
00468     if (Opnd0_0 == Opnd1_0 || Opnd0_0 == Opnd1_1)
00469       Factor = Opnd0_0;
00470     else if (Opnd0_1 == Opnd1_0 || Opnd0_1 == Opnd1_1)
00471       Factor = Opnd0_1;
00472 
00473     if (Factor) {
00474       AddSub0 = (Factor == Opnd0_0) ? Opnd0_1 : Opnd0_0;
00475       AddSub1 = (Factor == Opnd1_0) ? Opnd1_1 : Opnd1_0;
00476     }
00477   } else if (Opnd0_1 == Opnd1_1) {
00478     Factor = Opnd0_1;
00479     AddSub0 = Opnd0_0;
00480     AddSub1 = Opnd1_0;
00481   }
00482 
00483   if (!Factor)
00484     return 0;
00485 
00486   FastMathFlags Flags;
00487   Flags.setUnsafeAlgebra();
00488   if (I0) Flags &= I->getFastMathFlags();
00489   if (I1) Flags &= I->getFastMathFlags();
00490 
00491   // Create expression "NewAddSub = AddSub0 +/- AddsSub1"
00492   Value *NewAddSub = (I->getOpcode() == Instruction::FAdd) ?
00493                       createFAdd(AddSub0, AddSub1) :
00494                       createFSub(AddSub0, AddSub1);
00495   if (ConstantFP *CFP = dyn_cast<ConstantFP>(NewAddSub)) {
00496     const APFloat &F = CFP->getValueAPF();
00497     if (!F.isNormal())
00498       return 0;
00499   } else if (Instruction *II = dyn_cast<Instruction>(NewAddSub))
00500     II->setFastMathFlags(Flags);
00501 
00502   if (isMpy) {
00503     Value *RI = createFMul(Factor, NewAddSub);
00504     if (Instruction *II = dyn_cast<Instruction>(RI))
00505       II->setFastMathFlags(Flags);
00506     return RI;
00507   }
00508 
00509   Value *RI = createFDiv(NewAddSub, Factor);
00510   if (Instruction *II = dyn_cast<Instruction>(RI))
00511     II->setFastMathFlags(Flags);
00512   return RI;
00513 }
00514 
00515 Value *FAddCombine::simplify(Instruction *I) {
00516   assert(I->hasUnsafeAlgebra() && "Should be in unsafe mode");
00517 
00518   // Currently we are not able to handle vector type.
00519   if (I->getType()->isVectorTy())
00520     return 0;
00521 
00522   assert((I->getOpcode() == Instruction::FAdd ||
00523           I->getOpcode() == Instruction::FSub) && "Expect add/sub");
00524 
00525   // Save the instruction before calling other member-functions.
00526   Instr = I;
00527 
00528   FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1;
00529 
00530   unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1);
00531 
00532   // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1.
00533   unsigned Opnd0_ExpNum = 0;
00534   unsigned Opnd1_ExpNum = 0;
00535 
00536   if (!Opnd0.isConstant())
00537     Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1);
00538 
00539   // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1.
00540   if (OpndNum == 2 && !Opnd1.isConstant())
00541     Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1);
00542 
00543   // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1
00544   if (Opnd0_ExpNum && Opnd1_ExpNum) {
00545     AddendVect AllOpnds;
00546     AllOpnds.push_back(&Opnd0_0);
00547     AllOpnds.push_back(&Opnd1_0);
00548     if (Opnd0_ExpNum == 2)
00549       AllOpnds.push_back(&Opnd0_1);
00550     if (Opnd1_ExpNum == 2)
00551       AllOpnds.push_back(&Opnd1_1);
00552 
00553     // Compute instruction quota. We should save at least one instruction.
00554     unsigned InstQuota = 0;
00555 
00556     Value *V0 = I->getOperand(0);
00557     Value *V1 = I->getOperand(1);
00558     InstQuota = ((!isa<Constant>(V0) && V0->hasOneUse()) &&
00559                  (!isa<Constant>(V1) && V1->hasOneUse())) ? 2 : 1;
00560 
00561     if (Value *R = simplifyFAdd(AllOpnds, InstQuota))
00562       return R;
00563   }
00564 
00565   if (OpndNum != 2) {
00566     // The input instruction is : "I=0.0 +/- V". If the "V" were able to be
00567     // splitted into two addends, say "V = X - Y", the instruction would have
00568     // been optimized into "I = Y - X" in the previous steps.
00569     //
00570     const FAddendCoef &CE = Opnd0.getCoef();
00571     return CE.isOne() ? Opnd0.getSymVal() : 0;
00572   }
00573 
00574   // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1]
00575   if (Opnd1_ExpNum) {
00576     AddendVect AllOpnds;
00577     AllOpnds.push_back(&Opnd0);
00578     AllOpnds.push_back(&Opnd1_0);
00579     if (Opnd1_ExpNum == 2)
00580       AllOpnds.push_back(&Opnd1_1);
00581 
00582     if (Value *R = simplifyFAdd(AllOpnds, 1))
00583       return R;
00584   }
00585 
00586   // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1]
00587   if (Opnd0_ExpNum) {
00588     AddendVect AllOpnds;
00589     AllOpnds.push_back(&Opnd1);
00590     AllOpnds.push_back(&Opnd0_0);
00591     if (Opnd0_ExpNum == 2)
00592       AllOpnds.push_back(&Opnd0_1);
00593 
00594     if (Value *R = simplifyFAdd(AllOpnds, 1))
00595       return R;
00596   }
00597 
00598   // step 6: Try factorization as the last resort,
00599   return performFactorization(I);
00600 }
00601 
00602 Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) {
00603 
00604   unsigned AddendNum = Addends.size();
00605   assert(AddendNum <= 4 && "Too many addends");
00606 
00607   // For saving intermediate results;
00608   unsigned NextTmpIdx = 0;
00609   FAddend TmpResult[3];
00610 
00611   // Points to the constant addend of the resulting simplified expression.
00612   // If the resulting expr has constant-addend, this constant-addend is
00613   // desirable to reside at the top of the resulting expression tree. Placing
00614   // constant close to supper-expr(s) will potentially reveal some optimization
00615   // opportunities in super-expr(s).
00616   //
00617   const FAddend *ConstAdd = 0;
00618 
00619   // Simplified addends are placed <SimpVect>.
00620   AddendVect SimpVect;
00621 
00622   // The outer loop works on one symbolic-value at a time. Suppose the input
00623   // addends are : <a1, x>, <b1, y>, <a2, x>, <c1, z>, <b2, y>, ...
00624   // The symbolic-values will be processed in this order: x, y, z.
00625   //
00626   for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) {
00627 
00628     const FAddend *ThisAddend = Addends[SymIdx];
00629     if (!ThisAddend) {
00630       // This addend was processed before.
00631       continue;
00632     }
00633 
00634     Value *Val = ThisAddend->getSymVal();
00635     unsigned StartIdx = SimpVect.size();
00636     SimpVect.push_back(ThisAddend);
00637 
00638     // The inner loop collects addends sharing same symbolic-value, and these
00639     // addends will be later on folded into a single addend. Following above
00640     // example, if the symbolic value "y" is being processed, the inner loop
00641     // will collect two addends "<b1,y>" and "<b2,Y>". These two addends will
00642     // be later on folded into "<b1+b2, y>".
00643     //
00644     for (unsigned SameSymIdx = SymIdx + 1;
00645          SameSymIdx < AddendNum; SameSymIdx++) {
00646       const FAddend *T = Addends[SameSymIdx];
00647       if (T && T->getSymVal() == Val) {
00648         // Set null such that next iteration of the outer loop will not process
00649         // this addend again.
00650         Addends[SameSymIdx] = 0;
00651         SimpVect.push_back(T);
00652       }
00653     }
00654 
00655     // If multiple addends share same symbolic value, fold them together.
00656     if (StartIdx + 1 != SimpVect.size()) {
00657       FAddend &R = TmpResult[NextTmpIdx ++];
00658       R = *SimpVect[StartIdx];
00659       for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++)
00660         R += *SimpVect[Idx];
00661 
00662       // Pop all addends being folded and push the resulting folded addend.
00663       SimpVect.resize(StartIdx);
00664       if (Val != 0) {
00665         if (!R.isZero()) {
00666           SimpVect.push_back(&R);
00667         }
00668       } else {
00669         // Don't push constant addend at this time. It will be the last element
00670         // of <SimpVect>.
00671         ConstAdd = &R;
00672       }
00673     }
00674   }
00675 
00676   assert((NextTmpIdx <= array_lengthof(TmpResult) + 1) &&
00677          "out-of-bound access");
00678 
00679   if (ConstAdd)
00680     SimpVect.push_back(ConstAdd);
00681 
00682   Value *Result;
00683   if (!SimpVect.empty())
00684     Result = createNaryFAdd(SimpVect, InstrQuota);
00685   else {
00686     // The addition is folded to 0.0.
00687     Result = ConstantFP::get(Instr->getType(), 0.0);
00688   }
00689 
00690   return Result;
00691 }
00692 
00693 Value *FAddCombine::createNaryFAdd
00694   (const AddendVect &Opnds, unsigned InstrQuota) {
00695   assert(!Opnds.empty() && "Expect at least one addend");
00696 
00697   // Step 1: Check if the # of instructions needed exceeds the quota.
00698   //
00699   unsigned InstrNeeded = calcInstrNumber(Opnds);
00700   if (InstrNeeded > InstrQuota)
00701     return 0;
00702 
00703   initCreateInstNum();
00704 
00705   // step 2: Emit the N-ary addition.
00706   // Note that at most three instructions are involved in Fadd-InstCombine: the
00707   // addition in question, and at most two neighboring instructions.
00708   // The resulting optimized addition should have at least one less instruction
00709   // than the original addition expression tree. This implies that the resulting
00710   // N-ary addition has at most two instructions, and we don't need to worry
00711   // about tree-height when constructing the N-ary addition.
00712 
00713   Value *LastVal = 0;
00714   bool LastValNeedNeg = false;
00715 
00716   // Iterate the addends, creating fadd/fsub using adjacent two addends.
00717   for (AddendVect::const_iterator I = Opnds.begin(), E = Opnds.end();
00718        I != E; I++) {
00719     bool NeedNeg;
00720     Value *V = createAddendVal(**I, NeedNeg);
00721     if (!LastVal) {
00722       LastVal = V;
00723       LastValNeedNeg = NeedNeg;
00724       continue;
00725     }
00726 
00727     if (LastValNeedNeg == NeedNeg) {
00728       LastVal = createFAdd(LastVal, V);
00729       continue;
00730     }
00731 
00732     if (LastValNeedNeg)
00733       LastVal = createFSub(V, LastVal);
00734     else
00735       LastVal = createFSub(LastVal, V);
00736 
00737     LastValNeedNeg = false;
00738   }
00739 
00740   if (LastValNeedNeg) {
00741     LastVal = createFNeg(LastVal);
00742   }
00743 
00744   #ifndef NDEBUG
00745     assert(CreateInstrNum == InstrNeeded &&
00746            "Inconsistent in instruction numbers");
00747   #endif
00748 
00749   return LastVal;
00750 }
00751 
00752 Value *FAddCombine::createFSub
00753   (Value *Opnd0, Value *Opnd1) {
00754   Value *V = Builder->CreateFSub(Opnd0, Opnd1);
00755   if (Instruction *I = dyn_cast<Instruction>(V))
00756     createInstPostProc(I);
00757   return V;
00758 }
00759 
00760 Value *FAddCombine::createFNeg(Value *V) {
00761   Value *Zero = cast<Value>(ConstantFP::get(V->getType(), 0.0));
00762   Value *NewV = createFSub(Zero, V);
00763   if (Instruction *I = dyn_cast<Instruction>(NewV))
00764     createInstPostProc(I, true); // fneg's don't receive instruction numbers.
00765   return NewV;
00766 }
00767 
00768 Value *FAddCombine::createFAdd
00769   (Value *Opnd0, Value *Opnd1) {
00770   Value *V = Builder->CreateFAdd(Opnd0, Opnd1);
00771   if (Instruction *I = dyn_cast<Instruction>(V))
00772     createInstPostProc(I);
00773   return V;
00774 }
00775 
00776 Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) {
00777   Value *V = Builder->CreateFMul(Opnd0, Opnd1);
00778   if (Instruction *I = dyn_cast<Instruction>(V))
00779     createInstPostProc(I);
00780   return V;
00781 }
00782 
00783 Value *FAddCombine::createFDiv(Value *Opnd0, Value *Opnd1) {
00784   Value *V = Builder->CreateFDiv(Opnd0, Opnd1);
00785   if (Instruction *I = dyn_cast<Instruction>(V))
00786     createInstPostProc(I);
00787   return V;
00788 }
00789 
00790 void FAddCombine::createInstPostProc(Instruction *NewInstr,
00791                                      bool NoNumber) {
00792   NewInstr->setDebugLoc(Instr->getDebugLoc());
00793 
00794   // Keep track of the number of instruction created.
00795   if (!NoNumber)
00796     incCreateInstNum();
00797 
00798   // Propagate fast-math flags
00799   NewInstr->setFastMathFlags(Instr->getFastMathFlags());
00800 }
00801 
00802 // Return the number of instruction needed to emit the N-ary addition.
00803 // NOTE: Keep this function in sync with createAddendVal().
00804 unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) {
00805   unsigned OpndNum = Opnds.size();
00806   unsigned InstrNeeded = OpndNum - 1;
00807 
00808   // The number of addends in the form of "(-1)*x".
00809   unsigned NegOpndNum = 0;
00810 
00811   // Adjust the number of instructions needed to emit the N-ary add.
00812   for (AddendVect::const_iterator I = Opnds.begin(), E = Opnds.end();
00813        I != E; I++) {
00814     const FAddend *Opnd = *I;
00815     if (Opnd->isConstant())
00816       continue;
00817 
00818     const FAddendCoef &CE = Opnd->getCoef();
00819     if (CE.isMinusOne() || CE.isMinusTwo())
00820       NegOpndNum++;
00821 
00822     // Let the addend be "c * x". If "c == +/-1", the value of the addend
00823     // is immediately available; otherwise, it needs exactly one instruction
00824     // to evaluate the value.
00825     if (!CE.isMinusOne() && !CE.isOne())
00826       InstrNeeded++;
00827   }
00828   if (NegOpndNum == OpndNum)
00829     InstrNeeded++;
00830   return InstrNeeded;
00831 }
00832 
00833 // Input Addend        Value           NeedNeg(output)
00834 // ================================================================
00835 // Constant C          C               false
00836 // <+/-1, V>           V               coefficient is -1
00837 // <2/-2, V>          "fadd V, V"      coefficient is -2
00838 // <C, V>             "fmul V, C"      false
00839 //
00840 // NOTE: Keep this function in sync with FAddCombine::calcInstrNumber.
00841 Value *FAddCombine::createAddendVal
00842   (const FAddend &Opnd, bool &NeedNeg) {
00843   const FAddendCoef &Coeff = Opnd.getCoef();
00844 
00845   if (Opnd.isConstant()) {
00846     NeedNeg = false;
00847     return Coeff.getValue(Instr->getType());
00848   }
00849 
00850   Value *OpndVal = Opnd.getSymVal();
00851 
00852   if (Coeff.isMinusOne() || Coeff.isOne()) {
00853     NeedNeg = Coeff.isMinusOne();
00854     return OpndVal;
00855   }
00856 
00857   if (Coeff.isTwo() || Coeff.isMinusTwo()) {
00858     NeedNeg = Coeff.isMinusTwo();
00859     return createFAdd(OpndVal, OpndVal);
00860   }
00861 
00862   NeedNeg = false;
00863   return createFMul(OpndVal, Coeff.getValue(Instr->getType()));
00864 }
00865 
00866 // dyn_castFoldableMul - If this value is a multiply that can be folded into
00867 // other computations (because it has a constant operand), return the
00868 // non-constant operand of the multiply, and set CST to point to the multiplier.
00869 // Otherwise, return null.
00870 //
00871 static inline Value *dyn_castFoldableMul(Value *V, Constant *&CST) {
00872   if (!V->hasOneUse() || !V->getType()->isIntOrIntVectorTy())
00873     return 0;
00874 
00875   Instruction *I = dyn_cast<Instruction>(V);
00876   if (I == 0) return 0;
00877 
00878   if (I->getOpcode() == Instruction::Mul)
00879     if ((CST = dyn_cast<Constant>(I->getOperand(1))))
00880       return I->getOperand(0);
00881   if (I->getOpcode() == Instruction::Shl)
00882     if ((CST = dyn_cast<Constant>(I->getOperand(1)))) {
00883       // The multiplier is really 1 << CST.
00884       CST = ConstantExpr::getShl(ConstantInt::get(V->getType(), 1), CST);
00885       return I->getOperand(0);
00886     }
00887   return 0;
00888 }
00889 
00890 
00891 /// WillNotOverflowSignedAdd - Return true if we can prove that:
00892 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
00893 /// This basically requires proving that the add in the original type would not
00894 /// overflow to change the sign bit or have a carry out.
00895 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
00896   // There are different heuristics we can use for this.  Here are some simple
00897   // ones.
00898 
00899   // Add has the property that adding any two 2's complement numbers can only
00900   // have one carry bit which can change a sign.  As such, if LHS and RHS each
00901   // have at least two sign bits, we know that the addition of the two values
00902   // will sign extend fine.
00903   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
00904     return true;
00905 
00906 
00907   // If one of the operands only has one non-zero bit, and if the other operand
00908   // has a known-zero bit in a more significant place than it (not including the
00909   // sign bit) the ripple may go up to and fill the zero, but won't change the
00910   // sign.  For example, (X & ~4) + 1.
00911 
00912   // TODO: Implement.
00913 
00914   return false;
00915 }
00916 
00917 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
00918   bool Changed = SimplifyAssociativeOrCommutative(I);
00919   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
00920 
00921   if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
00922                                  I.hasNoUnsignedWrap(), DL))
00923     return ReplaceInstUsesWith(I, V);
00924 
00925   // (A*B)+(A*C) -> A*(B+C) etc
00926   if (Value *V = SimplifyUsingDistributiveLaws(I))
00927     return ReplaceInstUsesWith(I, V);
00928 
00929   if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
00930     // X + (signbit) --> X ^ signbit
00931     const APInt &Val = CI->getValue();
00932     if (Val.isSignBit())
00933       return BinaryOperator::CreateXor(LHS, RHS);
00934 
00935     // See if SimplifyDemandedBits can simplify this.  This handles stuff like
00936     // (X & 254)+1 -> (X&254)|1
00937     if (SimplifyDemandedInstructionBits(I))
00938       return &I;
00939 
00940     // zext(bool) + C -> bool ? C + 1 : C
00941     if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
00942       if (ZI->getSrcTy()->isIntegerTy(1))
00943         return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
00944 
00945     Value *XorLHS = 0; ConstantInt *XorRHS = 0;
00946     if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
00947       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
00948       const APInt &RHSVal = CI->getValue();
00949       unsigned ExtendAmt = 0;
00950       // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
00951       // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
00952       if (XorRHS->getValue() == -RHSVal) {
00953         if (RHSVal.isPowerOf2())
00954           ExtendAmt = TySizeBits - RHSVal.logBase2() - 1;
00955         else if (XorRHS->getValue().isPowerOf2())
00956           ExtendAmt = TySizeBits - XorRHS->getValue().logBase2() - 1;
00957       }
00958 
00959       if (ExtendAmt) {
00960         APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt);
00961         if (!MaskedValueIsZero(XorLHS, Mask))
00962           ExtendAmt = 0;
00963       }
00964 
00965       if (ExtendAmt) {
00966         Constant *ShAmt = ConstantInt::get(I.getType(), ExtendAmt);
00967         Value *NewShl = Builder->CreateShl(XorLHS, ShAmt, "sext");
00968         return BinaryOperator::CreateAShr(NewShl, ShAmt);
00969       }
00970 
00971       // If this is a xor that was canonicalized from a sub, turn it back into
00972       // a sub and fuse this add with it.
00973       if (LHS->hasOneUse() && (XorRHS->getValue()+1).isPowerOf2()) {
00974         IntegerType *IT = cast<IntegerType>(I.getType());
00975         APInt LHSKnownOne(IT->getBitWidth(), 0);
00976         APInt LHSKnownZero(IT->getBitWidth(), 0);
00977         ComputeMaskedBits(XorLHS, LHSKnownZero, LHSKnownOne);
00978         if ((XorRHS->getValue() | LHSKnownZero).isAllOnesValue())
00979           return BinaryOperator::CreateSub(ConstantExpr::getAdd(XorRHS, CI),
00980                                            XorLHS);
00981       }
00982       // (X + signbit) + C could have gotten canonicalized to (X ^ signbit) + C,
00983       // transform them into (X + (signbit ^ C))
00984       if (XorRHS->getValue().isSignBit())
00985           return BinaryOperator::CreateAdd(XorLHS,
00986                                            ConstantExpr::getXor(XorRHS, CI));
00987     }
00988   }
00989 
00990   if (isa<Constant>(RHS) && isa<PHINode>(LHS))
00991     if (Instruction *NV = FoldOpIntoPhi(I))
00992       return NV;
00993 
00994   if (I.getType()->getScalarType()->isIntegerTy(1))
00995     return BinaryOperator::CreateXor(LHS, RHS);
00996 
00997   // X + X --> X << 1
00998   if (LHS == RHS) {
00999     BinaryOperator *New =
01000       BinaryOperator::CreateShl(LHS, ConstantInt::get(I.getType(), 1));
01001     New->setHasNoSignedWrap(I.hasNoSignedWrap());
01002     New->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
01003     return New;
01004   }
01005 
01006   // -A + B  -->  B - A
01007   // -A + -B  -->  -(A + B)
01008   if (Value *LHSV = dyn_castNegVal(LHS)) {
01009     if (!isa<Constant>(RHS))
01010       if (Value *RHSV = dyn_castNegVal(RHS)) {
01011         Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
01012         return BinaryOperator::CreateNeg(NewAdd);
01013       }
01014 
01015     return BinaryOperator::CreateSub(RHS, LHSV);
01016   }
01017 
01018   // A + -B  -->  A - B
01019   if (!isa<Constant>(RHS))
01020     if (Value *V = dyn_castNegVal(RHS))
01021       return BinaryOperator::CreateSub(LHS, V);
01022 
01023 
01024   {
01025     Constant *C2;
01026     if (Value *X = dyn_castFoldableMul(LHS, C2)) {
01027       if (X == RHS) // X*C + X --> X * (C+1)
01028         return BinaryOperator::CreateMul(RHS, AddOne(C2));
01029 
01030       // X*C1 + X*C2 --> X * (C1+C2)
01031       Constant *C1;
01032       if (X == dyn_castFoldableMul(RHS, C1))
01033         return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
01034     }
01035 
01036     // X + X*C --> X * (C+1)
01037     if (dyn_castFoldableMul(RHS, C2) == LHS)
01038       return BinaryOperator::CreateMul(LHS, AddOne(C2));
01039   }
01040 
01041   // A+B --> A|B iff A and B have no bits set in common.
01042   if (IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
01043     APInt LHSKnownOne(IT->getBitWidth(), 0);
01044     APInt LHSKnownZero(IT->getBitWidth(), 0);
01045     ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
01046     if (LHSKnownZero != 0) {
01047       APInt RHSKnownOne(IT->getBitWidth(), 0);
01048       APInt RHSKnownZero(IT->getBitWidth(), 0);
01049       ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
01050 
01051       // No bits in common -> bitwise or.
01052       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
01053         return BinaryOperator::CreateOr(LHS, RHS);
01054     }
01055   }
01056 
01057   // W*X + Y*Z --> W * (X+Z)  iff W == Y
01058   {
01059     Value *W, *X, *Y, *Z;
01060     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
01061         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
01062       if (W != Y) {
01063         if (W == Z) {
01064           std::swap(Y, Z);
01065         } else if (Y == X) {
01066           std::swap(W, X);
01067         } else if (X == Z) {
01068           std::swap(Y, Z);
01069           std::swap(W, X);
01070         }
01071       }
01072 
01073       if (W == Y) {
01074         Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
01075         return BinaryOperator::CreateMul(W, NewAdd);
01076       }
01077     }
01078   }
01079 
01080   if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
01081     Value *X;
01082     if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
01083       return BinaryOperator::CreateSub(SubOne(CRHS), X);
01084   }
01085 
01086   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
01087     // (X & FF00) + xx00  -> (X+xx00) & FF00
01088     Value *X;
01089     ConstantInt *C2;
01090     if (LHS->hasOneUse() &&
01091         match(LHS, m_And(m_Value(X), m_ConstantInt(C2))) &&
01092         CRHS->getValue() == (CRHS->getValue() & C2->getValue())) {
01093       // See if all bits from the first bit set in the Add RHS up are included
01094       // in the mask.  First, get the rightmost bit.
01095       const APInt &AddRHSV = CRHS->getValue();
01096 
01097       // Form a mask of all bits from the lowest bit added through the top.
01098       APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
01099 
01100       // See if the and mask includes all of these bits.
01101       APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
01102 
01103       if (AddRHSHighBits == AddRHSHighBitsAnd) {
01104         // Okay, the xform is safe.  Insert the new add pronto.
01105         Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
01106         return BinaryOperator::CreateAnd(NewAdd, C2);
01107       }
01108     }
01109 
01110     // Try to fold constant add into select arguments.
01111     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
01112       if (Instruction *R = FoldOpIntoSelect(I, SI))
01113         return R;
01114   }
01115 
01116   // add (select X 0 (sub n A)) A  -->  select X A n
01117   {
01118     SelectInst *SI = dyn_cast<SelectInst>(LHS);
01119     Value *A = RHS;
01120     if (!SI) {
01121       SI = dyn_cast<SelectInst>(RHS);
01122       A = LHS;
01123     }
01124     if (SI && SI->hasOneUse()) {
01125       Value *TV = SI->getTrueValue();
01126       Value *FV = SI->getFalseValue();
01127       Value *N;
01128 
01129       // Can we fold the add into the argument of the select?
01130       // We check both true and false select arguments for a matching subtract.
01131       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
01132         // Fold the add into the true select value.
01133         return SelectInst::Create(SI->getCondition(), N, A);
01134 
01135       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
01136         // Fold the add into the false select value.
01137         return SelectInst::Create(SI->getCondition(), A, N);
01138     }
01139   }
01140 
01141   // Check for (add (sext x), y), see if we can merge this into an
01142   // integer add followed by a sext.
01143   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
01144     // (add (sext x), cst) --> (sext (add x, cst'))
01145     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
01146       Constant *CI =
01147         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
01148       if (LHSConv->hasOneUse() &&
01149           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
01150           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
01151         // Insert the new, smaller add.
01152         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
01153                                               CI, "addconv");
01154         return new SExtInst(NewAdd, I.getType());
01155       }
01156     }
01157 
01158     // (add (sext x), (sext y)) --> (sext (add int x, y))
01159     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
01160       // Only do this if x/y have the same type, if at last one of them has a
01161       // single use (so we don't increase the number of sexts), and if the
01162       // integer add will not overflow.
01163       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
01164           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
01165           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
01166                                    RHSConv->getOperand(0))) {
01167         // Insert the new integer add.
01168         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
01169                                              RHSConv->getOperand(0), "addconv");
01170         return new SExtInst(NewAdd, I.getType());
01171       }
01172     }
01173   }
01174 
01175   // Check for (x & y) + (x ^ y)
01176   {
01177     Value *A = 0, *B = 0;
01178     if (match(RHS, m_Xor(m_Value(A), m_Value(B))) &&
01179         (match(LHS, m_And(m_Specific(A), m_Specific(B))) ||
01180          match(LHS, m_And(m_Specific(B), m_Specific(A)))))
01181       return BinaryOperator::CreateOr(A, B);
01182 
01183     if (match(LHS, m_Xor(m_Value(A), m_Value(B))) &&
01184         (match(RHS, m_And(m_Specific(A), m_Specific(B))) ||
01185          match(RHS, m_And(m_Specific(B), m_Specific(A)))))
01186       return BinaryOperator::CreateOr(A, B);
01187   }
01188 
01189   return Changed ? &I : 0;
01190 }
01191 
01192 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
01193   bool Changed = SimplifyAssociativeOrCommutative(I);
01194   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
01195 
01196   if (Value *V = SimplifyFAddInst(LHS, RHS, I.getFastMathFlags(), DL))
01197     return ReplaceInstUsesWith(I, V);
01198 
01199   if (isa<Constant>(RHS)) {
01200     if (isa<PHINode>(LHS))
01201       if (Instruction *NV = FoldOpIntoPhi(I))
01202         return NV;
01203 
01204     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
01205       if (Instruction *NV = FoldOpIntoSelect(I, SI))
01206         return NV;
01207   }
01208 
01209   // -A + B  -->  B - A
01210   // -A + -B  -->  -(A + B)
01211   if (Value *LHSV = dyn_castFNegVal(LHS)) {
01212     Instruction *RI = BinaryOperator::CreateFSub(RHS, LHSV);
01213     RI->copyFastMathFlags(&I);
01214     return RI;
01215   }
01216 
01217   // A + -B  -->  A - B
01218   if (!isa<Constant>(RHS))
01219     if (Value *V = dyn_castFNegVal(RHS)) {
01220       Instruction *RI = BinaryOperator::CreateFSub(LHS, V);
01221       RI->copyFastMathFlags(&I);
01222       return RI;
01223     }
01224 
01225   // Check for (fadd double (sitofp x), y), see if we can merge this into an
01226   // integer add followed by a promotion.
01227   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
01228     // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
01229     // ... if the constant fits in the integer value.  This is useful for things
01230     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
01231     // requires a constant pool load, and generally allows the add to be better
01232     // instcombined.
01233     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
01234       Constant *CI =
01235       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
01236       if (LHSConv->hasOneUse() &&
01237           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
01238           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
01239         // Insert the new integer add.
01240         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
01241                                               CI, "addconv");
01242         return new SIToFPInst(NewAdd, I.getType());
01243       }
01244     }
01245 
01246     // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
01247     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
01248       // Only do this if x/y have the same type, if at last one of them has a
01249       // single use (so we don't increase the number of int->fp conversions),
01250       // and if the integer add will not overflow.
01251       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
01252           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
01253           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
01254                                    RHSConv->getOperand(0))) {
01255         // Insert the new integer add.
01256         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
01257                                               RHSConv->getOperand(0),"addconv");
01258         return new SIToFPInst(NewAdd, I.getType());
01259       }
01260     }
01261   }
01262 
01263   // select C, 0, B + select C, A, 0 -> select C, A, B
01264   {
01265     Value *A1, *B1, *C1, *A2, *B2, *C2;
01266     if (match(LHS, m_Select(m_Value(C1), m_Value(A1), m_Value(B1))) &&
01267         match(RHS, m_Select(m_Value(C2), m_Value(A2), m_Value(B2)))) {
01268       if (C1 == C2) {
01269         Constant *Z1=0, *Z2=0;
01270         Value *A, *B, *C=C1;
01271         if (match(A1, m_AnyZero()) && match(B2, m_AnyZero())) {
01272             Z1 = dyn_cast<Constant>(A1); A = A2;
01273             Z2 = dyn_cast<Constant>(B2); B = B1;
01274         } else if (match(B1, m_AnyZero()) && match(A2, m_AnyZero())) {
01275             Z1 = dyn_cast<Constant>(B1); B = B2;
01276             Z2 = dyn_cast<Constant>(A2); A = A1; 
01277         }
01278         
01279         if (Z1 && Z2 && 
01280             (I.hasNoSignedZeros() || 
01281              (Z1->isNegativeZeroValue() && Z2->isNegativeZeroValue()))) {
01282           return SelectInst::Create(C, A, B);
01283         }
01284       }
01285     }
01286   }
01287 
01288   if (I.hasUnsafeAlgebra()) {
01289     if (Value *V = FAddCombine(Builder).simplify(&I))
01290       return ReplaceInstUsesWith(I, V);
01291   }
01292 
01293   return Changed ? &I : 0;
01294 }
01295 
01296 
01297 /// Optimize pointer differences into the same array into a size.  Consider:
01298 ///  &A[10] - &A[0]: we should compile this to "10".  LHS/RHS are the pointer
01299 /// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
01300 ///
01301 Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
01302                                                Type *Ty) {
01303   assert(DL && "Must have target data info for this");
01304 
01305   // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
01306   // this.
01307   bool Swapped = false;
01308   GEPOperator *GEP1 = 0, *GEP2 = 0;
01309 
01310   // For now we require one side to be the base pointer "A" or a constant
01311   // GEP derived from it.
01312   if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
01313     // (gep X, ...) - X
01314     if (LHSGEP->getOperand(0) == RHS) {
01315       GEP1 = LHSGEP;
01316       Swapped = false;
01317     } else if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
01318       // (gep X, ...) - (gep X, ...)
01319       if (LHSGEP->getOperand(0)->stripPointerCasts() ==
01320             RHSGEP->getOperand(0)->stripPointerCasts()) {
01321         GEP2 = RHSGEP;
01322         GEP1 = LHSGEP;
01323         Swapped = false;
01324       }
01325     }
01326   }
01327 
01328   if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
01329     // X - (gep X, ...)
01330     if (RHSGEP->getOperand(0) == LHS) {
01331       GEP1 = RHSGEP;
01332       Swapped = true;
01333     } else if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
01334       // (gep X, ...) - (gep X, ...)
01335       if (RHSGEP->getOperand(0)->stripPointerCasts() ==
01336             LHSGEP->getOperand(0)->stripPointerCasts()) {
01337         GEP2 = LHSGEP;
01338         GEP1 = RHSGEP;
01339         Swapped = true;
01340       }
01341     }
01342   }
01343 
01344   // Avoid duplicating the arithmetic if GEP2 has non-constant indices and
01345   // multiple users.
01346   if (GEP1 == 0 ||
01347       (GEP2 != 0 && !GEP2->hasAllConstantIndices() && !GEP2->hasOneUse()))
01348     return 0;
01349 
01350   // Emit the offset of the GEP and an intptr_t.
01351   Value *Result = EmitGEPOffset(GEP1);
01352 
01353   // If we had a constant expression GEP on the other side offsetting the
01354   // pointer, subtract it from the offset we have.
01355   if (GEP2) {
01356     Value *Offset = EmitGEPOffset(GEP2);
01357     Result = Builder->CreateSub(Result, Offset);
01358   }
01359 
01360   // If we have p - gep(p, ...)  then we have to negate the result.
01361   if (Swapped)
01362     Result = Builder->CreateNeg(Result, "diff.neg");
01363 
01364   return Builder->CreateIntCast(Result, Ty, true);
01365 }
01366 
01367 
01368 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
01369   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
01370 
01371   if (Value *V = SimplifySubInst(Op0, Op1, I.hasNoSignedWrap(),
01372                                  I.hasNoUnsignedWrap(), DL))
01373     return ReplaceInstUsesWith(I, V);
01374 
01375   // (A*B)-(A*C) -> A*(B-C) etc
01376   if (Value *V = SimplifyUsingDistributiveLaws(I))
01377     return ReplaceInstUsesWith(I, V);
01378 
01379   // If this is a 'B = x-(-A)', change to B = x+A.  This preserves NSW/NUW.
01380   if (Value *V = dyn_castNegVal(Op1)) {
01381     BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
01382     Res->setHasNoSignedWrap(I.hasNoSignedWrap());
01383     Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
01384     return Res;
01385   }
01386 
01387   if (I.getType()->isIntegerTy(1))
01388     return BinaryOperator::CreateXor(Op0, Op1);
01389 
01390   // Replace (-1 - A) with (~A).
01391   if (match(Op0, m_AllOnes()))
01392     return BinaryOperator::CreateNot(Op1);
01393 
01394   if (Constant *C = dyn_cast<Constant>(Op0)) {
01395     // C - ~X == X + (1+C)
01396     Value *X = 0;
01397     if (match(Op1, m_Not(m_Value(X))))
01398       return BinaryOperator::CreateAdd(X, AddOne(C));
01399 
01400     // Try to fold constant sub into select arguments.
01401     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
01402       if (Instruction *R = FoldOpIntoSelect(I, SI))
01403         return R;
01404 
01405     // C-(X+C2) --> (C-C2)-X
01406     Constant *C2;
01407     if (match(Op1, m_Add(m_Value(X), m_Constant(C2))))
01408       return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
01409 
01410     if (SimplifyDemandedInstructionBits(I))
01411       return &I;
01412 
01413     // Fold (sub 0, (zext bool to B)) --> (sext bool to B)
01414     if (C->isNullValue() && match(Op1, m_ZExt(m_Value(X))))
01415       if (X->getType()->getScalarType()->isIntegerTy(1))
01416         return CastInst::CreateSExtOrBitCast(X, Op1->getType());
01417 
01418     // Fold (sub 0, (sext bool to B)) --> (zext bool to B)
01419     if (C->isNullValue() && match(Op1, m_SExt(m_Value(X))))
01420       if (X->getType()->getScalarType()->isIntegerTy(1))
01421         return CastInst::CreateZExtOrBitCast(X, Op1->getType());
01422   }
01423 
01424   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
01425     // -(X >>u 31) -> (X >>s 31)
01426     // -(X >>s 31) -> (X >>u 31)
01427     if (C->isZero()) {
01428       Value *X; ConstantInt *CI;
01429       if (match(Op1, m_LShr(m_Value(X), m_ConstantInt(CI))) &&
01430           // Verify we are shifting out everything but the sign bit.
01431           CI->getValue() == I.getType()->getPrimitiveSizeInBits()-1)
01432         return BinaryOperator::CreateAShr(X, CI);
01433 
01434       if (match(Op1, m_AShr(m_Value(X), m_ConstantInt(CI))) &&
01435           // Verify we are shifting out everything but the sign bit.
01436           CI->getValue() == I.getType()->getPrimitiveSizeInBits()-1)
01437         return BinaryOperator::CreateLShr(X, CI);
01438     }
01439   }
01440 
01441 
01442   { Value *Y;
01443     // X-(X+Y) == -Y    X-(Y+X) == -Y
01444     if (match(Op1, m_Add(m_Specific(Op0), m_Value(Y))) ||
01445         match(Op1, m_Add(m_Value(Y), m_Specific(Op0))))
01446       return BinaryOperator::CreateNeg(Y);
01447 
01448     // (X-Y)-X == -Y
01449     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y))))
01450       return BinaryOperator::CreateNeg(Y);
01451   }
01452 
01453   if (Op1->hasOneUse()) {
01454     Value *X = 0, *Y = 0, *Z = 0;
01455     Constant *C = 0;
01456     Constant *CI = 0;
01457 
01458     // (X - (Y - Z))  -->  (X + (Z - Y)).
01459     if (match(Op1, m_Sub(m_Value(Y), m_Value(Z))))
01460       return BinaryOperator::CreateAdd(Op0,
01461                                       Builder->CreateSub(Z, Y, Op1->getName()));
01462 
01463     // (X - (X & Y))   -->   (X & ~Y)
01464     //
01465     if (match(Op1, m_And(m_Value(Y), m_Specific(Op0))) ||
01466         match(Op1, m_And(m_Specific(Op0), m_Value(Y))))
01467       return BinaryOperator::CreateAnd(Op0,
01468                                   Builder->CreateNot(Y, Y->getName() + ".not"));
01469 
01470     // 0 - (X sdiv C)  -> (X sdiv -C)
01471     if (match(Op1, m_SDiv(m_Value(X), m_Constant(C))) &&
01472         match(Op0, m_Zero()))
01473       return BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(C));
01474 
01475     // 0 - (X << Y)  -> (-X << Y)   when X is freely negatable.
01476     if (match(Op1, m_Shl(m_Value(X), m_Value(Y))) && match(Op0, m_Zero()))
01477       if (Value *XNeg = dyn_castNegVal(X))
01478         return BinaryOperator::CreateShl(XNeg, Y);
01479 
01480     // X - X*C --> X * (1-C)
01481     if (match(Op1, m_Mul(m_Specific(Op0), m_Constant(CI)))) {
01482       Constant *CP1 = ConstantExpr::getSub(ConstantInt::get(I.getType(),1), CI);
01483       return BinaryOperator::CreateMul(Op0, CP1);
01484     }
01485 
01486     // X - X<<C --> X * (1-(1<<C))
01487     if (match(Op1, m_Shl(m_Specific(Op0), m_Constant(CI)))) {
01488       Constant *One = ConstantInt::get(I.getType(), 1);
01489       C = ConstantExpr::getSub(One, ConstantExpr::getShl(One, CI));
01490       return BinaryOperator::CreateMul(Op0, C);
01491     }
01492 
01493     // X - A*-B -> X + A*B
01494     // X - -A*B -> X + A*B
01495     Value *A, *B;
01496     if (match(Op1, m_Mul(m_Value(A), m_Neg(m_Value(B)))) ||
01497         match(Op1, m_Mul(m_Neg(m_Value(A)), m_Value(B))))
01498       return BinaryOperator::CreateAdd(Op0, Builder->CreateMul(A, B));
01499 
01500     // X - A*CI -> X + A*-CI
01501     // X - CI*A -> X + A*-CI
01502     if (match(Op1, m_Mul(m_Value(A), m_Constant(CI))) ||
01503         match(Op1, m_Mul(m_Constant(CI), m_Value(A)))) {
01504       Value *NewMul = Builder->CreateMul(A, ConstantExpr::getNeg(CI));
01505       return BinaryOperator::CreateAdd(Op0, NewMul);
01506     }
01507   }
01508 
01509   Constant *C1;
01510   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
01511     if (X == Op1)  // X*C - X --> X * (C-1)
01512       return BinaryOperator::CreateMul(Op1, SubOne(C1));
01513 
01514     Constant *C2;   // X*C1 - X*C2 -> X * (C1-C2)
01515     if (X == dyn_castFoldableMul(Op1, C2))
01516       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
01517   }
01518 
01519   // Optimize pointer differences into the same array into a size.  Consider:
01520   //  &A[10] - &A[0]: we should compile this to "10".
01521   if (DL) {
01522     Value *LHSOp, *RHSOp;
01523     if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
01524         match(Op1, m_PtrToInt(m_Value(RHSOp))))
01525       if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
01526         return ReplaceInstUsesWith(I, Res);
01527 
01528     // trunc(p)-trunc(q) -> trunc(p-q)
01529     if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
01530         match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
01531       if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
01532         return ReplaceInstUsesWith(I, Res);
01533   }
01534 
01535   return 0;
01536 }
01537 
01538 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
01539   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
01540 
01541   if (Value *V = SimplifyFSubInst(Op0, Op1, I.getFastMathFlags(), DL))
01542     return ReplaceInstUsesWith(I, V);
01543 
01544   if (isa<Constant>(Op0))
01545     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
01546       if (Instruction *NV = FoldOpIntoSelect(I, SI))
01547         return NV;
01548 
01549   // If this is a 'B = x-(-A)', change to B = x+A, potentially looking
01550   // through FP extensions/truncations along the way.
01551   if (Value *V = dyn_castFNegVal(Op1)) {
01552     Instruction *NewI = BinaryOperator::CreateFAdd(Op0, V);
01553     NewI->copyFastMathFlags(&I);
01554     return NewI;
01555   }
01556   if (FPTruncInst *FPTI = dyn_cast<FPTruncInst>(Op1)) {
01557     if (Value *V = dyn_castFNegVal(FPTI->getOperand(0))) {
01558       Value *NewTrunc = Builder->CreateFPTrunc(V, I.getType());
01559       Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewTrunc);
01560       NewI->copyFastMathFlags(&I);
01561       return NewI;
01562     }
01563   } else if (FPExtInst *FPEI = dyn_cast<FPExtInst>(Op1)) {
01564     if (Value *V = dyn_castFNegVal(FPEI->getOperand(0))) {
01565       Value *NewExt = Builder->CreateFPExt(V, I.getType());
01566       Instruction *NewI = BinaryOperator::CreateFAdd(Op0, NewExt);
01567       NewI->copyFastMathFlags(&I);
01568       return NewI;
01569     }
01570   }
01571 
01572   if (I.hasUnsafeAlgebra()) {
01573     if (Value *V = FAddCombine(Builder).simplify(&I))
01574       return ReplaceInstUsesWith(I, V);
01575   }
01576 
01577   return 0;
01578 }