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