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