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