LLVM  mainline
LoopStrengthReduce.cpp
Go to the documentation of this file.
00001 //===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===//
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 transformation analyzes and transforms the induction variables (and
00011 // computations derived from them) into forms suitable for efficient execution
00012 // on the target.
00013 //
00014 // This pass performs a strength reduction on array references inside loops that
00015 // have as one or more of their components the loop induction variable, it
00016 // rewrites expressions to take advantage of scaled-index addressing modes
00017 // available on the target, and it performs a variety of other optimizations
00018 // related to loop induction variables.
00019 //
00020 // Terminology note: this code has a lot of handling for "post-increment" or
00021 // "post-inc" users. This is not talking about post-increment addressing modes;
00022 // it is instead talking about code like this:
00023 //
00024 //   %i = phi [ 0, %entry ], [ %i.next, %latch ]
00025 //   ...
00026 //   %i.next = add %i, 1
00027 //   %c = icmp eq %i.next, %n
00028 //
00029 // The SCEV for %i is {0,+,1}<%L>. The SCEV for %i.next is {1,+,1}<%L>, however
00030 // it's useful to think about these as the same register, with some uses using
00031 // the value of the register before the add and some using it after. In this
00032 // example, the icmp is a post-increment user, since it uses %i.next, which is
00033 // the value of the induction variable after the increment. The other common
00034 // case of post-increment users is users outside the loop.
00035 //
00036 // TODO: More sophistication in the way Formulae are generated and filtered.
00037 //
00038 // TODO: Handle multiple loops at a time.
00039 //
00040 // TODO: Should the addressing mode BaseGV be changed to a ConstantExpr instead
00041 //       of a GlobalValue?
00042 //
00043 // TODO: When truncation is free, truncate ICmp users' operands to make it a
00044 //       smaller encoding (on x86 at least).
00045 //
00046 // TODO: When a negated register is used by an add (such as in a list of
00047 //       multiple base registers, or as the increment expression in an addrec),
00048 //       we may not actually need both reg and (-1 * reg) in registers; the
00049 //       negation can be implemented by using a sub instead of an add. The
00050 //       lack of support for taking this into consideration when making
00051 //       register pressure decisions is partly worked around by the "Special"
00052 //       use kind.
00053 //
00054 //===----------------------------------------------------------------------===//
00055 
00056 #include "llvm/Transforms/Scalar.h"
00057 #include "llvm/ADT/DenseSet.h"
00058 #include "llvm/ADT/Hashing.h"
00059 #include "llvm/ADT/STLExtras.h"
00060 #include "llvm/ADT/SetVector.h"
00061 #include "llvm/ADT/SmallBitVector.h"
00062 #include "llvm/Analysis/IVUsers.h"
00063 #include "llvm/Analysis/LoopPass.h"
00064 #include "llvm/Analysis/ScalarEvolutionExpander.h"
00065 #include "llvm/Analysis/TargetTransformInfo.h"
00066 #include "llvm/IR/Constants.h"
00067 #include "llvm/IR/DerivedTypes.h"
00068 #include "llvm/IR/Dominators.h"
00069 #include "llvm/IR/Instructions.h"
00070 #include "llvm/IR/IntrinsicInst.h"
00071 #include "llvm/IR/Module.h"
00072 #include "llvm/IR/ValueHandle.h"
00073 #include "llvm/Support/CommandLine.h"
00074 #include "llvm/Support/Debug.h"
00075 #include "llvm/Support/raw_ostream.h"
00076 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00077 #include "llvm/Transforms/Utils/Local.h"
00078 #include <algorithm>
00079 using namespace llvm;
00080 
00081 #define DEBUG_TYPE "loop-reduce"
00082 
00083 /// MaxIVUsers is an arbitrary threshold that provides an early opportunitiy for
00084 /// bail out. This threshold is far beyond the number of users that LSR can
00085 /// conceivably solve, so it should not affect generated code, but catches the
00086 /// worst cases before LSR burns too much compile time and stack space.
00087 static const unsigned MaxIVUsers = 200;
00088 
00089 // Temporary flag to cleanup congruent phis after LSR phi expansion.
00090 // It's currently disabled until we can determine whether it's truly useful or
00091 // not. The flag should be removed after the v3.0 release.
00092 // This is now needed for ivchains.
00093 static cl::opt<bool> EnablePhiElim(
00094   "enable-lsr-phielim", cl::Hidden, cl::init(true),
00095   cl::desc("Enable LSR phi elimination"));
00096 
00097 #ifndef NDEBUG
00098 // Stress test IV chain generation.
00099 static cl::opt<bool> StressIVChain(
00100   "stress-ivchain", cl::Hidden, cl::init(false),
00101   cl::desc("Stress test LSR IV chains"));
00102 #else
00103 static bool StressIVChain = false;
00104 #endif
00105 
00106 namespace {
00107 
00108 /// RegSortData - This class holds data which is used to order reuse candidates.
00109 class RegSortData {
00110 public:
00111   /// UsedByIndices - This represents the set of LSRUse indices which reference
00112   /// a particular register.
00113   SmallBitVector UsedByIndices;
00114 
00115   void print(raw_ostream &OS) const;
00116   void dump() const;
00117 };
00118 
00119 }
00120 
00121 void RegSortData::print(raw_ostream &OS) const {
00122   OS << "[NumUses=" << UsedByIndices.count() << ']';
00123 }
00124 
00125 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00126 void RegSortData::dump() const {
00127   print(errs()); errs() << '\n';
00128 }
00129 #endif
00130 
00131 namespace {
00132 
00133 /// RegUseTracker - Map register candidates to information about how they are
00134 /// used.
00135 class RegUseTracker {
00136   typedef DenseMap<const SCEV *, RegSortData> RegUsesTy;
00137 
00138   RegUsesTy RegUsesMap;
00139   SmallVector<const SCEV *, 16> RegSequence;
00140 
00141 public:
00142   void CountRegister(const SCEV *Reg, size_t LUIdx);
00143   void DropRegister(const SCEV *Reg, size_t LUIdx);
00144   void SwapAndDropUse(size_t LUIdx, size_t LastLUIdx);
00145 
00146   bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const;
00147 
00148   const SmallBitVector &getUsedByIndices(const SCEV *Reg) const;
00149 
00150   void clear();
00151 
00152   typedef SmallVectorImpl<const SCEV *>::iterator iterator;
00153   typedef SmallVectorImpl<const SCEV *>::const_iterator const_iterator;
00154   iterator begin() { return RegSequence.begin(); }
00155   iterator end()   { return RegSequence.end(); }
00156   const_iterator begin() const { return RegSequence.begin(); }
00157   const_iterator end() const   { return RegSequence.end(); }
00158 };
00159 
00160 }
00161 
00162 void
00163 RegUseTracker::CountRegister(const SCEV *Reg, size_t LUIdx) {
00164   std::pair<RegUsesTy::iterator, bool> Pair =
00165     RegUsesMap.insert(std::make_pair(Reg, RegSortData()));
00166   RegSortData &RSD = Pair.first->second;
00167   if (Pair.second)
00168     RegSequence.push_back(Reg);
00169   RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1));
00170   RSD.UsedByIndices.set(LUIdx);
00171 }
00172 
00173 void
00174 RegUseTracker::DropRegister(const SCEV *Reg, size_t LUIdx) {
00175   RegUsesTy::iterator It = RegUsesMap.find(Reg);
00176   assert(It != RegUsesMap.end());
00177   RegSortData &RSD = It->second;
00178   assert(RSD.UsedByIndices.size() > LUIdx);
00179   RSD.UsedByIndices.reset(LUIdx);
00180 }
00181 
00182 void
00183 RegUseTracker::SwapAndDropUse(size_t LUIdx, size_t LastLUIdx) {
00184   assert(LUIdx <= LastLUIdx);
00185 
00186   // Update RegUses. The data structure is not optimized for this purpose;
00187   // we must iterate through it and update each of the bit vectors.
00188   for (RegUsesTy::iterator I = RegUsesMap.begin(), E = RegUsesMap.end();
00189        I != E; ++I) {
00190     SmallBitVector &UsedByIndices = I->second.UsedByIndices;
00191     if (LUIdx < UsedByIndices.size())
00192       UsedByIndices[LUIdx] =
00193         LastLUIdx < UsedByIndices.size() ? UsedByIndices[LastLUIdx] : 0;
00194     UsedByIndices.resize(std::min(UsedByIndices.size(), LastLUIdx));
00195   }
00196 }
00197 
00198 bool
00199 RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const {
00200   RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
00201   if (I == RegUsesMap.end())
00202     return false;
00203   const SmallBitVector &UsedByIndices = I->second.UsedByIndices;
00204   int i = UsedByIndices.find_first();
00205   if (i == -1) return false;
00206   if ((size_t)i != LUIdx) return true;
00207   return UsedByIndices.find_next(i) != -1;
00208 }
00209 
00210 const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const {
00211   RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
00212   assert(I != RegUsesMap.end() && "Unknown register!");
00213   return I->second.UsedByIndices;
00214 }
00215 
00216 void RegUseTracker::clear() {
00217   RegUsesMap.clear();
00218   RegSequence.clear();
00219 }
00220 
00221 namespace {
00222 
00223 /// Formula - This class holds information that describes a formula for
00224 /// computing satisfying a use. It may include broken-out immediates and scaled
00225 /// registers.
00226 struct Formula {
00227   /// Global base address used for complex addressing.
00228   GlobalValue *BaseGV;
00229 
00230   /// Base offset for complex addressing.
00231   int64_t BaseOffset;
00232 
00233   /// Whether any complex addressing has a base register.
00234   bool HasBaseReg;
00235 
00236   /// The scale of any complex addressing.
00237   int64_t Scale;
00238 
00239   /// BaseRegs - The list of "base" registers for this use. When this is
00240   /// non-empty. The canonical representation of a formula is
00241   /// 1. BaseRegs.size > 1 implies ScaledReg != NULL and
00242   /// 2. ScaledReg != NULL implies Scale != 1 || !BaseRegs.empty().
00243   /// #1 enforces that the scaled register is always used when at least two
00244   /// registers are needed by the formula: e.g., reg1 + reg2 is reg1 + 1 * reg2.
00245   /// #2 enforces that 1 * reg is reg.
00246   /// This invariant can be temporarly broken while building a formula.
00247   /// However, every formula inserted into the LSRInstance must be in canonical
00248   /// form.
00249   SmallVector<const SCEV *, 4> BaseRegs;
00250 
00251   /// ScaledReg - The 'scaled' register for this use. This should be non-null
00252   /// when Scale is not zero.
00253   const SCEV *ScaledReg;
00254 
00255   /// UnfoldedOffset - An additional constant offset which added near the
00256   /// use. This requires a temporary register, but the offset itself can
00257   /// live in an add immediate field rather than a register.
00258   int64_t UnfoldedOffset;
00259 
00260   Formula()
00261       : BaseGV(nullptr), BaseOffset(0), HasBaseReg(false), Scale(0),
00262         ScaledReg(nullptr), UnfoldedOffset(0) {}
00263 
00264   void InitialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE);
00265 
00266   bool isCanonical() const;
00267 
00268   void Canonicalize();
00269 
00270   bool Unscale();
00271 
00272   size_t getNumRegs() const;
00273   Type *getType() const;
00274 
00275   void DeleteBaseReg(const SCEV *&S);
00276 
00277   bool referencesReg(const SCEV *S) const;
00278   bool hasRegsUsedByUsesOtherThan(size_t LUIdx,
00279                                   const RegUseTracker &RegUses) const;
00280 
00281   void print(raw_ostream &OS) const;
00282   void dump() const;
00283 };
00284 
00285 }
00286 
00287 /// DoInitialMatch - Recursion helper for InitialMatch.
00288 static void DoInitialMatch(const SCEV *S, Loop *L,
00289                            SmallVectorImpl<const SCEV *> &Good,
00290                            SmallVectorImpl<const SCEV *> &Bad,
00291                            ScalarEvolution &SE) {
00292   // Collect expressions which properly dominate the loop header.
00293   if (SE.properlyDominates(S, L->getHeader())) {
00294     Good.push_back(S);
00295     return;
00296   }
00297 
00298   // Look at add operands.
00299   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
00300     for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
00301          I != E; ++I)
00302       DoInitialMatch(*I, L, Good, Bad, SE);
00303     return;
00304   }
00305 
00306   // Look at addrec operands.
00307   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
00308     if (!AR->getStart()->isZero()) {
00309       DoInitialMatch(AR->getStart(), L, Good, Bad, SE);
00310       DoInitialMatch(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
00311                                       AR->getStepRecurrence(SE),
00312                                       // FIXME: AR->getNoWrapFlags()
00313                                       AR->getLoop(), SCEV::FlagAnyWrap),
00314                      L, Good, Bad, SE);
00315       return;
00316     }
00317 
00318   // Handle a multiplication by -1 (negation) if it didn't fold.
00319   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S))
00320     if (Mul->getOperand(0)->isAllOnesValue()) {
00321       SmallVector<const SCEV *, 4> Ops(Mul->op_begin()+1, Mul->op_end());
00322       const SCEV *NewMul = SE.getMulExpr(Ops);
00323 
00324       SmallVector<const SCEV *, 4> MyGood;
00325       SmallVector<const SCEV *, 4> MyBad;
00326       DoInitialMatch(NewMul, L, MyGood, MyBad, SE);
00327       const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue(
00328         SE.getEffectiveSCEVType(NewMul->getType())));
00329       for (SmallVectorImpl<const SCEV *>::const_iterator I = MyGood.begin(),
00330            E = MyGood.end(); I != E; ++I)
00331         Good.push_back(SE.getMulExpr(NegOne, *I));
00332       for (SmallVectorImpl<const SCEV *>::const_iterator I = MyBad.begin(),
00333            E = MyBad.end(); I != E; ++I)
00334         Bad.push_back(SE.getMulExpr(NegOne, *I));
00335       return;
00336     }
00337 
00338   // Ok, we can't do anything interesting. Just stuff the whole thing into a
00339   // register and hope for the best.
00340   Bad.push_back(S);
00341 }
00342 
00343 /// InitialMatch - Incorporate loop-variant parts of S into this Formula,
00344 /// attempting to keep all loop-invariant and loop-computable values in a
00345 /// single base register.
00346 void Formula::InitialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE) {
00347   SmallVector<const SCEV *, 4> Good;
00348   SmallVector<const SCEV *, 4> Bad;
00349   DoInitialMatch(S, L, Good, Bad, SE);
00350   if (!Good.empty()) {
00351     const SCEV *Sum = SE.getAddExpr(Good);
00352     if (!Sum->isZero())
00353       BaseRegs.push_back(Sum);
00354     HasBaseReg = true;
00355   }
00356   if (!Bad.empty()) {
00357     const SCEV *Sum = SE.getAddExpr(Bad);
00358     if (!Sum->isZero())
00359       BaseRegs.push_back(Sum);
00360     HasBaseReg = true;
00361   }
00362   Canonicalize();
00363 }
00364 
00365 /// \brief Check whether or not this formula statisfies the canonical
00366 /// representation.
00367 /// \see Formula::BaseRegs.
00368 bool Formula::isCanonical() const {
00369   if (ScaledReg)
00370     return Scale != 1 || !BaseRegs.empty();
00371   return BaseRegs.size() <= 1;
00372 }
00373 
00374 /// \brief Helper method to morph a formula into its canonical representation.
00375 /// \see Formula::BaseRegs.
00376 /// Every formula having more than one base register, must use the ScaledReg
00377 /// field. Otherwise, we would have to do special cases everywhere in LSR
00378 /// to treat reg1 + reg2 + ... the same way as reg1 + 1*reg2 + ...
00379 /// On the other hand, 1*reg should be canonicalized into reg.
00380 void Formula::Canonicalize() {
00381   if (isCanonical())
00382     return;
00383   // So far we did not need this case. This is easy to implement but it is
00384   // useless to maintain dead code. Beside it could hurt compile time.
00385   assert(!BaseRegs.empty() && "1*reg => reg, should not be needed.");
00386   // Keep the invariant sum in BaseRegs and one of the variant sum in ScaledReg.
00387   ScaledReg = BaseRegs.back();
00388   BaseRegs.pop_back();
00389   Scale = 1;
00390   size_t BaseRegsSize = BaseRegs.size();
00391   size_t Try = 0;
00392   // If ScaledReg is an invariant, try to find a variant expression.
00393   while (Try < BaseRegsSize && !isa<SCEVAddRecExpr>(ScaledReg))
00394     std::swap(ScaledReg, BaseRegs[Try++]);
00395 }
00396 
00397 /// \brief Get rid of the scale in the formula.
00398 /// In other words, this method morphes reg1 + 1*reg2 into reg1 + reg2.
00399 /// \return true if it was possible to get rid of the scale, false otherwise.
00400 /// \note After this operation the formula may not be in the canonical form.
00401 bool Formula::Unscale() {
00402   if (Scale != 1)
00403     return false;
00404   Scale = 0;
00405   BaseRegs.push_back(ScaledReg);
00406   ScaledReg = nullptr;
00407   return true;
00408 }
00409 
00410 /// getNumRegs - Return the total number of register operands used by this
00411 /// formula. This does not include register uses implied by non-constant
00412 /// addrec strides.
00413 size_t Formula::getNumRegs() const {
00414   return !!ScaledReg + BaseRegs.size();
00415 }
00416 
00417 /// getType - Return the type of this formula, if it has one, or null
00418 /// otherwise. This type is meaningless except for the bit size.
00419 Type *Formula::getType() const {
00420   return !BaseRegs.empty() ? BaseRegs.front()->getType() :
00421          ScaledReg ? ScaledReg->getType() :
00422          BaseGV ? BaseGV->getType() :
00423          nullptr;
00424 }
00425 
00426 /// DeleteBaseReg - Delete the given base reg from the BaseRegs list.
00427 void Formula::DeleteBaseReg(const SCEV *&S) {
00428   if (&S != &BaseRegs.back())
00429     std::swap(S, BaseRegs.back());
00430   BaseRegs.pop_back();
00431 }
00432 
00433 /// referencesReg - Test if this formula references the given register.
00434 bool Formula::referencesReg(const SCEV *S) const {
00435   return S == ScaledReg ||
00436          std::find(BaseRegs.begin(), BaseRegs.end(), S) != BaseRegs.end();
00437 }
00438 
00439 /// hasRegsUsedByUsesOtherThan - Test whether this formula uses registers
00440 /// which are used by uses other than the use with the given index.
00441 bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,
00442                                          const RegUseTracker &RegUses) const {
00443   if (ScaledReg)
00444     if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
00445       return true;
00446   for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
00447        E = BaseRegs.end(); I != E; ++I)
00448     if (RegUses.isRegUsedByUsesOtherThan(*I, LUIdx))
00449       return true;
00450   return false;
00451 }
00452 
00453 void Formula::print(raw_ostream &OS) const {
00454   bool First = true;
00455   if (BaseGV) {
00456     if (!First) OS << " + "; else First = false;
00457     BaseGV->printAsOperand(OS, /*PrintType=*/false);
00458   }
00459   if (BaseOffset != 0) {
00460     if (!First) OS << " + "; else First = false;
00461     OS << BaseOffset;
00462   }
00463   for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
00464        E = BaseRegs.end(); I != E; ++I) {
00465     if (!First) OS << " + "; else First = false;
00466     OS << "reg(" << **I << ')';
00467   }
00468   if (HasBaseReg && BaseRegs.empty()) {
00469     if (!First) OS << " + "; else First = false;
00470     OS << "**error: HasBaseReg**";
00471   } else if (!HasBaseReg && !BaseRegs.empty()) {
00472     if (!First) OS << " + "; else First = false;
00473     OS << "**error: !HasBaseReg**";
00474   }
00475   if (Scale != 0) {
00476     if (!First) OS << " + "; else First = false;
00477     OS << Scale << "*reg(";
00478     if (ScaledReg)
00479       OS << *ScaledReg;
00480     else
00481       OS << "<unknown>";
00482     OS << ')';
00483   }
00484   if (UnfoldedOffset != 0) {
00485     if (!First) OS << " + ";
00486     OS << "imm(" << UnfoldedOffset << ')';
00487   }
00488 }
00489 
00490 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00491 void Formula::dump() const {
00492   print(errs()); errs() << '\n';
00493 }
00494 #endif
00495 
00496 /// isAddRecSExtable - Return true if the given addrec can be sign-extended
00497 /// without changing its value.
00498 static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
00499   Type *WideTy =
00500     IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(AR->getType()) + 1);
00501   return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
00502 }
00503 
00504 /// isAddSExtable - Return true if the given add can be sign-extended
00505 /// without changing its value.
00506 static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {
00507   Type *WideTy =
00508     IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(A->getType()) + 1);
00509   return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy));
00510 }
00511 
00512 /// isMulSExtable - Return true if the given mul can be sign-extended
00513 /// without changing its value.
00514 static bool isMulSExtable(const SCEVMulExpr *M, ScalarEvolution &SE) {
00515   Type *WideTy =
00516     IntegerType::get(SE.getContext(),
00517                      SE.getTypeSizeInBits(M->getType()) * M->getNumOperands());
00518   return isa<SCEVMulExpr>(SE.getSignExtendExpr(M, WideTy));
00519 }
00520 
00521 /// getExactSDiv - Return an expression for LHS /s RHS, if it can be determined
00522 /// and if the remainder is known to be zero,  or null otherwise. If
00523 /// IgnoreSignificantBits is true, expressions like (X * Y) /s Y are simplified
00524 /// to Y, ignoring that the multiplication may overflow, which is useful when
00525 /// the result will be used in a context where the most significant bits are
00526 /// ignored.
00527 static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,
00528                                 ScalarEvolution &SE,
00529                                 bool IgnoreSignificantBits = false) {
00530   // Handle the trivial case, which works for any SCEV type.
00531   if (LHS == RHS)
00532     return SE.getConstant(LHS->getType(), 1);
00533 
00534   // Handle a few RHS special cases.
00535   const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
00536   if (RC) {
00537     const APInt &RA = RC->getValue()->getValue();
00538     // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do
00539     // some folding.
00540     if (RA.isAllOnesValue())
00541       return SE.getMulExpr(LHS, RC);
00542     // Handle x /s 1 as x.
00543     if (RA == 1)
00544       return LHS;
00545   }
00546 
00547   // Check for a division of a constant by a constant.
00548   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
00549     if (!RC)
00550       return nullptr;
00551     const APInt &LA = C->getValue()->getValue();
00552     const APInt &RA = RC->getValue()->getValue();
00553     if (LA.srem(RA) != 0)
00554       return nullptr;
00555     return SE.getConstant(LA.sdiv(RA));
00556   }
00557 
00558   // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
00559   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
00560     if (IgnoreSignificantBits || isAddRecSExtable(AR, SE)) {
00561       const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE,
00562                                       IgnoreSignificantBits);
00563       if (!Step) return nullptr;
00564       const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE,
00565                                        IgnoreSignificantBits);
00566       if (!Start) return nullptr;
00567       // FlagNW is independent of the start value, step direction, and is
00568       // preserved with smaller magnitude steps.
00569       // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
00570       return SE.getAddRecExpr(Start, Step, AR->getLoop(), SCEV::FlagAnyWrap);
00571     }
00572     return nullptr;
00573   }
00574 
00575   // Distribute the sdiv over add operands, if the add doesn't overflow.
00576   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
00577     if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {
00578       SmallVector<const SCEV *, 8> Ops;
00579       for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
00580            I != E; ++I) {
00581         const SCEV *Op = getExactSDiv(*I, RHS, SE,
00582                                       IgnoreSignificantBits);
00583         if (!Op) return nullptr;
00584         Ops.push_back(Op);
00585       }
00586       return SE.getAddExpr(Ops);
00587     }
00588     return nullptr;
00589   }
00590 
00591   // Check for a multiply operand that we can pull RHS out of.
00592   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS)) {
00593     if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {
00594       SmallVector<const SCEV *, 4> Ops;
00595       bool Found = false;
00596       for (SCEVMulExpr::op_iterator I = Mul->op_begin(), E = Mul->op_end();
00597            I != E; ++I) {
00598         const SCEV *S = *I;
00599         if (!Found)
00600           if (const SCEV *Q = getExactSDiv(S, RHS, SE,
00601                                            IgnoreSignificantBits)) {
00602             S = Q;
00603             Found = true;
00604           }
00605         Ops.push_back(S);
00606       }
00607       return Found ? SE.getMulExpr(Ops) : nullptr;
00608     }
00609     return nullptr;
00610   }
00611 
00612   // Otherwise we don't know.
00613   return nullptr;
00614 }
00615 
00616 /// ExtractImmediate - If S involves the addition of a constant integer value,
00617 /// return that integer value, and mutate S to point to a new SCEV with that
00618 /// value excluded.
00619 static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
00620   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
00621     if (C->getValue()->getValue().getMinSignedBits() <= 64) {
00622       S = SE.getConstant(C->getType(), 0);
00623       return C->getValue()->getSExtValue();
00624     }
00625   } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
00626     SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
00627     int64_t Result = ExtractImmediate(NewOps.front(), SE);
00628     if (Result != 0)
00629       S = SE.getAddExpr(NewOps);
00630     return Result;
00631   } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
00632     SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
00633     int64_t Result = ExtractImmediate(NewOps.front(), SE);
00634     if (Result != 0)
00635       S = SE.getAddRecExpr(NewOps, AR->getLoop(),
00636                            // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
00637                            SCEV::FlagAnyWrap);
00638     return Result;
00639   }
00640   return 0;
00641 }
00642 
00643 /// ExtractSymbol - If S involves the addition of a GlobalValue address,
00644 /// return that symbol, and mutate S to point to a new SCEV with that
00645 /// value excluded.
00646 static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
00647   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
00648     if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
00649       S = SE.getConstant(GV->getType(), 0);
00650       return GV;
00651     }
00652   } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
00653     SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
00654     GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
00655     if (Result)
00656       S = SE.getAddExpr(NewOps);
00657     return Result;
00658   } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
00659     SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
00660     GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
00661     if (Result)
00662       S = SE.getAddRecExpr(NewOps, AR->getLoop(),
00663                            // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
00664                            SCEV::FlagAnyWrap);
00665     return Result;
00666   }
00667   return nullptr;
00668 }
00669 
00670 /// isAddressUse - Returns true if the specified instruction is using the
00671 /// specified value as an address.
00672 static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
00673   bool isAddress = isa<LoadInst>(Inst);
00674   if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
00675     if (SI->getOperand(1) == OperandVal)
00676       isAddress = true;
00677   } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
00678     // Addressing modes can also be folded into prefetches and a variety
00679     // of intrinsics.
00680     switch (II->getIntrinsicID()) {
00681       default: break;
00682       case Intrinsic::prefetch:
00683       case Intrinsic::x86_sse_storeu_ps:
00684       case Intrinsic::x86_sse2_storeu_pd:
00685       case Intrinsic::x86_sse2_storeu_dq:
00686       case Intrinsic::x86_sse2_storel_dq:
00687         if (II->getArgOperand(0) == OperandVal)
00688           isAddress = true;
00689         break;
00690     }
00691   }
00692   return isAddress;
00693 }
00694 
00695 /// getAccessType - Return the type of the memory being accessed.
00696 static Type *getAccessType(const Instruction *Inst) {
00697   Type *AccessTy = Inst->getType();
00698   if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
00699     AccessTy = SI->getOperand(0)->getType();
00700   else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
00701     // Addressing modes can also be folded into prefetches and a variety
00702     // of intrinsics.
00703     switch (II->getIntrinsicID()) {
00704     default: break;
00705     case Intrinsic::x86_sse_storeu_ps:
00706     case Intrinsic::x86_sse2_storeu_pd:
00707     case Intrinsic::x86_sse2_storeu_dq:
00708     case Intrinsic::x86_sse2_storel_dq:
00709       AccessTy = II->getArgOperand(0)->getType();
00710       break;
00711     }
00712   }
00713 
00714   // All pointers have the same requirements, so canonicalize them to an
00715   // arbitrary pointer type to minimize variation.
00716   if (PointerType *PTy = dyn_cast<PointerType>(AccessTy))
00717     AccessTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
00718                                 PTy->getAddressSpace());
00719 
00720   return AccessTy;
00721 }
00722 
00723 /// isExistingPhi - Return true if this AddRec is already a phi in its loop.
00724 static bool isExistingPhi(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
00725   for (BasicBlock::iterator I = AR->getLoop()->getHeader()->begin();
00726        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
00727     if (SE.isSCEVable(PN->getType()) &&
00728         (SE.getEffectiveSCEVType(PN->getType()) ==
00729          SE.getEffectiveSCEVType(AR->getType())) &&
00730         SE.getSCEV(PN) == AR)
00731       return true;
00732   }
00733   return false;
00734 }
00735 
00736 /// Check if expanding this expression is likely to incur significant cost. This
00737 /// is tricky because SCEV doesn't track which expressions are actually computed
00738 /// by the current IR.
00739 ///
00740 /// We currently allow expansion of IV increments that involve adds,
00741 /// multiplication by constants, and AddRecs from existing phis.
00742 ///
00743 /// TODO: Allow UDivExpr if we can find an existing IV increment that is an
00744 /// obvious multiple of the UDivExpr.
00745 static bool isHighCostExpansion(const SCEV *S,
00746                                 SmallPtrSetImpl<const SCEV*> &Processed,
00747                                 ScalarEvolution &SE) {
00748   // Zero/One operand expressions
00749   switch (S->getSCEVType()) {
00750   case scUnknown:
00751   case scConstant:
00752     return false;
00753   case scTruncate:
00754     return isHighCostExpansion(cast<SCEVTruncateExpr>(S)->getOperand(),
00755                                Processed, SE);
00756   case scZeroExtend:
00757     return isHighCostExpansion(cast<SCEVZeroExtendExpr>(S)->getOperand(),
00758                                Processed, SE);
00759   case scSignExtend:
00760     return isHighCostExpansion(cast<SCEVSignExtendExpr>(S)->getOperand(),
00761                                Processed, SE);
00762   }
00763 
00764   if (!Processed.insert(S).second)
00765     return false;
00766 
00767   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
00768     for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
00769          I != E; ++I) {
00770       if (isHighCostExpansion(*I, Processed, SE))
00771         return true;
00772     }
00773     return false;
00774   }
00775 
00776   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
00777     if (Mul->getNumOperands() == 2) {
00778       // Multiplication by a constant is ok
00779       if (isa<SCEVConstant>(Mul->getOperand(0)))
00780         return isHighCostExpansion(Mul->getOperand(1), Processed, SE);
00781 
00782       // If we have the value of one operand, check if an existing
00783       // multiplication already generates this expression.
00784       if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Mul->getOperand(1))) {
00785         Value *UVal = U->getValue();
00786         for (User *UR : UVal->users()) {
00787           // If U is a constant, it may be used by a ConstantExpr.
00788           Instruction *UI = dyn_cast<Instruction>(UR);
00789           if (UI && UI->getOpcode() == Instruction::Mul &&
00790               SE.isSCEVable(UI->getType())) {
00791             return SE.getSCEV(UI) == Mul;
00792           }
00793         }
00794       }
00795     }
00796   }
00797 
00798   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
00799     if (isExistingPhi(AR, SE))
00800       return false;
00801   }
00802 
00803   // Fow now, consider any other type of expression (div/mul/min/max) high cost.
00804   return true;
00805 }
00806 
00807 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
00808 /// specified set are trivially dead, delete them and see if this makes any of
00809 /// their operands subsequently dead.
00810 static bool
00811 DeleteTriviallyDeadInstructions(SmallVectorImpl<WeakVH> &DeadInsts) {
00812   bool Changed = false;
00813 
00814   while (!DeadInsts.empty()) {
00815     Value *V = DeadInsts.pop_back_val();
00816     Instruction *I = dyn_cast_or_null<Instruction>(V);
00817 
00818     if (!I || !isInstructionTriviallyDead(I))
00819       continue;
00820 
00821     for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
00822       if (Instruction *U = dyn_cast<Instruction>(*OI)) {
00823         *OI = nullptr;
00824         if (U->use_empty())
00825           DeadInsts.push_back(U);
00826       }
00827 
00828     I->eraseFromParent();
00829     Changed = true;
00830   }
00831 
00832   return Changed;
00833 }
00834 
00835 namespace {
00836 class LSRUse;
00837 }
00838 
00839 /// \brief Check if the addressing mode defined by \p F is completely
00840 /// folded in \p LU at isel time.
00841 /// This includes address-mode folding and special icmp tricks.
00842 /// This function returns true if \p LU can accommodate what \p F
00843 /// defines and up to 1 base + 1 scaled + offset.
00844 /// In other words, if \p F has several base registers, this function may
00845 /// still return true. Therefore, users still need to account for
00846 /// additional base registers and/or unfolded offsets to derive an
00847 /// accurate cost model.
00848 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
00849                                  const LSRUse &LU, const Formula &F);
00850 // Get the cost of the scaling factor used in F for LU.
00851 static unsigned getScalingFactorCost(const TargetTransformInfo &TTI,
00852                                      const LSRUse &LU, const Formula &F);
00853 
00854 namespace {
00855 
00856 /// Cost - This class is used to measure and compare candidate formulae.
00857 class Cost {
00858   /// TODO: Some of these could be merged. Also, a lexical ordering
00859   /// isn't always optimal.
00860   unsigned NumRegs;
00861   unsigned AddRecCost;
00862   unsigned NumIVMuls;
00863   unsigned NumBaseAdds;
00864   unsigned ImmCost;
00865   unsigned SetupCost;
00866   unsigned ScaleCost;
00867 
00868 public:
00869   Cost()
00870     : NumRegs(0), AddRecCost(0), NumIVMuls(0), NumBaseAdds(0), ImmCost(0),
00871       SetupCost(0), ScaleCost(0) {}
00872 
00873   bool operator<(const Cost &Other) const;
00874 
00875   void Lose();
00876 
00877 #ifndef NDEBUG
00878   // Once any of the metrics loses, they must all remain losers.
00879   bool isValid() {
00880     return ((NumRegs | AddRecCost | NumIVMuls | NumBaseAdds
00881              | ImmCost | SetupCost | ScaleCost) != ~0u)
00882       || ((NumRegs & AddRecCost & NumIVMuls & NumBaseAdds
00883            & ImmCost & SetupCost & ScaleCost) == ~0u);
00884   }
00885 #endif
00886 
00887   bool isLoser() {
00888     assert(isValid() && "invalid cost");
00889     return NumRegs == ~0u;
00890   }
00891 
00892   void RateFormula(const TargetTransformInfo &TTI,
00893                    const Formula &F,
00894                    SmallPtrSetImpl<const SCEV *> &Regs,
00895                    const DenseSet<const SCEV *> &VisitedRegs,
00896                    const Loop *L,
00897                    const SmallVectorImpl<int64_t> &Offsets,
00898                    ScalarEvolution &SE, DominatorTree &DT,
00899                    const LSRUse &LU,
00900                    SmallPtrSetImpl<const SCEV *> *LoserRegs = nullptr);
00901 
00902   void print(raw_ostream &OS) const;
00903   void dump() const;
00904 
00905 private:
00906   void RateRegister(const SCEV *Reg,
00907                     SmallPtrSetImpl<const SCEV *> &Regs,
00908                     const Loop *L,
00909                     ScalarEvolution &SE, DominatorTree &DT);
00910   void RatePrimaryRegister(const SCEV *Reg,
00911                            SmallPtrSetImpl<const SCEV *> &Regs,
00912                            const Loop *L,
00913                            ScalarEvolution &SE, DominatorTree &DT,
00914                            SmallPtrSetImpl<const SCEV *> *LoserRegs);
00915 };
00916 
00917 }
00918 
00919 /// RateRegister - Tally up interesting quantities from the given register.
00920 void Cost::RateRegister(const SCEV *Reg,
00921                         SmallPtrSetImpl<const SCEV *> &Regs,
00922                         const Loop *L,
00923                         ScalarEvolution &SE, DominatorTree &DT) {
00924   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
00925     // If this is an addrec for another loop, don't second-guess its addrec phi
00926     // nodes. LSR isn't currently smart enough to reason about more than one
00927     // loop at a time. LSR has already run on inner loops, will not run on outer
00928     // loops, and cannot be expected to change sibling loops.
00929     if (AR->getLoop() != L) {
00930       // If the AddRec exists, consider it's register free and leave it alone.
00931       if (isExistingPhi(AR, SE))
00932         return;
00933 
00934       // Otherwise, do not consider this formula at all.
00935       Lose();
00936       return;
00937     }
00938     AddRecCost += 1; /// TODO: This should be a function of the stride.
00939 
00940     // Add the step value register, if it needs one.
00941     // TODO: The non-affine case isn't precisely modeled here.
00942     if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1))) {
00943       if (!Regs.count(AR->getOperand(1))) {
00944         RateRegister(AR->getOperand(1), Regs, L, SE, DT);
00945         if (isLoser())
00946           return;
00947       }
00948     }
00949   }
00950   ++NumRegs;
00951 
00952   // Rough heuristic; favor registers which don't require extra setup
00953   // instructions in the preheader.
00954   if (!isa<SCEVUnknown>(Reg) &&
00955       !isa<SCEVConstant>(Reg) &&
00956       !(isa<SCEVAddRecExpr>(Reg) &&
00957         (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(Reg)->getStart()) ||
00958          isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart()))))
00959     ++SetupCost;
00960 
00961     NumIVMuls += isa<SCEVMulExpr>(Reg) &&
00962                  SE.hasComputableLoopEvolution(Reg, L);
00963 }
00964 
00965 /// RatePrimaryRegister - Record this register in the set. If we haven't seen it
00966 /// before, rate it. Optional LoserRegs provides a way to declare any formula
00967 /// that refers to one of those regs an instant loser.
00968 void Cost::RatePrimaryRegister(const SCEV *Reg,
00969                                SmallPtrSetImpl<const SCEV *> &Regs,
00970                                const Loop *L,
00971                                ScalarEvolution &SE, DominatorTree &DT,
00972                                SmallPtrSetImpl<const SCEV *> *LoserRegs) {
00973   if (LoserRegs && LoserRegs->count(Reg)) {
00974     Lose();
00975     return;
00976   }
00977   if (Regs.insert(Reg).second) {
00978     RateRegister(Reg, Regs, L, SE, DT);
00979     if (LoserRegs && isLoser())
00980       LoserRegs->insert(Reg);
00981   }
00982 }
00983 
00984 void Cost::RateFormula(const TargetTransformInfo &TTI,
00985                        const Formula &F,
00986                        SmallPtrSetImpl<const SCEV *> &Regs,
00987                        const DenseSet<const SCEV *> &VisitedRegs,
00988                        const Loop *L,
00989                        const SmallVectorImpl<int64_t> &Offsets,
00990                        ScalarEvolution &SE, DominatorTree &DT,
00991                        const LSRUse &LU,
00992                        SmallPtrSetImpl<const SCEV *> *LoserRegs) {
00993   assert(F.isCanonical() && "Cost is accurate only for canonical formula");
00994   // Tally up the registers.
00995   if (const SCEV *ScaledReg = F.ScaledReg) {
00996     if (VisitedRegs.count(ScaledReg)) {
00997       Lose();
00998       return;
00999     }
01000     RatePrimaryRegister(ScaledReg, Regs, L, SE, DT, LoserRegs);
01001     if (isLoser())
01002       return;
01003   }
01004   for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
01005        E = F.BaseRegs.end(); I != E; ++I) {
01006     const SCEV *BaseReg = *I;
01007     if (VisitedRegs.count(BaseReg)) {
01008       Lose();
01009       return;
01010     }
01011     RatePrimaryRegister(BaseReg, Regs, L, SE, DT, LoserRegs);
01012     if (isLoser())
01013       return;
01014   }
01015 
01016   // Determine how many (unfolded) adds we'll need inside the loop.
01017   size_t NumBaseParts = F.getNumRegs();
01018   if (NumBaseParts > 1)
01019     // Do not count the base and a possible second register if the target
01020     // allows to fold 2 registers.
01021     NumBaseAdds +=
01022         NumBaseParts - (1 + (F.Scale && isAMCompletelyFolded(TTI, LU, F)));
01023   NumBaseAdds += (F.UnfoldedOffset != 0);
01024 
01025   // Accumulate non-free scaling amounts.
01026   ScaleCost += getScalingFactorCost(TTI, LU, F);
01027 
01028   // Tally up the non-zero immediates.
01029   for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
01030        E = Offsets.end(); I != E; ++I) {
01031     int64_t Offset = (uint64_t)*I + F.BaseOffset;
01032     if (F.BaseGV)
01033       ImmCost += 64; // Handle symbolic values conservatively.
01034                      // TODO: This should probably be the pointer size.
01035     else if (Offset != 0)
01036       ImmCost += APInt(64, Offset, true).getMinSignedBits();
01037   }
01038   assert(isValid() && "invalid cost");
01039 }
01040 
01041 /// Lose - Set this cost to a losing value.
01042 void Cost::Lose() {
01043   NumRegs = ~0u;
01044   AddRecCost = ~0u;
01045   NumIVMuls = ~0u;
01046   NumBaseAdds = ~0u;
01047   ImmCost = ~0u;
01048   SetupCost = ~0u;
01049   ScaleCost = ~0u;
01050 }
01051 
01052 /// operator< - Choose the lower cost.
01053 bool Cost::operator<(const Cost &Other) const {
01054   return std::tie(NumRegs, AddRecCost, NumIVMuls, NumBaseAdds, ScaleCost,
01055                   ImmCost, SetupCost) <
01056          std::tie(Other.NumRegs, Other.AddRecCost, Other.NumIVMuls,
01057                   Other.NumBaseAdds, Other.ScaleCost, Other.ImmCost,
01058                   Other.SetupCost);
01059 }
01060 
01061 void Cost::print(raw_ostream &OS) const {
01062   OS << NumRegs << " reg" << (NumRegs == 1 ? "" : "s");
01063   if (AddRecCost != 0)
01064     OS << ", with addrec cost " << AddRecCost;
01065   if (NumIVMuls != 0)
01066     OS << ", plus " << NumIVMuls << " IV mul" << (NumIVMuls == 1 ? "" : "s");
01067   if (NumBaseAdds != 0)
01068     OS << ", plus " << NumBaseAdds << " base add"
01069        << (NumBaseAdds == 1 ? "" : "s");
01070   if (ScaleCost != 0)
01071     OS << ", plus " << ScaleCost << " scale cost";
01072   if (ImmCost != 0)
01073     OS << ", plus " << ImmCost << " imm cost";
01074   if (SetupCost != 0)
01075     OS << ", plus " << SetupCost << " setup cost";
01076 }
01077 
01078 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
01079 void Cost::dump() const {
01080   print(errs()); errs() << '\n';
01081 }
01082 #endif
01083 
01084 namespace {
01085 
01086 /// LSRFixup - An operand value in an instruction which is to be replaced
01087 /// with some equivalent, possibly strength-reduced, replacement.
01088 struct LSRFixup {
01089   /// UserInst - The instruction which will be updated.
01090   Instruction *UserInst;
01091 
01092   /// OperandValToReplace - The operand of the instruction which will
01093   /// be replaced. The operand may be used more than once; every instance
01094   /// will be replaced.
01095   Value *OperandValToReplace;
01096 
01097   /// PostIncLoops - If this user is to use the post-incremented value of an
01098   /// induction variable, this variable is non-null and holds the loop
01099   /// associated with the induction variable.
01100   PostIncLoopSet PostIncLoops;
01101 
01102   /// LUIdx - The index of the LSRUse describing the expression which
01103   /// this fixup needs, minus an offset (below).
01104   size_t LUIdx;
01105 
01106   /// Offset - A constant offset to be added to the LSRUse expression.
01107   /// This allows multiple fixups to share the same LSRUse with different
01108   /// offsets, for example in an unrolled loop.
01109   int64_t Offset;
01110 
01111   bool isUseFullyOutsideLoop(const Loop *L) const;
01112 
01113   LSRFixup();
01114 
01115   void print(raw_ostream &OS) const;
01116   void dump() const;
01117 };
01118 
01119 }
01120 
01121 LSRFixup::LSRFixup()
01122   : UserInst(nullptr), OperandValToReplace(nullptr), LUIdx(~size_t(0)),
01123     Offset(0) {}
01124 
01125 /// isUseFullyOutsideLoop - Test whether this fixup always uses its
01126 /// value outside of the given loop.
01127 bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const {
01128   // PHI nodes use their value in their incoming blocks.
01129   if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
01130     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
01131       if (PN->getIncomingValue(i) == OperandValToReplace &&
01132           L->contains(PN->getIncomingBlock(i)))
01133         return false;
01134     return true;
01135   }
01136 
01137   return !L->contains(UserInst);
01138 }
01139 
01140 void LSRFixup::print(raw_ostream &OS) const {
01141   OS << "UserInst=";
01142   // Store is common and interesting enough to be worth special-casing.
01143   if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
01144     OS << "store ";
01145     Store->getOperand(0)->printAsOperand(OS, /*PrintType=*/false);
01146   } else if (UserInst->getType()->isVoidTy())
01147     OS << UserInst->getOpcodeName();
01148   else
01149     UserInst->printAsOperand(OS, /*PrintType=*/false);
01150 
01151   OS << ", OperandValToReplace=";
01152   OperandValToReplace->printAsOperand(OS, /*PrintType=*/false);
01153 
01154   for (PostIncLoopSet::const_iterator I = PostIncLoops.begin(),
01155        E = PostIncLoops.end(); I != E; ++I) {
01156     OS << ", PostIncLoop=";
01157     (*I)->getHeader()->printAsOperand(OS, /*PrintType=*/false);
01158   }
01159 
01160   if (LUIdx != ~size_t(0))
01161     OS << ", LUIdx=" << LUIdx;
01162 
01163   if (Offset != 0)
01164     OS << ", Offset=" << Offset;
01165 }
01166 
01167 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
01168 void LSRFixup::dump() const {
01169   print(errs()); errs() << '\n';
01170 }
01171 #endif
01172 
01173 namespace {
01174 
01175 /// UniquifierDenseMapInfo - A DenseMapInfo implementation for holding
01176 /// DenseMaps and DenseSets of sorted SmallVectors of const SCEV*.
01177 struct UniquifierDenseMapInfo {
01178   static SmallVector<const SCEV *, 4> getEmptyKey() {
01179     SmallVector<const SCEV *, 4>  V;
01180     V.push_back(reinterpret_cast<const SCEV *>(-1));
01181     return V;
01182   }
01183 
01184   static SmallVector<const SCEV *, 4> getTombstoneKey() {
01185     SmallVector<const SCEV *, 4> V;
01186     V.push_back(reinterpret_cast<const SCEV *>(-2));
01187     return V;
01188   }
01189 
01190   static unsigned getHashValue(const SmallVector<const SCEV *, 4> &V) {
01191     return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
01192   }
01193 
01194   static bool isEqual(const SmallVector<const SCEV *, 4> &LHS,
01195                       const SmallVector<const SCEV *, 4> &RHS) {
01196     return LHS == RHS;
01197   }
01198 };
01199 
01200 /// LSRUse - This class holds the state that LSR keeps for each use in
01201 /// IVUsers, as well as uses invented by LSR itself. It includes information
01202 /// about what kinds of things can be folded into the user, information about
01203 /// the user itself, and information about how the use may be satisfied.
01204 /// TODO: Represent multiple users of the same expression in common?
01205 class LSRUse {
01206   DenseSet<SmallVector<const SCEV *, 4>, UniquifierDenseMapInfo> Uniquifier;
01207 
01208 public:
01209   /// KindType - An enum for a kind of use, indicating what types of
01210   /// scaled and immediate operands it might support.
01211   enum KindType {
01212     Basic,   ///< A normal use, with no folding.
01213     Special, ///< A special case of basic, allowing -1 scales.
01214     Address, ///< An address use; folding according to TargetLowering
01215     ICmpZero ///< An equality icmp with both operands folded into one.
01216     // TODO: Add a generic icmp too?
01217   };
01218 
01219   typedef PointerIntPair<const SCEV *, 2, KindType> SCEVUseKindPair;
01220 
01221   KindType Kind;
01222   Type *AccessTy;
01223 
01224   SmallVector<int64_t, 8> Offsets;
01225   int64_t MinOffset;
01226   int64_t MaxOffset;
01227 
01228   /// AllFixupsOutsideLoop - This records whether all of the fixups using this
01229   /// LSRUse are outside of the loop, in which case some special-case heuristics
01230   /// may be used.
01231   bool AllFixupsOutsideLoop;
01232 
01233   /// RigidFormula is set to true to guarantee that this use will be associated
01234   /// with a single formula--the one that initially matched. Some SCEV
01235   /// expressions cannot be expanded. This allows LSR to consider the registers
01236   /// used by those expressions without the need to expand them later after
01237   /// changing the formula.
01238   bool RigidFormula;
01239 
01240   /// WidestFixupType - This records the widest use type for any fixup using
01241   /// this LSRUse. FindUseWithSimilarFormula can't consider uses with different
01242   /// max fixup widths to be equivalent, because the narrower one may be relying
01243   /// on the implicit truncation to truncate away bogus bits.
01244   Type *WidestFixupType;
01245 
01246   /// Formulae - A list of ways to build a value that can satisfy this user.
01247   /// After the list is populated, one of these is selected heuristically and
01248   /// used to formulate a replacement for OperandValToReplace in UserInst.
01249   SmallVector<Formula, 12> Formulae;
01250 
01251   /// Regs - The set of register candidates used by all formulae in this LSRUse.
01252   SmallPtrSet<const SCEV *, 4> Regs;
01253 
01254   LSRUse(KindType K, Type *T) : Kind(K), AccessTy(T),
01255                                       MinOffset(INT64_MAX),
01256                                       MaxOffset(INT64_MIN),
01257                                       AllFixupsOutsideLoop(true),
01258                                       RigidFormula(false),
01259                                       WidestFixupType(nullptr) {}
01260 
01261   bool HasFormulaWithSameRegs(const Formula &F) const;
01262   bool InsertFormula(const Formula &F);
01263   void DeleteFormula(Formula &F);
01264   void RecomputeRegs(size_t LUIdx, RegUseTracker &Reguses);
01265 
01266   void print(raw_ostream &OS) const;
01267   void dump() const;
01268 };
01269 
01270 }
01271 
01272 /// HasFormula - Test whether this use as a formula which has the same
01273 /// registers as the given formula.
01274 bool LSRUse::HasFormulaWithSameRegs(const Formula &F) const {
01275   SmallVector<const SCEV *, 4> Key = F.BaseRegs;
01276   if (F.ScaledReg) Key.push_back(F.ScaledReg);
01277   // Unstable sort by host order ok, because this is only used for uniquifying.
01278   std::sort(Key.begin(), Key.end());
01279   return Uniquifier.count(Key);
01280 }
01281 
01282 /// InsertFormula - If the given formula has not yet been inserted, add it to
01283 /// the list, and return true. Return false otherwise.
01284 /// The formula must be in canonical form.
01285 bool LSRUse::InsertFormula(const Formula &F) {
01286   assert(F.isCanonical() && "Invalid canonical representation");
01287 
01288   if (!Formulae.empty() && RigidFormula)
01289     return false;
01290 
01291   SmallVector<const SCEV *, 4> Key = F.BaseRegs;
01292   if (F.ScaledReg) Key.push_back(F.ScaledReg);
01293   // Unstable sort by host order ok, because this is only used for uniquifying.
01294   std::sort(Key.begin(), Key.end());
01295 
01296   if (!Uniquifier.insert(Key).second)
01297     return false;
01298 
01299   // Using a register to hold the value of 0 is not profitable.
01300   assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
01301          "Zero allocated in a scaled register!");
01302 #ifndef NDEBUG
01303   for (SmallVectorImpl<const SCEV *>::const_iterator I =
01304        F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I)
01305     assert(!(*I)->isZero() && "Zero allocated in a base register!");
01306 #endif
01307 
01308   // Add the formula to the list.
01309   Formulae.push_back(F);
01310 
01311   // Record registers now being used by this use.
01312   Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
01313   if (F.ScaledReg)
01314     Regs.insert(F.ScaledReg);
01315 
01316   return true;
01317 }
01318 
01319 /// DeleteFormula - Remove the given formula from this use's list.
01320 void LSRUse::DeleteFormula(Formula &F) {
01321   if (&F != &Formulae.back())
01322     std::swap(F, Formulae.back());
01323   Formulae.pop_back();
01324 }
01325 
01326 /// RecomputeRegs - Recompute the Regs field, and update RegUses.
01327 void LSRUse::RecomputeRegs(size_t LUIdx, RegUseTracker &RegUses) {
01328   // Now that we've filtered out some formulae, recompute the Regs set.
01329   SmallPtrSet<const SCEV *, 4> OldRegs = std::move(Regs);
01330   Regs.clear();
01331   for (const Formula &F : Formulae) {
01332     if (F.ScaledReg) Regs.insert(F.ScaledReg);
01333     Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
01334   }
01335 
01336   // Update the RegTracker.
01337   for (const SCEV *S : OldRegs)
01338     if (!Regs.count(S))
01339       RegUses.DropRegister(S, LUIdx);
01340 }
01341 
01342 void LSRUse::print(raw_ostream &OS) const {
01343   OS << "LSR Use: Kind=";
01344   switch (Kind) {
01345   case Basic:    OS << "Basic"; break;
01346   case Special:  OS << "Special"; break;
01347   case ICmpZero: OS << "ICmpZero"; break;
01348   case Address:
01349     OS << "Address of ";
01350     if (AccessTy->isPointerTy())
01351       OS << "pointer"; // the full pointer type could be really verbose
01352     else
01353       OS << *AccessTy;
01354   }
01355 
01356   OS << ", Offsets={";
01357   for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
01358        E = Offsets.end(); I != E; ++I) {
01359     OS << *I;
01360     if (std::next(I) != E)
01361       OS << ',';
01362   }
01363   OS << '}';
01364 
01365   if (AllFixupsOutsideLoop)
01366     OS << ", all-fixups-outside-loop";
01367 
01368   if (WidestFixupType)
01369     OS << ", widest fixup type: " << *WidestFixupType;
01370 }
01371 
01372 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
01373 void LSRUse::dump() const {
01374   print(errs()); errs() << '\n';
01375 }
01376 #endif
01377 
01378 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
01379                                  LSRUse::KindType Kind, Type *AccessTy,
01380                                  GlobalValue *BaseGV, int64_t BaseOffset,
01381                                  bool HasBaseReg, int64_t Scale) {
01382   switch (Kind) {
01383   case LSRUse::Address:
01384     return TTI.isLegalAddressingMode(AccessTy, BaseGV, BaseOffset, HasBaseReg, Scale);
01385 
01386   case LSRUse::ICmpZero:
01387     // There's not even a target hook for querying whether it would be legal to
01388     // fold a GV into an ICmp.
01389     if (BaseGV)
01390       return false;
01391 
01392     // ICmp only has two operands; don't allow more than two non-trivial parts.
01393     if (Scale != 0 && HasBaseReg && BaseOffset != 0)
01394       return false;
01395 
01396     // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
01397     // putting the scaled register in the other operand of the icmp.
01398     if (Scale != 0 && Scale != -1)
01399       return false;
01400 
01401     // If we have low-level target information, ask the target if it can fold an
01402     // integer immediate on an icmp.
01403     if (BaseOffset != 0) {
01404       // We have one of:
01405       // ICmpZero     BaseReg + BaseOffset => ICmp BaseReg, -BaseOffset
01406       // ICmpZero -1*ScaleReg + BaseOffset => ICmp ScaleReg, BaseOffset
01407       // Offs is the ICmp immediate.
01408       if (Scale == 0)
01409         // The cast does the right thing with INT64_MIN.
01410         BaseOffset = -(uint64_t)BaseOffset;
01411       return TTI.isLegalICmpImmediate(BaseOffset);
01412     }
01413 
01414     // ICmpZero BaseReg + -1*ScaleReg => ICmp BaseReg, ScaleReg
01415     return true;
01416 
01417   case LSRUse::Basic:
01418     // Only handle single-register values.
01419     return !BaseGV && Scale == 0 && BaseOffset == 0;
01420 
01421   case LSRUse::Special:
01422     // Special case Basic to handle -1 scales.
01423     return !BaseGV && (Scale == 0 || Scale == -1) && BaseOffset == 0;
01424   }
01425 
01426   llvm_unreachable("Invalid LSRUse Kind!");
01427 }
01428 
01429 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
01430                                  int64_t MinOffset, int64_t MaxOffset,
01431                                  LSRUse::KindType Kind, Type *AccessTy,
01432                                  GlobalValue *BaseGV, int64_t BaseOffset,
01433                                  bool HasBaseReg, int64_t Scale) {
01434   // Check for overflow.
01435   if (((int64_t)((uint64_t)BaseOffset + MinOffset) > BaseOffset) !=
01436       (MinOffset > 0))
01437     return false;
01438   MinOffset = (uint64_t)BaseOffset + MinOffset;
01439   if (((int64_t)((uint64_t)BaseOffset + MaxOffset) > BaseOffset) !=
01440       (MaxOffset > 0))
01441     return false;
01442   MaxOffset = (uint64_t)BaseOffset + MaxOffset;
01443 
01444   return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MinOffset,
01445                               HasBaseReg, Scale) &&
01446          isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MaxOffset,
01447                               HasBaseReg, Scale);
01448 }
01449 
01450 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
01451                                  int64_t MinOffset, int64_t MaxOffset,
01452                                  LSRUse::KindType Kind, Type *AccessTy,
01453                                  const Formula &F) {
01454   // For the purpose of isAMCompletelyFolded either having a canonical formula
01455   // or a scale not equal to zero is correct.
01456   // Problems may arise from non canonical formulae having a scale == 0.
01457   // Strictly speaking it would best to just rely on canonical formulae.
01458   // However, when we generate the scaled formulae, we first check that the
01459   // scaling factor is profitable before computing the actual ScaledReg for
01460   // compile time sake.
01461   assert((F.isCanonical() || F.Scale != 0));
01462   return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
01463                               F.BaseGV, F.BaseOffset, F.HasBaseReg, F.Scale);
01464 }
01465 
01466 /// isLegalUse - Test whether we know how to expand the current formula.
01467 static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset,
01468                        int64_t MaxOffset, LSRUse::KindType Kind, Type *AccessTy,
01469                        GlobalValue *BaseGV, int64_t BaseOffset, bool HasBaseReg,
01470                        int64_t Scale) {
01471   // We know how to expand completely foldable formulae.
01472   return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
01473                               BaseOffset, HasBaseReg, Scale) ||
01474          // Or formulae that use a base register produced by a sum of base
01475          // registers.
01476          (Scale == 1 &&
01477           isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
01478                                BaseGV, BaseOffset, true, 0));
01479 }
01480 
01481 static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset,
01482                        int64_t MaxOffset, LSRUse::KindType Kind, Type *AccessTy,
01483                        const Formula &F) {
01484   return isLegalUse(TTI, MinOffset, MaxOffset, Kind, AccessTy, F.BaseGV,
01485                     F.BaseOffset, F.HasBaseReg, F.Scale);
01486 }
01487 
01488 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
01489                                  const LSRUse &LU, const Formula &F) {
01490   return isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,
01491                               LU.AccessTy, F.BaseGV, F.BaseOffset, F.HasBaseReg,
01492                               F.Scale);
01493 }
01494 
01495 static unsigned getScalingFactorCost(const TargetTransformInfo &TTI,
01496                                      const LSRUse &LU, const Formula &F) {
01497   if (!F.Scale)
01498     return 0;
01499 
01500   // If the use is not completely folded in that instruction, we will have to
01501   // pay an extra cost only for scale != 1.
01502   if (!isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,
01503                             LU.AccessTy, F))
01504     return F.Scale != 1;
01505 
01506   switch (LU.Kind) {
01507   case LSRUse::Address: {
01508     // Check the scaling factor cost with both the min and max offsets.
01509     int ScaleCostMinOffset =
01510       TTI.getScalingFactorCost(LU.AccessTy, F.BaseGV,
01511                                F.BaseOffset + LU.MinOffset,
01512                                F.HasBaseReg, F.Scale);
01513     int ScaleCostMaxOffset =
01514       TTI.getScalingFactorCost(LU.AccessTy, F.BaseGV,
01515                                F.BaseOffset + LU.MaxOffset,
01516                                F.HasBaseReg, F.Scale);
01517 
01518     assert(ScaleCostMinOffset >= 0 && ScaleCostMaxOffset >= 0 &&
01519            "Legal addressing mode has an illegal cost!");
01520     return std::max(ScaleCostMinOffset, ScaleCostMaxOffset);
01521   }
01522   case LSRUse::ICmpZero:
01523   case LSRUse::Basic:
01524   case LSRUse::Special:
01525     // The use is completely folded, i.e., everything is folded into the
01526     // instruction.
01527     return 0;
01528   }
01529 
01530   llvm_unreachable("Invalid LSRUse Kind!");
01531 }
01532 
01533 static bool isAlwaysFoldable(const TargetTransformInfo &TTI,
01534                              LSRUse::KindType Kind, Type *AccessTy,
01535                              GlobalValue *BaseGV, int64_t BaseOffset,
01536                              bool HasBaseReg) {
01537   // Fast-path: zero is always foldable.
01538   if (BaseOffset == 0 && !BaseGV) return true;
01539 
01540   // Conservatively, create an address with an immediate and a
01541   // base and a scale.
01542   int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
01543 
01544   // Canonicalize a scale of 1 to a base register if the formula doesn't
01545   // already have a base register.
01546   if (!HasBaseReg && Scale == 1) {
01547     Scale = 0;
01548     HasBaseReg = true;
01549   }
01550 
01551   return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, BaseOffset,
01552                               HasBaseReg, Scale);
01553 }
01554 
01555 static bool isAlwaysFoldable(const TargetTransformInfo &TTI,
01556                              ScalarEvolution &SE, int64_t MinOffset,
01557                              int64_t MaxOffset, LSRUse::KindType Kind,
01558                              Type *AccessTy, const SCEV *S, bool HasBaseReg) {
01559   // Fast-path: zero is always foldable.
01560   if (S->isZero()) return true;
01561 
01562   // Conservatively, create an address with an immediate and a
01563   // base and a scale.
01564   int64_t BaseOffset = ExtractImmediate(S, SE);
01565   GlobalValue *BaseGV = ExtractSymbol(S, SE);
01566 
01567   // If there's anything else involved, it's not foldable.
01568   if (!S->isZero()) return false;
01569 
01570   // Fast-path: zero is always foldable.
01571   if (BaseOffset == 0 && !BaseGV) return true;
01572 
01573   // Conservatively, create an address with an immediate and a
01574   // base and a scale.
01575   int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
01576 
01577   return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
01578                               BaseOffset, HasBaseReg, Scale);
01579 }
01580 
01581 namespace {
01582 
01583 /// IVInc - An individual increment in a Chain of IV increments.
01584 /// Relate an IV user to an expression that computes the IV it uses from the IV
01585 /// used by the previous link in the Chain.
01586 ///
01587 /// For the head of a chain, IncExpr holds the absolute SCEV expression for the
01588 /// original IVOperand. The head of the chain's IVOperand is only valid during
01589 /// chain collection, before LSR replaces IV users. During chain generation,
01590 /// IncExpr can be used to find the new IVOperand that computes the same
01591 /// expression.
01592 struct IVInc {
01593   Instruction *UserInst;
01594   Value* IVOperand;
01595   const SCEV *IncExpr;
01596 
01597   IVInc(Instruction *U, Value *O, const SCEV *E):
01598     UserInst(U), IVOperand(O), IncExpr(E) {}
01599 };
01600 
01601 // IVChain - The list of IV increments in program order.
01602 // We typically add the head of a chain without finding subsequent links.
01603 struct IVChain {
01604   SmallVector<IVInc,1> Incs;
01605   const SCEV *ExprBase;
01606 
01607   IVChain() : ExprBase(nullptr) {}
01608 
01609   IVChain(const IVInc &Head, const SCEV *Base)
01610     : Incs(1, Head), ExprBase(Base) {}
01611 
01612   typedef SmallVectorImpl<IVInc>::const_iterator const_iterator;
01613 
01614   // begin - return the first increment in the chain.
01615   const_iterator begin() const {
01616     assert(!Incs.empty());
01617     return std::next(Incs.begin());
01618   }
01619   const_iterator end() const {
01620     return Incs.end();
01621   }
01622 
01623   // hasIncs - Returns true if this chain contains any increments.
01624   bool hasIncs() const { return Incs.size() >= 2; }
01625 
01626   // add - Add an IVInc to the end of this chain.
01627   void add(const IVInc &X) { Incs.push_back(X); }
01628 
01629   // tailUserInst - Returns the last UserInst in the chain.
01630   Instruction *tailUserInst() const { return Incs.back().UserInst; }
01631 
01632   // isProfitableIncrement - Returns true if IncExpr can be profitably added to
01633   // this chain.
01634   bool isProfitableIncrement(const SCEV *OperExpr,
01635                              const SCEV *IncExpr,
01636                              ScalarEvolution&);
01637 };
01638 
01639 /// ChainUsers - Helper for CollectChains to track multiple IV increment uses.
01640 /// Distinguish between FarUsers that definitely cross IV increments and
01641 /// NearUsers that may be used between IV increments.
01642 struct ChainUsers {
01643   SmallPtrSet<Instruction*, 4> FarUsers;
01644   SmallPtrSet<Instruction*, 4> NearUsers;
01645 };
01646 
01647 /// LSRInstance - This class holds state for the main loop strength reduction
01648 /// logic.
01649 class LSRInstance {
01650   IVUsers &IU;
01651   ScalarEvolution &SE;
01652   DominatorTree &DT;
01653   LoopInfo &LI;
01654   const TargetTransformInfo &TTI;
01655   Loop *const L;
01656   bool Changed;
01657 
01658   /// IVIncInsertPos - This is the insert position that the current loop's
01659   /// induction variable increment should be placed. In simple loops, this is
01660   /// the latch block's terminator. But in more complicated cases, this is a
01661   /// position which will dominate all the in-loop post-increment users.
01662   Instruction *IVIncInsertPos;
01663 
01664   /// Factors - Interesting factors between use strides.
01665   SmallSetVector<int64_t, 8> Factors;
01666 
01667   /// Types - Interesting use types, to facilitate truncation reuse.
01668   SmallSetVector<Type *, 4> Types;
01669 
01670   /// Fixups - The list of operands which are to be replaced.
01671   SmallVector<LSRFixup, 16> Fixups;
01672 
01673   /// Uses - The list of interesting uses.
01674   SmallVector<LSRUse, 16> Uses;
01675 
01676   /// RegUses - Track which uses use which register candidates.
01677   RegUseTracker RegUses;
01678 
01679   // Limit the number of chains to avoid quadratic behavior. We don't expect to
01680   // have more than a few IV increment chains in a loop. Missing a Chain falls
01681   // back to normal LSR behavior for those uses.
01682   static const unsigned MaxChains = 8;
01683 
01684   /// IVChainVec - IV users can form a chain of IV increments.
01685   SmallVector<IVChain, MaxChains> IVChainVec;
01686 
01687   /// IVIncSet - IV users that belong to profitable IVChains.
01688   SmallPtrSet<Use*, MaxChains> IVIncSet;
01689 
01690   void OptimizeShadowIV();
01691   bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
01692   ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
01693   void OptimizeLoopTermCond();
01694 
01695   void ChainInstruction(Instruction *UserInst, Instruction *IVOper,
01696                         SmallVectorImpl<ChainUsers> &ChainUsersVec);
01697   void FinalizeChain(IVChain &Chain);
01698   void CollectChains();
01699   void GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter,
01700                        SmallVectorImpl<WeakVH> &DeadInsts);
01701 
01702   void CollectInterestingTypesAndFactors();
01703   void CollectFixupsAndInitialFormulae();
01704 
01705   LSRFixup &getNewFixup() {
01706     Fixups.push_back(LSRFixup());
01707     return Fixups.back();
01708   }
01709 
01710   // Support for sharing of LSRUses between LSRFixups.
01711   typedef DenseMap<LSRUse::SCEVUseKindPair, size_t> UseMapTy;
01712   UseMapTy UseMap;
01713 
01714   bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
01715                           LSRUse::KindType Kind, Type *AccessTy);
01716 
01717   std::pair<size_t, int64_t> getUse(const SCEV *&Expr,
01718                                     LSRUse::KindType Kind,
01719                                     Type *AccessTy);
01720 
01721   void DeleteUse(LSRUse &LU, size_t LUIdx);
01722 
01723   LSRUse *FindUseWithSimilarFormula(const Formula &F, const LSRUse &OrigLU);
01724 
01725   void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
01726   void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
01727   void CountRegisters(const Formula &F, size_t LUIdx);
01728   bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
01729 
01730   void CollectLoopInvariantFixupsAndFormulae();
01731 
01732   void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
01733                               unsigned Depth = 0);
01734 
01735   void GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
01736                                   const Formula &Base, unsigned Depth,
01737                                   size_t Idx, bool IsScaledReg = false);
01738   void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
01739   void GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
01740                                    const Formula &Base, size_t Idx,
01741                                    bool IsScaledReg = false);
01742   void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
01743   void GenerateConstantOffsetsImpl(LSRUse &LU, unsigned LUIdx,
01744                                    const Formula &Base,
01745                                    const SmallVectorImpl<int64_t> &Worklist,
01746                                    size_t Idx, bool IsScaledReg = false);
01747   void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
01748   void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
01749   void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
01750   void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
01751   void GenerateCrossUseConstantOffsets();
01752   void GenerateAllReuseFormulae();
01753 
01754   void FilterOutUndesirableDedicatedRegisters();
01755 
01756   size_t EstimateSearchSpaceComplexity() const;
01757   void NarrowSearchSpaceByDetectingSupersets();
01758   void NarrowSearchSpaceByCollapsingUnrolledCode();
01759   void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
01760   void NarrowSearchSpaceByPickingWinnerRegs();
01761   void NarrowSearchSpaceUsingHeuristics();
01762 
01763   void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
01764                     Cost &SolutionCost,
01765                     SmallVectorImpl<const Formula *> &Workspace,
01766                     const Cost &CurCost,
01767                     const SmallPtrSet<const SCEV *, 16> &CurRegs,
01768                     DenseSet<const SCEV *> &VisitedRegs) const;
01769   void Solve(SmallVectorImpl<const Formula *> &Solution) const;
01770 
01771   BasicBlock::iterator
01772     HoistInsertPosition(BasicBlock::iterator IP,
01773                         const SmallVectorImpl<Instruction *> &Inputs) const;
01774   BasicBlock::iterator
01775     AdjustInsertPositionForExpand(BasicBlock::iterator IP,
01776                                   const LSRFixup &LF,
01777                                   const LSRUse &LU,
01778                                   SCEVExpander &Rewriter) const;
01779 
01780   Value *Expand(const LSRFixup &LF,
01781                 const Formula &F,
01782                 BasicBlock::iterator IP,
01783                 SCEVExpander &Rewriter,
01784                 SmallVectorImpl<WeakVH> &DeadInsts) const;
01785   void RewriteForPHI(PHINode *PN, const LSRFixup &LF,
01786                      const Formula &F,
01787                      SCEVExpander &Rewriter,
01788                      SmallVectorImpl<WeakVH> &DeadInsts,
01789                      Pass *P) const;
01790   void Rewrite(const LSRFixup &LF,
01791                const Formula &F,
01792                SCEVExpander &Rewriter,
01793                SmallVectorImpl<WeakVH> &DeadInsts,
01794                Pass *P) const;
01795   void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
01796                          Pass *P);
01797 
01798 public:
01799   LSRInstance(Loop *L, Pass *P);
01800 
01801   bool getChanged() const { return Changed; }
01802 
01803   void print_factors_and_types(raw_ostream &OS) const;
01804   void print_fixups(raw_ostream &OS) const;
01805   void print_uses(raw_ostream &OS) const;
01806   void print(raw_ostream &OS) const;
01807   void dump() const;
01808 };
01809 
01810 }
01811 
01812 /// OptimizeShadowIV - If IV is used in a int-to-float cast
01813 /// inside the loop then try to eliminate the cast operation.
01814 void LSRInstance::OptimizeShadowIV() {
01815   const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
01816   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
01817     return;
01818 
01819   for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
01820        UI != E; /* empty */) {
01821     IVUsers::const_iterator CandidateUI = UI;
01822     ++UI;
01823     Instruction *ShadowUse = CandidateUI->getUser();
01824     Type *DestTy = nullptr;
01825     bool IsSigned = false;
01826 
01827     /* If shadow use is a int->float cast then insert a second IV
01828        to eliminate this cast.
01829 
01830          for (unsigned i = 0; i < n; ++i)
01831            foo((double)i);
01832 
01833        is transformed into
01834 
01835          double d = 0.0;
01836          for (unsigned i = 0; i < n; ++i, ++d)
01837            foo(d);
01838     */
01839     if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser())) {
01840       IsSigned = false;
01841       DestTy = UCast->getDestTy();
01842     }
01843     else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser())) {
01844       IsSigned = true;
01845       DestTy = SCast->getDestTy();
01846     }
01847     if (!DestTy) continue;
01848 
01849     // If target does not support DestTy natively then do not apply
01850     // this transformation.
01851     if (!TTI.isTypeLegal(DestTy)) continue;
01852 
01853     PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
01854     if (!PH) continue;
01855     if (PH->getNumIncomingValues() != 2) continue;
01856 
01857     Type *SrcTy = PH->getType();
01858     int Mantissa = DestTy->getFPMantissaWidth();
01859     if (Mantissa == -1) continue;
01860     if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
01861       continue;
01862 
01863     unsigned Entry, Latch;
01864     if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
01865       Entry = 0;
01866       Latch = 1;
01867     } else {
01868       Entry = 1;
01869       Latch = 0;
01870     }
01871 
01872     ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
01873     if (!Init) continue;
01874     Constant *NewInit = ConstantFP::get(DestTy, IsSigned ?
01875                                         (double)Init->getSExtValue() :
01876                                         (double)Init->getZExtValue());
01877 
01878     BinaryOperator *Incr =
01879       dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
01880     if (!Incr) continue;
01881     if (Incr->getOpcode() != Instruction::Add
01882         && Incr->getOpcode() != Instruction::Sub)
01883       continue;
01884 
01885     /* Initialize new IV, double d = 0.0 in above example. */
01886     ConstantInt *C = nullptr;
01887     if (Incr->getOperand(0) == PH)
01888       C = dyn_cast<ConstantInt>(Incr->getOperand(1));
01889     else if (Incr->getOperand(1) == PH)
01890       C = dyn_cast<ConstantInt>(Incr->getOperand(0));
01891     else
01892       continue;
01893 
01894     if (!C) continue;
01895 
01896     // Ignore negative constants, as the code below doesn't handle them
01897     // correctly. TODO: Remove this restriction.
01898     if (!C->getValue().isStrictlyPositive()) continue;
01899 
01900     /* Add new PHINode. */
01901     PHINode *NewPH = PHINode::Create(DestTy, 2, "IV.S.", PH);
01902 
01903     /* create new increment. '++d' in above example. */
01904     Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
01905     BinaryOperator *NewIncr =
01906       BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
01907                                Instruction::FAdd : Instruction::FSub,
01908                              NewPH, CFP, "IV.S.next.", Incr);
01909 
01910     NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
01911     NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
01912 
01913     /* Remove cast operation */
01914     ShadowUse->replaceAllUsesWith(NewPH);
01915     ShadowUse->eraseFromParent();
01916     Changed = true;
01917     break;
01918   }
01919 }
01920 
01921 /// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
01922 /// set the IV user and stride information and return true, otherwise return
01923 /// false.
01924 bool LSRInstance::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse) {
01925   for (IVUsers::iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
01926     if (UI->getUser() == Cond) {
01927       // NOTE: we could handle setcc instructions with multiple uses here, but
01928       // InstCombine does it as well for simple uses, it's not clear that it
01929       // occurs enough in real life to handle.
01930       CondUse = UI;
01931       return true;
01932     }
01933   return false;
01934 }
01935 
01936 /// OptimizeMax - Rewrite the loop's terminating condition if it uses
01937 /// a max computation.
01938 ///
01939 /// This is a narrow solution to a specific, but acute, problem. For loops
01940 /// like this:
01941 ///
01942 ///   i = 0;
01943 ///   do {
01944 ///     p[i] = 0.0;
01945 ///   } while (++i < n);
01946 ///
01947 /// the trip count isn't just 'n', because 'n' might not be positive. And
01948 /// unfortunately this can come up even for loops where the user didn't use
01949 /// a C do-while loop. For example, seemingly well-behaved top-test loops
01950 /// will commonly be lowered like this:
01951 //
01952 ///   if (n > 0) {
01953 ///     i = 0;
01954 ///     do {
01955 ///       p[i] = 0.0;
01956 ///     } while (++i < n);
01957 ///   }
01958 ///
01959 /// and then it's possible for subsequent optimization to obscure the if
01960 /// test in such a way that indvars can't find it.
01961 ///
01962 /// When indvars can't find the if test in loops like this, it creates a
01963 /// max expression, which allows it to give the loop a canonical
01964 /// induction variable:
01965 ///
01966 ///   i = 0;
01967 ///   max = n < 1 ? 1 : n;
01968 ///   do {
01969 ///     p[i] = 0.0;
01970 ///   } while (++i != max);
01971 ///
01972 /// Canonical induction variables are necessary because the loop passes
01973 /// are designed around them. The most obvious example of this is the
01974 /// LoopInfo analysis, which doesn't remember trip count values. It
01975 /// expects to be able to rediscover the trip count each time it is
01976 /// needed, and it does this using a simple analysis that only succeeds if
01977 /// the loop has a canonical induction variable.
01978 ///
01979 /// However, when it comes time to generate code, the maximum operation
01980 /// can be quite costly, especially if it's inside of an outer loop.
01981 ///
01982 /// This function solves this problem by detecting this type of loop and
01983 /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
01984 /// the instructions for the maximum computation.
01985 ///
01986 ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
01987   // Check that the loop matches the pattern we're looking for.
01988   if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
01989       Cond->getPredicate() != CmpInst::ICMP_NE)
01990     return Cond;
01991 
01992   SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
01993   if (!Sel || !Sel->hasOneUse()) return Cond;
01994 
01995   const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
01996   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
01997     return Cond;
01998   const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1);
01999 
02000   // Add one to the backedge-taken count to get the trip count.
02001   const SCEV *IterationCount = SE.getAddExpr(One, BackedgeTakenCount);
02002   if (IterationCount != SE.getSCEV(Sel)) return Cond;
02003 
02004   // Check for a max calculation that matches the pattern. There's no check
02005   // for ICMP_ULE here because the comparison would be with zero, which
02006   // isn't interesting.
02007   CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
02008   const SCEVNAryExpr *Max = nullptr;
02009   if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) {
02010     Pred = ICmpInst::ICMP_SLE;
02011     Max = S;
02012   } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) {
02013     Pred = ICmpInst::ICMP_SLT;
02014     Max = S;
02015   } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) {
02016     Pred = ICmpInst::ICMP_ULT;
02017     Max = U;
02018   } else {
02019     // No match; bail.
02020     return Cond;
02021   }
02022 
02023   // To handle a max with more than two operands, this optimization would
02024   // require additional checking and setup.
02025   if (Max->getNumOperands() != 2)
02026     return Cond;
02027 
02028   const SCEV *MaxLHS = Max->getOperand(0);
02029   const SCEV *MaxRHS = Max->getOperand(1);
02030 
02031   // ScalarEvolution canonicalizes constants to the left. For < and >, look
02032   // for a comparison with 1. For <= and >=, a comparison with zero.
02033   if (!MaxLHS ||
02034       (ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One)))
02035     return Cond;
02036 
02037   // Check the relevant induction variable for conformance to
02038   // the pattern.
02039   const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
02040   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
02041   if (!AR || !AR->isAffine() ||
02042       AR->getStart() != One ||
02043       AR->getStepRecurrence(SE) != One)
02044     return Cond;
02045 
02046   assert(AR->getLoop() == L &&
02047          "Loop condition operand is an addrec in a different loop!");
02048 
02049   // Check the right operand of the select, and remember it, as it will
02050   // be used in the new comparison instruction.
02051   Value *NewRHS = nullptr;
02052   if (ICmpInst::isTrueWhenEqual(Pred)) {
02053     // Look for n+1, and grab n.
02054     if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1)))
02055       if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
02056          if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)
02057            NewRHS = BO->getOperand(0);
02058     if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2)))
02059       if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
02060         if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)
02061           NewRHS = BO->getOperand(0);
02062     if (!NewRHS)
02063       return Cond;
02064   } else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
02065     NewRHS = Sel->getOperand(1);
02066   else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
02067     NewRHS = Sel->getOperand(2);
02068   else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(MaxRHS))
02069     NewRHS = SU->getValue();
02070   else
02071     // Max doesn't match expected pattern.
02072     return Cond;
02073 
02074   // Determine the new comparison opcode. It may be signed or unsigned,
02075   // and the original comparison may be either equality or inequality.
02076   if (Cond->getPredicate() == CmpInst::ICMP_EQ)
02077     Pred = CmpInst::getInversePredicate(Pred);
02078 
02079   // Ok, everything looks ok to change the condition into an SLT or SGE and
02080   // delete the max calculation.
02081   ICmpInst *NewCond =
02082     new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
02083 
02084   // Delete the max calculation instructions.
02085   Cond->replaceAllUsesWith(NewCond);
02086   CondUse->setUser(NewCond);
02087   Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
02088   Cond->eraseFromParent();
02089   Sel->eraseFromParent();
02090   if (Cmp->use_empty())
02091     Cmp->eraseFromParent();
02092   return NewCond;
02093 }
02094 
02095 /// OptimizeLoopTermCond - Change loop terminating condition to use the
02096 /// postinc iv when possible.
02097 void
02098 LSRInstance::OptimizeLoopTermCond() {
02099   SmallPtrSet<Instruction *, 4> PostIncs;
02100 
02101   BasicBlock *LatchBlock = L->getLoopLatch();
02102   SmallVector<BasicBlock*, 8> ExitingBlocks;
02103   L->getExitingBlocks(ExitingBlocks);
02104 
02105   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
02106     BasicBlock *ExitingBlock = ExitingBlocks[i];
02107 
02108     // Get the terminating condition for the loop if possible.  If we
02109     // can, we want to change it to use a post-incremented version of its
02110     // induction variable, to allow coalescing the live ranges for the IV into
02111     // one register value.
02112 
02113     BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
02114     if (!TermBr)
02115       continue;
02116     // FIXME: Overly conservative, termination condition could be an 'or' etc..
02117     if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
02118       continue;
02119 
02120     // Search IVUsesByStride to find Cond's IVUse if there is one.
02121     IVStrideUse *CondUse = nullptr;
02122     ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
02123     if (!FindIVUserForCond(Cond, CondUse))
02124       continue;
02125 
02126     // If the trip count is computed in terms of a max (due to ScalarEvolution
02127     // being unable to find a sufficient guard, for example), change the loop
02128     // comparison to use SLT or ULT instead of NE.
02129     // One consequence of doing this now is that it disrupts the count-down
02130     // optimization. That's not always a bad thing though, because in such
02131     // cases it may still be worthwhile to avoid a max.
02132     Cond = OptimizeMax(Cond, CondUse);
02133 
02134     // If this exiting block dominates the latch block, it may also use
02135     // the post-inc value if it won't be shared with other uses.
02136     // Check for dominance.
02137     if (!DT.dominates(ExitingBlock, LatchBlock))
02138       continue;
02139 
02140     // Conservatively avoid trying to use the post-inc value in non-latch
02141     // exits if there may be pre-inc users in intervening blocks.
02142     if (LatchBlock != ExitingBlock)
02143       for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
02144         // Test if the use is reachable from the exiting block. This dominator
02145         // query is a conservative approximation of reachability.
02146         if (&*UI != CondUse &&
02147             !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
02148           // Conservatively assume there may be reuse if the quotient of their
02149           // strides could be a legal scale.
02150           const SCEV *A = IU.getStride(*CondUse, L);
02151           const SCEV *B = IU.getStride(*UI, L);
02152           if (!A || !B) continue;
02153           if (SE.getTypeSizeInBits(A->getType()) !=
02154               SE.getTypeSizeInBits(B->getType())) {
02155             if (SE.getTypeSizeInBits(A->getType()) >
02156                 SE.getTypeSizeInBits(B->getType()))
02157               B = SE.getSignExtendExpr(B, A->getType());
02158             else
02159               A = SE.getSignExtendExpr(A, B->getType());
02160           }
02161           if (const SCEVConstant *D =
02162                 dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {
02163             const ConstantInt *C = D->getValue();
02164             // Stride of one or negative one can have reuse with non-addresses.
02165             if (C->isOne() || C->isAllOnesValue())
02166               goto decline_post_inc;
02167             // Avoid weird situations.
02168             if (C->getValue().getMinSignedBits() >= 64 ||
02169                 C->getValue().isMinSignedValue())
02170               goto decline_post_inc;
02171             // Check for possible scaled-address reuse.
02172             Type *AccessTy = getAccessType(UI->getUser());
02173             int64_t Scale = C->getSExtValue();
02174             if (TTI.isLegalAddressingMode(AccessTy, /*BaseGV=*/ nullptr,
02175                                           /*BaseOffset=*/ 0,
02176                                           /*HasBaseReg=*/ false, Scale))
02177               goto decline_post_inc;
02178             Scale = -Scale;
02179             if (TTI.isLegalAddressingMode(AccessTy, /*BaseGV=*/ nullptr,
02180                                           /*BaseOffset=*/ 0,
02181                                           /*HasBaseReg=*/ false, Scale))
02182               goto decline_post_inc;
02183           }
02184         }
02185 
02186     DEBUG(dbgs() << "  Change loop exiting icmp to use postinc iv: "
02187                  << *Cond << '\n');
02188 
02189     // It's possible for the setcc instruction to be anywhere in the loop, and
02190     // possible for it to have multiple users.  If it is not immediately before
02191     // the exiting block branch, move it.
02192     if (&*++BasicBlock::iterator(Cond) != TermBr) {
02193       if (Cond->hasOneUse()) {
02194         Cond->moveBefore(TermBr);
02195       } else {
02196         // Clone the terminating condition and insert into the loopend.
02197         ICmpInst *OldCond = Cond;
02198         Cond = cast<ICmpInst>(Cond->clone());
02199         Cond->setName(L->getHeader()->getName() + ".termcond");
02200         ExitingBlock->getInstList().insert(TermBr, Cond);
02201 
02202         // Clone the IVUse, as the old use still exists!
02203         CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());
02204         TermBr->replaceUsesOfWith(OldCond, Cond);
02205       }
02206     }
02207 
02208     // If we get to here, we know that we can transform the setcc instruction to
02209     // use the post-incremented version of the IV, allowing us to coalesce the
02210     // live ranges for the IV correctly.
02211     CondUse->transformToPostInc(L);
02212     Changed = true;
02213 
02214     PostIncs.insert(Cond);
02215   decline_post_inc:;
02216   }
02217 
02218   // Determine an insertion point for the loop induction variable increment. It
02219   // must dominate all the post-inc comparisons we just set up, and it must
02220   // dominate the loop latch edge.
02221   IVIncInsertPos = L->getLoopLatch()->getTerminator();
02222   for (Instruction *Inst : PostIncs) {
02223     BasicBlock *BB =
02224       DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
02225                                     Inst->getParent());
02226     if (BB == Inst->getParent())
02227       IVIncInsertPos = Inst;
02228     else if (BB != IVIncInsertPos->getParent())
02229       IVIncInsertPos = BB->getTerminator();
02230   }
02231 }
02232 
02233 /// reconcileNewOffset - Determine if the given use can accommodate a fixup
02234 /// at the given offset and other details. If so, update the use and
02235 /// return true.
02236 bool
02237 LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
02238                                 LSRUse::KindType Kind, Type *AccessTy) {
02239   int64_t NewMinOffset = LU.MinOffset;
02240   int64_t NewMaxOffset = LU.MaxOffset;
02241   Type *NewAccessTy = AccessTy;
02242 
02243   // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
02244   // something conservative, however this can pessimize in the case that one of
02245   // the uses will have all its uses outside the loop, for example.
02246   if (LU.Kind != Kind)
02247     return false;
02248 
02249   // Check for a mismatched access type, and fall back conservatively as needed.
02250   // TODO: Be less conservative when the type is similar and can use the same
02251   // addressing modes.
02252   if (Kind == LSRUse::Address && AccessTy != LU.AccessTy)
02253     NewAccessTy = Type::getVoidTy(AccessTy->getContext());
02254 
02255   // Conservatively assume HasBaseReg is true for now.
02256   if (NewOffset < LU.MinOffset) {
02257     if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,
02258                           LU.MaxOffset - NewOffset, HasBaseReg))
02259       return false;
02260     NewMinOffset = NewOffset;
02261   } else if (NewOffset > LU.MaxOffset) {
02262     if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,
02263                           NewOffset - LU.MinOffset, HasBaseReg))
02264       return false;
02265     NewMaxOffset = NewOffset;
02266   }
02267 
02268   // Update the use.
02269   LU.MinOffset = NewMinOffset;
02270   LU.MaxOffset = NewMaxOffset;
02271   LU.AccessTy = NewAccessTy;
02272   if (NewOffset != LU.Offsets.back())
02273     LU.Offsets.push_back(NewOffset);
02274   return true;
02275 }
02276 
02277 /// getUse - Return an LSRUse index and an offset value for a fixup which
02278 /// needs the given expression, with the given kind and optional access type.
02279 /// Either reuse an existing use or create a new one, as needed.
02280 std::pair<size_t, int64_t>
02281 LSRInstance::getUse(const SCEV *&Expr,
02282                     LSRUse::KindType Kind, Type *AccessTy) {
02283   const SCEV *Copy = Expr;
02284   int64_t Offset = ExtractImmediate(Expr, SE);
02285 
02286   // Basic uses can't accept any offset, for example.
02287   if (!isAlwaysFoldable(TTI, Kind, AccessTy, /*BaseGV=*/ nullptr,
02288                         Offset, /*HasBaseReg=*/ true)) {
02289     Expr = Copy;
02290     Offset = 0;
02291   }
02292 
02293   std::pair<UseMapTy::iterator, bool> P =
02294     UseMap.insert(std::make_pair(LSRUse::SCEVUseKindPair(Expr, Kind), 0));
02295   if (!P.second) {
02296     // A use already existed with this base.
02297     size_t LUIdx = P.first->second;
02298     LSRUse &LU = Uses[LUIdx];
02299     if (reconcileNewOffset(LU, Offset, /*HasBaseReg=*/true, Kind, AccessTy))
02300       // Reuse this use.
02301       return std::make_pair(LUIdx, Offset);
02302   }
02303 
02304   // Create a new use.
02305   size_t LUIdx = Uses.size();
02306   P.first->second = LUIdx;
02307   Uses.push_back(LSRUse(Kind, AccessTy));
02308   LSRUse &LU = Uses[LUIdx];
02309 
02310   // We don't need to track redundant offsets, but we don't need to go out
02311   // of our way here to avoid them.
02312   if (LU.Offsets.empty() || Offset != LU.Offsets.back())
02313     LU.Offsets.push_back(Offset);
02314 
02315   LU.MinOffset = Offset;
02316   LU.MaxOffset = Offset;
02317   return std::make_pair(LUIdx, Offset);
02318 }
02319 
02320 /// DeleteUse - Delete the given use from the Uses list.
02321 void LSRInstance::DeleteUse(LSRUse &LU, size_t LUIdx) {
02322   if (&LU != &Uses.back())
02323     std::swap(LU, Uses.back());
02324   Uses.pop_back();
02325 
02326   // Update RegUses.
02327   RegUses.SwapAndDropUse(LUIdx, Uses.size());
02328 }
02329 
02330 /// FindUseWithFormula - Look for a use distinct from OrigLU which is has
02331 /// a formula that has the same registers as the given formula.
02332 LSRUse *
02333 LSRInstance::FindUseWithSimilarFormula(const Formula &OrigF,
02334                                        const LSRUse &OrigLU) {
02335   // Search all uses for the formula. This could be more clever.
02336   for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
02337     LSRUse &LU = Uses[LUIdx];
02338     // Check whether this use is close enough to OrigLU, to see whether it's
02339     // worthwhile looking through its formulae.
02340     // Ignore ICmpZero uses because they may contain formulae generated by
02341     // GenerateICmpZeroScales, in which case adding fixup offsets may
02342     // be invalid.
02343     if (&LU != &OrigLU &&
02344         LU.Kind != LSRUse::ICmpZero &&
02345         LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy &&
02346         LU.WidestFixupType == OrigLU.WidestFixupType &&
02347         LU.HasFormulaWithSameRegs(OrigF)) {
02348       // Scan through this use's formulae.
02349       for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
02350            E = LU.Formulae.end(); I != E; ++I) {
02351         const Formula &F = *I;
02352         // Check to see if this formula has the same registers and symbols
02353         // as OrigF.
02354         if (F.BaseRegs == OrigF.BaseRegs &&
02355             F.ScaledReg == OrigF.ScaledReg &&
02356             F.BaseGV == OrigF.BaseGV &&
02357             F.Scale == OrigF.Scale &&
02358             F.UnfoldedOffset == OrigF.UnfoldedOffset) {
02359           if (F.BaseOffset == 0)
02360             return &LU;
02361           // This is the formula where all the registers and symbols matched;
02362           // there aren't going to be any others. Since we declined it, we
02363           // can skip the rest of the formulae and proceed to the next LSRUse.
02364           break;
02365         }
02366       }
02367     }
02368   }
02369 
02370   // Nothing looked good.
02371   return nullptr;
02372 }
02373 
02374 void LSRInstance::CollectInterestingTypesAndFactors() {
02375   SmallSetVector<const SCEV *, 4> Strides;
02376 
02377   // Collect interesting types and strides.
02378   SmallVector<const SCEV *, 4> Worklist;
02379   for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
02380     const SCEV *Expr = IU.getExpr(*UI);
02381 
02382     // Collect interesting types.
02383     Types.insert(SE.getEffectiveSCEVType(Expr->getType()));
02384 
02385     // Add strides for mentioned loops.
02386     Worklist.push_back(Expr);
02387     do {
02388       const SCEV *S = Worklist.pop_back_val();
02389       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
02390         if (AR->getLoop() == L)
02391           Strides.insert(AR->getStepRecurrence(SE));
02392         Worklist.push_back(AR->getStart());
02393       } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
02394         Worklist.append(Add->op_begin(), Add->op_end());
02395       }
02396     } while (!Worklist.empty());
02397   }
02398 
02399   // Compute interesting factors from the set of interesting strides.
02400   for (SmallSetVector<const SCEV *, 4>::const_iterator
02401        I = Strides.begin(), E = Strides.end(); I != E; ++I)
02402     for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =
02403          std::next(I); NewStrideIter != E; ++NewStrideIter) {
02404       const SCEV *OldStride = *I;
02405       const SCEV *NewStride = *NewStrideIter;
02406 
02407       if (SE.getTypeSizeInBits(OldStride->getType()) !=
02408           SE.getTypeSizeInBits(NewStride->getType())) {
02409         if (SE.getTypeSizeInBits(OldStride->getType()) >
02410             SE.getTypeSizeInBits(NewStride->getType()))
02411           NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
02412         else
02413           OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
02414       }
02415       if (const SCEVConstant *Factor =
02416             dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,
02417                                                         SE, true))) {
02418         if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
02419           Factors.insert(Factor->getValue()->getValue().getSExtValue());
02420       } else if (const SCEVConstant *Factor =
02421                    dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride,
02422                                                                NewStride,
02423                                                                SE, true))) {
02424         if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
02425           Factors.insert(Factor->getValue()->getValue().getSExtValue());
02426       }
02427     }
02428 
02429   // If all uses use the same type, don't bother looking for truncation-based
02430   // reuse.
02431   if (Types.size() == 1)
02432     Types.clear();
02433 
02434   DEBUG(print_factors_and_types(dbgs()));
02435 }
02436 
02437 /// findIVOperand - Helper for CollectChains that finds an IV operand (computed
02438 /// by an AddRec in this loop) within [OI,OE) or returns OE. If IVUsers mapped
02439 /// Instructions to IVStrideUses, we could partially skip this.
02440 static User::op_iterator
02441 findIVOperand(User::op_iterator OI, User::op_iterator OE,
02442               Loop *L, ScalarEvolution &SE) {
02443   for(; OI != OE; ++OI) {
02444     if (Instruction *Oper = dyn_cast<Instruction>(*OI)) {
02445       if (!SE.isSCEVable(Oper->getType()))
02446         continue;
02447 
02448       if (const SCEVAddRecExpr *AR =
02449           dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Oper))) {
02450         if (AR->getLoop() == L)
02451           break;
02452       }
02453     }
02454   }
02455   return OI;
02456 }
02457 
02458 /// getWideOperand - IVChain logic must consistenctly peek base TruncInst
02459 /// operands, so wrap it in a convenient helper.
02460 static Value *getWideOperand(Value *Oper) {
02461   if (TruncInst *Trunc = dyn_cast<TruncInst>(Oper))
02462     return Trunc->getOperand(0);
02463   return Oper;
02464 }
02465 
02466 /// isCompatibleIVType - Return true if we allow an IV chain to include both
02467 /// types.
02468 static bool isCompatibleIVType(Value *LVal, Value *RVal) {
02469   Type *LType = LVal->getType();
02470   Type *RType = RVal->getType();
02471   return (LType == RType) || (LType->isPointerTy() && RType->isPointerTy());
02472 }
02473 
02474 /// getExprBase - Return an approximation of this SCEV expression's "base", or
02475 /// NULL for any constant. Returning the expression itself is
02476 /// conservative. Returning a deeper subexpression is more precise and valid as
02477 /// long as it isn't less complex than another subexpression. For expressions
02478 /// involving multiple unscaled values, we need to return the pointer-type
02479 /// SCEVUnknown. This avoids forming chains across objects, such as:
02480 /// PrevOper==a[i], IVOper==b[i], IVInc==b-a.
02481 ///
02482 /// Since SCEVUnknown is the rightmost type, and pointers are the rightmost
02483 /// SCEVUnknown, we simply return the rightmost SCEV operand.
02484 static const SCEV *getExprBase(const SCEV *S) {
02485   switch (S->getSCEVType()) {
02486   default: // uncluding scUnknown.
02487     return S;
02488   case scConstant:
02489     return nullptr;
02490   case scTruncate:
02491     return getExprBase(cast<SCEVTruncateExpr>(S)->getOperand());
02492   case scZeroExtend:
02493     return getExprBase(cast<SCEVZeroExtendExpr>(S)->getOperand());
02494   case scSignExtend:
02495     return getExprBase(cast<SCEVSignExtendExpr>(S)->getOperand());
02496   case scAddExpr: {
02497     // Skip over scaled operands (scMulExpr) to follow add operands as long as
02498     // there's nothing more complex.
02499     // FIXME: not sure if we want to recognize negation.
02500     const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
02501     for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(Add->op_end()),
02502            E(Add->op_begin()); I != E; ++I) {
02503       const SCEV *SubExpr = *I;
02504       if (SubExpr->getSCEVType() == scAddExpr)
02505         return getExprBase(SubExpr);
02506 
02507       if (SubExpr->getSCEVType() != scMulExpr)
02508         return SubExpr;
02509     }
02510     return S; // all operands are scaled, be conservative.
02511   }
02512   case scAddRecExpr:
02513     return getExprBase(cast<SCEVAddRecExpr>(S)->getStart());
02514   }
02515 }
02516 
02517 /// Return true if the chain increment is profitable to expand into a loop
02518 /// invariant value, which may require its own register. A profitable chain
02519 /// increment will be an offset relative to the same base. We allow such offsets
02520 /// to potentially be used as chain increment as long as it's not obviously
02521 /// expensive to expand using real instructions.
02522 bool IVChain::isProfitableIncrement(const SCEV *OperExpr,
02523                                     const SCEV *IncExpr,
02524                                     ScalarEvolution &SE) {
02525   // Aggressively form chains when -stress-ivchain.
02526   if (StressIVChain)
02527     return true;
02528 
02529   // Do not replace a constant offset from IV head with a nonconstant IV
02530   // increment.
02531   if (!isa<SCEVConstant>(IncExpr)) {
02532     const SCEV *HeadExpr = SE.getSCEV(getWideOperand(Incs[0].IVOperand));
02533     if (isa<SCEVConstant>(SE.getMinusSCEV(OperExpr, HeadExpr)))
02534       return 0;
02535   }
02536 
02537   SmallPtrSet<const SCEV*, 8> Processed;
02538   return !isHighCostExpansion(IncExpr, Processed, SE);
02539 }
02540 
02541 /// Return true if the number of registers needed for the chain is estimated to
02542 /// be less than the number required for the individual IV users. First prohibit
02543 /// any IV users that keep the IV live across increments (the Users set should
02544 /// be empty). Next count the number and type of increments in the chain.
02545 ///
02546 /// Chaining IVs can lead to considerable code bloat if ISEL doesn't
02547 /// effectively use postinc addressing modes. Only consider it profitable it the
02548 /// increments can be computed in fewer registers when chained.
02549 ///
02550 /// TODO: Consider IVInc free if it's already used in another chains.
02551 static bool
02552 isProfitableChain(IVChain &Chain, SmallPtrSetImpl<Instruction*> &Users,
02553                   ScalarEvolution &SE, const TargetTransformInfo &TTI) {
02554   if (StressIVChain)
02555     return true;
02556 
02557   if (!Chain.hasIncs())
02558     return false;
02559 
02560   if (!Users.empty()) {
02561     DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " users:\n";
02562           for (Instruction *Inst : Users) {
02563             dbgs() << "  " << *Inst << "\n";
02564           });
02565     return false;
02566   }
02567   assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
02568 
02569   // The chain itself may require a register, so intialize cost to 1.
02570   int cost = 1;
02571 
02572   // A complete chain likely eliminates the need for keeping the original IV in
02573   // a register. LSR does not currently know how to form a complete chain unless
02574   // the header phi already exists.
02575   if (isa<PHINode>(Chain.tailUserInst())
02576       && SE.getSCEV(Chain.tailUserInst()) == Chain.Incs[0].IncExpr) {
02577     --cost;
02578   }
02579   const SCEV *LastIncExpr = nullptr;
02580   unsigned NumConstIncrements = 0;
02581   unsigned NumVarIncrements = 0;
02582   unsigned NumReusedIncrements = 0;
02583   for (IVChain::const_iterator I = Chain.begin(), E = Chain.end();
02584        I != E; ++I) {
02585 
02586     if (I->IncExpr->isZero())
02587       continue;
02588 
02589     // Incrementing by zero or some constant is neutral. We assume constants can
02590     // be folded into an addressing mode or an add's immediate operand.
02591     if (isa<SCEVConstant>(I->IncExpr)) {
02592       ++NumConstIncrements;
02593       continue;
02594     }
02595 
02596     if (I->IncExpr == LastIncExpr)
02597       ++NumReusedIncrements;
02598     else
02599       ++NumVarIncrements;
02600 
02601     LastIncExpr = I->IncExpr;
02602   }
02603   // An IV chain with a single increment is handled by LSR's postinc
02604   // uses. However, a chain with multiple increments requires keeping the IV's
02605   // value live longer than it needs to be if chained.
02606   if (NumConstIncrements > 1)
02607     --cost;
02608 
02609   // Materializing increment expressions in the preheader that didn't exist in
02610   // the original code may cost a register. For example, sign-extended array
02611   // indices can produce ridiculous increments like this:
02612   // IV + ((sext i32 (2 * %s) to i64) + (-1 * (sext i32 %s to i64)))
02613   cost += NumVarIncrements;
02614 
02615   // Reusing variable increments likely saves a register to hold the multiple of
02616   // the stride.
02617   cost -= NumReusedIncrements;
02618 
02619   DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " Cost: " << cost
02620                << "\n");
02621 
02622   return cost < 0;
02623 }
02624 
02625 /// ChainInstruction - Add this IV user to an existing chain or make it the head
02626 /// of a new chain.
02627 void LSRInstance::ChainInstruction(Instruction *UserInst, Instruction *IVOper,
02628                                    SmallVectorImpl<ChainUsers> &ChainUsersVec) {
02629   // When IVs are used as types of varying widths, they are generally converted
02630   // to a wider type with some uses remaining narrow under a (free) trunc.
02631   Value *const NextIV = getWideOperand(IVOper);
02632   const SCEV *const OperExpr = SE.getSCEV(NextIV);
02633   const SCEV *const OperExprBase = getExprBase(OperExpr);
02634 
02635   // Visit all existing chains. Check if its IVOper can be computed as a
02636   // profitable loop invariant increment from the last link in the Chain.
02637   unsigned ChainIdx = 0, NChains = IVChainVec.size();
02638   const SCEV *LastIncExpr = nullptr;
02639   for (; ChainIdx < NChains; ++ChainIdx) {
02640     IVChain &Chain = IVChainVec[ChainIdx];
02641 
02642     // Prune the solution space aggressively by checking that both IV operands
02643     // are expressions that operate on the same unscaled SCEVUnknown. This
02644     // "base" will be canceled by the subsequent getMinusSCEV call. Checking
02645     // first avoids creating extra SCEV expressions.
02646     if (!StressIVChain && Chain.ExprBase != OperExprBase)
02647       continue;
02648 
02649     Value *PrevIV = getWideOperand(Chain.Incs.back().IVOperand);
02650     if (!isCompatibleIVType(PrevIV, NextIV))
02651       continue;
02652 
02653     // A phi node terminates a chain.
02654     if (isa<PHINode>(UserInst) && isa<PHINode>(Chain.tailUserInst()))
02655       continue;
02656 
02657     // The increment must be loop-invariant so it can be kept in a register.
02658     const SCEV *PrevExpr = SE.getSCEV(PrevIV);
02659     const SCEV *IncExpr = SE.getMinusSCEV(OperExpr, PrevExpr);
02660     if (!SE.isLoopInvariant(IncExpr, L))
02661       continue;
02662 
02663     if (Chain.isProfitableIncrement(OperExpr, IncExpr, SE)) {
02664       LastIncExpr = IncExpr;
02665       break;
02666     }
02667   }
02668   // If we haven't found a chain, create a new one, unless we hit the max. Don't
02669   // bother for phi nodes, because they must be last in the chain.
02670   if (ChainIdx == NChains) {
02671     if (isa<PHINode>(UserInst))
02672       return;
02673     if (NChains >= MaxChains && !StressIVChain) {
02674       DEBUG(dbgs() << "IV Chain Limit\n");
02675       return;
02676     }
02677     LastIncExpr = OperExpr;
02678     // IVUsers may have skipped over sign/zero extensions. We don't currently
02679     // attempt to form chains involving extensions unless they can be hoisted
02680     // into this loop's AddRec.
02681     if (!isa<SCEVAddRecExpr>(LastIncExpr))
02682       return;
02683     ++NChains;
02684     IVChainVec.push_back(IVChain(IVInc(UserInst, IVOper, LastIncExpr),
02685                                  OperExprBase));
02686     ChainUsersVec.resize(NChains);
02687     DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Head: (" << *UserInst
02688                  << ") IV=" << *LastIncExpr << "\n");
02689   } else {
02690     DEBUG(dbgs() << "IV Chain#" << ChainIdx << "  Inc: (" << *UserInst
02691                  << ") IV+" << *LastIncExpr << "\n");
02692     // Add this IV user to the end of the chain.
02693     IVChainVec[ChainIdx].add(IVInc(UserInst, IVOper, LastIncExpr));
02694   }
02695   IVChain &Chain = IVChainVec[ChainIdx];
02696 
02697   SmallPtrSet<Instruction*,4> &NearUsers = ChainUsersVec[ChainIdx].NearUsers;
02698   // This chain's NearUsers become FarUsers.
02699   if (!LastIncExpr->isZero()) {
02700     ChainUsersVec[ChainIdx].FarUsers.insert(NearUsers.begin(),
02701                                             NearUsers.end());
02702     NearUsers.clear();
02703   }
02704 
02705   // All other uses of IVOperand become near uses of the chain.
02706   // We currently ignore intermediate values within SCEV expressions, assuming
02707   // they will eventually be used be the current chain, or can be computed
02708   // from one of the chain increments. To be more precise we could
02709   // transitively follow its user and only add leaf IV users to the set.
02710   for (User *U : IVOper->users()) {
02711     Instruction *OtherUse = dyn_cast<Instruction>(U);
02712     if (!OtherUse)
02713       continue;
02714     // Uses in the chain will no longer be uses if the chain is formed.
02715     // Include the head of the chain in this iteration (not Chain.begin()).
02716     IVChain::const_iterator IncIter = Chain.Incs.begin();
02717     IVChain::const_iterator IncEnd = Chain.Incs.end();
02718     for( ; IncIter != IncEnd; ++IncIter) {
02719       if (IncIter->UserInst == OtherUse)
02720         break;
02721     }
02722     if (IncIter != IncEnd)
02723       continue;
02724 
02725     if (SE.isSCEVable(OtherUse->getType())
02726         && !isa<SCEVUnknown>(SE.getSCEV(OtherUse))
02727         && IU.isIVUserOrOperand(OtherUse)) {
02728       continue;
02729     }
02730     NearUsers.insert(OtherUse);
02731   }
02732 
02733   // Since this user is part of the chain, it's no longer considered a use
02734   // of the chain.
02735   ChainUsersVec[ChainIdx].FarUsers.erase(UserInst);
02736 }
02737 
02738 /// CollectChains - Populate the vector of Chains.
02739 ///
02740 /// This decreases ILP at the architecture level. Targets with ample registers,
02741 /// multiple memory ports, and no register renaming probably don't want
02742 /// this. However, such targets should probably disable LSR altogether.
02743 ///
02744 /// The job of LSR is to make a reasonable choice of induction variables across
02745 /// the loop. Subsequent passes can easily "unchain" computation exposing more
02746 /// ILP *within the loop* if the target wants it.
02747 ///
02748 /// Finding the best IV chain is potentially a scheduling problem. Since LSR
02749 /// will not reorder memory operations, it will recognize this as a chain, but
02750 /// will generate redundant IV increments. Ideally this would be corrected later
02751 /// by a smart scheduler:
02752 ///        = A[i]
02753 ///        = A[i+x]
02754 /// A[i]   =
02755 /// A[i+x] =
02756 ///
02757 /// TODO: Walk the entire domtree within this loop, not just the path to the
02758 /// loop latch. This will discover chains on side paths, but requires
02759 /// maintaining multiple copies of the Chains state.
02760 void LSRInstance::CollectChains() {
02761   DEBUG(dbgs() << "Collecting IV Chains.\n");
02762   SmallVector<ChainUsers, 8> ChainUsersVec;
02763 
02764   SmallVector<BasicBlock *,8> LatchPath;
02765   BasicBlock *LoopHeader = L->getHeader();
02766   for (DomTreeNode *Rung = DT.getNode(L->getLoopLatch());
02767        Rung->getBlock() != LoopHeader; Rung = Rung->getIDom()) {
02768     LatchPath.push_back(Rung->getBlock());
02769   }
02770   LatchPath.push_back(LoopHeader);
02771 
02772   // Walk the instruction stream from the loop header to the loop latch.
02773   for (SmallVectorImpl<BasicBlock *>::reverse_iterator
02774          BBIter = LatchPath.rbegin(), BBEnd = LatchPath.rend();
02775        BBIter != BBEnd; ++BBIter) {
02776     for (BasicBlock::iterator I = (*BBIter)->begin(), E = (*BBIter)->end();
02777          I != E; ++I) {
02778       // Skip instructions that weren't seen by IVUsers analysis.
02779       if (isa<PHINode>(I) || !IU.isIVUserOrOperand(I))
02780         continue;
02781 
02782       // Ignore users that are part of a SCEV expression. This way we only
02783       // consider leaf IV Users. This effectively rediscovers a portion of
02784       // IVUsers analysis but in program order this time.
02785       if (SE.isSCEVable(I->getType()) && !isa<SCEVUnknown>(SE.getSCEV(I)))
02786         continue;
02787 
02788       // Remove this instruction from any NearUsers set it may be in.
02789       for (unsigned ChainIdx = 0, NChains = IVChainVec.size();
02790            ChainIdx < NChains; ++ChainIdx) {
02791         ChainUsersVec[ChainIdx].NearUsers.erase(I);
02792       }
02793       // Search for operands that can be chained.
02794       SmallPtrSet<Instruction*, 4> UniqueOperands;
02795       User::op_iterator IVOpEnd = I->op_end();
02796       User::op_iterator IVOpIter = findIVOperand(I->op_begin(), IVOpEnd, L, SE);
02797       while (IVOpIter != IVOpEnd) {
02798         Instruction *IVOpInst = cast<Instruction>(*IVOpIter);
02799         if (UniqueOperands.insert(IVOpInst).second)
02800           ChainInstruction(I, IVOpInst, ChainUsersVec);
02801         IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
02802       }
02803     } // Continue walking down the instructions.
02804   } // Continue walking down the domtree.
02805   // Visit phi backedges to determine if the chain can generate the IV postinc.
02806   for (BasicBlock::iterator I = L->getHeader()->begin();
02807        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
02808     if (!SE.isSCEVable(PN->getType()))
02809       continue;
02810 
02811     Instruction *IncV =
02812       dyn_cast<Instruction>(PN->getIncomingValueForBlock(L->getLoopLatch()));
02813     if (IncV)
02814       ChainInstruction(PN, IncV, ChainUsersVec);
02815   }
02816   // Remove any unprofitable chains.
02817   unsigned ChainIdx = 0;
02818   for (unsigned UsersIdx = 0, NChains = IVChainVec.size();
02819        UsersIdx < NChains; ++UsersIdx) {
02820     if (!isProfitableChain(IVChainVec[UsersIdx],
02821                            ChainUsersVec[UsersIdx].FarUsers, SE, TTI))
02822       continue;
02823     // Preserve the chain at UsesIdx.
02824     if (ChainIdx != UsersIdx)
02825       IVChainVec[ChainIdx] = IVChainVec[UsersIdx];
02826     FinalizeChain(IVChainVec[ChainIdx]);
02827     ++ChainIdx;
02828   }
02829   IVChainVec.resize(ChainIdx);
02830 }
02831 
02832 void LSRInstance::FinalizeChain(IVChain &Chain) {
02833   assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
02834   DEBUG(dbgs() << "Final Chain: " << *Chain.Incs[0].UserInst << "\n");
02835 
02836   for (IVChain::const_iterator I = Chain.begin(), E = Chain.end();
02837        I != E; ++I) {
02838     DEBUG(dbgs() << "        Inc: " << *I->UserInst << "\n");
02839     User::op_iterator UseI =
02840       std::find(I->UserInst->op_begin(), I->UserInst->op_end(), I->IVOperand);
02841     assert(UseI != I->UserInst->op_end() && "cannot find IV operand");
02842     IVIncSet.insert(UseI);
02843   }
02844 }
02845 
02846 /// Return true if the IVInc can be folded into an addressing mode.
02847 static bool canFoldIVIncExpr(const SCEV *IncExpr, Instruction *UserInst,
02848                              Value *Operand, const TargetTransformInfo &TTI) {
02849   const SCEVConstant *IncConst = dyn_cast<SCEVConstant>(IncExpr);
02850   if (!IncConst || !isAddressUse(UserInst, Operand))
02851     return false;
02852 
02853   if (IncConst->getValue()->getValue().getMinSignedBits() > 64)
02854     return false;
02855 
02856   int64_t IncOffset = IncConst->getValue()->getSExtValue();
02857   if (!isAlwaysFoldable(TTI, LSRUse::Address,
02858                         getAccessType(UserInst), /*BaseGV=*/ nullptr,
02859                         IncOffset, /*HaseBaseReg=*/ false))
02860     return false;
02861 
02862   return true;
02863 }
02864 
02865 /// GenerateIVChains - Generate an add or subtract for each IVInc in a chain to
02866 /// materialize the IV user's operand from the previous IV user's operand.
02867 void LSRInstance::GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter,
02868                                   SmallVectorImpl<WeakVH> &DeadInsts) {
02869   // Find the new IVOperand for the head of the chain. It may have been replaced
02870   // by LSR.
02871   const IVInc &Head = Chain.Incs[0];
02872   User::op_iterator IVOpEnd = Head.UserInst->op_end();
02873   // findIVOperand returns IVOpEnd if it can no longer find a valid IV user.
02874   User::op_iterator IVOpIter = findIVOperand(Head.UserInst->op_begin(),
02875                                              IVOpEnd, L, SE);
02876   Value *IVSrc = nullptr;
02877   while (IVOpIter != IVOpEnd) {
02878     IVSrc = getWideOperand(*IVOpIter);
02879 
02880     // If this operand computes the expression that the chain needs, we may use
02881     // it. (Check this after setting IVSrc which is used below.)
02882     //
02883     // Note that if Head.IncExpr is wider than IVSrc, then this phi is too
02884     // narrow for the chain, so we can no longer use it. We do allow using a
02885     // wider phi, assuming the LSR checked for free truncation. In that case we
02886     // should already have a truncate on this operand such that
02887     // getSCEV(IVSrc) == IncExpr.
02888     if (SE.getSCEV(*IVOpIter) == Head.IncExpr
02889         || SE.getSCEV(IVSrc) == Head.IncExpr) {
02890       break;
02891     }
02892     IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
02893   }
02894   if (IVOpIter == IVOpEnd) {
02895     // Gracefully give up on this chain.
02896     DEBUG(dbgs() << "Concealed chain head: " << *Head.UserInst << "\n");
02897     return;
02898   }
02899 
02900   DEBUG(dbgs() << "Generate chain at: " << *IVSrc << "\n");
02901   Type *IVTy = IVSrc->getType();
02902   Type *IntTy = SE.getEffectiveSCEVType(IVTy);
02903   const SCEV *LeftOverExpr = nullptr;
02904   for (IVChain::const_iterator IncI = Chain.begin(),
02905          IncE = Chain.end(); IncI != IncE; ++IncI) {
02906 
02907     Instruction *InsertPt = IncI->UserInst;
02908     if (isa<PHINode>(InsertPt))
02909       InsertPt = L->getLoopLatch()->getTerminator();
02910 
02911     // IVOper will replace the current IV User's operand. IVSrc is the IV
02912     // value currently held in a register.
02913     Value *IVOper = IVSrc;
02914     if (!IncI->IncExpr->isZero()) {
02915       // IncExpr was the result of subtraction of two narrow values, so must
02916       // be signed.
02917       const SCEV *IncExpr = SE.getNoopOrSignExtend(IncI->IncExpr, IntTy);
02918       LeftOverExpr = LeftOverExpr ?
02919         SE.getAddExpr(LeftOverExpr, IncExpr) : IncExpr;
02920     }
02921     if (LeftOverExpr && !LeftOverExpr->isZero()) {
02922       // Expand the IV increment.
02923       Rewriter.clearPostInc();
02924       Value *IncV = Rewriter.expandCodeFor(LeftOverExpr, IntTy, InsertPt);
02925       const SCEV *IVOperExpr = SE.getAddExpr(SE.getUnknown(IVSrc),
02926                                              SE.getUnknown(IncV));
02927       IVOper = Rewriter.expandCodeFor(IVOperExpr, IVTy, InsertPt);
02928 
02929       // If an IV increment can't be folded, use it as the next IV value.
02930       if (!canFoldIVIncExpr(LeftOverExpr, IncI->UserInst, IncI->IVOperand,
02931                             TTI)) {
02932         assert(IVTy == IVOper->getType() && "inconsistent IV increment type");
02933         IVSrc = IVOper;
02934         LeftOverExpr = nullptr;
02935       }
02936     }
02937     Type *OperTy = IncI->IVOperand->getType();
02938     if (IVTy != OperTy) {
02939       assert(SE.getTypeSizeInBits(IVTy) >= SE.getTypeSizeInBits(OperTy) &&
02940              "cannot extend a chained IV");
02941       IRBuilder<> Builder(InsertPt);
02942       IVOper = Builder.CreateTruncOrBitCast(IVOper, OperTy, "lsr.chain");
02943     }
02944     IncI->UserInst->replaceUsesOfWith(IncI->IVOperand, IVOper);
02945     DeadInsts.push_back(IncI->IVOperand);
02946   }
02947   // If LSR created a new, wider phi, we may also replace its postinc. We only
02948   // do this if we also found a wide value for the head of the chain.
02949   if (isa<PHINode>(Chain.tailUserInst())) {
02950     for (BasicBlock::iterator I = L->getHeader()->begin();
02951          PHINode *Phi = dyn_cast<PHINode>(I); ++I) {
02952       if (!isCompatibleIVType(Phi, IVSrc))
02953         continue;
02954       Instruction *PostIncV = dyn_cast<Instruction>(
02955         Phi->getIncomingValueForBlock(L->getLoopLatch()));
02956       if (!PostIncV || (SE.getSCEV(PostIncV) != SE.getSCEV(IVSrc)))
02957         continue;
02958       Value *IVOper = IVSrc;
02959       Type *PostIncTy = PostIncV->getType();
02960       if (IVTy != PostIncTy) {
02961         assert(PostIncTy->isPointerTy() && "mixing int/ptr IV types");
02962         IRBuilder<> Builder(L->getLoopLatch()->getTerminator());
02963         Builder.SetCurrentDebugLocation(PostIncV->getDebugLoc());
02964         IVOper = Builder.CreatePointerCast(IVSrc, PostIncTy, "lsr.chain");
02965       }
02966       Phi->replaceUsesOfWith(PostIncV, IVOper);
02967       DeadInsts.push_back(PostIncV);
02968     }
02969   }
02970 }
02971 
02972 void LSRInstance::CollectFixupsAndInitialFormulae() {
02973   for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
02974     Instruction *UserInst = UI->getUser();
02975     // Skip IV users that are part of profitable IV Chains.
02976     User::op_iterator UseI = std::find(UserInst->op_begin(), UserInst->op_end(),
02977                                        UI->getOperandValToReplace());
02978     assert(UseI != UserInst->op_end() && "cannot find IV operand");
02979     if (IVIncSet.count(UseI))
02980       continue;
02981 
02982     // Record the uses.
02983     LSRFixup &LF = getNewFixup();
02984     LF.UserInst = UserInst;
02985     LF.OperandValToReplace = UI->getOperandValToReplace();
02986     LF.PostIncLoops = UI->getPostIncLoops();
02987 
02988     LSRUse::KindType Kind = LSRUse::Basic;
02989     Type *AccessTy = nullptr;
02990     if (isAddressUse(LF.UserInst, LF.OperandValToReplace)) {
02991       Kind = LSRUse::Address;
02992       AccessTy = getAccessType(LF.UserInst);
02993     }
02994 
02995     const SCEV *S = IU.getExpr(*UI);
02996 
02997     // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
02998     // (N - i == 0), and this allows (N - i) to be the expression that we work
02999     // with rather than just N or i, so we can consider the register
03000     // requirements for both N and i at the same time. Limiting this code to
03001     // equality icmps is not a problem because all interesting loops use
03002     // equality icmps, thanks to IndVarSimplify.
03003     if (ICmpInst *CI = dyn_cast<ICmpInst>(LF.UserInst))
03004       if (CI->isEquality()) {
03005         // Swap the operands if needed to put the OperandValToReplace on the
03006         // left, for consistency.
03007         Value *NV = CI->getOperand(1);
03008         if (NV == LF.OperandValToReplace) {
03009           CI->setOperand(1, CI->getOperand(0));
03010           CI->setOperand(0, NV);
03011           NV = CI->getOperand(1);
03012           Changed = true;
03013         }
03014 
03015         // x == y  -->  x - y == 0
03016         const SCEV *N = SE.getSCEV(NV);
03017         if (SE.isLoopInvariant(N, L) && isSafeToExpand(N, SE)) {
03018           // S is normalized, so normalize N before folding it into S
03019           // to keep the result normalized.
03020           N = TransformForPostIncUse(Normalize, N, CI, nullptr,
03021                                      LF.PostIncLoops, SE, DT);
03022           Kind = LSRUse::ICmpZero;
03023           S = SE.getMinusSCEV(N, S);
03024         }
03025 
03026         // -1 and the negations of all interesting strides (except the negation
03027         // of -1) are now also interesting.
03028         for (size_t i = 0, e = Factors.size(); i != e; ++i)
03029           if (Factors[i] != -1)
03030             Factors.insert(-(uint64_t)Factors[i]);
03031         Factors.insert(-1);
03032       }
03033 
03034     // Set up the initial formula for this use.
03035     std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
03036     LF.LUIdx = P.first;
03037     LF.Offset = P.second;
03038     LSRUse &LU = Uses[LF.LUIdx];
03039     LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
03040     if (!LU.WidestFixupType ||
03041         SE.getTypeSizeInBits(LU.WidestFixupType) <
03042         SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
03043       LU.WidestFixupType = LF.OperandValToReplace->getType();
03044 
03045     // If this is the first use of this LSRUse, give it a formula.
03046     if (LU.Formulae.empty()) {
03047       InsertInitialFormula(S, LU, LF.LUIdx);
03048       CountRegisters(LU.Formulae.back(), LF.LUIdx);
03049     }
03050   }
03051 
03052   DEBUG(print_fixups(dbgs()));
03053 }
03054 
03055 /// InsertInitialFormula - Insert a formula for the given expression into
03056 /// the given use, separating out loop-variant portions from loop-invariant
03057 /// and loop-computable portions.
03058 void
03059 LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx) {
03060   // Mark uses whose expressions cannot be expanded.
03061   if (!isSafeToExpand(S, SE))
03062     LU.RigidFormula = true;
03063 
03064   Formula F;
03065   F.InitialMatch(S, L, SE);
03066   bool Inserted = InsertFormula(LU, LUIdx, F);
03067   assert(Inserted && "Initial formula already exists!"); (void)Inserted;
03068 }
03069 
03070 /// InsertSupplementalFormula - Insert a simple single-register formula for
03071 /// the given expression into the given use.
03072 void
03073 LSRInstance::InsertSupplementalFormula(const SCEV *S,
03074                                        LSRUse &LU, size_t LUIdx) {
03075   Formula F;
03076   F.BaseRegs.push_back(S);
03077   F.HasBaseReg = true;
03078   bool Inserted = InsertFormula(LU, LUIdx, F);
03079   assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
03080 }
03081 
03082 /// CountRegisters - Note which registers are used by the given formula,
03083 /// updating RegUses.
03084 void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
03085   if (F.ScaledReg)
03086     RegUses.CountRegister(F.ScaledReg, LUIdx);
03087   for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
03088        E = F.BaseRegs.end(); I != E; ++I)
03089     RegUses.CountRegister(*I, LUIdx);
03090 }
03091 
03092 /// InsertFormula - If the given formula has not yet been inserted, add it to
03093 /// the list, and return true. Return false otherwise.
03094 bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
03095   // Do not insert formula that we will not be able to expand.
03096   assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F) &&
03097          "Formula is illegal");
03098   if (!LU.InsertFormula(F))
03099     return false;
03100 
03101   CountRegisters(F, LUIdx);
03102   return true;
03103 }
03104 
03105 /// CollectLoopInvariantFixupsAndFormulae - Check for other uses of
03106 /// loop-invariant values which we're tracking. These other uses will pin these
03107 /// values in registers, making them less profitable for elimination.
03108 /// TODO: This currently misses non-constant addrec step registers.
03109 /// TODO: Should this give more weight to users inside the loop?
03110 void
03111 LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
03112   SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
03113   SmallPtrSet<const SCEV *, 32> Visited;
03114 
03115   while (!Worklist.empty()) {
03116     const SCEV *S = Worklist.pop_back_val();
03117 
03118     // Don't process the same SCEV twice
03119     if (!Visited.insert(S).second)
03120       continue;
03121 
03122     if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
03123       Worklist.append(N->op_begin(), N->op_end());
03124     else if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
03125       Worklist.push_back(C->getOperand());
03126     else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
03127       Worklist.push_back(D->getLHS());
03128       Worklist.push_back(D->getRHS());
03129     } else if (const SCEVUnknown *US = dyn_cast<SCEVUnknown>(S)) {
03130       const Value *V = US->getValue();
03131       if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
03132         // Look for instructions defined outside the loop.
03133         if (L->contains(Inst)) continue;
03134       } else if (isa<UndefValue>(V))
03135         // Undef doesn't have a live range, so it doesn't matter.
03136         continue;
03137       for (const Use &U : V->uses()) {
03138         const Instruction *UserInst = dyn_cast<Instruction>(U.getUser());
03139         // Ignore non-instructions.
03140         if (!UserInst)
03141           continue;
03142         // Ignore instructions in other functions (as can happen with
03143         // Constants).
03144         if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
03145           continue;
03146         // Ignore instructions not dominated by the loop.
03147         const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
03148           UserInst->getParent() :
03149           cast<PHINode>(UserInst)->getIncomingBlock(
03150             PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
03151         if (!DT.dominates(L->getHeader(), UseBB))
03152           continue;
03153         // Ignore uses which are part of other SCEV expressions, to avoid
03154         // analyzing them multiple times.
03155         if (SE.isSCEVable(UserInst->getType())) {
03156           const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst));
03157           // If the user is a no-op, look through to its uses.
03158           if (!isa<SCEVUnknown>(UserS))
03159             continue;
03160           if (UserS == US) {
03161             Worklist.push_back(
03162               SE.getUnknown(const_cast<Instruction *>(UserInst)));
03163             continue;
03164           }
03165         }
03166         // Ignore icmp instructions which are already being analyzed.
03167         if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
03168           unsigned OtherIdx = !U.getOperandNo();
03169           Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
03170           if (SE.hasComputableLoopEvolution(SE.getSCEV(OtherOp), L))
03171             continue;
03172         }
03173 
03174         LSRFixup &LF = getNewFixup();
03175         LF.UserInst = const_cast<Instruction *>(UserInst);
03176         LF.OperandValToReplace = U;
03177         std::pair<size_t, int64_t> P = getUse(S, LSRUse::Basic, nullptr);
03178         LF.LUIdx = P.first;
03179         LF.Offset = P.second;
03180         LSRUse &LU = Uses[LF.LUIdx];
03181         LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
03182         if (!LU.WidestFixupType ||
03183             SE.getTypeSizeInBits(LU.WidestFixupType) <
03184             SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
03185           LU.WidestFixupType = LF.OperandValToReplace->getType();
03186         InsertSupplementalFormula(US, LU, LF.LUIdx);
03187         CountRegisters(LU.Formulae.back(), Uses.size() - 1);
03188         break;
03189       }
03190     }
03191   }
03192 }
03193 
03194 /// CollectSubexprs - Split S into subexpressions which can be pulled out into
03195 /// separate registers. If C is non-null, multiply each subexpression by C.
03196 ///
03197 /// Return remainder expression after factoring the subexpressions captured by
03198 /// Ops. If Ops is complete, return NULL.
03199 static const SCEV *CollectSubexprs(const SCEV *S, const SCEVConstant *C,
03200                                    SmallVectorImpl<const SCEV *> &Ops,
03201                                    const Loop *L,
03202                                    ScalarEvolution &SE,
03203                                    unsigned Depth = 0) {
03204   // Arbitrarily cap recursion to protect compile time.
03205   if (Depth >= 3)
03206     return S;
03207 
03208   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
03209     // Break out add operands.
03210     for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
03211          I != E; ++I) {
03212       const SCEV *Remainder = CollectSubexprs(*I, C, Ops, L, SE, Depth+1);
03213       if (Remainder)
03214         Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
03215     }
03216     return nullptr;
03217   } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
03218     // Split a non-zero base out of an addrec.
03219     if (AR->getStart()->isZero())
03220       return S;
03221 
03222     const SCEV *Remainder = CollectSubexprs(AR->getStart(),
03223                                             C, Ops, L, SE, Depth+1);
03224     // Split the non-zero AddRec unless it is part of a nested recurrence that
03225     // does not pertain to this loop.
03226     if (Remainder && (AR->getLoop() == L || !isa<SCEVAddRecExpr>(Remainder))) {
03227       Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
03228       Remainder = nullptr;
03229     }
03230     if (Remainder != AR->getStart()) {
03231       if (!Remainder)
03232         Remainder = SE.getConstant(AR->getType(), 0);
03233       return SE.getAddRecExpr(Remainder,
03234                               AR->getStepRecurrence(SE),
03235                               AR->getLoop(),
03236                               //FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
03237                               SCEV::FlagAnyWrap);
03238     }
03239   } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
03240     // Break (C * (a + b + c)) into C*a + C*b + C*c.
03241     if (Mul->getNumOperands() != 2)
03242       return S;
03243     if (const SCEVConstant *Op0 =
03244         dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
03245       C = C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0;
03246       const SCEV *Remainder =
03247         CollectSubexprs(Mul->getOperand(1), C, Ops, L, SE, Depth+1);
03248       if (Remainder)
03249         Ops.push_back(SE.getMulExpr(C, Remainder));
03250       return nullptr;
03251     }
03252   }
03253   return S;
03254 }
03255 
03256 /// \brief Helper function for LSRInstance::GenerateReassociations.
03257 void LSRInstance::GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
03258                                              const Formula &Base,
03259                                              unsigned Depth, size_t Idx,
03260                                              bool IsScaledReg) {
03261   const SCEV *BaseReg = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
03262   SmallVector<const SCEV *, 8> AddOps;
03263   const SCEV *Remainder = CollectSubexprs(BaseReg, nullptr, AddOps, L, SE);
03264   if (Remainder)
03265     AddOps.push_back(Remainder);
03266 
03267   if (AddOps.size() == 1)
03268     return;
03269 
03270   for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),
03271                                                      JE = AddOps.end();
03272        J != JE; ++J) {
03273 
03274     // Loop-variant "unknown" values are uninteresting; we won't be able to
03275     // do anything meaningful with them.
03276     if (isa<SCEVUnknown>(*J) && !SE.isLoopInvariant(*J, L))
03277       continue;
03278 
03279     // Don't pull a constant into a register if the constant could be folded
03280     // into an immediate field.
03281     if (isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,
03282                          LU.AccessTy, *J, Base.getNumRegs() > 1))
03283       continue;
03284 
03285     // Collect all operands except *J.
03286     SmallVector<const SCEV *, 8> InnerAddOps(
03287         ((const SmallVector<const SCEV *, 8> &)AddOps).begin(), J);
03288     InnerAddOps.append(std::next(J),
03289                        ((const SmallVector<const SCEV *, 8> &)AddOps).end());
03290 
03291     // Don't leave just a constant behind in a register if the constant could
03292     // be folded into an immediate field.
03293     if (InnerAddOps.size() == 1 &&
03294         isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,
03295                          LU.AccessTy, InnerAddOps[0], Base.getNumRegs() > 1))
03296       continue;
03297 
03298     const SCEV *InnerSum = SE.getAddExpr(InnerAddOps);
03299     if (InnerSum->isZero())
03300       continue;
03301     Formula F = Base;
03302 
03303     // Add the remaining pieces of the add back into the new formula.
03304     const SCEVConstant *InnerSumSC = dyn_cast<SCEVConstant>(InnerSum);
03305     if (InnerSumSC && SE.getTypeSizeInBits(InnerSumSC->getType()) <= 64 &&
03306         TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
03307                                 InnerSumSC->getValue()->getZExtValue())) {
03308       F.UnfoldedOffset =
03309           (uint64_t)F.UnfoldedOffset + InnerSumSC->getValue()->getZExtValue();
03310       if (IsScaledReg)
03311         F.ScaledReg = nullptr;
03312       else
03313         F.BaseRegs.erase(F.BaseRegs.begin() + Idx);
03314     } else if (IsScaledReg)
03315       F.ScaledReg = InnerSum;
03316     else
03317       F.BaseRegs[Idx] = InnerSum;
03318 
03319     // Add J as its own register, or an unfolded immediate.
03320     const SCEVConstant *SC = dyn_cast<SCEVConstant>(*J);
03321     if (SC && SE.getTypeSizeInBits(SC->getType()) <= 64 &&
03322         TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
03323                                 SC->getValue()->getZExtValue()))
03324       F.UnfoldedOffset =
03325           (uint64_t)F.UnfoldedOffset + SC->getValue()->getZExtValue();
03326     else
03327       F.BaseRegs.push_back(*J);
03328     // We may have changed the number of register in base regs, adjust the
03329     // formula accordingly.
03330     F.Canonicalize();
03331 
03332     if (InsertFormula(LU, LUIdx, F))
03333       // If that formula hadn't been seen before, recurse to find more like
03334       // it.
03335       GenerateReassociations(LU, LUIdx, LU.Formulae.back(), Depth + 1);
03336   }
03337 }
03338 
03339 /// GenerateReassociations - Split out subexpressions from adds and the bases of
03340 /// addrecs.
03341 void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
03342                                          Formula Base, unsigned Depth) {
03343   assert(Base.isCanonical() && "Input must be in the canonical form");
03344   // Arbitrarily cap recursion to protect compile time.
03345   if (Depth >= 3)
03346     return;
03347 
03348   for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
03349     GenerateReassociationsImpl(LU, LUIdx, Base, Depth, i);
03350 
03351   if (Base.Scale == 1)
03352     GenerateReassociationsImpl(LU, LUIdx, Base, Depth,
03353                                /* Idx */ -1, /* IsScaledReg */ true);
03354 }
03355 
03356 /// GenerateCombinations - Generate a formula consisting of all of the
03357 /// loop-dominating registers added into a single register.
03358 void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
03359                                        Formula Base) {
03360   // This method is only interesting on a plurality of registers.
03361   if (Base.BaseRegs.size() + (Base.Scale == 1) <= 1)
03362     return;
03363 
03364   // Flatten the representation, i.e., reg1 + 1*reg2 => reg1 + reg2, before
03365   // processing the formula.
03366   Base.Unscale();
03367   Formula F = Base;
03368   F.BaseRegs.clear();
03369   SmallVector<const SCEV *, 4> Ops;
03370   for (SmallVectorImpl<const SCEV *>::const_iterator
03371        I = Base.BaseRegs.begin(), E = Base.BaseRegs.end(); I != E; ++I) {
03372     const SCEV *BaseReg = *I;
03373     if (SE.properlyDominates(BaseReg, L->getHeader()) &&
03374         !SE.hasComputableLoopEvolution(BaseReg, L))
03375       Ops.push_back(BaseReg);
03376     else
03377       F.BaseRegs.push_back(BaseReg);
03378   }
03379   if (Ops.size() > 1) {
03380     const SCEV *Sum = SE.getAddExpr(Ops);
03381     // TODO: If Sum is zero, it probably means ScalarEvolution missed an
03382     // opportunity to fold something. For now, just ignore such cases
03383     // rather than proceed with zero in a register.
03384     if (!Sum->isZero()) {
03385       F.BaseRegs.push_back(Sum);
03386       F.Canonicalize();
03387       (void)InsertFormula(LU, LUIdx, F);
03388     }
03389   }
03390 }
03391 
03392 /// \brief Helper function for LSRInstance::GenerateSymbolicOffsets.
03393 void LSRInstance::GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
03394                                               const Formula &Base, size_t Idx,
03395                                               bool IsScaledReg) {
03396   const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
03397   GlobalValue *GV = ExtractSymbol(G, SE);
03398   if (G->isZero() || !GV)
03399     return;
03400   Formula F = Base;
03401   F.BaseGV = GV;
03402   if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
03403     return;
03404   if (IsScaledReg)
03405     F.ScaledReg = G;
03406   else
03407     F.BaseRegs[Idx] = G;
03408   (void)InsertFormula(LU, LUIdx, F);
03409 }
03410 
03411 /// GenerateSymbolicOffsets - Generate reuse formulae using symbolic offsets.
03412 void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
03413                                           Formula Base) {
03414   // We can't add a symbolic offset if the address already contains one.
03415   if (Base.BaseGV) return;
03416 
03417   for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
03418     GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, i);
03419   if (Base.Scale == 1)
03420     GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, /* Idx */ -1,
03421                                 /* IsScaledReg */ true);
03422 }
03423 
03424 /// \brief Helper function for LSRInstance::GenerateConstantOffsets.
03425 void LSRInstance::GenerateConstantOffsetsImpl(
03426     LSRUse &LU, unsigned LUIdx, const Formula &Base,
03427     const SmallVectorImpl<int64_t> &Worklist, size_t Idx, bool IsScaledReg) {
03428   const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
03429   for (SmallVectorImpl<int64_t>::const_iterator I = Worklist.begin(),
03430                                                 E = Worklist.end();
03431        I != E; ++I) {
03432     Formula F = Base;
03433     F.BaseOffset = (uint64_t)Base.BaseOffset - *I;
03434     if (isLegalUse(TTI, LU.MinOffset - *I, LU.MaxOffset - *I, LU.Kind,
03435                    LU.AccessTy, F)) {
03436       // Add the offset to the base register.
03437       const SCEV *NewG = SE.getAddExpr(SE.getConstant(G->getType(), *I), G);
03438       // If it cancelled out, drop the base register, otherwise update it.
03439       if (NewG->isZero()) {
03440         if (IsScaledReg) {
03441           F.Scale = 0;
03442           F.ScaledReg = nullptr;
03443         } else
03444           F.DeleteBaseReg(F.BaseRegs[Idx]);
03445         F.Canonicalize();
03446       } else if (IsScaledReg)
03447         F.ScaledReg = NewG;
03448       else
03449         F.BaseRegs[Idx] = NewG;
03450 
03451       (void)InsertFormula(LU, LUIdx, F);
03452     }
03453   }
03454 
03455   int64_t Imm = ExtractImmediate(G, SE);
03456   if (G->isZero() || Imm == 0)
03457     return;
03458   Formula F = Base;
03459   F.BaseOffset = (uint64_t)F.BaseOffset + Imm;
03460   if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
03461     return;
03462   if (IsScaledReg)
03463     F.ScaledReg = G;
03464   else
03465     F.BaseRegs[Idx] = G;
03466   (void)InsertFormula(LU, LUIdx, F);
03467 }
03468 
03469 /// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
03470 void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
03471                                           Formula Base) {
03472   // TODO: For now, just add the min and max offset, because it usually isn't
03473   // worthwhile looking at everything inbetween.
03474   SmallVector<int64_t, 2> Worklist;
03475   Worklist.push_back(LU.MinOffset);
03476   if (LU.MaxOffset != LU.MinOffset)
03477     Worklist.push_back(LU.MaxOffset);
03478 
03479   for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
03480     GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, i);
03481   if (Base.Scale == 1)
03482     GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, /* Idx */ -1,
03483                                 /* IsScaledReg */ true);
03484 }
03485 
03486 /// GenerateICmpZeroScales - For ICmpZero, check to see if we can scale up
03487 /// the comparison. For example, x == y -> x*c == y*c.
03488 void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
03489                                          Formula Base) {
03490   if (LU.Kind != LSRUse::ICmpZero) return;
03491 
03492   // Determine the integer type for the base formula.
03493   Type *IntTy = Base.getType();
03494   if (!IntTy) return;
03495   if (SE.getTypeSizeInBits(IntTy) > 64) return;
03496 
03497   // Don't do this if there is more than one offset.
03498   if (LU.MinOffset != LU.MaxOffset) return;
03499 
03500   assert(!Base.BaseGV && "ICmpZero use is not legal!");
03501 
03502   // Check each interesting stride.
03503   for (SmallSetVector<int64_t, 8>::const_iterator
03504        I = Factors.begin(), E = Factors.end(); I != E; ++I) {
03505     int64_t Factor = *I;
03506 
03507     // Check that the multiplication doesn't overflow.
03508     if (Base.BaseOffset == INT64_MIN && Factor == -1)
03509       continue;
03510     int64_t NewBaseOffset = (uint64_t)Base.BaseOffset * Factor;
03511     if (NewBaseOffset / Factor != Base.BaseOffset)
03512       continue;
03513     // If the offset will be truncated at this use, check that it is in bounds.
03514     if (!IntTy->isPointerTy() &&
03515         !ConstantInt::isValueValidForType(IntTy, NewBaseOffset))
03516       continue;
03517 
03518     // Check that multiplying with the use offset doesn't overflow.
03519     int64_t Offset = LU.MinOffset;
03520     if (Offset == INT64_MIN && Factor == -1)
03521       continue;
03522     Offset = (uint64_t)Offset * Factor;
03523     if (Offset / Factor != LU.MinOffset)
03524       continue;
03525     // If the offset will be truncated at this use, check that it is in bounds.
03526     if (!IntTy->isPointerTy() &&
03527         !ConstantInt::isValueValidForType(IntTy, Offset))
03528       continue;
03529 
03530     Formula F = Base;
03531     F.BaseOffset = NewBaseOffset;
03532 
03533     // Check that this scale is legal.
03534     if (!isLegalUse(TTI, Offset, Offset, LU.Kind, LU.AccessTy, F))
03535       continue;
03536 
03537     // Compensate for the use having MinOffset built into it.
03538     F.BaseOffset = (uint64_t)F.BaseOffset + Offset - LU.MinOffset;
03539 
03540     const SCEV *FactorS = SE.getConstant(IntTy, Factor);
03541 
03542     // Check that multiplying with each base register doesn't overflow.
03543     for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
03544       F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
03545       if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
03546         goto next;
03547     }
03548 
03549     // Check that multiplying with the scaled register doesn't overflow.
03550     if (F.ScaledReg) {
03551       F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
03552       if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
03553         continue;
03554     }
03555 
03556     // Check that multiplying with the unfolded offset doesn't overflow.
03557     if (F.UnfoldedOffset != 0) {
03558       if (F.UnfoldedOffset == INT64_MIN && Factor == -1)
03559         continue;
03560       F.UnfoldedOffset = (uint64_t)F.UnfoldedOffset * Factor;
03561       if (F.UnfoldedOffset / Factor != Base.UnfoldedOffset)
03562         continue;
03563       // If the offset will be truncated, check that it is in bounds.
03564       if (!IntTy->isPointerTy() &&
03565           !ConstantInt::isValueValidForType(IntTy, F.UnfoldedOffset))
03566         continue;
03567     }
03568 
03569     // If we make it here and it's legal, add it.
03570     (void)InsertFormula(LU, LUIdx, F);
03571   next:;
03572   }
03573 }
03574 
03575 /// GenerateScales - Generate stride factor reuse formulae by making use of
03576 /// scaled-offset address modes, for example.
03577 void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base) {
03578   // Determine the integer type for the base formula.
03579   Type *IntTy = Base.getType();
03580   if (!IntTy) return;
03581 
03582   // If this Formula already has a scaled register, we can't add another one.
03583   // Try to unscale the formula to generate a better scale.
03584   if (Base.Scale != 0 && !Base.Unscale())
03585     return;
03586 
03587   assert(Base.Scale == 0 && "Unscale did not did its job!");
03588 
03589   // Check each interesting stride.
03590   for (SmallSetVector<int64_t, 8>::const_iterator
03591        I = Factors.begin(), E = Factors.end(); I != E; ++I) {
03592     int64_t Factor = *I;
03593 
03594     Base.Scale = Factor;
03595     Base.HasBaseReg = Base.BaseRegs.size() > 1;
03596     // Check whether this scale is going to be legal.
03597     if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
03598                     Base)) {
03599       // As a special-case, handle special out-of-loop Basic users specially.
03600       // TODO: Reconsider this special case.
03601       if (LU.Kind == LSRUse::Basic &&
03602           isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LSRUse::Special,
03603                      LU.AccessTy, Base) &&
03604           LU.AllFixupsOutsideLoop)
03605         LU.Kind = LSRUse::Special;
03606       else
03607         continue;
03608     }
03609     // For an ICmpZero, negating a solitary base register won't lead to
03610     // new solutions.
03611     if (LU.Kind == LSRUse::ICmpZero &&
03612         !Base.HasBaseReg && Base.BaseOffset == 0 && !Base.BaseGV)
03613       continue;
03614     // For each addrec base reg, apply the scale, if possible.
03615     for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
03616       if (const SCEVAddRecExpr *AR =
03617             dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i])) {
03618         const SCEV *FactorS = SE.getConstant(IntTy, Factor);
03619         if (FactorS->isZero())
03620           continue;
03621         // Divide out the factor, ignoring high bits, since we'll be
03622         // scaling the value back up in the end.
03623         if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) {
03624           // TODO: This could be optimized to avoid all the copying.
03625           Formula F = Base;
03626           F.ScaledReg = Quotient;
03627           F.DeleteBaseReg(F.BaseRegs[i]);
03628           // The canonical representation of 1*reg is reg, which is already in
03629           // Base. In that case, do not try to insert the formula, it will be
03630           // rejected anyway.
03631           if (F.Scale == 1 && F.BaseRegs.empty())
03632             continue;
03633           (void)InsertFormula(LU, LUIdx, F);
03634         }
03635       }
03636   }
03637 }
03638 
03639 /// GenerateTruncates - Generate reuse formulae from different IV types.
03640 void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base) {
03641   // Don't bother truncating symbolic values.
03642   if (Base.BaseGV) return;
03643 
03644   // Determine the integer type for the base formula.
03645   Type *DstTy = Base.getType();
03646   if (!DstTy) return;
03647   DstTy = SE.getEffectiveSCEVType(DstTy);
03648 
03649   for (SmallSetVector<Type *, 4>::const_iterator
03650        I = Types.begin(), E = Types.end(); I != E; ++I) {
03651     Type *SrcTy = *I;
03652     if (SrcTy != DstTy && TTI.isTruncateFree(SrcTy, DstTy)) {
03653       Formula F = Base;
03654 
03655       if (F.ScaledReg) F.ScaledReg = SE.getAnyExtendExpr(F.ScaledReg, *I);
03656       for (SmallVectorImpl<const SCEV *>::iterator J = F.BaseRegs.begin(),
03657            JE = F.BaseRegs.end(); J != JE; ++J)
03658         *J = SE.getAnyExtendExpr(*J, SrcTy);
03659 
03660       // TODO: This assumes we've done basic processing on all uses and
03661       // have an idea what the register usage is.
03662       if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
03663         continue;
03664 
03665       (void)InsertFormula(LU, LUIdx, F);
03666     }
03667   }
03668 }
03669 
03670 namespace {
03671 
03672 /// WorkItem - Helper class for GenerateCrossUseConstantOffsets. It's used to
03673 /// defer modifications so that the search phase doesn't have to worry about
03674 /// the data structures moving underneath it.
03675 struct WorkItem {
03676   size_t LUIdx;
03677   int64_t Imm;
03678   const SCEV *OrigReg;
03679 
03680   WorkItem(size_t LI, int64_t I, const SCEV *R)
03681     : LUIdx(LI), Imm(I), OrigReg(R) {}
03682 
03683   void print(raw_ostream &OS) const;
03684   void dump() const;
03685 };
03686 
03687 }
03688 
03689 void WorkItem::print(raw_ostream &OS) const {
03690   OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
03691      << " , add offset " << Imm;
03692 }
03693 
03694 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
03695 void WorkItem::dump() const {
03696   print(errs()); errs() << '\n';
03697 }
03698 #endif
03699 
03700 /// GenerateCrossUseConstantOffsets - Look for registers which are a constant
03701 /// distance apart and try to form reuse opportunities between them.
03702 void LSRInstance::GenerateCrossUseConstantOffsets() {
03703   // Group the registers by their value without any added constant offset.
03704   typedef std::map<int64_t, const SCEV *> ImmMapTy;
03705   typedef DenseMap<const SCEV *, ImmMapTy> RegMapTy;
03706   RegMapTy Map;
03707   DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
03708   SmallVector<const SCEV *, 8> Sequence;
03709   for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
03710        I != E; ++I) {
03711     const SCEV *Reg = *I;
03712     int64_t Imm = ExtractImmediate(Reg, SE);
03713     std::pair<RegMapTy::iterator, bool> Pair =
03714       Map.insert(std::make_pair(Reg, ImmMapTy()));
03715     if (Pair.second)
03716       Sequence.push_back(Reg);
03717     Pair.first->second.insert(std::make_pair(Imm, *I));
03718     UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(*I);
03719   }
03720 
03721   // Now examine each set of registers with the same base value. Build up
03722   // a list of work to do and do the work in a separate step so that we're
03723   // not adding formulae and register counts while we're searching.
03724   SmallVector<WorkItem, 32> WorkItems;
03725   SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems;
03726   for (SmallVectorImpl<const SCEV *>::const_iterator I = Sequence.begin(),
03727        E = Sequence.end(); I != E; ++I) {
03728     const SCEV *Reg = *I;
03729     const ImmMapTy &Imms = Map.find(Reg)->second;
03730 
03731     // It's not worthwhile looking for reuse if there's only one offset.
03732     if (Imms.size() == 1)
03733       continue;
03734 
03735     DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
03736           for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
03737                J != JE; ++J)
03738             dbgs() << ' ' << J->first;
03739           dbgs() << '\n');
03740 
03741     // Examine each offset.
03742     for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
03743          J != JE; ++J) {
03744       const SCEV *OrigReg = J->second;
03745 
03746       int64_t JImm = J->first;
03747       const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
03748 
03749       if (!isa<SCEVConstant>(OrigReg) &&
03750           UsedByIndicesMap[Reg].count() == 1) {
03751         DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg << '\n');
03752         continue;
03753       }
03754 
03755       // Conservatively examine offsets between this orig reg a few selected
03756       // other orig regs.
03757       ImmMapTy::const_iterator OtherImms[] = {
03758         Imms.begin(), std::prev(Imms.end()),
03759         Imms.lower_bound((Imms.begin()->first + std::prev(Imms.end())->first) /
03760                          2)
03761       };
03762       for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) {
03763         ImmMapTy::const_iterator M = OtherImms[i];
03764         if (M == J || M == JE) continue;
03765 
03766         // Compute the difference between the two.
03767         int64_t Imm = (uint64_t)JImm - M->first;
03768         for (int LUIdx = UsedByIndices.find_first(); LUIdx != -1;
03769              LUIdx = UsedByIndices.find_next(LUIdx))
03770           // Make a memo of this use, offset, and register tuple.
03771           if (UniqueItems.insert(std::make_pair(LUIdx, Imm)).second)
03772             WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
03773       }
03774     }
03775   }
03776 
03777   Map.clear();
03778   Sequence.clear();
03779   UsedByIndicesMap.clear();
03780   UniqueItems.clear();
03781 
03782   // Now iterate through the worklist and add new formulae.
03783   for (SmallVectorImpl<WorkItem>::const_iterator I = WorkItems.begin(),
03784        E = WorkItems.end(); I != E; ++I) {
03785     const WorkItem &WI = *I;
03786     size_t LUIdx = WI.LUIdx;
03787     LSRUse &LU = Uses[LUIdx];
03788     int64_t Imm = WI.Imm;
03789     const SCEV *OrigReg = WI.OrigReg;
03790 
03791     Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
03792     const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
03793     unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
03794 
03795     // TODO: Use a more targeted data structure.
03796     for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
03797       Formula F = LU.Formulae[L];
03798       // FIXME: The code for the scaled and unscaled registers looks
03799       // very similar but slightly different. Investigate if they
03800       // could be merged. That way, we would not have to unscale the
03801       // Formula.
03802       F.Unscale();
03803       // Use the immediate in the scaled register.
03804       if (F.ScaledReg == OrigReg) {
03805         int64_t Offset = (uint64_t)F.BaseOffset + Imm * (uint64_t)F.Scale;
03806         // Don't create 50 + reg(-50).
03807         if (F.referencesReg(SE.getSCEV(
03808                    ConstantInt::get(IntTy, -(uint64_t)Offset))))
03809           continue;
03810         Formula NewF = F;
03811         NewF.BaseOffset = Offset;
03812         if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
03813                         NewF))
03814           continue;
03815         NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
03816 
03817         // If the new scale is a constant in a register, and adding the constant
03818         // value to the immediate would produce a value closer to zero than the
03819         // immediate itself, then the formula isn't worthwhile.
03820         if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
03821           if (C->getValue()->isNegative() !=
03822                 (NewF.BaseOffset < 0) &&
03823               (C->getValue()->getValue().abs() * APInt(BitWidth, F.Scale))
03824                 .ule(std::abs(NewF.BaseOffset)))
03825             continue;
03826 
03827         // OK, looks good.
03828         NewF.Canonicalize();
03829         (void)InsertFormula(LU, LUIdx, NewF);
03830       } else {
03831         // Use the immediate in a base register.
03832         for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
03833           const SCEV *BaseReg = F.BaseRegs[N];
03834           if (BaseReg != OrigReg)
03835             continue;
03836           Formula NewF = F;
03837           NewF.BaseOffset = (uint64_t)NewF.BaseOffset + Imm;
03838           if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset,
03839                           LU.Kind, LU.AccessTy, NewF)) {
03840             if (!TTI.isLegalAddImmediate((uint64_t)NewF.UnfoldedOffset + Imm))
03841               continue;
03842             NewF = F;
03843             NewF.UnfoldedOffset = (uint64_t)NewF.UnfoldedOffset + Imm;
03844           }
03845           NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
03846 
03847           // If the new formula has a constant in a register, and adding the
03848           // constant value to the immediate would produce a value closer to
03849           // zero than the immediate itself, then the formula isn't worthwhile.
03850           for (SmallVectorImpl<const SCEV *>::const_iterator
03851                J = NewF.BaseRegs.begin(), JE = NewF.BaseRegs.end();
03852                J != JE; ++J)
03853             if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*J))
03854               if ((C->getValue()->getValue() + NewF.BaseOffset).abs().slt(
03855                    std::abs(NewF.BaseOffset)) &&
03856                   (C->getValue()->getValue() +
03857                    NewF.BaseOffset).countTrailingZeros() >=
03858                    countTrailingZeros<uint64_t>(NewF.BaseOffset))
03859                 goto skip_formula;
03860 
03861           // Ok, looks good.
03862           NewF.Canonicalize();
03863           (void)InsertFormula(LU, LUIdx, NewF);
03864           break;
03865         skip_formula:;
03866         }
03867       }
03868     }
03869   }
03870 }
03871 
03872 /// GenerateAllReuseFormulae - Generate formulae for each use.
03873 void
03874 LSRInstance::GenerateAllReuseFormulae() {
03875   // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
03876   // queries are more precise.
03877   for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
03878     LSRUse &LU = Uses[LUIdx];
03879     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
03880       GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
03881     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
03882       GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
03883   }
03884   for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
03885     LSRUse &LU = Uses[LUIdx];
03886     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
03887       GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
03888     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
03889       GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
03890     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
03891       GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
03892     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
03893       GenerateScales(LU, LUIdx, LU.Formulae[i]);
03894   }
03895   for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
03896     LSRUse &LU = Uses[LUIdx];
03897     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
03898       GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
03899   }
03900 
03901   GenerateCrossUseConstantOffsets();
03902 
03903   DEBUG(dbgs() << "\n"
03904                   "After generating reuse formulae:\n";
03905         print_uses(dbgs()));
03906 }
03907 
03908 /// If there are multiple formulae with the same set of registers used
03909 /// by other uses, pick the best one and delete the others.
03910 void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
03911   DenseSet<const SCEV *> VisitedRegs;
03912   SmallPtrSet<const SCEV *, 16> Regs;
03913   SmallPtrSet<const SCEV *, 16> LoserRegs;
03914 #ifndef NDEBUG
03915   bool ChangedFormulae = false;
03916 #endif
03917 
03918   // Collect the best formula for each unique set of shared registers. This
03919   // is reset for each use.
03920   typedef DenseMap<SmallVector<const SCEV *, 4>, size_t, UniquifierDenseMapInfo>
03921     BestFormulaeTy;
03922   BestFormulaeTy BestFormulae;
03923 
03924   for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
03925     LSRUse &LU = Uses[LUIdx];
03926     DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs()); dbgs() << '\n');
03927 
03928     bool Any = false;
03929     for (size_t FIdx = 0, NumForms = LU.Formulae.size();
03930          FIdx != NumForms; ++FIdx) {
03931       Formula &F = LU.Formulae[FIdx];
03932 
03933       // Some formulas are instant losers. For example, they may depend on
03934       // nonexistent AddRecs from other loops. These need to be filtered
03935       // immediately, otherwise heuristics could choose them over others leading
03936       // to an unsatisfactory solution. Passing LoserRegs into RateFormula here
03937       // avoids the need to recompute this information across formulae using the
03938       // same bad AddRec. Passing LoserRegs is also essential unless we remove
03939       // the corresponding bad register from the Regs set.
03940       Cost CostF;
03941       Regs.clear();
03942       CostF.RateFormula(TTI, F, Regs, VisitedRegs, L, LU.Offsets, SE, DT, LU,
03943                         &LoserRegs);
03944       if (CostF.isLoser()) {
03945         // During initial formula generation, undesirable formulae are generated
03946         // by uses within other loops that have some non-trivial address mode or
03947         // use the postinc form of the IV. LSR needs to provide these formulae
03948         // as the basis of rediscovering the desired formula that uses an AddRec
03949         // corresponding to the existing phi. Once all formulae have been
03950         // generated, these initial losers may be pruned.
03951         DEBUG(dbgs() << "  Filtering loser "; F.print(dbgs());
03952               dbgs() << "\n");
03953       }
03954       else {
03955         SmallVector<const SCEV *, 4> Key;
03956         for (SmallVectorImpl<const SCEV *>::const_iterator J = F.BaseRegs.begin(),
03957                JE = F.BaseRegs.end(); J != JE; ++J) {
03958           const SCEV *Reg = *J;
03959           if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
03960             Key.push_back(Reg);
03961         }
03962         if (F.ScaledReg &&
03963             RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
03964           Key.push_back(F.ScaledReg);
03965         // Unstable sort by host order ok, because this is only used for
03966         // uniquifying.
03967         std::sort(Key.begin(), Key.end());
03968 
03969         std::pair<BestFormulaeTy::const_iterator, bool> P =
03970           BestFormulae.insert(std::make_pair(Key, FIdx));
03971         if (P.second)
03972           continue;
03973 
03974         Formula &Best = LU.Formulae[P.first->second];
03975 
03976         Cost CostBest;
03977         Regs.clear();
03978         CostBest.RateFormula(TTI, Best, Regs, VisitedRegs, L, LU.Offsets, SE,
03979                              DT, LU);
03980         if (CostF < CostBest)
03981           std::swap(F, Best);
03982         DEBUG(dbgs() << "  Filtering out formula "; F.print(dbgs());
03983               dbgs() << "\n"
03984                         "    in favor of formula "; Best.print(dbgs());
03985               dbgs() << '\n');
03986       }
03987 #ifndef NDEBUG
03988       ChangedFormulae = true;
03989 #endif
03990       LU.DeleteFormula(F);
03991       --FIdx;
03992       --NumForms;
03993       Any = true;
03994     }
03995 
03996     // Now that we've filtered out some formulae, recompute the Regs set.
03997     if (Any)
03998       LU.RecomputeRegs(LUIdx, RegUses);
03999 
04000     // Reset this to prepare for the next use.
04001     BestFormulae.clear();
04002   }
04003 
04004   DEBUG(if (ChangedFormulae) {
04005           dbgs() << "\n"
04006                     "After filtering out undesirable candidates:\n";
04007           print_uses(dbgs());
04008         });
04009 }
04010 
04011 // This is a rough guess that seems to work fairly well.
04012 static const size_t ComplexityLimit = UINT16_MAX;
04013 
04014 /// EstimateSearchSpaceComplexity - Estimate the worst-case number of
04015 /// solutions the solver might have to consider. It almost never considers
04016 /// this many solutions because it prune the search space, but the pruning
04017 /// isn't always sufficient.
04018 size_t LSRInstance::EstimateSearchSpaceComplexity() const {
04019   size_t Power = 1;
04020   for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
04021        E = Uses.end(); I != E; ++I) {
04022     size_t FSize = I->Formulae.size();
04023     if (FSize >= ComplexityLimit) {
04024       Power = ComplexityLimit;
04025       break;
04026     }
04027     Power *= FSize;
04028     if (Power >= ComplexityLimit)
04029       break;
04030   }
04031   return Power;
04032 }
04033 
04034 /// NarrowSearchSpaceByDetectingSupersets - When one formula uses a superset
04035 /// of the registers of another formula, it won't help reduce register
04036 /// pressure (though it may not necessarily hurt register pressure); remove
04037 /// it to simplify the system.
04038 void LSRInstance::NarrowSearchSpaceByDetectingSupersets() {
04039   if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
04040     DEBUG(dbgs() << "The search space is too complex.\n");
04041 
04042     DEBUG(dbgs() << "Narrowing the search space by eliminating formulae "
04043                     "which use a superset of registers used by other "
04044                     "formulae.\n");
04045 
04046     for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
04047       LSRUse &LU = Uses[LUIdx];
04048       bool Any = false;
04049       for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
04050         Formula &F = LU.Formulae[i];
04051         // Look for a formula with a constant or GV in a register. If the use
04052         // also has a formula with that same value in an immediate field,
04053         // delete the one that uses a register.
04054         for (SmallVectorImpl<const SCEV *>::const_iterator
04055              I = F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I) {
04056           if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*I)) {
04057             Formula NewF = F;
04058             NewF.BaseOffset += C->getValue()->getSExtValue();
04059             NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
04060                                 (I - F.BaseRegs.begin()));
04061             if (LU.HasFormulaWithSameRegs(NewF)) {
04062               DEBUG(dbgs() << "  Deleting "; F.print(dbgs()); dbgs() << '\n');
04063               LU.DeleteFormula(F);
04064               --i;
04065               --e;
04066               Any = true;
04067               break;
04068             }
04069           } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) {
04070             if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue()))
04071               if (!F.BaseGV) {
04072                 Formula NewF = F;
04073                 NewF.BaseGV = GV;
04074                 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
04075                                     (I - F.BaseRegs.begin()));
04076                 if (LU.HasFormulaWithSameRegs(NewF)) {
04077                   DEBUG(dbgs() << "  Deleting "; F.print(dbgs());
04078                         dbgs() << '\n');
04079                   LU.DeleteFormula(F);
04080                   --i;
04081                   --e;
04082                   Any = true;
04083                   break;
04084                 }
04085               }
04086           }
04087         }
04088       }
04089       if (Any)
04090         LU.RecomputeRegs(LUIdx, RegUses);
04091     }
04092 
04093     DEBUG(dbgs() << "After pre-selection:\n";
04094           print_uses(dbgs()));
04095   }
04096 }
04097 
04098 /// NarrowSearchSpaceByCollapsingUnrolledCode - When there are many registers
04099 /// for expressions like A, A+1, A+2, etc., allocate a single register for
04100 /// them.
04101 void LSRInstance::NarrowSearchSpaceByCollapsingUnrolledCode() {
04102   if (EstimateSearchSpaceComplexity() < ComplexityLimit)
04103     return;
04104 
04105   DEBUG(dbgs() << "The search space is too complex.\n"
04106                   "Narrowing the search space by assuming that uses separated "
04107                   "by a constant offset will use the same registers.\n");
04108 
04109   // This is especially useful for unrolled loops.
04110 
04111   for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
04112     LSRUse &LU = Uses[LUIdx];
04113     for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
04114          E = LU.Formulae.end(); I != E; ++I) {
04115       const Formula &F = *I;
04116       if (F.BaseOffset == 0 || (F.Scale != 0 && F.Scale != 1))
04117         continue;
04118 
04119       LSRUse *LUThatHas = FindUseWithSimilarFormula(F, LU);
04120       if (!LUThatHas)
04121         continue;
04122 
04123       if (!reconcileNewOffset(*LUThatHas, F.BaseOffset, /*HasBaseReg=*/ false,
04124                               LU.Kind, LU.AccessTy))
04125         continue;
04126 
04127       DEBUG(dbgs() << "  Deleting use "; LU.print(dbgs()); dbgs() << '\n');
04128 
04129       LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop;
04130 
04131       // Update the relocs to reference the new use.
04132       for (SmallVectorImpl<LSRFixup>::iterator I = Fixups.begin(),
04133            E = Fixups.end(); I != E; ++I) {
04134         LSRFixup &Fixup = *I;
04135         if (Fixup.LUIdx == LUIdx) {
04136           Fixup.LUIdx = LUThatHas - &Uses.front();
04137           Fixup.Offset += F.BaseOffset;
04138           // Add the new offset to LUThatHas' offset list.
04139           if (LUThatHas->Offsets.back() != Fixup.Offset) {
04140             LUThatHas->Offsets.push_back(Fixup.Offset);
04141             if (Fixup.Offset > LUThatHas->MaxOffset)
04142               LUThatHas->MaxOffset = Fixup.Offset;
04143             if (Fixup.Offset < LUThatHas->MinOffset)
04144               LUThatHas->MinOffset = Fixup.Offset;
04145           }
04146           DEBUG(dbgs() << "New fixup has offset " << Fixup.Offset << '\n');
04147         }
04148         if (Fixup.LUIdx == NumUses-1)
04149           Fixup.LUIdx = LUIdx;
04150       }
04151 
04152       // Delete formulae from the new use which are no longer legal.
04153       bool Any = false;
04154       for (size_t i = 0, e = LUThatHas->Formulae.size(); i != e; ++i) {
04155         Formula &F = LUThatHas->Formulae[i];
04156         if (!isLegalUse(TTI, LUThatHas->MinOffset, LUThatHas->MaxOffset,
04157                         LUThatHas->Kind, LUThatHas->AccessTy, F)) {
04158           DEBUG(dbgs() << "  Deleting "; F.print(dbgs());
04159                 dbgs() << '\n');
04160           LUThatHas->DeleteFormula(F);
04161           --i;
04162           --e;
04163           Any = true;
04164         }
04165       }
04166 
04167       if (Any)
04168         LUThatHas->RecomputeRegs(LUThatHas - &Uses.front(), RegUses);
04169 
04170       // Delete the old use.
04171       DeleteUse(LU, LUIdx);
04172       --LUIdx;
04173       --NumUses;
04174       break;
04175     }
04176   }
04177 
04178   DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
04179 }
04180 
04181 /// NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters - Call
04182 /// FilterOutUndesirableDedicatedRegisters again, if necessary, now that
04183 /// we've done more filtering, as it may be able to find more formulae to
04184 /// eliminate.
04185 void LSRInstance::NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(){
04186   if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
04187     DEBUG(dbgs() << "The search space is too complex.\n");
04188 
04189     DEBUG(dbgs() << "Narrowing the search space by re-filtering out "
04190                     "undesirable dedicated registers.\n");
04191 
04192     FilterOutUndesirableDedicatedRegisters();
04193 
04194     DEBUG(dbgs() << "After pre-selection:\n";
04195           print_uses(dbgs()));
04196   }
04197 }
04198 
04199 /// NarrowSearchSpaceByPickingWinnerRegs - Pick a register which seems likely
04200 /// to be profitable, and then in any use which has any reference to that
04201 /// register, delete all formulae which do not reference that register.
04202 void LSRInstance::NarrowSearchSpaceByPickingWinnerRegs() {
04203   // With all other options exhausted, loop until the system is simple
04204   // enough to handle.
04205   SmallPtrSet<const SCEV *, 4> Taken;
04206   while (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
04207     // Ok, we have too many of formulae on our hands to conveniently handle.
04208     // Use a rough heuristic to thin out the list.
04209     DEBUG(dbgs() << "The search space is too complex.\n");
04210 
04211     // Pick the register which is used by the most LSRUses, which is likely
04212     // to be a good reuse register candidate.
04213     const SCEV *Best = nullptr;
04214     unsigned BestNum = 0;
04215     for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
04216          I != E; ++I) {
04217       const SCEV *Reg = *I;
04218       if (Taken.count(Reg))
04219         continue;
04220       if (!Best)
04221         Best = Reg;
04222       else {
04223         unsigned Count = RegUses.getUsedByIndices(Reg).count();
04224         if (Count > BestNum) {
04225           Best = Reg;
04226           BestNum = Count;
04227         }
04228       }
04229     }
04230 
04231     DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
04232                  << " will yield profitable reuse.\n");
04233     Taken.insert(Best);
04234 
04235     // In any use with formulae which references this register, delete formulae
04236     // which don't reference it.
04237     for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
04238       LSRUse &LU = Uses[LUIdx];
04239       if (!LU.Regs.count(Best)) continue;
04240 
04241       bool Any = false;
04242       for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
04243         Formula &F = LU.Formulae[i];
04244         if (!F.referencesReg(Best)) {
04245           DEBUG(dbgs() << "  Deleting "; F.print(dbgs()); dbgs() << '\n');
04246           LU.DeleteFormula(F);
04247           --e;
04248           --i;
04249           Any = true;
04250           assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?");
04251           continue;
04252         }
04253       }
04254 
04255       if (Any)
04256         LU.RecomputeRegs(LUIdx, RegUses);
04257     }
04258 
04259     DEBUG(dbgs() << "After pre-selection:\n";
04260           print_uses(dbgs()));
04261   }
04262 }
04263 
04264 /// NarrowSearchSpaceUsingHeuristics - If there are an extraordinary number of
04265 /// formulae to choose from, use some rough heuristics to prune down the number
04266 /// of formulae. This keeps the main solver from taking an extraordinary amount
04267 /// of time in some worst-case scenarios.
04268 void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
04269   NarrowSearchSpaceByDetectingSupersets();
04270   NarrowSearchSpaceByCollapsingUnrolledCode();
04271   NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
04272   NarrowSearchSpaceByPickingWinnerRegs();
04273 }
04274 
04275 /// SolveRecurse - This is the recursive solver.
04276 void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
04277                                Cost &SolutionCost,
04278                                SmallVectorImpl<const Formula *> &Workspace,
04279                                const Cost &CurCost,
04280                                const SmallPtrSet<const SCEV *, 16> &CurRegs,
04281                                DenseSet<const SCEV *> &VisitedRegs) const {
04282   // Some ideas:
04283   //  - prune more:
04284   //    - use more aggressive filtering
04285   //    - sort the formula so that the most profitable solutions are found first
04286   //    - sort the uses too
04287   //  - search faster:
04288   //    - don't compute a cost, and then compare. compare while computing a cost
04289   //      and bail early.
04290   //    - track register sets with SmallBitVector
04291 
04292   const LSRUse &LU = Uses[Workspace.size()];
04293 
04294   // If this use references any register that's already a part of the
04295   // in-progress solution, consider it a requirement that a formula must
04296   // reference that register in order to be considered. This prunes out
04297   // unprofitable searching.
04298   SmallSetVector<const SCEV *, 4> ReqRegs;
04299   for (const SCEV *S : CurRegs)
04300     if (LU.Regs.count(S))
04301       ReqRegs.insert(S);
04302 
04303   SmallPtrSet<const SCEV *, 16> NewRegs;
04304   Cost NewCost;
04305   for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
04306        E = LU.Formulae.end(); I != E; ++I) {
04307     const Formula &F = *I;
04308 
04309     // Ignore formulae which may not be ideal in terms of register reuse of
04310     // ReqRegs.  The formula should use all required registers before
04311     // introducing new ones.
04312     int NumReqRegsToFind = std::min(F.getNumRegs(), ReqRegs.size());
04313     for (SmallSetVector<const SCEV *, 4>::const_iterator J = ReqRegs.begin(),
04314          JE = ReqRegs.end(); J != JE; ++J) {
04315       const SCEV *Reg = *J;
04316       if ((F.ScaledReg && F.ScaledReg == Reg) ||
04317           std::find(F.BaseRegs.begin(), F.BaseRegs.end(), Reg) !=
04318           F.BaseRegs.end()) {
04319         --NumReqRegsToFind;
04320         if (NumReqRegsToFind == 0)
04321           break;
04322       }
04323     }
04324     if (NumReqRegsToFind != 0) {
04325       // If none of the formulae satisfied the required registers, then we could
04326       // clear ReqRegs and try again. Currently, we simply give up in this case.
04327       continue;
04328     }
04329 
04330     // Evaluate the cost of the current formula. If it's already worse than
04331     // the current best, prune the search at that point.
04332     NewCost = CurCost;
04333     NewRegs = CurRegs;
04334     NewCost.RateFormula(TTI, F, NewRegs, VisitedRegs, L, LU.Offsets, SE, DT,
04335                         LU);
04336     if (NewCost < SolutionCost) {
04337       Workspace.push_back(&F);
04338       if (Workspace.size() != Uses.size()) {
04339         SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
04340                      NewRegs, VisitedRegs);
04341         if (F.getNumRegs() == 1 && Workspace.size() == 1)
04342           VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
04343       } else {
04344         DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
04345               dbgs() << ".\n Regs:";
04346               for (const SCEV *S : NewRegs)
04347                 dbgs() << ' ' << *S;
04348               dbgs() << '\n');
04349 
04350         SolutionCost = NewCost;
04351         Solution = Workspace;
04352       }
04353       Workspace.pop_back();
04354     }
04355   }
04356 }
04357 
04358 /// Solve - Choose one formula from each use. Return the results in the given
04359 /// Solution vector.
04360 void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
04361   SmallVector<const Formula *, 8> Workspace;
04362   Cost SolutionCost;
04363   SolutionCost.Lose();
04364   Cost CurCost;
04365   SmallPtrSet<const SCEV *, 16> CurRegs;
04366   DenseSet<const SCEV *> VisitedRegs;
04367   Workspace.reserve(Uses.size());
04368 
04369   // SolveRecurse does all the work.
04370   SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
04371                CurRegs, VisitedRegs);
04372   if (Solution.empty()) {
04373     DEBUG(dbgs() << "\nNo Satisfactory Solution\n");
04374     return;
04375   }
04376 
04377   // Ok, we've now made all our decisions.
04378   DEBUG(dbgs() << "\n"
04379                   "The chosen solution requires "; SolutionCost.print(dbgs());
04380         dbgs() << ":\n";
04381         for (size_t i = 0, e = Uses.size(); i != e; ++i) {
04382           dbgs() << "  ";
04383           Uses[i].print(dbgs());
04384           dbgs() << "\n"
04385                     "    ";
04386           Solution[i]->print(dbgs());
04387           dbgs() << '\n';
04388         });
04389 
04390   assert(Solution.size() == Uses.size() && "Malformed solution!");
04391 }
04392 
04393 /// HoistInsertPosition - Helper for AdjustInsertPositionForExpand. Climb up
04394 /// the dominator tree far as we can go while still being dominated by the
04395 /// input positions. This helps canonicalize the insert position, which
04396 /// encourages sharing.
04397 BasicBlock::iterator
04398 LSRInstance::HoistInsertPosition(BasicBlock::iterator IP,
04399                                  const SmallVectorImpl<Instruction *> &Inputs)
04400                                                                          const {
04401   for (;;) {
04402     const Loop *IPLoop = LI.getLoopFor(IP->getParent());
04403     unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0;
04404 
04405     BasicBlock *IDom;
04406     for (DomTreeNode *Rung = DT.getNode(IP->getParent()); ; ) {
04407       if (!Rung) return IP;
04408       Rung = Rung->getIDom();
04409       if (!Rung) return IP;
04410       IDom = Rung->getBlock();
04411 
04412       // Don't climb into a loop though.
04413       const Loop *IDomLoop = LI.getLoopFor(IDom);
04414       unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0;
04415       if (IDomDepth <= IPLoopDepth &&
04416           (IDomDepth != IPLoopDepth || IDomLoop == IPLoop))
04417         break;
04418     }
04419 
04420     bool AllDominate = true;
04421     Instruction *BetterPos = nullptr;
04422     Instruction *Tentative = IDom->getTerminator();
04423     for (SmallVectorImpl<Instruction *>::const_iterator I = Inputs.begin(),
04424          E = Inputs.end(); I != E; ++I) {
04425       Instruction *Inst = *I;
04426       if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
04427         AllDominate = false;
04428         break;
04429       }
04430       // Attempt to find an insert position in the middle of the block,
04431       // instead of at the end, so that it can be used for other expansions.
04432       if (IDom == Inst->getParent() &&
04433           (!BetterPos || !DT.dominates(Inst, BetterPos)))
04434         BetterPos = std::next(BasicBlock::iterator(Inst));
04435     }
04436     if (!AllDominate)
04437       break;
04438     if (BetterPos)
04439       IP = BetterPos;
04440     else
04441       IP = Tentative;
04442   }
04443 
04444   return IP;
04445 }
04446 
04447 /// AdjustInsertPositionForExpand - Determine an input position which will be
04448 /// dominated by the operands and which will dominate the result.
04449 BasicBlock::iterator
04450 LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator LowestIP,
04451                                            const LSRFixup &LF,
04452                                            const LSRUse &LU,
04453                                            SCEVExpander &Rewriter) const {
04454   // Collect some instructions which must be dominated by the
04455   // expanding replacement. These must be dominated by any operands that
04456   // will be required in the expansion.
04457   SmallVector<Instruction *, 4> Inputs;
04458   if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
04459     Inputs.push_back(I);
04460   if (LU.Kind == LSRUse::ICmpZero)
04461     if (Instruction *I =
04462           dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
04463       Inputs.push_back(I);
04464   if (LF.PostIncLoops.count(L)) {
04465     if (LF.isUseFullyOutsideLoop(L))
04466       Inputs.push_back(L->getLoopLatch()->getTerminator());
04467     else
04468       Inputs.push_back(IVIncInsertPos);
04469   }
04470   // The expansion must also be dominated by the increment positions of any
04471   // loops it for which it is using post-inc mode.
04472   for (PostIncLoopSet::const_iterator I = LF.PostIncLoops.begin(),
04473        E = LF.PostIncLoops.end(); I != E; ++I) {
04474     const Loop *PIL = *I;
04475     if (PIL == L) continue;
04476 
04477     // Be dominated by the loop exit.
04478     SmallVector<BasicBlock *, 4> ExitingBlocks;
04479     PIL->getExitingBlocks(ExitingBlocks);
04480     if (!ExitingBlocks.empty()) {
04481       BasicBlock *BB = ExitingBlocks[0];
04482       for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i)
04483         BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]);
04484       Inputs.push_back(BB->getTerminator());
04485     }
04486   }
04487 
04488   assert(!isa<PHINode>(LowestIP) && !isa<LandingPadInst>(LowestIP)
04489          && !isa<DbgInfoIntrinsic>(LowestIP) &&
04490          "Insertion point must be a normal instruction");
04491 
04492   // Then, climb up the immediate dominator tree as far as we can go while
04493   // still being dominated by the input positions.
04494   BasicBlock::iterator IP = HoistInsertPosition(LowestIP, Inputs);
04495 
04496   // Don't insert instructions before PHI nodes.
04497   while (isa<PHINode>(IP)) ++IP;
04498 
04499   // Ignore landingpad instructions.
04500   while (isa<LandingPadInst>(IP)) ++IP;
04501 
04502   // Ignore debug intrinsics.
04503   while (isa<DbgInfoIntrinsic>(IP)) ++IP;
04504 
04505   // Set IP below instructions recently inserted by SCEVExpander. This keeps the
04506   // IP consistent across expansions and allows the previously inserted
04507   // instructions to be reused by subsequent expansion.
04508   while (Rewriter.isInsertedInstruction(IP) && IP != LowestIP) ++IP;
04509 
04510   return IP;
04511 }
04512 
04513 /// Expand - Emit instructions for the leading candidate expression for this
04514 /// LSRUse (this is called "expanding").
04515 Value *LSRInstance::Expand(const LSRFixup &LF,
04516                            const Formula &F,
04517                            BasicBlock::iterator IP,
04518                            SCEVExpander &Rewriter,
04519                            SmallVectorImpl<WeakVH> &DeadInsts) const {
04520   const LSRUse &LU = Uses[LF.LUIdx];
04521   if (LU.RigidFormula)
04522     return LF.OperandValToReplace;
04523 
04524   // Determine an input position which will be dominated by the operands and
04525   // which will dominate the result.
04526   IP = AdjustInsertPositionForExpand(IP, LF, LU, Rewriter);
04527 
04528   // Inform the Rewriter if we have a post-increment use, so that it can
04529   // perform an advantageous expansion.
04530   Rewriter.setPostInc(LF.PostIncLoops);
04531 
04532   // This is the type that the user actually needs.
04533   Type *OpTy = LF.OperandValToReplace->getType();
04534   // This will be the type that we'll initially expand to.
04535   Type *Ty = F.getType();
04536   if (!Ty)
04537     // No type known; just expand directly to the ultimate type.
04538     Ty = OpTy;
04539   else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
04540     // Expand directly to the ultimate type if it's the right size.
04541     Ty = OpTy;
04542   // This is the type to do integer arithmetic in.
04543   Type *IntTy = SE.getEffectiveSCEVType(Ty);
04544 
04545   // Build up a list of operands to add together to form the full base.
04546   SmallVector<const SCEV *, 8> Ops;
04547 
04548   // Expand the BaseRegs portion.
04549   for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
04550        E = F.BaseRegs.end(); I != E; ++I) {
04551     const SCEV *Reg = *I;
04552     assert(!Reg->isZero() && "Zero allocated in a base register!");
04553 
04554     // If we're expanding for a post-inc user, make the post-inc adjustment.
04555     PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
04556     Reg = TransformForPostIncUse(Denormalize, Reg,
04557                                  LF.UserInst, LF.OperandValToReplace,
04558                                  Loops, SE, DT);
04559 
04560     Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, nullptr, IP)));
04561   }
04562 
04563   // Expand the ScaledReg portion.
04564   Value *ICmpScaledV = nullptr;
04565   if (F.Scale != 0) {
04566     const SCEV *ScaledS = F.ScaledReg;
04567 
04568     // If we're expanding for a post-inc user, make the post-inc adjustment.
04569     PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
04570     ScaledS = TransformForPostIncUse(Denormalize, ScaledS,
04571                                      LF.UserInst, LF.OperandValToReplace,
04572                                      Loops, SE, DT);
04573 
04574     if (LU.Kind == LSRUse::ICmpZero) {
04575       // Expand ScaleReg as if it was part of the base regs.
04576       if (F.Scale == 1)
04577         Ops.push_back(
04578             SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr, IP)));
04579       else {
04580         // An interesting way of "folding" with an icmp is to use a negated
04581         // scale, which we'll implement by inserting it into the other operand
04582         // of the icmp.
04583         assert(F.Scale == -1 &&
04584                "The only scale supported by ICmpZero uses is -1!");
04585         ICmpScaledV = Rewriter.expandCodeFor(ScaledS, nullptr, IP);
04586       }
04587     } else {
04588       // Otherwise just expand the scaled register and an explicit scale,
04589       // which is expected to be matched as part of the address.
04590 
04591       // Flush the operand list to suppress SCEVExpander hoisting address modes.
04592       // Unless the addressing mode will not be folded.
04593       if (!Ops.empty() && LU.Kind == LSRUse::Address &&
04594           isAMCompletelyFolded(TTI, LU, F)) {
04595         Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
04596         Ops.clear();
04597         Ops.push_back(SE.getUnknown(FullV));
04598       }
04599       ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr, IP));
04600       if (F.Scale != 1)
04601         ScaledS =
04602             SE.getMulExpr(ScaledS, SE.getConstant(ScaledS->getType(), F.Scale));
04603       Ops.push_back(ScaledS);
04604     }
04605   }
04606 
04607   // Expand the GV portion.
04608   if (F.BaseGV) {
04609     // Flush the operand list to suppress SCEVExpander hoisting.
04610     if (!Ops.empty()) {
04611       Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
04612       Ops.clear();
04613       Ops.push_back(SE.getUnknown(FullV));
04614     }
04615     Ops.push_back(SE.getUnknown(F.BaseGV));
04616   }
04617 
04618   // Flush the operand list to suppress SCEVExpander hoisting of both folded and
04619   // unfolded offsets. LSR assumes they both live next to their uses.
04620   if (!Ops.empty()) {
04621     Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
04622     Ops.clear();
04623     Ops.push_back(SE.getUnknown(FullV));
04624   }
04625 
04626   // Expand the immediate portion.
04627   int64_t Offset = (uint64_t)F.BaseOffset + LF.Offset;
04628   if (Offset != 0) {
04629     if (LU.Kind == LSRUse::ICmpZero) {
04630       // The other interesting way of "folding" with an ICmpZero is to use a
04631       // negated immediate.
04632       if (!ICmpScaledV)
04633         ICmpScaledV = ConstantInt::get(IntTy, -(uint64_t)Offset);
04634       else {
04635         Ops.push_back(SE.getUnknown(ICmpScaledV));
04636         ICmpScaledV = ConstantInt::get(IntTy, Offset);
04637       }
04638     } else {
04639       // Just add the immediate values. These again are expected to be matched
04640       // as part of the address.
04641       Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset)));
04642     }
04643   }
04644 
04645   // Expand the unfolded offset portion.
04646   int64_t UnfoldedOffset = F.UnfoldedOffset;
04647   if (UnfoldedOffset != 0) {
04648     // Just add the immediate values.
04649     Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy,
04650                                                        UnfoldedOffset)));
04651   }
04652 
04653   // Emit instructions summing all the operands.
04654   const SCEV *FullS = Ops.empty() ?
04655                       SE.getConstant(IntTy, 0) :
04656                       SE.getAddExpr(Ops);
04657   Value *FullV = Rewriter.expandCodeFor(FullS, Ty, IP);
04658 
04659   // We're done expanding now, so reset the rewriter.
04660   Rewriter.clearPostInc();
04661 
04662   // An ICmpZero Formula represents an ICmp which we're handling as a
04663   // comparison against zero. Now that we've expanded an expression for that
04664   // form, update the ICmp's other operand.
04665   if (LU.Kind == LSRUse::ICmpZero) {
04666     ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
04667     DeadInsts.push_back(CI->getOperand(1));
04668     assert(!F.BaseGV && "ICmp does not support folding a global value and "
04669                            "a scale at the same time!");
04670     if (F.Scale == -1) {
04671       if (ICmpScaledV->getType() != OpTy) {
04672         Instruction *Cast =
04673           CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
04674                                                    OpTy, false),
04675                            ICmpScaledV, OpTy, "tmp", CI);
04676         ICmpScaledV = Cast;
04677       }
04678       CI->setOperand(1, ICmpScaledV);
04679     } else {
04680       // A scale of 1 means that the scale has been expanded as part of the
04681       // base regs.
04682       assert((F.Scale == 0 || F.Scale == 1) &&
04683              "ICmp does not support folding a global value and "
04684              "a scale at the same time!");
04685       Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),
04686                                            -(uint64_t)Offset);
04687       if (C->getType() != OpTy)
04688         C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
04689                                                           OpTy, false),
04690                                   C, OpTy);
04691 
04692       CI->setOperand(1, C);
04693     }
04694   }
04695 
04696   return FullV;
04697 }
04698 
04699 /// RewriteForPHI - Helper for Rewrite. PHI nodes are special because the use
04700 /// of their operands effectively happens in their predecessor blocks, so the
04701 /// expression may need to be expanded in multiple places.
04702 void LSRInstance::RewriteForPHI(PHINode *PN,
04703                                 const LSRFixup &LF,
04704                                 const Formula &F,
04705                                 SCEVExpander &Rewriter,
04706                                 SmallVectorImpl<WeakVH> &DeadInsts,
04707                                 Pass *P) const {
04708   DenseMap<BasicBlock *, Value *> Inserted;
04709   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
04710     if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
04711       BasicBlock *BB = PN->getIncomingBlock(i);
04712 
04713       // If this is a critical edge, split the edge so that we do not insert
04714       // the code on all predecessor/successor paths.  We do this unless this
04715       // is the canonical backedge for this loop, which complicates post-inc
04716       // users.
04717       if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
04718           !isa<IndirectBrInst>(BB->getTerminator())) {
04719         BasicBlock *Parent = PN->getParent();
04720         Loop *PNLoop = LI.getLoopFor(Parent);
04721         if (!PNLoop || Parent != PNLoop->getHeader()) {
04722           // Split the critical edge.
04723           BasicBlock *NewBB = nullptr;
04724           if (!Parent->isLandingPad()) {
04725             NewBB = SplitCriticalEdge(BB, Parent,
04726                                       CriticalEdgeSplittingOptions(&DT, &LI)
04727                                           .setMergeIdenticalEdges()
04728                                           .setDontDeleteUselessPHIs());
04729           } else {
04730             SmallVector<BasicBlock*, 2> NewBBs;
04731             SplitLandingPadPredecessors(Parent, BB, "", "", NewBBs,
04732                                         /*AliasAnalysis*/ nullptr, &DT, &LI);
04733             NewBB = NewBBs[0];
04734           }
04735           // If NewBB==NULL, then SplitCriticalEdge refused to split because all
04736           // phi predecessors are identical. The simple thing to do is skip
04737           // splitting in this case rather than complicate the API.
04738           if (NewBB) {
04739             // If PN is outside of the loop and BB is in the loop, we want to
04740             // move the block to be immediately before the PHI block, not
04741             // immediately after BB.
04742             if (L->contains(BB) && !L->contains(PN))
04743               NewBB->moveBefore(PN->getParent());
04744 
04745             // Splitting the edge can reduce the number of PHI entries we have.
04746             e = PN->getNumIncomingValues();
04747             BB = NewBB;
04748             i = PN->getBasicBlockIndex(BB);
04749           }
04750         }
04751       }
04752 
04753       std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
04754         Inserted.insert(std::make_pair(BB, static_cast<Value *>(nullptr)));
04755       if (!Pair.second)
04756         PN->setIncomingValue(i, Pair.first->second);
04757       else {
04758         Value *FullV = Expand(LF, F, BB->getTerminator(), Rewriter, DeadInsts);
04759 
04760         // If this is reuse-by-noop-cast, insert the noop cast.
04761         Type *OpTy = LF.OperandValToReplace->getType();
04762         if (FullV->getType() != OpTy)
04763           FullV =
04764             CastInst::Create(CastInst::getCastOpcode(FullV, false,
04765                                                      OpTy, false),
04766                              FullV, LF.OperandValToReplace->getType(),
04767                              "tmp", BB->getTerminator());
04768 
04769         PN->setIncomingValue(i, FullV);
04770         Pair.first->second = FullV;
04771       }
04772     }
04773 }
04774 
04775 /// Rewrite - Emit instructions for the leading candidate expression for this
04776 /// LSRUse (this is called "expanding"), and update the UserInst to reference
04777 /// the newly expanded value.
04778 void LSRInstance::Rewrite(const LSRFixup &LF,
04779                           const Formula &F,
04780                           SCEVExpander &Rewriter,
04781                           SmallVectorImpl<WeakVH> &DeadInsts,
04782                           Pass *P) const {
04783   // First, find an insertion point that dominates UserInst. For PHI nodes,
04784   // find the nearest block which dominates all the relevant uses.
04785   if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
04786     RewriteForPHI(PN, LF, F, Rewriter, DeadInsts, P);
04787   } else {
04788     Value *FullV = Expand(LF, F, LF.UserInst, Rewriter, DeadInsts);
04789 
04790     // If this is reuse-by-noop-cast, insert the noop cast.
04791     Type *OpTy = LF.OperandValToReplace->getType();
04792     if (FullV->getType() != OpTy) {
04793       Instruction *Cast =
04794         CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
04795                          FullV, OpTy, "tmp", LF.UserInst);
04796       FullV = Cast;
04797     }
04798 
04799     // Update the user. ICmpZero is handled specially here (for now) because
04800     // Expand may have updated one of the operands of the icmp already, and
04801     // its new value may happen to be equal to LF.OperandValToReplace, in
04802     // which case doing replaceUsesOfWith leads to replacing both operands
04803     // with the same value. TODO: Reorganize this.
04804     if (Uses[LF.LUIdx].Kind == LSRUse::ICmpZero)
04805       LF.UserInst->setOperand(0, FullV);
04806     else
04807       LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
04808   }
04809 
04810   DeadInsts.push_back(LF.OperandValToReplace);
04811 }
04812 
04813 /// ImplementSolution - Rewrite all the fixup locations with new values,
04814 /// following the chosen solution.
04815 void
04816 LSRInstance::ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
04817                                Pass *P) {
04818   // Keep track of instructions we may have made dead, so that
04819   // we can remove them after we are done working.
04820   SmallVector<WeakVH, 16> DeadInsts;
04821 
04822   SCEVExpander Rewriter(SE, L->getHeader()->getModule()->getDataLayout(),
04823                         "lsr");
04824 #ifndef NDEBUG
04825   Rewriter.setDebugType(DEBUG_TYPE);
04826 #endif
04827   Rewriter.disableCanonicalMode();
04828   Rewriter.enableLSRMode();
04829   Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
04830 
04831   // Mark phi nodes that terminate chains so the expander tries to reuse them.
04832   for (SmallVectorImpl<IVChain>::const_iterator ChainI = IVChainVec.begin(),
04833          ChainE = IVChainVec.end(); ChainI != ChainE; ++ChainI) {
04834     if (PHINode *PN = dyn_cast<PHINode>(ChainI->tailUserInst()))
04835       Rewriter.setChainedPhi(PN);
04836   }
04837 
04838   // Expand the new value definitions and update the users.
04839   for (SmallVectorImpl<LSRFixup>::const_iterator I = Fixups.begin(),
04840        E = Fixups.end(); I != E; ++I) {
04841     const LSRFixup &Fixup = *I;
04842 
04843     Rewrite(Fixup, *Solution[Fixup.LUIdx], Rewriter, DeadInsts, P);
04844 
04845     Changed = true;
04846   }
04847 
04848   for (SmallVectorImpl<IVChain>::const_iterator ChainI = IVChainVec.begin(),
04849          ChainE = IVChainVec.end(); ChainI != ChainE; ++ChainI) {
04850     GenerateIVChain(*ChainI, Rewriter, DeadInsts);
04851     Changed = true;
04852   }
04853   // Clean up after ourselves. This must be done before deleting any
04854   // instructions.
04855   Rewriter.clear();
04856 
04857   Changed |= DeleteTriviallyDeadInstructions(DeadInsts);
04858 }
04859 
04860 LSRInstance::LSRInstance(Loop *L, Pass *P)
04861     : IU(P->getAnalysis<IVUsers>()), SE(P->getAnalysis<ScalarEvolution>()),
04862       DT(P->getAnalysis<DominatorTreeWrapperPass>().getDomTree()),
04863       LI(P->getAnalysis<LoopInfoWrapperPass>().getLoopInfo()),
04864       TTI(P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
04865           *L->getHeader()->getParent())),
04866       L(L), Changed(false), IVIncInsertPos(nullptr) {
04867   // If LoopSimplify form is not available, stay out of trouble.
04868   if (!L->isLoopSimplifyForm())
04869     return;
04870 
04871   // If there's no interesting work to be done, bail early.
04872   if (IU.empty()) return;
04873 
04874   // If there's too much analysis to be done, bail early. We won't be able to
04875   // model the problem anyway.
04876   unsigned NumUsers = 0;
04877   for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
04878     if (++NumUsers > MaxIVUsers) {
04879       DEBUG(dbgs() << "LSR skipping loop, too many IV Users in " << *L
04880             << "\n");
04881       return;
04882     }
04883   }
04884 
04885 #ifndef NDEBUG
04886   // All dominating loops must have preheaders, or SCEVExpander may not be able
04887   // to materialize an AddRecExpr whose Start is an outer AddRecExpr.
04888   //
04889   // IVUsers analysis should only create users that are dominated by simple loop
04890   // headers. Since this loop should dominate all of its users, its user list
04891   // should be empty if this loop itself is not within a simple loop nest.
04892   for (DomTreeNode *Rung = DT.getNode(L->getLoopPreheader());
04893        Rung; Rung = Rung->getIDom()) {
04894     BasicBlock *BB = Rung->getBlock();
04895     const Loop *DomLoop = LI.getLoopFor(BB);
04896     if (DomLoop && DomLoop->getHeader() == BB) {
04897       assert(DomLoop->getLoopPreheader() && "LSR needs a simplified loop nest");
04898     }
04899   }
04900 #endif // DEBUG
04901 
04902   DEBUG(dbgs() << "\nLSR on loop ";
04903         L->getHeader()->printAsOperand(dbgs(), /*PrintType=*/false);
04904         dbgs() << ":\n");
04905 
04906   // First, perform some low-level loop optimizations.
04907   OptimizeShadowIV();
04908   OptimizeLoopTermCond();
04909 
04910   // If loop preparation eliminates all interesting IV users, bail.
04911   if (IU.empty()) return;
04912 
04913   // Skip nested loops until we can model them better with formulae.
04914   if (!L->empty()) {
04915     DEBUG(dbgs() << "LSR skipping outer loop " << *L << "\n");
04916     return;
04917   }
04918 
04919   // Start collecting data and preparing for the solver.
04920   CollectChains();
04921   CollectInterestingTypesAndFactors();
04922   CollectFixupsAndInitialFormulae();
04923   CollectLoopInvariantFixupsAndFormulae();
04924 
04925   assert(!Uses.empty() && "IVUsers reported at least one use");
04926   DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
04927         print_uses(dbgs()));
04928 
04929   // Now use the reuse data to generate a bunch of interesting ways
04930   // to formulate the values needed for the uses.
04931   GenerateAllReuseFormulae();
04932 
04933   FilterOutUndesirableDedicatedRegisters();
04934   NarrowSearchSpaceUsingHeuristics();
04935 
04936   SmallVector<const Formula *, 8> Solution;
04937   Solve(Solution);
04938 
04939   // Release memory that is no longer needed.
04940   Factors.clear();
04941   Types.clear();
04942   RegUses.clear();
04943 
04944   if (Solution.empty())
04945     return;
04946 
04947 #ifndef NDEBUG
04948   // Formulae should be legal.
04949   for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(), E = Uses.end();
04950        I != E; ++I) {
04951     const LSRUse &LU = *I;
04952     for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
04953                                                   JE = LU.Formulae.end();
04954          J != JE; ++J)
04955       assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
04956                         *J) && "Illegal formula generated!");
04957   };
04958 #endif
04959 
04960   // Now that we've decided what we want, make it so.
04961   ImplementSolution(Solution, P);
04962 }
04963 
04964 void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
04965   if (Factors.empty() && Types.empty()) return;
04966 
04967   OS << "LSR has identified the following interesting factors and types: ";
04968   bool First = true;
04969 
04970   for (SmallSetVector<int64_t, 8>::const_iterator
04971        I = Factors.begin(), E = Factors.end(); I != E; ++I) {
04972     if (!First) OS << ", ";
04973     First = false;
04974     OS << '*' << *I;
04975   }
04976 
04977   for (SmallSetVector<Type *, 4>::const_iterator
04978        I = Types.begin(), E = Types.end(); I != E; ++I) {
04979     if (!First) OS << ", ";
04980     First = false;
04981     OS << '(' << **I << ')';
04982   }
04983   OS << '\n';
04984 }
04985 
04986 void LSRInstance::print_fixups(raw_ostream &OS) const {
04987   OS << "LSR is examining the following fixup sites:\n";
04988   for (SmallVectorImpl<LSRFixup>::const_iterator I = Fixups.begin(),
04989        E = Fixups.end(); I != E; ++I) {
04990     dbgs() << "  ";
04991     I->print(OS);
04992     OS << '\n';
04993   }
04994 }
04995 
04996 void LSRInstance::print_uses(raw_ostream &OS) const {
04997   OS << "LSR is examining the following uses:\n";
04998   for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
04999        E = Uses.end(); I != E; ++I) {
05000     const LSRUse &LU = *I;
05001     dbgs() << "  ";
05002     LU.print(OS);
05003     OS << '\n';
05004     for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
05005          JE = LU.Formulae.end(); J != JE; ++J) {
05006       OS << "    ";
05007       J->print(OS);
05008       OS << '\n';
05009     }
05010   }
05011 }
05012 
05013 void LSRInstance::print(raw_ostream &OS) const {
05014   print_factors_and_types(OS);
05015   print_fixups(OS);
05016   print_uses(OS);
05017 }
05018 
05019 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
05020 void LSRInstance::dump() const {
05021   print(errs()); errs() << '\n';
05022 }
05023 #endif
05024 
05025 namespace {
05026 
05027 class LoopStrengthReduce : public LoopPass {
05028 public:
05029   static char ID; // Pass ID, replacement for typeid
05030   LoopStrengthReduce();
05031 
05032 private:
05033   bool runOnLoop(Loop *L, LPPassManager &LPM) override;
05034   void getAnalysisUsage(AnalysisUsage &AU) const override;
05035 };
05036 
05037 }
05038 
05039 char LoopStrengthReduce::ID = 0;
05040 INITIALIZE_PASS_BEGIN(LoopStrengthReduce, "loop-reduce",
05041                 "Loop Strength Reduction", false, false)
05042 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
05043 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
05044 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
05045 INITIALIZE_PASS_DEPENDENCY(IVUsers)
05046 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
05047 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
05048 INITIALIZE_PASS_END(LoopStrengthReduce, "loop-reduce",
05049                 "Loop Strength Reduction", false, false)
05050 
05051 
05052 Pass *llvm::createLoopStrengthReducePass() {
05053   return new LoopStrengthReduce();
05054 }
05055 
05056 LoopStrengthReduce::LoopStrengthReduce() : LoopPass(ID) {
05057   initializeLoopStrengthReducePass(*PassRegistry::getPassRegistry());
05058 }
05059 
05060 void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
05061   // We split critical edges, so we change the CFG.  However, we do update
05062   // many analyses if they are around.
05063   AU.addPreservedID(LoopSimplifyID);
05064 
05065   AU.addRequired<LoopInfoWrapperPass>();
05066   AU.addPreserved<LoopInfoWrapperPass>();
05067   AU.addRequiredID(LoopSimplifyID);
05068   AU.addRequired<DominatorTreeWrapperPass>();
05069   AU.addPreserved<DominatorTreeWrapperPass>();
05070   AU.addRequired<ScalarEvolution>();
05071   AU.addPreserved<ScalarEvolution>();
05072   // Requiring LoopSimplify a second time here prevents IVUsers from running
05073   // twice, since LoopSimplify was invalidated by running ScalarEvolution.
05074   AU.addRequiredID(LoopSimplifyID);
05075   AU.addRequired<IVUsers>();
05076   AU.addPreserved<IVUsers>();
05077   AU.addRequired<TargetTransformInfoWrapperPass>();
05078 }
05079 
05080 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
05081   if (skipOptnoneFunction(L))
05082     return false;
05083 
05084   bool Changed = false;
05085 
05086   // Run the main LSR transformation.
05087   Changed |= LSRInstance(L, this).getChanged();
05088 
05089   // Remove any extra phis created by processing inner loops.
05090   Changed |= DeleteDeadPHIs(L->getHeader());
05091   if (EnablePhiElim && L->isLoopSimplifyForm()) {
05092     SmallVector<WeakVH, 16> DeadInsts;
05093     const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
05094     SCEVExpander Rewriter(getAnalysis<ScalarEvolution>(), DL, "lsr");
05095 #ifndef NDEBUG
05096     Rewriter.setDebugType(DEBUG_TYPE);
05097 #endif
05098     unsigned numFolded = Rewriter.replaceCongruentIVs(
05099         L, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(), DeadInsts,
05100         &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
05101             *L->getHeader()->getParent()));
05102     if (numFolded) {
05103       Changed = true;
05104       DeleteTriviallyDeadInstructions(DeadInsts);
05105       DeleteDeadPHIs(L->getHeader());
05106     }
05107   }
05108   return Changed;
05109 }