LLVM API Documentation

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