1 //===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This transformation analyzes and transforms the induction variables (and
10 // computations derived from them) into forms suitable for efficient execution
11 // on the target.
12 //
13 // This pass performs a strength reduction on array references inside loops that
14 // have as one or more of their components the loop induction variable, it
15 // rewrites expressions to take advantage of scaled-index addressing modes
16 // available on the target, and it performs a variety of other optimizations
17 // related to loop induction variables.
18 //
19 // Terminology note: this code has a lot of handling for "post-increment" or
20 // "post-inc" users. This is not talking about post-increment addressing modes;
21 // it is instead talking about code like this:
22 //
23 //   %i = phi [ 0, %entry ], [ %i.next, %latch ]
24 //   ...
25 //   %i.next = add %i, 1
26 //   %c = icmp eq %i.next, %n
27 //
28 // The SCEV for %i is {0,+,1}<%L>. The SCEV for %i.next is {1,+,1}<%L>, however
29 // it's useful to think about these as the same register, with some uses using
30 // the value of the register before the add and some using it after. In this
31 // example, the icmp is a post-increment user, since it uses %i.next, which is
32 // the value of the induction variable after the increment. The other common
33 // case of post-increment users is users outside the loop.
34 //
35 // TODO: More sophistication in the way Formulae are generated and filtered.
36 //
37 // TODO: Handle multiple loops at a time.
38 //
39 // TODO: Should the addressing mode BaseGV be changed to a ConstantExpr instead
40 //       of a GlobalValue?
41 //
42 // TODO: When truncation is free, truncate ICmp users' operands to make it a
43 //       smaller encoding (on x86 at least).
44 //
45 // TODO: When a negated register is used by an add (such as in a list of
46 //       multiple base registers, or as the increment expression in an addrec),
47 //       we may not actually need both reg and (-1 * reg) in registers; the
48 //       negation can be implemented by using a sub instead of an add. The
49 //       lack of support for taking this into consideration when making
50 //       register pressure decisions is partly worked around by the "Special"
51 //       use kind.
52 //
53 //===----------------------------------------------------------------------===//
54 
55 #include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
56 #include "llvm/ADT/APInt.h"
57 #include "llvm/ADT/DenseMap.h"
58 #include "llvm/ADT/DenseSet.h"
59 #include "llvm/ADT/Hashing.h"
60 #include "llvm/ADT/PointerIntPair.h"
61 #include "llvm/ADT/STLExtras.h"
62 #include "llvm/ADT/SetVector.h"
63 #include "llvm/ADT/SmallBitVector.h"
64 #include "llvm/ADT/SmallPtrSet.h"
65 #include "llvm/ADT/SmallSet.h"
66 #include "llvm/ADT/SmallVector.h"
67 #include "llvm/ADT/iterator_range.h"
68 #include "llvm/Analysis/AssumptionCache.h"
69 #include "llvm/Analysis/IVUsers.h"
70 #include "llvm/Analysis/LoopAnalysisManager.h"
71 #include "llvm/Analysis/LoopInfo.h"
72 #include "llvm/Analysis/LoopPass.h"
73 #include "llvm/Analysis/MemorySSA.h"
74 #include "llvm/Analysis/MemorySSAUpdater.h"
75 #include "llvm/Analysis/ScalarEvolution.h"
76 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
77 #include "llvm/Analysis/ScalarEvolutionNormalization.h"
78 #include "llvm/Analysis/TargetLibraryInfo.h"
79 #include "llvm/Analysis/TargetTransformInfo.h"
80 #include "llvm/Config/llvm-config.h"
81 #include "llvm/IR/BasicBlock.h"
82 #include "llvm/IR/Constant.h"
83 #include "llvm/IR/Constants.h"
84 #include "llvm/IR/DerivedTypes.h"
85 #include "llvm/IR/Dominators.h"
86 #include "llvm/IR/GlobalValue.h"
87 #include "llvm/IR/IRBuilder.h"
88 #include "llvm/IR/InstrTypes.h"
89 #include "llvm/IR/Instruction.h"
90 #include "llvm/IR/Instructions.h"
91 #include "llvm/IR/IntrinsicInst.h"
92 #include "llvm/IR/Intrinsics.h"
93 #include "llvm/IR/Module.h"
94 #include "llvm/IR/OperandTraits.h"
95 #include "llvm/IR/Operator.h"
96 #include "llvm/IR/PassManager.h"
97 #include "llvm/IR/Type.h"
98 #include "llvm/IR/Use.h"
99 #include "llvm/IR/User.h"
100 #include "llvm/IR/Value.h"
101 #include "llvm/IR/ValueHandle.h"
102 #include "llvm/InitializePasses.h"
103 #include "llvm/Pass.h"
104 #include "llvm/Support/Casting.h"
105 #include "llvm/Support/CommandLine.h"
106 #include "llvm/Support/Compiler.h"
107 #include "llvm/Support/Debug.h"
108 #include "llvm/Support/ErrorHandling.h"
109 #include "llvm/Support/MathExtras.h"
110 #include "llvm/Support/raw_ostream.h"
111 #include "llvm/Transforms/Scalar.h"
112 #include "llvm/Transforms/Utils.h"
113 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
114 #include "llvm/Transforms/Utils/Local.h"
115 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
116 #include <algorithm>
117 #include <cassert>
118 #include <cstddef>
119 #include <cstdint>
120 #include <cstdlib>
121 #include <iterator>
122 #include <limits>
123 #include <map>
124 #include <numeric>
125 #include <utility>
126 
127 using namespace llvm;
128 
129 #define DEBUG_TYPE "loop-reduce"
130 
131 /// MaxIVUsers is an arbitrary threshold that provides an early opportunity for
132 /// bail out. This threshold is far beyond the number of users that LSR can
133 /// conceivably solve, so it should not affect generated code, but catches the
134 /// worst cases before LSR burns too much compile time and stack space.
135 static const unsigned MaxIVUsers = 200;
136 
137 // Temporary flag to cleanup congruent phis after LSR phi expansion.
138 // It's currently disabled until we can determine whether it's truly useful or
139 // not. The flag should be removed after the v3.0 release.
140 // This is now needed for ivchains.
141 static cl::opt<bool> EnablePhiElim(
142   "enable-lsr-phielim", cl::Hidden, cl::init(true),
143   cl::desc("Enable LSR phi elimination"));
144 
145 // The flag adds instruction count to solutions cost comparision.
146 static cl::opt<bool> InsnsCost(
147   "lsr-insns-cost", cl::Hidden, cl::init(true),
148   cl::desc("Add instruction count to a LSR cost model"));
149 
150 // Flag to choose how to narrow complex lsr solution
151 static cl::opt<bool> LSRExpNarrow(
152   "lsr-exp-narrow", cl::Hidden, cl::init(false),
153   cl::desc("Narrow LSR complex solution using"
154            " expectation of registers number"));
155 
156 // Flag to narrow search space by filtering non-optimal formulae with
157 // the same ScaledReg and Scale.
158 static cl::opt<bool> FilterSameScaledReg(
159     "lsr-filter-same-scaled-reg", cl::Hidden, cl::init(true),
160     cl::desc("Narrow LSR search space by filtering non-optimal formulae"
161              " with the same ScaledReg and Scale"));
162 
163 static cl::opt<bool> EnableBackedgeIndexing(
164   "lsr-backedge-indexing", cl::Hidden, cl::init(true),
165   cl::desc("Enable the generation of cross iteration indexed memops"));
166 
167 static cl::opt<unsigned> ComplexityLimit(
168   "lsr-complexity-limit", cl::Hidden,
169   cl::init(std::numeric_limits<uint16_t>::max()),
170   cl::desc("LSR search space complexity limit"));
171 
172 static cl::opt<unsigned> SetupCostDepthLimit(
173     "lsr-setupcost-depth-limit", cl::Hidden, cl::init(7),
174     cl::desc("The limit on recursion depth for LSRs setup cost"));
175 
176 #ifndef NDEBUG
177 // Stress test IV chain generation.
178 static cl::opt<bool> StressIVChain(
179   "stress-ivchain", cl::Hidden, cl::init(false),
180   cl::desc("Stress test LSR IV chains"));
181 #else
182 static bool StressIVChain = false;
183 #endif
184 
185 namespace {
186 
187 struct MemAccessTy {
188   /// Used in situations where the accessed memory type is unknown.
189   static const unsigned UnknownAddressSpace =
190       std::numeric_limits<unsigned>::max();
191 
192   Type *MemTy = nullptr;
193   unsigned AddrSpace = UnknownAddressSpace;
194 
195   MemAccessTy() = default;
196   MemAccessTy(Type *Ty, unsigned AS) : MemTy(Ty), AddrSpace(AS) {}
197 
198   bool operator==(MemAccessTy Other) const {
199     return MemTy == Other.MemTy && AddrSpace == Other.AddrSpace;
200   }
201 
202   bool operator!=(MemAccessTy Other) const { return !(*this == Other); }
203 
204   static MemAccessTy getUnknown(LLVMContext &Ctx,
205                                 unsigned AS = UnknownAddressSpace) {
206     return MemAccessTy(Type::getVoidTy(Ctx), AS);
207   }
208 
209   Type *getType() { return MemTy; }
210 };
211 
212 /// This class holds data which is used to order reuse candidates.
213 class RegSortData {
214 public:
215   /// This represents the set of LSRUse indices which reference
216   /// a particular register.
217   SmallBitVector UsedByIndices;
218 
219   void print(raw_ostream &OS) const;
220   void dump() const;
221 };
222 
223 } // end anonymous namespace
224 
225 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
226 void RegSortData::print(raw_ostream &OS) const {
227   OS << "[NumUses=" << UsedByIndices.count() << ']';
228 }
229 
230 LLVM_DUMP_METHOD void RegSortData::dump() const {
231   print(errs()); errs() << '\n';
232 }
233 #endif
234 
235 namespace {
236 
237 /// Map register candidates to information about how they are used.
238 class RegUseTracker {
239   using RegUsesTy = DenseMap<const SCEV *, RegSortData>;
240 
241   RegUsesTy RegUsesMap;
242   SmallVector<const SCEV *, 16> RegSequence;
243 
244 public:
245   void countRegister(const SCEV *Reg, size_t LUIdx);
246   void dropRegister(const SCEV *Reg, size_t LUIdx);
247   void swapAndDropUse(size_t LUIdx, size_t LastLUIdx);
248 
249   bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const;
250 
251   const SmallBitVector &getUsedByIndices(const SCEV *Reg) const;
252 
253   void clear();
254 
255   using iterator = SmallVectorImpl<const SCEV *>::iterator;
256   using const_iterator = SmallVectorImpl<const SCEV *>::const_iterator;
257 
258   iterator begin() { return RegSequence.begin(); }
259   iterator end()   { return RegSequence.end(); }
260   const_iterator begin() const { return RegSequence.begin(); }
261   const_iterator end() const   { return RegSequence.end(); }
262 };
263 
264 } // end anonymous namespace
265 
266 void
267 RegUseTracker::countRegister(const SCEV *Reg, size_t LUIdx) {
268   std::pair<RegUsesTy::iterator, bool> Pair =
269     RegUsesMap.insert(std::make_pair(Reg, RegSortData()));
270   RegSortData &RSD = Pair.first->second;
271   if (Pair.second)
272     RegSequence.push_back(Reg);
273   RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1));
274   RSD.UsedByIndices.set(LUIdx);
275 }
276 
277 void
278 RegUseTracker::dropRegister(const SCEV *Reg, size_t LUIdx) {
279   RegUsesTy::iterator It = RegUsesMap.find(Reg);
280   assert(It != RegUsesMap.end());
281   RegSortData &RSD = It->second;
282   assert(RSD.UsedByIndices.size() > LUIdx);
283   RSD.UsedByIndices.reset(LUIdx);
284 }
285 
286 void
287 RegUseTracker::swapAndDropUse(size_t LUIdx, size_t LastLUIdx) {
288   assert(LUIdx <= LastLUIdx);
289 
290   // Update RegUses. The data structure is not optimized for this purpose;
291   // we must iterate through it and update each of the bit vectors.
292   for (auto &Pair : RegUsesMap) {
293     SmallBitVector &UsedByIndices = Pair.second.UsedByIndices;
294     if (LUIdx < UsedByIndices.size())
295       UsedByIndices[LUIdx] =
296         LastLUIdx < UsedByIndices.size() ? UsedByIndices[LastLUIdx] : false;
297     UsedByIndices.resize(std::min(UsedByIndices.size(), LastLUIdx));
298   }
299 }
300 
301 bool
302 RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const {
303   RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
304   if (I == RegUsesMap.end())
305     return false;
306   const SmallBitVector &UsedByIndices = I->second.UsedByIndices;
307   int i = UsedByIndices.find_first();
308   if (i == -1) return false;
309   if ((size_t)i != LUIdx) return true;
310   return UsedByIndices.find_next(i) != -1;
311 }
312 
313 const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const {
314   RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
315   assert(I != RegUsesMap.end() && "Unknown register!");
316   return I->second.UsedByIndices;
317 }
318 
319 void RegUseTracker::clear() {
320   RegUsesMap.clear();
321   RegSequence.clear();
322 }
323 
324 namespace {
325 
326 /// This class holds information that describes a formula for computing
327 /// satisfying a use. It may include broken-out immediates and scaled registers.
328 struct Formula {
329   /// Global base address used for complex addressing.
330   GlobalValue *BaseGV = nullptr;
331 
332   /// Base offset for complex addressing.
333   int64_t BaseOffset = 0;
334 
335   /// Whether any complex addressing has a base register.
336   bool HasBaseReg = false;
337 
338   /// The scale of any complex addressing.
339   int64_t Scale = 0;
340 
341   /// The list of "base" registers for this use. When this is non-empty. The
342   /// canonical representation of a formula is
343   /// 1. BaseRegs.size > 1 implies ScaledReg != NULL and
344   /// 2. ScaledReg != NULL implies Scale != 1 || !BaseRegs.empty().
345   /// 3. The reg containing recurrent expr related with currect loop in the
346   /// formula should be put in the ScaledReg.
347   /// #1 enforces that the scaled register is always used when at least two
348   /// registers are needed by the formula: e.g., reg1 + reg2 is reg1 + 1 * reg2.
349   /// #2 enforces that 1 * reg is reg.
350   /// #3 ensures invariant regs with respect to current loop can be combined
351   /// together in LSR codegen.
352   /// This invariant can be temporarily broken while building a formula.
353   /// However, every formula inserted into the LSRInstance must be in canonical
354   /// form.
355   SmallVector<const SCEV *, 4> BaseRegs;
356 
357   /// The 'scaled' register for this use. This should be non-null when Scale is
358   /// not zero.
359   const SCEV *ScaledReg = nullptr;
360 
361   /// An additional constant offset which added near the use. This requires a
362   /// temporary register, but the offset itself can live in an add immediate
363   /// field rather than a register.
364   int64_t UnfoldedOffset = 0;
365 
366   Formula() = default;
367 
368   void initialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE);
369 
370   bool isCanonical(const Loop &L) const;
371 
372   void canonicalize(const Loop &L);
373 
374   bool unscale();
375 
376   bool hasZeroEnd() const;
377 
378   size_t getNumRegs() const;
379   Type *getType() const;
380 
381   void deleteBaseReg(const SCEV *&S);
382 
383   bool referencesReg(const SCEV *S) const;
384   bool hasRegsUsedByUsesOtherThan(size_t LUIdx,
385                                   const RegUseTracker &RegUses) const;
386 
387   void print(raw_ostream &OS) const;
388   void dump() const;
389 };
390 
391 } // end anonymous namespace
392 
393 /// Recursion helper for initialMatch.
394 static void DoInitialMatch(const SCEV *S, Loop *L,
395                            SmallVectorImpl<const SCEV *> &Good,
396                            SmallVectorImpl<const SCEV *> &Bad,
397                            ScalarEvolution &SE) {
398   // Collect expressions which properly dominate the loop header.
399   if (SE.properlyDominates(S, L->getHeader())) {
400     Good.push_back(S);
401     return;
402   }
403 
404   // Look at add operands.
405   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
406     for (const SCEV *S : Add->operands())
407       DoInitialMatch(S, L, Good, Bad, SE);
408     return;
409   }
410 
411   // Look at addrec operands.
412   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
413     if (!AR->getStart()->isZero() && AR->isAffine()) {
414       DoInitialMatch(AR->getStart(), L, Good, Bad, SE);
415       DoInitialMatch(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
416                                       AR->getStepRecurrence(SE),
417                                       // FIXME: AR->getNoWrapFlags()
418                                       AR->getLoop(), SCEV::FlagAnyWrap),
419                      L, Good, Bad, SE);
420       return;
421     }
422 
423   // Handle a multiplication by -1 (negation) if it didn't fold.
424   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S))
425     if (Mul->getOperand(0)->isAllOnesValue()) {
426       SmallVector<const SCEV *, 4> Ops(Mul->op_begin()+1, Mul->op_end());
427       const SCEV *NewMul = SE.getMulExpr(Ops);
428 
429       SmallVector<const SCEV *, 4> MyGood;
430       SmallVector<const SCEV *, 4> MyBad;
431       DoInitialMatch(NewMul, L, MyGood, MyBad, SE);
432       const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue(
433         SE.getEffectiveSCEVType(NewMul->getType())));
434       for (const SCEV *S : MyGood)
435         Good.push_back(SE.getMulExpr(NegOne, S));
436       for (const SCEV *S : MyBad)
437         Bad.push_back(SE.getMulExpr(NegOne, S));
438       return;
439     }
440 
441   // Ok, we can't do anything interesting. Just stuff the whole thing into a
442   // register and hope for the best.
443   Bad.push_back(S);
444 }
445 
446 /// Incorporate loop-variant parts of S into this Formula, attempting to keep
447 /// all loop-invariant and loop-computable values in a single base register.
448 void Formula::initialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE) {
449   SmallVector<const SCEV *, 4> Good;
450   SmallVector<const SCEV *, 4> Bad;
451   DoInitialMatch(S, L, Good, Bad, SE);
452   if (!Good.empty()) {
453     const SCEV *Sum = SE.getAddExpr(Good);
454     if (!Sum->isZero())
455       BaseRegs.push_back(Sum);
456     HasBaseReg = true;
457   }
458   if (!Bad.empty()) {
459     const SCEV *Sum = SE.getAddExpr(Bad);
460     if (!Sum->isZero())
461       BaseRegs.push_back(Sum);
462     HasBaseReg = true;
463   }
464   canonicalize(*L);
465 }
466 
467 /// Check whether or not this formula satisfies the canonical
468 /// representation.
469 /// \see Formula::BaseRegs.
470 bool Formula::isCanonical(const Loop &L) const {
471   if (!ScaledReg)
472     return BaseRegs.size() <= 1;
473 
474   if (Scale != 1)
475     return true;
476 
477   if (Scale == 1 && BaseRegs.empty())
478     return false;
479 
480   const SCEVAddRecExpr *SAR = dyn_cast<const SCEVAddRecExpr>(ScaledReg);
481   if (SAR && SAR->getLoop() == &L)
482     return true;
483 
484   // If ScaledReg is not a recurrent expr, or it is but its loop is not current
485   // loop, meanwhile BaseRegs contains a recurrent expr reg related with current
486   // loop, we want to swap the reg in BaseRegs with ScaledReg.
487   auto I =
488       find_if(make_range(BaseRegs.begin(), BaseRegs.end()), [&](const SCEV *S) {
489         return isa<const SCEVAddRecExpr>(S) &&
490                (cast<SCEVAddRecExpr>(S)->getLoop() == &L);
491       });
492   return I == BaseRegs.end();
493 }
494 
495 /// Helper method to morph a formula into its canonical representation.
496 /// \see Formula::BaseRegs.
497 /// Every formula having more than one base register, must use the ScaledReg
498 /// field. Otherwise, we would have to do special cases everywhere in LSR
499 /// to treat reg1 + reg2 + ... the same way as reg1 + 1*reg2 + ...
500 /// On the other hand, 1*reg should be canonicalized into reg.
501 void Formula::canonicalize(const Loop &L) {
502   if (isCanonical(L))
503     return;
504   // So far we did not need this case. This is easy to implement but it is
505   // useless to maintain dead code. Beside it could hurt compile time.
506   assert(!BaseRegs.empty() && "1*reg => reg, should not be needed.");
507 
508   // Keep the invariant sum in BaseRegs and one of the variant sum in ScaledReg.
509   if (!ScaledReg) {
510     ScaledReg = BaseRegs.back();
511     BaseRegs.pop_back();
512     Scale = 1;
513   }
514 
515   // If ScaledReg is an invariant with respect to L, find the reg from
516   // BaseRegs containing the recurrent expr related with Loop L. Swap the
517   // reg with ScaledReg.
518   const SCEVAddRecExpr *SAR = dyn_cast<const SCEVAddRecExpr>(ScaledReg);
519   if (!SAR || SAR->getLoop() != &L) {
520     auto I = find_if(make_range(BaseRegs.begin(), BaseRegs.end()),
521                      [&](const SCEV *S) {
522                        return isa<const SCEVAddRecExpr>(S) &&
523                               (cast<SCEVAddRecExpr>(S)->getLoop() == &L);
524                      });
525     if (I != BaseRegs.end())
526       std::swap(ScaledReg, *I);
527   }
528 }
529 
530 /// Get rid of the scale in the formula.
531 /// In other words, this method morphes reg1 + 1*reg2 into reg1 + reg2.
532 /// \return true if it was possible to get rid of the scale, false otherwise.
533 /// \note After this operation the formula may not be in the canonical form.
534 bool Formula::unscale() {
535   if (Scale != 1)
536     return false;
537   Scale = 0;
538   BaseRegs.push_back(ScaledReg);
539   ScaledReg = nullptr;
540   return true;
541 }
542 
543 bool Formula::hasZeroEnd() const {
544   if (UnfoldedOffset || BaseOffset)
545     return false;
546   if (BaseRegs.size() != 1 || ScaledReg)
547     return false;
548   return true;
549 }
550 
551 /// Return the total number of register operands used by this formula. This does
552 /// not include register uses implied by non-constant addrec strides.
553 size_t Formula::getNumRegs() const {
554   return !!ScaledReg + BaseRegs.size();
555 }
556 
557 /// Return the type of this formula, if it has one, or null otherwise. This type
558 /// is meaningless except for the bit size.
559 Type *Formula::getType() const {
560   return !BaseRegs.empty() ? BaseRegs.front()->getType() :
561          ScaledReg ? ScaledReg->getType() :
562          BaseGV ? BaseGV->getType() :
563          nullptr;
564 }
565 
566 /// Delete the given base reg from the BaseRegs list.
567 void Formula::deleteBaseReg(const SCEV *&S) {
568   if (&S != &BaseRegs.back())
569     std::swap(S, BaseRegs.back());
570   BaseRegs.pop_back();
571 }
572 
573 /// Test if this formula references the given register.
574 bool Formula::referencesReg(const SCEV *S) const {
575   return S == ScaledReg || is_contained(BaseRegs, S);
576 }
577 
578 /// Test whether this formula uses registers which are used by uses other than
579 /// the use with the given index.
580 bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,
581                                          const RegUseTracker &RegUses) const {
582   if (ScaledReg)
583     if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
584       return true;
585   for (const SCEV *BaseReg : BaseRegs)
586     if (RegUses.isRegUsedByUsesOtherThan(BaseReg, LUIdx))
587       return true;
588   return false;
589 }
590 
591 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
592 void Formula::print(raw_ostream &OS) const {
593   bool First = true;
594   if (BaseGV) {
595     if (!First) OS << " + "; else First = false;
596     BaseGV->printAsOperand(OS, /*PrintType=*/false);
597   }
598   if (BaseOffset != 0) {
599     if (!First) OS << " + "; else First = false;
600     OS << BaseOffset;
601   }
602   for (const SCEV *BaseReg : BaseRegs) {
603     if (!First) OS << " + "; else First = false;
604     OS << "reg(" << *BaseReg << ')';
605   }
606   if (HasBaseReg && BaseRegs.empty()) {
607     if (!First) OS << " + "; else First = false;
608     OS << "**error: HasBaseReg**";
609   } else if (!HasBaseReg && !BaseRegs.empty()) {
610     if (!First) OS << " + "; else First = false;
611     OS << "**error: !HasBaseReg**";
612   }
613   if (Scale != 0) {
614     if (!First) OS << " + "; else First = false;
615     OS << Scale << "*reg(";
616     if (ScaledReg)
617       OS << *ScaledReg;
618     else
619       OS << "<unknown>";
620     OS << ')';
621   }
622   if (UnfoldedOffset != 0) {
623     if (!First) OS << " + ";
624     OS << "imm(" << UnfoldedOffset << ')';
625   }
626 }
627 
628 LLVM_DUMP_METHOD void Formula::dump() const {
629   print(errs()); errs() << '\n';
630 }
631 #endif
632 
633 /// Return true if the given addrec can be sign-extended without changing its
634 /// value.
635 static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
636   Type *WideTy =
637     IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(AR->getType()) + 1);
638   return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
639 }
640 
641 /// Return true if the given add can be sign-extended without changing its
642 /// value.
643 static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {
644   Type *WideTy =
645     IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(A->getType()) + 1);
646   return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy));
647 }
648 
649 /// Return true if the given mul can be sign-extended without changing its
650 /// value.
651 static bool isMulSExtable(const SCEVMulExpr *M, ScalarEvolution &SE) {
652   Type *WideTy =
653     IntegerType::get(SE.getContext(),
654                      SE.getTypeSizeInBits(M->getType()) * M->getNumOperands());
655   return isa<SCEVMulExpr>(SE.getSignExtendExpr(M, WideTy));
656 }
657 
658 /// Return an expression for LHS /s RHS, if it can be determined and if the
659 /// remainder is known to be zero, or null otherwise. If IgnoreSignificantBits
660 /// is true, expressions like (X * Y) /s Y are simplified to Y, ignoring that
661 /// the multiplication may overflow, which is useful when the result will be
662 /// used in a context where the most significant bits are ignored.
663 static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,
664                                 ScalarEvolution &SE,
665                                 bool IgnoreSignificantBits = false) {
666   // Handle the trivial case, which works for any SCEV type.
667   if (LHS == RHS)
668     return SE.getConstant(LHS->getType(), 1);
669 
670   // Handle a few RHS special cases.
671   const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
672   if (RC) {
673     const APInt &RA = RC->getAPInt();
674     // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do
675     // some folding.
676     if (RA.isAllOnesValue())
677       return SE.getMulExpr(LHS, RC);
678     // Handle x /s 1 as x.
679     if (RA == 1)
680       return LHS;
681   }
682 
683   // Check for a division of a constant by a constant.
684   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
685     if (!RC)
686       return nullptr;
687     const APInt &LA = C->getAPInt();
688     const APInt &RA = RC->getAPInt();
689     if (LA.srem(RA) != 0)
690       return nullptr;
691     return SE.getConstant(LA.sdiv(RA));
692   }
693 
694   // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
695   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
696     if ((IgnoreSignificantBits || isAddRecSExtable(AR, SE)) && AR->isAffine()) {
697       const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE,
698                                       IgnoreSignificantBits);
699       if (!Step) return nullptr;
700       const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE,
701                                        IgnoreSignificantBits);
702       if (!Start) return nullptr;
703       // FlagNW is independent of the start value, step direction, and is
704       // preserved with smaller magnitude steps.
705       // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
706       return SE.getAddRecExpr(Start, Step, AR->getLoop(), SCEV::FlagAnyWrap);
707     }
708     return nullptr;
709   }
710 
711   // Distribute the sdiv over add operands, if the add doesn't overflow.
712   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
713     if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {
714       SmallVector<const SCEV *, 8> Ops;
715       for (const SCEV *S : Add->operands()) {
716         const SCEV *Op = getExactSDiv(S, RHS, SE, IgnoreSignificantBits);
717         if (!Op) return nullptr;
718         Ops.push_back(Op);
719       }
720       return SE.getAddExpr(Ops);
721     }
722     return nullptr;
723   }
724 
725   // Check for a multiply operand that we can pull RHS out of.
726   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS)) {
727     if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {
728       SmallVector<const SCEV *, 4> Ops;
729       bool Found = false;
730       for (const SCEV *S : Mul->operands()) {
731         if (!Found)
732           if (const SCEV *Q = getExactSDiv(S, RHS, SE,
733                                            IgnoreSignificantBits)) {
734             S = Q;
735             Found = true;
736           }
737         Ops.push_back(S);
738       }
739       return Found ? SE.getMulExpr(Ops) : nullptr;
740     }
741     return nullptr;
742   }
743 
744   // Otherwise we don't know.
745   return nullptr;
746 }
747 
748 /// If S involves the addition of a constant integer value, return that integer
749 /// value, and mutate S to point to a new SCEV with that value excluded.
750 static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
751   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
752     if (C->getAPInt().getMinSignedBits() <= 64) {
753       S = SE.getConstant(C->getType(), 0);
754       return C->getValue()->getSExtValue();
755     }
756   } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
757     SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
758     int64_t Result = ExtractImmediate(NewOps.front(), SE);
759     if (Result != 0)
760       S = SE.getAddExpr(NewOps);
761     return Result;
762   } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
763     SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
764     int64_t Result = ExtractImmediate(NewOps.front(), SE);
765     if (Result != 0)
766       S = SE.getAddRecExpr(NewOps, AR->getLoop(),
767                            // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
768                            SCEV::FlagAnyWrap);
769     return Result;
770   }
771   return 0;
772 }
773 
774 /// If S involves the addition of a GlobalValue address, return that symbol, and
775 /// mutate S to point to a new SCEV with that value excluded.
776 static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
777   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
778     if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
779       S = SE.getConstant(GV->getType(), 0);
780       return GV;
781     }
782   } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
783     SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
784     GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
785     if (Result)
786       S = SE.getAddExpr(NewOps);
787     return Result;
788   } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
789     SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
790     GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
791     if (Result)
792       S = SE.getAddRecExpr(NewOps, AR->getLoop(),
793                            // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
794                            SCEV::FlagAnyWrap);
795     return Result;
796   }
797   return nullptr;
798 }
799 
800 /// Returns true if the specified instruction is using the specified value as an
801 /// address.
802 static bool isAddressUse(const TargetTransformInfo &TTI,
803                          Instruction *Inst, Value *OperandVal) {
804   bool isAddress = isa<LoadInst>(Inst);
805   if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
806     if (SI->getPointerOperand() == OperandVal)
807       isAddress = true;
808   } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
809     // Addressing modes can also be folded into prefetches and a variety
810     // of intrinsics.
811     switch (II->getIntrinsicID()) {
812     case Intrinsic::memset:
813     case Intrinsic::prefetch:
814     case Intrinsic::masked_load:
815       if (II->getArgOperand(0) == OperandVal)
816         isAddress = true;
817       break;
818     case Intrinsic::masked_store:
819       if (II->getArgOperand(1) == OperandVal)
820         isAddress = true;
821       break;
822     case Intrinsic::memmove:
823     case Intrinsic::memcpy:
824       if (II->getArgOperand(0) == OperandVal ||
825           II->getArgOperand(1) == OperandVal)
826         isAddress = true;
827       break;
828     default: {
829       MemIntrinsicInfo IntrInfo;
830       if (TTI.getTgtMemIntrinsic(II, IntrInfo)) {
831         if (IntrInfo.PtrVal == OperandVal)
832           isAddress = true;
833       }
834     }
835     }
836   } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) {
837     if (RMW->getPointerOperand() == OperandVal)
838       isAddress = true;
839   } else if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) {
840     if (CmpX->getPointerOperand() == OperandVal)
841       isAddress = true;
842   }
843   return isAddress;
844 }
845 
846 /// Return the type of the memory being accessed.
847 static MemAccessTy getAccessType(const TargetTransformInfo &TTI,
848                                  Instruction *Inst, Value *OperandVal) {
849   MemAccessTy AccessTy(Inst->getType(), MemAccessTy::UnknownAddressSpace);
850   if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
851     AccessTy.MemTy = SI->getOperand(0)->getType();
852     AccessTy.AddrSpace = SI->getPointerAddressSpace();
853   } else if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
854     AccessTy.AddrSpace = LI->getPointerAddressSpace();
855   } else if (const AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) {
856     AccessTy.AddrSpace = RMW->getPointerAddressSpace();
857   } else if (const AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) {
858     AccessTy.AddrSpace = CmpX->getPointerAddressSpace();
859   } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
860     switch (II->getIntrinsicID()) {
861     case Intrinsic::prefetch:
862     case Intrinsic::memset:
863       AccessTy.AddrSpace = II->getArgOperand(0)->getType()->getPointerAddressSpace();
864       AccessTy.MemTy = OperandVal->getType();
865       break;
866     case Intrinsic::memmove:
867     case Intrinsic::memcpy:
868       AccessTy.AddrSpace = OperandVal->getType()->getPointerAddressSpace();
869       AccessTy.MemTy = OperandVal->getType();
870       break;
871     case Intrinsic::masked_load:
872       AccessTy.AddrSpace =
873           II->getArgOperand(0)->getType()->getPointerAddressSpace();
874       break;
875     case Intrinsic::masked_store:
876       AccessTy.MemTy = II->getOperand(0)->getType();
877       AccessTy.AddrSpace =
878           II->getArgOperand(1)->getType()->getPointerAddressSpace();
879       break;
880     default: {
881       MemIntrinsicInfo IntrInfo;
882       if (TTI.getTgtMemIntrinsic(II, IntrInfo) && IntrInfo.PtrVal) {
883         AccessTy.AddrSpace
884           = IntrInfo.PtrVal->getType()->getPointerAddressSpace();
885       }
886 
887       break;
888     }
889     }
890   }
891 
892   // All pointers have the same requirements, so canonicalize them to an
893   // arbitrary pointer type to minimize variation.
894   if (PointerType *PTy = dyn_cast<PointerType>(AccessTy.MemTy))
895     AccessTy.MemTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
896                                       PTy->getAddressSpace());
897 
898   return AccessTy;
899 }
900 
901 /// Return true if this AddRec is already a phi in its loop.
902 static bool isExistingPhi(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
903   for (PHINode &PN : AR->getLoop()->getHeader()->phis()) {
904     if (SE.isSCEVable(PN.getType()) &&
905         (SE.getEffectiveSCEVType(PN.getType()) ==
906          SE.getEffectiveSCEVType(AR->getType())) &&
907         SE.getSCEV(&PN) == AR)
908       return true;
909   }
910   return false;
911 }
912 
913 /// Check if expanding this expression is likely to incur significant cost. This
914 /// is tricky because SCEV doesn't track which expressions are actually computed
915 /// by the current IR.
916 ///
917 /// We currently allow expansion of IV increments that involve adds,
918 /// multiplication by constants, and AddRecs from existing phis.
919 ///
920 /// TODO: Allow UDivExpr if we can find an existing IV increment that is an
921 /// obvious multiple of the UDivExpr.
922 static bool isHighCostExpansion(const SCEV *S,
923                                 SmallPtrSetImpl<const SCEV*> &Processed,
924                                 ScalarEvolution &SE) {
925   // Zero/One operand expressions
926   switch (S->getSCEVType()) {
927   case scUnknown:
928   case scConstant:
929     return false;
930   case scTruncate:
931     return isHighCostExpansion(cast<SCEVTruncateExpr>(S)->getOperand(),
932                                Processed, SE);
933   case scZeroExtend:
934     return isHighCostExpansion(cast<SCEVZeroExtendExpr>(S)->getOperand(),
935                                Processed, SE);
936   case scSignExtend:
937     return isHighCostExpansion(cast<SCEVSignExtendExpr>(S)->getOperand(),
938                                Processed, SE);
939   default:
940     break;
941   }
942 
943   if (!Processed.insert(S).second)
944     return false;
945 
946   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
947     for (const SCEV *S : Add->operands()) {
948       if (isHighCostExpansion(S, Processed, SE))
949         return true;
950     }
951     return false;
952   }
953 
954   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
955     if (Mul->getNumOperands() == 2) {
956       // Multiplication by a constant is ok
957       if (isa<SCEVConstant>(Mul->getOperand(0)))
958         return isHighCostExpansion(Mul->getOperand(1), Processed, SE);
959 
960       // If we have the value of one operand, check if an existing
961       // multiplication already generates this expression.
962       if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Mul->getOperand(1))) {
963         Value *UVal = U->getValue();
964         for (User *UR : UVal->users()) {
965           // If U is a constant, it may be used by a ConstantExpr.
966           Instruction *UI = dyn_cast<Instruction>(UR);
967           if (UI && UI->getOpcode() == Instruction::Mul &&
968               SE.isSCEVable(UI->getType())) {
969             return SE.getSCEV(UI) == Mul;
970           }
971         }
972       }
973     }
974   }
975 
976   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
977     if (isExistingPhi(AR, SE))
978       return false;
979   }
980 
981   // Fow now, consider any other type of expression (div/mul/min/max) high cost.
982   return true;
983 }
984 
985 namespace {
986 
987 class LSRUse;
988 
989 } // end anonymous namespace
990 
991 /// Check if the addressing mode defined by \p F is completely
992 /// folded in \p LU at isel time.
993 /// This includes address-mode folding and special icmp tricks.
994 /// This function returns true if \p LU can accommodate what \p F
995 /// defines and up to 1 base + 1 scaled + offset.
996 /// In other words, if \p F has several base registers, this function may
997 /// still return true. Therefore, users still need to account for
998 /// additional base registers and/or unfolded offsets to derive an
999 /// accurate cost model.
1000 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1001                                  const LSRUse &LU, const Formula &F);
1002 
1003 // Get the cost of the scaling factor used in F for LU.
1004 static unsigned getScalingFactorCost(const TargetTransformInfo &TTI,
1005                                      const LSRUse &LU, const Formula &F,
1006                                      const Loop &L);
1007 
1008 namespace {
1009 
1010 /// This class is used to measure and compare candidate formulae.
1011 class Cost {
1012   const Loop *L = nullptr;
1013   ScalarEvolution *SE = nullptr;
1014   const TargetTransformInfo *TTI = nullptr;
1015   TargetTransformInfo::LSRCost C;
1016 
1017 public:
1018   Cost() = delete;
1019   Cost(const Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI) :
1020     L(L), SE(&SE), TTI(&TTI) {
1021     C.Insns = 0;
1022     C.NumRegs = 0;
1023     C.AddRecCost = 0;
1024     C.NumIVMuls = 0;
1025     C.NumBaseAdds = 0;
1026     C.ImmCost = 0;
1027     C.SetupCost = 0;
1028     C.ScaleCost = 0;
1029   }
1030 
1031   bool isLess(Cost &Other);
1032 
1033   void Lose();
1034 
1035 #ifndef NDEBUG
1036   // Once any of the metrics loses, they must all remain losers.
1037   bool isValid() {
1038     return ((C.Insns | C.NumRegs | C.AddRecCost | C.NumIVMuls | C.NumBaseAdds
1039              | C.ImmCost | C.SetupCost | C.ScaleCost) != ~0u)
1040       || ((C.Insns & C.NumRegs & C.AddRecCost & C.NumIVMuls & C.NumBaseAdds
1041            & C.ImmCost & C.SetupCost & C.ScaleCost) == ~0u);
1042   }
1043 #endif
1044 
1045   bool isLoser() {
1046     assert(isValid() && "invalid cost");
1047     return C.NumRegs == ~0u;
1048   }
1049 
1050   void RateFormula(const Formula &F,
1051                    SmallPtrSetImpl<const SCEV *> &Regs,
1052                    const DenseSet<const SCEV *> &VisitedRegs,
1053                    const LSRUse &LU,
1054                    SmallPtrSetImpl<const SCEV *> *LoserRegs = nullptr);
1055 
1056   void print(raw_ostream &OS) const;
1057   void dump() const;
1058 
1059 private:
1060   void RateRegister(const Formula &F, const SCEV *Reg,
1061                     SmallPtrSetImpl<const SCEV *> &Regs);
1062   void RatePrimaryRegister(const Formula &F, const SCEV *Reg,
1063                            SmallPtrSetImpl<const SCEV *> &Regs,
1064                            SmallPtrSetImpl<const SCEV *> *LoserRegs);
1065 };
1066 
1067 /// An operand value in an instruction which is to be replaced with some
1068 /// equivalent, possibly strength-reduced, replacement.
1069 struct LSRFixup {
1070   /// The instruction which will be updated.
1071   Instruction *UserInst = nullptr;
1072 
1073   /// The operand of the instruction which will be replaced. The operand may be
1074   /// used more than once; every instance will be replaced.
1075   Value *OperandValToReplace = nullptr;
1076 
1077   /// If this user is to use the post-incremented value of an induction
1078   /// variable, this set is non-empty and holds the loops associated with the
1079   /// induction variable.
1080   PostIncLoopSet PostIncLoops;
1081 
1082   /// A constant offset to be added to the LSRUse expression.  This allows
1083   /// multiple fixups to share the same LSRUse with different offsets, for
1084   /// example in an unrolled loop.
1085   int64_t Offset = 0;
1086 
1087   LSRFixup() = default;
1088 
1089   bool isUseFullyOutsideLoop(const Loop *L) const;
1090 
1091   void print(raw_ostream &OS) const;
1092   void dump() const;
1093 };
1094 
1095 /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of sorted
1096 /// SmallVectors of const SCEV*.
1097 struct UniquifierDenseMapInfo {
1098   static SmallVector<const SCEV *, 4> getEmptyKey() {
1099     SmallVector<const SCEV *, 4>  V;
1100     V.push_back(reinterpret_cast<const SCEV *>(-1));
1101     return V;
1102   }
1103 
1104   static SmallVector<const SCEV *, 4> getTombstoneKey() {
1105     SmallVector<const SCEV *, 4> V;
1106     V.push_back(reinterpret_cast<const SCEV *>(-2));
1107     return V;
1108   }
1109 
1110   static unsigned getHashValue(const SmallVector<const SCEV *, 4> &V) {
1111     return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
1112   }
1113 
1114   static bool isEqual(const SmallVector<const SCEV *, 4> &LHS,
1115                       const SmallVector<const SCEV *, 4> &RHS) {
1116     return LHS == RHS;
1117   }
1118 };
1119 
1120 /// This class holds the state that LSR keeps for each use in IVUsers, as well
1121 /// as uses invented by LSR itself. It includes information about what kinds of
1122 /// things can be folded into the user, information about the user itself, and
1123 /// information about how the use may be satisfied.  TODO: Represent multiple
1124 /// users of the same expression in common?
1125 class LSRUse {
1126   DenseSet<SmallVector<const SCEV *, 4>, UniquifierDenseMapInfo> Uniquifier;
1127 
1128 public:
1129   /// An enum for a kind of use, indicating what types of scaled and immediate
1130   /// operands it might support.
1131   enum KindType {
1132     Basic,   ///< A normal use, with no folding.
1133     Special, ///< A special case of basic, allowing -1 scales.
1134     Address, ///< An address use; folding according to TargetLowering
1135     ICmpZero ///< An equality icmp with both operands folded into one.
1136     // TODO: Add a generic icmp too?
1137   };
1138 
1139   using SCEVUseKindPair = PointerIntPair<const SCEV *, 2, KindType>;
1140 
1141   KindType Kind;
1142   MemAccessTy AccessTy;
1143 
1144   /// The list of operands which are to be replaced.
1145   SmallVector<LSRFixup, 8> Fixups;
1146 
1147   /// Keep track of the min and max offsets of the fixups.
1148   int64_t MinOffset = std::numeric_limits<int64_t>::max();
1149   int64_t MaxOffset = std::numeric_limits<int64_t>::min();
1150 
1151   /// This records whether all of the fixups using this LSRUse are outside of
1152   /// the loop, in which case some special-case heuristics may be used.
1153   bool AllFixupsOutsideLoop = true;
1154 
1155   /// RigidFormula is set to true to guarantee that this use will be associated
1156   /// with a single formula--the one that initially matched. Some SCEV
1157   /// expressions cannot be expanded. This allows LSR to consider the registers
1158   /// used by those expressions without the need to expand them later after
1159   /// changing the formula.
1160   bool RigidFormula = false;
1161 
1162   /// This records the widest use type for any fixup using this
1163   /// LSRUse. FindUseWithSimilarFormula can't consider uses with different max
1164   /// fixup widths to be equivalent, because the narrower one may be relying on
1165   /// the implicit truncation to truncate away bogus bits.
1166   Type *WidestFixupType = nullptr;
1167 
1168   /// A list of ways to build a value that can satisfy this user.  After the
1169   /// list is populated, one of these is selected heuristically and used to
1170   /// formulate a replacement for OperandValToReplace in UserInst.
1171   SmallVector<Formula, 12> Formulae;
1172 
1173   /// The set of register candidates used by all formulae in this LSRUse.
1174   SmallPtrSet<const SCEV *, 4> Regs;
1175 
1176   LSRUse(KindType K, MemAccessTy AT) : Kind(K), AccessTy(AT) {}
1177 
1178   LSRFixup &getNewFixup() {
1179     Fixups.push_back(LSRFixup());
1180     return Fixups.back();
1181   }
1182 
1183   void pushFixup(LSRFixup &f) {
1184     Fixups.push_back(f);
1185     if (f.Offset > MaxOffset)
1186       MaxOffset = f.Offset;
1187     if (f.Offset < MinOffset)
1188       MinOffset = f.Offset;
1189   }
1190 
1191   bool HasFormulaWithSameRegs(const Formula &F) const;
1192   float getNotSelectedProbability(const SCEV *Reg) const;
1193   bool InsertFormula(const Formula &F, const Loop &L);
1194   void DeleteFormula(Formula &F);
1195   void RecomputeRegs(size_t LUIdx, RegUseTracker &Reguses);
1196 
1197   void print(raw_ostream &OS) const;
1198   void dump() const;
1199 };
1200 
1201 } // end anonymous namespace
1202 
1203 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1204                                  LSRUse::KindType Kind, MemAccessTy AccessTy,
1205                                  GlobalValue *BaseGV, int64_t BaseOffset,
1206                                  bool HasBaseReg, int64_t Scale,
1207                                  Instruction *Fixup = nullptr);
1208 
1209 static unsigned getSetupCost(const SCEV *Reg, unsigned Depth) {
1210   if (isa<SCEVUnknown>(Reg) || isa<SCEVConstant>(Reg))
1211     return 1;
1212   if (Depth == 0)
1213     return 0;
1214   if (const auto *S = dyn_cast<SCEVAddRecExpr>(Reg))
1215     return getSetupCost(S->getStart(), Depth - 1);
1216   if (auto S = dyn_cast<SCEVIntegralCastExpr>(Reg))
1217     return getSetupCost(S->getOperand(), Depth - 1);
1218   if (auto S = dyn_cast<SCEVNAryExpr>(Reg))
1219     return std::accumulate(S->op_begin(), S->op_end(), 0,
1220                            [&](unsigned i, const SCEV *Reg) {
1221                              return i + getSetupCost(Reg, Depth - 1);
1222                            });
1223   if (auto S = dyn_cast<SCEVUDivExpr>(Reg))
1224     return getSetupCost(S->getLHS(), Depth - 1) +
1225            getSetupCost(S->getRHS(), Depth - 1);
1226   return 0;
1227 }
1228 
1229 /// Tally up interesting quantities from the given register.
1230 void Cost::RateRegister(const Formula &F, const SCEV *Reg,
1231                         SmallPtrSetImpl<const SCEV *> &Regs) {
1232   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
1233     // If this is an addrec for another loop, it should be an invariant
1234     // with respect to L since L is the innermost loop (at least
1235     // for now LSR only handles innermost loops).
1236     if (AR->getLoop() != L) {
1237       // If the AddRec exists, consider it's register free and leave it alone.
1238       if (isExistingPhi(AR, *SE) && !TTI->shouldFavorPostInc())
1239         return;
1240 
1241       // It is bad to allow LSR for current loop to add induction variables
1242       // for its sibling loops.
1243       if (!AR->getLoop()->contains(L)) {
1244         Lose();
1245         return;
1246       }
1247 
1248       // Otherwise, it will be an invariant with respect to Loop L.
1249       ++C.NumRegs;
1250       return;
1251     }
1252 
1253     unsigned LoopCost = 1;
1254     if (TTI->isIndexedLoadLegal(TTI->MIM_PostInc, AR->getType()) ||
1255         TTI->isIndexedStoreLegal(TTI->MIM_PostInc, AR->getType())) {
1256 
1257       // If the step size matches the base offset, we could use pre-indexed
1258       // addressing.
1259       if (TTI->shouldFavorBackedgeIndex(L)) {
1260         if (auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE)))
1261           if (Step->getAPInt() == F.BaseOffset)
1262             LoopCost = 0;
1263       }
1264 
1265       if (TTI->shouldFavorPostInc()) {
1266         const SCEV *LoopStep = AR->getStepRecurrence(*SE);
1267         if (isa<SCEVConstant>(LoopStep)) {
1268           const SCEV *LoopStart = AR->getStart();
1269           if (!isa<SCEVConstant>(LoopStart) &&
1270               SE->isLoopInvariant(LoopStart, L))
1271             LoopCost = 0;
1272         }
1273       }
1274     }
1275     C.AddRecCost += LoopCost;
1276 
1277     // Add the step value register, if it needs one.
1278     // TODO: The non-affine case isn't precisely modeled here.
1279     if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1))) {
1280       if (!Regs.count(AR->getOperand(1))) {
1281         RateRegister(F, AR->getOperand(1), Regs);
1282         if (isLoser())
1283           return;
1284       }
1285     }
1286   }
1287   ++C.NumRegs;
1288 
1289   // Rough heuristic; favor registers which don't require extra setup
1290   // instructions in the preheader.
1291   C.SetupCost += getSetupCost(Reg, SetupCostDepthLimit);
1292   // Ensure we don't, even with the recusion limit, produce invalid costs.
1293   C.SetupCost = std::min<unsigned>(C.SetupCost, 1 << 16);
1294 
1295   C.NumIVMuls += isa<SCEVMulExpr>(Reg) &&
1296                SE->hasComputableLoopEvolution(Reg, L);
1297 }
1298 
1299 /// Record this register in the set. If we haven't seen it before, rate
1300 /// it. Optional LoserRegs provides a way to declare any formula that refers to
1301 /// one of those regs an instant loser.
1302 void Cost::RatePrimaryRegister(const Formula &F, const SCEV *Reg,
1303                                SmallPtrSetImpl<const SCEV *> &Regs,
1304                                SmallPtrSetImpl<const SCEV *> *LoserRegs) {
1305   if (LoserRegs && LoserRegs->count(Reg)) {
1306     Lose();
1307     return;
1308   }
1309   if (Regs.insert(Reg).second) {
1310     RateRegister(F, Reg, Regs);
1311     if (LoserRegs && isLoser())
1312       LoserRegs->insert(Reg);
1313   }
1314 }
1315 
1316 void Cost::RateFormula(const Formula &F,
1317                        SmallPtrSetImpl<const SCEV *> &Regs,
1318                        const DenseSet<const SCEV *> &VisitedRegs,
1319                        const LSRUse &LU,
1320                        SmallPtrSetImpl<const SCEV *> *LoserRegs) {
1321   assert(F.isCanonical(*L) && "Cost is accurate only for canonical formula");
1322   // Tally up the registers.
1323   unsigned PrevAddRecCost = C.AddRecCost;
1324   unsigned PrevNumRegs = C.NumRegs;
1325   unsigned PrevNumBaseAdds = C.NumBaseAdds;
1326   if (const SCEV *ScaledReg = F.ScaledReg) {
1327     if (VisitedRegs.count(ScaledReg)) {
1328       Lose();
1329       return;
1330     }
1331     RatePrimaryRegister(F, ScaledReg, Regs, LoserRegs);
1332     if (isLoser())
1333       return;
1334   }
1335   for (const SCEV *BaseReg : F.BaseRegs) {
1336     if (VisitedRegs.count(BaseReg)) {
1337       Lose();
1338       return;
1339     }
1340     RatePrimaryRegister(F, BaseReg, Regs, LoserRegs);
1341     if (isLoser())
1342       return;
1343   }
1344 
1345   // Determine how many (unfolded) adds we'll need inside the loop.
1346   size_t NumBaseParts = F.getNumRegs();
1347   if (NumBaseParts > 1)
1348     // Do not count the base and a possible second register if the target
1349     // allows to fold 2 registers.
1350     C.NumBaseAdds +=
1351         NumBaseParts - (1 + (F.Scale && isAMCompletelyFolded(*TTI, LU, F)));
1352   C.NumBaseAdds += (F.UnfoldedOffset != 0);
1353 
1354   // Accumulate non-free scaling amounts.
1355   C.ScaleCost += getScalingFactorCost(*TTI, LU, F, *L);
1356 
1357   // Tally up the non-zero immediates.
1358   for (const LSRFixup &Fixup : LU.Fixups) {
1359     int64_t O = Fixup.Offset;
1360     int64_t Offset = (uint64_t)O + F.BaseOffset;
1361     if (F.BaseGV)
1362       C.ImmCost += 64; // Handle symbolic values conservatively.
1363                      // TODO: This should probably be the pointer size.
1364     else if (Offset != 0)
1365       C.ImmCost += APInt(64, Offset, true).getMinSignedBits();
1366 
1367     // Check with target if this offset with this instruction is
1368     // specifically not supported.
1369     if (LU.Kind == LSRUse::Address && Offset != 0 &&
1370         !isAMCompletelyFolded(*TTI, LSRUse::Address, LU.AccessTy, F.BaseGV,
1371                               Offset, F.HasBaseReg, F.Scale, Fixup.UserInst))
1372       C.NumBaseAdds++;
1373   }
1374 
1375   // If we don't count instruction cost exit here.
1376   if (!InsnsCost) {
1377     assert(isValid() && "invalid cost");
1378     return;
1379   }
1380 
1381   // Treat every new register that exceeds TTI.getNumberOfRegisters() - 1 as
1382   // additional instruction (at least fill).
1383   // TODO: Need distinguish register class?
1384   unsigned TTIRegNum = TTI->getNumberOfRegisters(
1385                        TTI->getRegisterClassForType(false, F.getType())) - 1;
1386   if (C.NumRegs > TTIRegNum) {
1387     // Cost already exceeded TTIRegNum, then only newly added register can add
1388     // new instructions.
1389     if (PrevNumRegs > TTIRegNum)
1390       C.Insns += (C.NumRegs - PrevNumRegs);
1391     else
1392       C.Insns += (C.NumRegs - TTIRegNum);
1393   }
1394 
1395   // If ICmpZero formula ends with not 0, it could not be replaced by
1396   // just add or sub. We'll need to compare final result of AddRec.
1397   // That means we'll need an additional instruction. But if the target can
1398   // macro-fuse a compare with a branch, don't count this extra instruction.
1399   // For -10 + {0, +, 1}:
1400   // i = i + 1;
1401   // cmp i, 10
1402   //
1403   // For {-10, +, 1}:
1404   // i = i + 1;
1405   if (LU.Kind == LSRUse::ICmpZero && !F.hasZeroEnd() &&
1406       !TTI->canMacroFuseCmp())
1407     C.Insns++;
1408   // Each new AddRec adds 1 instruction to calculation.
1409   C.Insns += (C.AddRecCost - PrevAddRecCost);
1410 
1411   // BaseAdds adds instructions for unfolded registers.
1412   if (LU.Kind != LSRUse::ICmpZero)
1413     C.Insns += C.NumBaseAdds - PrevNumBaseAdds;
1414   assert(isValid() && "invalid cost");
1415 }
1416 
1417 /// Set this cost to a losing value.
1418 void Cost::Lose() {
1419   C.Insns = std::numeric_limits<unsigned>::max();
1420   C.NumRegs = std::numeric_limits<unsigned>::max();
1421   C.AddRecCost = std::numeric_limits<unsigned>::max();
1422   C.NumIVMuls = std::numeric_limits<unsigned>::max();
1423   C.NumBaseAdds = std::numeric_limits<unsigned>::max();
1424   C.ImmCost = std::numeric_limits<unsigned>::max();
1425   C.SetupCost = std::numeric_limits<unsigned>::max();
1426   C.ScaleCost = std::numeric_limits<unsigned>::max();
1427 }
1428 
1429 /// Choose the lower cost.
1430 bool Cost::isLess(Cost &Other) {
1431   if (InsnsCost.getNumOccurrences() > 0 && InsnsCost &&
1432       C.Insns != Other.C.Insns)
1433     return C.Insns < Other.C.Insns;
1434   return TTI->isLSRCostLess(C, Other.C);
1435 }
1436 
1437 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1438 void Cost::print(raw_ostream &OS) const {
1439   if (InsnsCost)
1440     OS << C.Insns << " instruction" << (C.Insns == 1 ? " " : "s ");
1441   OS << C.NumRegs << " reg" << (C.NumRegs == 1 ? "" : "s");
1442   if (C.AddRecCost != 0)
1443     OS << ", with addrec cost " << C.AddRecCost;
1444   if (C.NumIVMuls != 0)
1445     OS << ", plus " << C.NumIVMuls << " IV mul"
1446        << (C.NumIVMuls == 1 ? "" : "s");
1447   if (C.NumBaseAdds != 0)
1448     OS << ", plus " << C.NumBaseAdds << " base add"
1449        << (C.NumBaseAdds == 1 ? "" : "s");
1450   if (C.ScaleCost != 0)
1451     OS << ", plus " << C.ScaleCost << " scale cost";
1452   if (C.ImmCost != 0)
1453     OS << ", plus " << C.ImmCost << " imm cost";
1454   if (C.SetupCost != 0)
1455     OS << ", plus " << C.SetupCost << " setup cost";
1456 }
1457 
1458 LLVM_DUMP_METHOD void Cost::dump() const {
1459   print(errs()); errs() << '\n';
1460 }
1461 #endif
1462 
1463 /// Test whether this fixup always uses its value outside of the given loop.
1464 bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const {
1465   // PHI nodes use their value in their incoming blocks.
1466   if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
1467     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1468       if (PN->getIncomingValue(i) == OperandValToReplace &&
1469           L->contains(PN->getIncomingBlock(i)))
1470         return false;
1471     return true;
1472   }
1473 
1474   return !L->contains(UserInst);
1475 }
1476 
1477 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1478 void LSRFixup::print(raw_ostream &OS) const {
1479   OS << "UserInst=";
1480   // Store is common and interesting enough to be worth special-casing.
1481   if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
1482     OS << "store ";
1483     Store->getOperand(0)->printAsOperand(OS, /*PrintType=*/false);
1484   } else if (UserInst->getType()->isVoidTy())
1485     OS << UserInst->getOpcodeName();
1486   else
1487     UserInst->printAsOperand(OS, /*PrintType=*/false);
1488 
1489   OS << ", OperandValToReplace=";
1490   OperandValToReplace->printAsOperand(OS, /*PrintType=*/false);
1491 
1492   for (const Loop *PIL : PostIncLoops) {
1493     OS << ", PostIncLoop=";
1494     PIL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
1495   }
1496 
1497   if (Offset != 0)
1498     OS << ", Offset=" << Offset;
1499 }
1500 
1501 LLVM_DUMP_METHOD void LSRFixup::dump() const {
1502   print(errs()); errs() << '\n';
1503 }
1504 #endif
1505 
1506 /// Test whether this use as a formula which has the same registers as the given
1507 /// formula.
1508 bool LSRUse::HasFormulaWithSameRegs(const Formula &F) const {
1509   SmallVector<const SCEV *, 4> Key = F.BaseRegs;
1510   if (F.ScaledReg) Key.push_back(F.ScaledReg);
1511   // Unstable sort by host order ok, because this is only used for uniquifying.
1512   llvm::sort(Key);
1513   return Uniquifier.count(Key);
1514 }
1515 
1516 /// The function returns a probability of selecting formula without Reg.
1517 float LSRUse::getNotSelectedProbability(const SCEV *Reg) const {
1518   unsigned FNum = 0;
1519   for (const Formula &F : Formulae)
1520     if (F.referencesReg(Reg))
1521       FNum++;
1522   return ((float)(Formulae.size() - FNum)) / Formulae.size();
1523 }
1524 
1525 /// If the given formula has not yet been inserted, add it to the list, and
1526 /// return true. Return false otherwise.  The formula must be in canonical form.
1527 bool LSRUse::InsertFormula(const Formula &F, const Loop &L) {
1528   assert(F.isCanonical(L) && "Invalid canonical representation");
1529 
1530   if (!Formulae.empty() && RigidFormula)
1531     return false;
1532 
1533   SmallVector<const SCEV *, 4> Key = F.BaseRegs;
1534   if (F.ScaledReg) Key.push_back(F.ScaledReg);
1535   // Unstable sort by host order ok, because this is only used for uniquifying.
1536   llvm::sort(Key);
1537 
1538   if (!Uniquifier.insert(Key).second)
1539     return false;
1540 
1541   // Using a register to hold the value of 0 is not profitable.
1542   assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
1543          "Zero allocated in a scaled register!");
1544 #ifndef NDEBUG
1545   for (const SCEV *BaseReg : F.BaseRegs)
1546     assert(!BaseReg->isZero() && "Zero allocated in a base register!");
1547 #endif
1548 
1549   // Add the formula to the list.
1550   Formulae.push_back(F);
1551 
1552   // Record registers now being used by this use.
1553   Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1554   if (F.ScaledReg)
1555     Regs.insert(F.ScaledReg);
1556 
1557   return true;
1558 }
1559 
1560 /// Remove the given formula from this use's list.
1561 void LSRUse::DeleteFormula(Formula &F) {
1562   if (&F != &Formulae.back())
1563     std::swap(F, Formulae.back());
1564   Formulae.pop_back();
1565 }
1566 
1567 /// Recompute the Regs field, and update RegUses.
1568 void LSRUse::RecomputeRegs(size_t LUIdx, RegUseTracker &RegUses) {
1569   // Now that we've filtered out some formulae, recompute the Regs set.
1570   SmallPtrSet<const SCEV *, 4> OldRegs = std::move(Regs);
1571   Regs.clear();
1572   for (const Formula &F : Formulae) {
1573     if (F.ScaledReg) Regs.insert(F.ScaledReg);
1574     Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1575   }
1576 
1577   // Update the RegTracker.
1578   for (const SCEV *S : OldRegs)
1579     if (!Regs.count(S))
1580       RegUses.dropRegister(S, LUIdx);
1581 }
1582 
1583 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1584 void LSRUse::print(raw_ostream &OS) const {
1585   OS << "LSR Use: Kind=";
1586   switch (Kind) {
1587   case Basic:    OS << "Basic"; break;
1588   case Special:  OS << "Special"; break;
1589   case ICmpZero: OS << "ICmpZero"; break;
1590   case Address:
1591     OS << "Address of ";
1592     if (AccessTy.MemTy->isPointerTy())
1593       OS << "pointer"; // the full pointer type could be really verbose
1594     else {
1595       OS << *AccessTy.MemTy;
1596     }
1597 
1598     OS << " in addrspace(" << AccessTy.AddrSpace << ')';
1599   }
1600 
1601   OS << ", Offsets={";
1602   bool NeedComma = false;
1603   for (const LSRFixup &Fixup : Fixups) {
1604     if (NeedComma) OS << ',';
1605     OS << Fixup.Offset;
1606     NeedComma = true;
1607   }
1608   OS << '}';
1609 
1610   if (AllFixupsOutsideLoop)
1611     OS << ", all-fixups-outside-loop";
1612 
1613   if (WidestFixupType)
1614     OS << ", widest fixup type: " << *WidestFixupType;
1615 }
1616 
1617 LLVM_DUMP_METHOD void LSRUse::dump() const {
1618   print(errs()); errs() << '\n';
1619 }
1620 #endif
1621 
1622 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1623                                  LSRUse::KindType Kind, MemAccessTy AccessTy,
1624                                  GlobalValue *BaseGV, int64_t BaseOffset,
1625                                  bool HasBaseReg, int64_t Scale,
1626                                  Instruction *Fixup/*= nullptr*/) {
1627   switch (Kind) {
1628   case LSRUse::Address:
1629     return TTI.isLegalAddressingMode(AccessTy.MemTy, BaseGV, BaseOffset,
1630                                      HasBaseReg, Scale, AccessTy.AddrSpace, Fixup);
1631 
1632   case LSRUse::ICmpZero:
1633     // There's not even a target hook for querying whether it would be legal to
1634     // fold a GV into an ICmp.
1635     if (BaseGV)
1636       return false;
1637 
1638     // ICmp only has two operands; don't allow more than two non-trivial parts.
1639     if (Scale != 0 && HasBaseReg && BaseOffset != 0)
1640       return false;
1641 
1642     // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
1643     // putting the scaled register in the other operand of the icmp.
1644     if (Scale != 0 && Scale != -1)
1645       return false;
1646 
1647     // If we have low-level target information, ask the target if it can fold an
1648     // integer immediate on an icmp.
1649     if (BaseOffset != 0) {
1650       // We have one of:
1651       // ICmpZero     BaseReg + BaseOffset => ICmp BaseReg, -BaseOffset
1652       // ICmpZero -1*ScaleReg + BaseOffset => ICmp ScaleReg, BaseOffset
1653       // Offs is the ICmp immediate.
1654       if (Scale == 0)
1655         // The cast does the right thing with
1656         // std::numeric_limits<int64_t>::min().
1657         BaseOffset = -(uint64_t)BaseOffset;
1658       return TTI.isLegalICmpImmediate(BaseOffset);
1659     }
1660 
1661     // ICmpZero BaseReg + -1*ScaleReg => ICmp BaseReg, ScaleReg
1662     return true;
1663 
1664   case LSRUse::Basic:
1665     // Only handle single-register values.
1666     return !BaseGV && Scale == 0 && BaseOffset == 0;
1667 
1668   case LSRUse::Special:
1669     // Special case Basic to handle -1 scales.
1670     return !BaseGV && (Scale == 0 || Scale == -1) && BaseOffset == 0;
1671   }
1672 
1673   llvm_unreachable("Invalid LSRUse Kind!");
1674 }
1675 
1676 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1677                                  int64_t MinOffset, int64_t MaxOffset,
1678                                  LSRUse::KindType Kind, MemAccessTy AccessTy,
1679                                  GlobalValue *BaseGV, int64_t BaseOffset,
1680                                  bool HasBaseReg, int64_t Scale) {
1681   // Check for overflow.
1682   if (((int64_t)((uint64_t)BaseOffset + MinOffset) > BaseOffset) !=
1683       (MinOffset > 0))
1684     return false;
1685   MinOffset = (uint64_t)BaseOffset + MinOffset;
1686   if (((int64_t)((uint64_t)BaseOffset + MaxOffset) > BaseOffset) !=
1687       (MaxOffset > 0))
1688     return false;
1689   MaxOffset = (uint64_t)BaseOffset + MaxOffset;
1690 
1691   return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MinOffset,
1692                               HasBaseReg, Scale) &&
1693          isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MaxOffset,
1694                               HasBaseReg, Scale);
1695 }
1696 
1697 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1698                                  int64_t MinOffset, int64_t MaxOffset,
1699                                  LSRUse::KindType Kind, MemAccessTy AccessTy,
1700                                  const Formula &F, const Loop &L) {
1701   // For the purpose of isAMCompletelyFolded either having a canonical formula
1702   // or a scale not equal to zero is correct.
1703   // Problems may arise from non canonical formulae having a scale == 0.
1704   // Strictly speaking it would best to just rely on canonical formulae.
1705   // However, when we generate the scaled formulae, we first check that the
1706   // scaling factor is profitable before computing the actual ScaledReg for
1707   // compile time sake.
1708   assert((F.isCanonical(L) || F.Scale != 0));
1709   return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
1710                               F.BaseGV, F.BaseOffset, F.HasBaseReg, F.Scale);
1711 }
1712 
1713 /// Test whether we know how to expand the current formula.
1714 static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset,
1715                        int64_t MaxOffset, LSRUse::KindType Kind,
1716                        MemAccessTy AccessTy, GlobalValue *BaseGV,
1717                        int64_t BaseOffset, bool HasBaseReg, int64_t Scale) {
1718   // We know how to expand completely foldable formulae.
1719   return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
1720                               BaseOffset, HasBaseReg, Scale) ||
1721          // Or formulae that use a base register produced by a sum of base
1722          // registers.
1723          (Scale == 1 &&
1724           isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
1725                                BaseGV, BaseOffset, true, 0));
1726 }
1727 
1728 static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset,
1729                        int64_t MaxOffset, LSRUse::KindType Kind,
1730                        MemAccessTy AccessTy, const Formula &F) {
1731   return isLegalUse(TTI, MinOffset, MaxOffset, Kind, AccessTy, F.BaseGV,
1732                     F.BaseOffset, F.HasBaseReg, F.Scale);
1733 }
1734 
1735 static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1736                                  const LSRUse &LU, const Formula &F) {
1737   // Target may want to look at the user instructions.
1738   if (LU.Kind == LSRUse::Address && TTI.LSRWithInstrQueries()) {
1739     for (const LSRFixup &Fixup : LU.Fixups)
1740       if (!isAMCompletelyFolded(TTI, LSRUse::Address, LU.AccessTy, F.BaseGV,
1741                                 (F.BaseOffset + Fixup.Offset), F.HasBaseReg,
1742                                 F.Scale, Fixup.UserInst))
1743         return false;
1744     return true;
1745   }
1746 
1747   return isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,
1748                               LU.AccessTy, F.BaseGV, F.BaseOffset, F.HasBaseReg,
1749                               F.Scale);
1750 }
1751 
1752 static unsigned getScalingFactorCost(const TargetTransformInfo &TTI,
1753                                      const LSRUse &LU, const Formula &F,
1754                                      const Loop &L) {
1755   if (!F.Scale)
1756     return 0;
1757 
1758   // If the use is not completely folded in that instruction, we will have to
1759   // pay an extra cost only for scale != 1.
1760   if (!isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,
1761                             LU.AccessTy, F, L))
1762     return F.Scale != 1;
1763 
1764   switch (LU.Kind) {
1765   case LSRUse::Address: {
1766     // Check the scaling factor cost with both the min and max offsets.
1767     int ScaleCostMinOffset = TTI.getScalingFactorCost(
1768         LU.AccessTy.MemTy, F.BaseGV, F.BaseOffset + LU.MinOffset, F.HasBaseReg,
1769         F.Scale, LU.AccessTy.AddrSpace);
1770     int ScaleCostMaxOffset = TTI.getScalingFactorCost(
1771         LU.AccessTy.MemTy, F.BaseGV, F.BaseOffset + LU.MaxOffset, F.HasBaseReg,
1772         F.Scale, LU.AccessTy.AddrSpace);
1773 
1774     assert(ScaleCostMinOffset >= 0 && ScaleCostMaxOffset >= 0 &&
1775            "Legal addressing mode has an illegal cost!");
1776     return std::max(ScaleCostMinOffset, ScaleCostMaxOffset);
1777   }
1778   case LSRUse::ICmpZero:
1779   case LSRUse::Basic:
1780   case LSRUse::Special:
1781     // The use is completely folded, i.e., everything is folded into the
1782     // instruction.
1783     return 0;
1784   }
1785 
1786   llvm_unreachable("Invalid LSRUse Kind!");
1787 }
1788 
1789 static bool isAlwaysFoldable(const TargetTransformInfo &TTI,
1790                              LSRUse::KindType Kind, MemAccessTy AccessTy,
1791                              GlobalValue *BaseGV, int64_t BaseOffset,
1792                              bool HasBaseReg) {
1793   // Fast-path: zero is always foldable.
1794   if (BaseOffset == 0 && !BaseGV) return true;
1795 
1796   // Conservatively, create an address with an immediate and a
1797   // base and a scale.
1798   int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1799 
1800   // Canonicalize a scale of 1 to a base register if the formula doesn't
1801   // already have a base register.
1802   if (!HasBaseReg && Scale == 1) {
1803     Scale = 0;
1804     HasBaseReg = true;
1805   }
1806 
1807   return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, BaseOffset,
1808                               HasBaseReg, Scale);
1809 }
1810 
1811 static bool isAlwaysFoldable(const TargetTransformInfo &TTI,
1812                              ScalarEvolution &SE, int64_t MinOffset,
1813                              int64_t MaxOffset, LSRUse::KindType Kind,
1814                              MemAccessTy AccessTy, const SCEV *S,
1815                              bool HasBaseReg) {
1816   // Fast-path: zero is always foldable.
1817   if (S->isZero()) return true;
1818 
1819   // Conservatively, create an address with an immediate and a
1820   // base and a scale.
1821   int64_t BaseOffset = ExtractImmediate(S, SE);
1822   GlobalValue *BaseGV = ExtractSymbol(S, SE);
1823 
1824   // If there's anything else involved, it's not foldable.
1825   if (!S->isZero()) return false;
1826 
1827   // Fast-path: zero is always foldable.
1828   if (BaseOffset == 0 && !BaseGV) return true;
1829 
1830   // Conservatively, create an address with an immediate and a
1831   // base and a scale.
1832   int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1833 
1834   return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
1835                               BaseOffset, HasBaseReg, Scale);
1836 }
1837 
1838 namespace {
1839 
1840 /// An individual increment in a Chain of IV increments.  Relate an IV user to
1841 /// an expression that computes the IV it uses from the IV used by the previous
1842 /// link in the Chain.
1843 ///
1844 /// For the head of a chain, IncExpr holds the absolute SCEV expression for the
1845 /// original IVOperand. The head of the chain's IVOperand is only valid during
1846 /// chain collection, before LSR replaces IV users. During chain generation,
1847 /// IncExpr can be used to find the new IVOperand that computes the same
1848 /// expression.
1849 struct IVInc {
1850   Instruction *UserInst;
1851   Value* IVOperand;
1852   const SCEV *IncExpr;
1853 
1854   IVInc(Instruction *U, Value *O, const SCEV *E)
1855       : UserInst(U), IVOperand(O), IncExpr(E) {}
1856 };
1857 
1858 // The list of IV increments in program order.  We typically add the head of a
1859 // chain without finding subsequent links.
1860 struct IVChain {
1861   SmallVector<IVInc, 1> Incs;
1862   const SCEV *ExprBase = nullptr;
1863 
1864   IVChain() = default;
1865   IVChain(const IVInc &Head, const SCEV *Base)
1866       : Incs(1, Head), ExprBase(Base) {}
1867 
1868   using const_iterator = SmallVectorImpl<IVInc>::const_iterator;
1869 
1870   // Return the first increment in the chain.
1871   const_iterator begin() const {
1872     assert(!Incs.empty());
1873     return std::next(Incs.begin());
1874   }
1875   const_iterator end() const {
1876     return Incs.end();
1877   }
1878 
1879   // Returns true if this chain contains any increments.
1880   bool hasIncs() const { return Incs.size() >= 2; }
1881 
1882   // Add an IVInc to the end of this chain.
1883   void add(const IVInc &X) { Incs.push_back(X); }
1884 
1885   // Returns the last UserInst in the chain.
1886   Instruction *tailUserInst() const { return Incs.back().UserInst; }
1887 
1888   // Returns true if IncExpr can be profitably added to this chain.
1889   bool isProfitableIncrement(const SCEV *OperExpr,
1890                              const SCEV *IncExpr,
1891                              ScalarEvolution&);
1892 };
1893 
1894 /// Helper for CollectChains to track multiple IV increment uses.  Distinguish
1895 /// between FarUsers that definitely cross IV increments and NearUsers that may
1896 /// be used between IV increments.
1897 struct ChainUsers {
1898   SmallPtrSet<Instruction*, 4> FarUsers;
1899   SmallPtrSet<Instruction*, 4> NearUsers;
1900 };
1901 
1902 /// This class holds state for the main loop strength reduction logic.
1903 class LSRInstance {
1904   IVUsers &IU;
1905   ScalarEvolution &SE;
1906   DominatorTree &DT;
1907   LoopInfo &LI;
1908   AssumptionCache &AC;
1909   TargetLibraryInfo &TLI;
1910   const TargetTransformInfo &TTI;
1911   Loop *const L;
1912   MemorySSAUpdater *MSSAU;
1913   bool FavorBackedgeIndex = false;
1914   bool Changed = false;
1915 
1916   /// This is the insert position that the current loop's induction variable
1917   /// increment should be placed. In simple loops, this is the latch block's
1918   /// terminator. But in more complicated cases, this is a position which will
1919   /// dominate all the in-loop post-increment users.
1920   Instruction *IVIncInsertPos = nullptr;
1921 
1922   /// Interesting factors between use strides.
1923   ///
1924   /// We explicitly use a SetVector which contains a SmallSet, instead of the
1925   /// default, a SmallDenseSet, because we need to use the full range of
1926   /// int64_ts, and there's currently no good way of doing that with
1927   /// SmallDenseSet.
1928   SetVector<int64_t, SmallVector<int64_t, 8>, SmallSet<int64_t, 8>> Factors;
1929 
1930   /// Interesting use types, to facilitate truncation reuse.
1931   SmallSetVector<Type *, 4> Types;
1932 
1933   /// The list of interesting uses.
1934   mutable SmallVector<LSRUse, 16> Uses;
1935 
1936   /// Track which uses use which register candidates.
1937   RegUseTracker RegUses;
1938 
1939   // Limit the number of chains to avoid quadratic behavior. We don't expect to
1940   // have more than a few IV increment chains in a loop. Missing a Chain falls
1941   // back to normal LSR behavior for those uses.
1942   static const unsigned MaxChains = 8;
1943 
1944   /// IV users can form a chain of IV increments.
1945   SmallVector<IVChain, MaxChains> IVChainVec;
1946 
1947   /// IV users that belong to profitable IVChains.
1948   SmallPtrSet<Use*, MaxChains> IVIncSet;
1949 
1950   void OptimizeShadowIV();
1951   bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
1952   ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
1953   void OptimizeLoopTermCond();
1954 
1955   void ChainInstruction(Instruction *UserInst, Instruction *IVOper,
1956                         SmallVectorImpl<ChainUsers> &ChainUsersVec);
1957   void FinalizeChain(IVChain &Chain);
1958   void CollectChains();
1959   void GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter,
1960                        SmallVectorImpl<WeakTrackingVH> &DeadInsts);
1961 
1962   void CollectInterestingTypesAndFactors();
1963   void CollectFixupsAndInitialFormulae();
1964 
1965   // Support for sharing of LSRUses between LSRFixups.
1966   using UseMapTy = DenseMap<LSRUse::SCEVUseKindPair, size_t>;
1967   UseMapTy UseMap;
1968 
1969   bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
1970                           LSRUse::KindType Kind, MemAccessTy AccessTy);
1971 
1972   std::pair<size_t, int64_t> getUse(const SCEV *&Expr, LSRUse::KindType Kind,
1973                                     MemAccessTy AccessTy);
1974 
1975   void DeleteUse(LSRUse &LU, size_t LUIdx);
1976 
1977   LSRUse *FindUseWithSimilarFormula(const Formula &F, const LSRUse &OrigLU);
1978 
1979   void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1980   void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1981   void CountRegisters(const Formula &F, size_t LUIdx);
1982   bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
1983 
1984   void CollectLoopInvariantFixupsAndFormulae();
1985 
1986   void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
1987                               unsigned Depth = 0);
1988 
1989   void GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
1990                                   const Formula &Base, unsigned Depth,
1991                                   size_t Idx, bool IsScaledReg = false);
1992   void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
1993   void GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
1994                                    const Formula &Base, size_t Idx,
1995                                    bool IsScaledReg = false);
1996   void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1997   void GenerateConstantOffsetsImpl(LSRUse &LU, unsigned LUIdx,
1998                                    const Formula &Base,
1999                                    const SmallVectorImpl<int64_t> &Worklist,
2000                                    size_t Idx, bool IsScaledReg = false);
2001   void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
2002   void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
2003   void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
2004   void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
2005   void GenerateCrossUseConstantOffsets();
2006   void GenerateAllReuseFormulae();
2007 
2008   void FilterOutUndesirableDedicatedRegisters();
2009 
2010   size_t EstimateSearchSpaceComplexity() const;
2011   void NarrowSearchSpaceByDetectingSupersets();
2012   void NarrowSearchSpaceByCollapsingUnrolledCode();
2013   void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
2014   void NarrowSearchSpaceByFilterFormulaWithSameScaledReg();
2015   void NarrowSearchSpaceByFilterPostInc();
2016   void NarrowSearchSpaceByDeletingCostlyFormulas();
2017   void NarrowSearchSpaceByPickingWinnerRegs();
2018   void NarrowSearchSpaceUsingHeuristics();
2019 
2020   void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
2021                     Cost &SolutionCost,
2022                     SmallVectorImpl<const Formula *> &Workspace,
2023                     const Cost &CurCost,
2024                     const SmallPtrSet<const SCEV *, 16> &CurRegs,
2025                     DenseSet<const SCEV *> &VisitedRegs) const;
2026   void Solve(SmallVectorImpl<const Formula *> &Solution) const;
2027 
2028   BasicBlock::iterator
2029     HoistInsertPosition(BasicBlock::iterator IP,
2030                         const SmallVectorImpl<Instruction *> &Inputs) const;
2031   BasicBlock::iterator
2032     AdjustInsertPositionForExpand(BasicBlock::iterator IP,
2033                                   const LSRFixup &LF,
2034                                   const LSRUse &LU,
2035                                   SCEVExpander &Rewriter) const;
2036 
2037   Value *Expand(const LSRUse &LU, const LSRFixup &LF, const Formula &F,
2038                 BasicBlock::iterator IP, SCEVExpander &Rewriter,
2039                 SmallVectorImpl<WeakTrackingVH> &DeadInsts) const;
2040   void RewriteForPHI(PHINode *PN, const LSRUse &LU, const LSRFixup &LF,
2041                      const Formula &F, SCEVExpander &Rewriter,
2042                      SmallVectorImpl<WeakTrackingVH> &DeadInsts) const;
2043   void Rewrite(const LSRUse &LU, const LSRFixup &LF, const Formula &F,
2044                SCEVExpander &Rewriter,
2045                SmallVectorImpl<WeakTrackingVH> &DeadInsts) const;
2046   void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution);
2047 
2048 public:
2049   LSRInstance(Loop *L, IVUsers &IU, ScalarEvolution &SE, DominatorTree &DT,
2050               LoopInfo &LI, const TargetTransformInfo &TTI, AssumptionCache &AC,
2051               TargetLibraryInfo &TLI, MemorySSAUpdater *MSSAU);
2052 
2053   bool getChanged() const { return Changed; }
2054 
2055   void print_factors_and_types(raw_ostream &OS) const;
2056   void print_fixups(raw_ostream &OS) const;
2057   void print_uses(raw_ostream &OS) const;
2058   void print(raw_ostream &OS) const;
2059   void dump() const;
2060 };
2061 
2062 } // end anonymous namespace
2063 
2064 /// If IV is used in a int-to-float cast inside the loop then try to eliminate
2065 /// the cast operation.
2066 void LSRInstance::OptimizeShadowIV() {
2067   const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
2068   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2069     return;
2070 
2071   for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
2072        UI != E; /* empty */) {
2073     IVUsers::const_iterator CandidateUI = UI;
2074     ++UI;
2075     Instruction *ShadowUse = CandidateUI->getUser();
2076     Type *DestTy = nullptr;
2077     bool IsSigned = false;
2078 
2079     /* If shadow use is a int->float cast then insert a second IV
2080        to eliminate this cast.
2081 
2082          for (unsigned i = 0; i < n; ++i)
2083            foo((double)i);
2084 
2085        is transformed into
2086 
2087          double d = 0.0;
2088          for (unsigned i = 0; i < n; ++i, ++d)
2089            foo(d);
2090     */
2091     if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser())) {
2092       IsSigned = false;
2093       DestTy = UCast->getDestTy();
2094     }
2095     else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser())) {
2096       IsSigned = true;
2097       DestTy = SCast->getDestTy();
2098     }
2099     if (!DestTy) continue;
2100 
2101     // If target does not support DestTy natively then do not apply
2102     // this transformation.
2103     if (!TTI.isTypeLegal(DestTy)) continue;
2104 
2105     PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
2106     if (!PH) continue;
2107     if (PH->getNumIncomingValues() != 2) continue;
2108 
2109     // If the calculation in integers overflows, the result in FP type will
2110     // differ. So we only can do this transformation if we are guaranteed to not
2111     // deal with overflowing values
2112     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(PH));
2113     if (!AR) continue;
2114     if (IsSigned && !AR->hasNoSignedWrap()) continue;
2115     if (!IsSigned && !AR->hasNoUnsignedWrap()) continue;
2116 
2117     Type *SrcTy = PH->getType();
2118     int Mantissa = DestTy->getFPMantissaWidth();
2119     if (Mantissa == -1) continue;
2120     if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
2121       continue;
2122 
2123     unsigned Entry, Latch;
2124     if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
2125       Entry = 0;
2126       Latch = 1;
2127     } else {
2128       Entry = 1;
2129       Latch = 0;
2130     }
2131 
2132     ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
2133     if (!Init) continue;
2134     Constant *NewInit = ConstantFP::get(DestTy, IsSigned ?
2135                                         (double)Init->getSExtValue() :
2136                                         (double)Init->getZExtValue());
2137 
2138     BinaryOperator *Incr =
2139       dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
2140     if (!Incr) continue;
2141     if (Incr->getOpcode() != Instruction::Add
2142         && Incr->getOpcode() != Instruction::Sub)
2143       continue;
2144 
2145     /* Initialize new IV, double d = 0.0 in above example. */
2146     ConstantInt *C = nullptr;
2147     if (Incr->getOperand(0) == PH)
2148       C = dyn_cast<ConstantInt>(Incr->getOperand(1));
2149     else if (Incr->getOperand(1) == PH)
2150       C = dyn_cast<ConstantInt>(Incr->getOperand(0));
2151     else
2152       continue;
2153 
2154     if (!C) continue;
2155 
2156     // Ignore negative constants, as the code below doesn't handle them
2157     // correctly. TODO: Remove this restriction.
2158     if (!C->getValue().isStrictlyPositive()) continue;
2159 
2160     /* Add new PHINode. */
2161     PHINode *NewPH = PHINode::Create(DestTy, 2, "IV.S.", PH);
2162 
2163     /* create new increment. '++d' in above example. */
2164     Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
2165     BinaryOperator *NewIncr =
2166       BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
2167                                Instruction::FAdd : Instruction::FSub,
2168                              NewPH, CFP, "IV.S.next.", Incr);
2169 
2170     NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
2171     NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
2172 
2173     /* Remove cast operation */
2174     ShadowUse->replaceAllUsesWith(NewPH);
2175     ShadowUse->eraseFromParent();
2176     Changed = true;
2177     break;
2178   }
2179 }
2180 
2181 /// If Cond has an operand that is an expression of an IV, set the IV user and
2182 /// stride information and return true, otherwise return false.
2183 bool LSRInstance::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse) {
2184   for (IVStrideUse &U : IU)
2185     if (U.getUser() == Cond) {
2186       // NOTE: we could handle setcc instructions with multiple uses here, but
2187       // InstCombine does it as well for simple uses, it's not clear that it
2188       // occurs enough in real life to handle.
2189       CondUse = &U;
2190       return true;
2191     }
2192   return false;
2193 }
2194 
2195 /// Rewrite the loop's terminating condition if it uses a max computation.
2196 ///
2197 /// This is a narrow solution to a specific, but acute, problem. For loops
2198 /// like this:
2199 ///
2200 ///   i = 0;
2201 ///   do {
2202 ///     p[i] = 0.0;
2203 ///   } while (++i < n);
2204 ///
2205 /// the trip count isn't just 'n', because 'n' might not be positive. And
2206 /// unfortunately this can come up even for loops where the user didn't use
2207 /// a C do-while loop. For example, seemingly well-behaved top-test loops
2208 /// will commonly be lowered like this:
2209 ///
2210 ///   if (n > 0) {
2211 ///     i = 0;
2212 ///     do {
2213 ///       p[i] = 0.0;
2214 ///     } while (++i < n);
2215 ///   }
2216 ///
2217 /// and then it's possible for subsequent optimization to obscure the if
2218 /// test in such a way that indvars can't find it.
2219 ///
2220 /// When indvars can't find the if test in loops like this, it creates a
2221 /// max expression, which allows it to give the loop a canonical
2222 /// induction variable:
2223 ///
2224 ///   i = 0;
2225 ///   max = n < 1 ? 1 : n;
2226 ///   do {
2227 ///     p[i] = 0.0;
2228 ///   } while (++i != max);
2229 ///
2230 /// Canonical induction variables are necessary because the loop passes
2231 /// are designed around them. The most obvious example of this is the
2232 /// LoopInfo analysis, which doesn't remember trip count values. It
2233 /// expects to be able to rediscover the trip count each time it is
2234 /// needed, and it does this using a simple analysis that only succeeds if
2235 /// the loop has a canonical induction variable.
2236 ///
2237 /// However, when it comes time to generate code, the maximum operation
2238 /// can be quite costly, especially if it's inside of an outer loop.
2239 ///
2240 /// This function solves this problem by detecting this type of loop and
2241 /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
2242 /// the instructions for the maximum computation.
2243 ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
2244   // Check that the loop matches the pattern we're looking for.
2245   if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
2246       Cond->getPredicate() != CmpInst::ICMP_NE)
2247     return Cond;
2248 
2249   SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
2250   if (!Sel || !Sel->hasOneUse()) return Cond;
2251 
2252   const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
2253   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2254     return Cond;
2255   const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1);
2256 
2257   // Add one to the backedge-taken count to get the trip count.
2258   const SCEV *IterationCount = SE.getAddExpr(One, BackedgeTakenCount);
2259   if (IterationCount != SE.getSCEV(Sel)) return Cond;
2260 
2261   // Check for a max calculation that matches the pattern. There's no check
2262   // for ICMP_ULE here because the comparison would be with zero, which
2263   // isn't interesting.
2264   CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
2265   const SCEVNAryExpr *Max = nullptr;
2266   if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) {
2267     Pred = ICmpInst::ICMP_SLE;
2268     Max = S;
2269   } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) {
2270     Pred = ICmpInst::ICMP_SLT;
2271     Max = S;
2272   } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) {
2273     Pred = ICmpInst::ICMP_ULT;
2274     Max = U;
2275   } else {
2276     // No match; bail.
2277     return Cond;
2278   }
2279 
2280   // To handle a max with more than two operands, this optimization would
2281   // require additional checking and setup.
2282   if (Max->getNumOperands() != 2)
2283     return Cond;
2284 
2285   const SCEV *MaxLHS = Max->getOperand(0);
2286   const SCEV *MaxRHS = Max->getOperand(1);
2287 
2288   // ScalarEvolution canonicalizes constants to the left. For < and >, look
2289   // for a comparison with 1. For <= and >=, a comparison with zero.
2290   if (!MaxLHS ||
2291       (ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One)))
2292     return Cond;
2293 
2294   // Check the relevant induction variable for conformance to
2295   // the pattern.
2296   const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
2297   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2298   if (!AR || !AR->isAffine() ||
2299       AR->getStart() != One ||
2300       AR->getStepRecurrence(SE) != One)
2301     return Cond;
2302 
2303   assert(AR->getLoop() == L &&
2304          "Loop condition operand is an addrec in a different loop!");
2305 
2306   // Check the right operand of the select, and remember it, as it will
2307   // be used in the new comparison instruction.
2308   Value *NewRHS = nullptr;
2309   if (ICmpInst::isTrueWhenEqual(Pred)) {
2310     // Look for n+1, and grab n.
2311     if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1)))
2312       if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
2313          if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)
2314            NewRHS = BO->getOperand(0);
2315     if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2)))
2316       if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
2317         if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)
2318           NewRHS = BO->getOperand(0);
2319     if (!NewRHS)
2320       return Cond;
2321   } else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
2322     NewRHS = Sel->getOperand(1);
2323   else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
2324     NewRHS = Sel->getOperand(2);
2325   else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(MaxRHS))
2326     NewRHS = SU->getValue();
2327   else
2328     // Max doesn't match expected pattern.
2329     return Cond;
2330 
2331   // Determine the new comparison opcode. It may be signed or unsigned,
2332   // and the original comparison may be either equality or inequality.
2333   if (Cond->getPredicate() == CmpInst::ICMP_EQ)
2334     Pred = CmpInst::getInversePredicate(Pred);
2335 
2336   // Ok, everything looks ok to change the condition into an SLT or SGE and
2337   // delete the max calculation.
2338   ICmpInst *NewCond =
2339     new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
2340 
2341   // Delete the max calculation instructions.
2342   Cond->replaceAllUsesWith(NewCond);
2343   CondUse->setUser(NewCond);
2344   Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
2345   Cond->eraseFromParent();
2346   Sel->eraseFromParent();
2347   if (Cmp->use_empty())
2348     Cmp->eraseFromParent();
2349   return NewCond;
2350 }
2351 
2352 /// Change loop terminating condition to use the postinc iv when possible.
2353 void
2354 LSRInstance::OptimizeLoopTermCond() {
2355   SmallPtrSet<Instruction *, 4> PostIncs;
2356 
2357   // We need a different set of heuristics for rotated and non-rotated loops.
2358   // If a loop is rotated then the latch is also the backedge, so inserting
2359   // post-inc expressions just before the latch is ideal. To reduce live ranges
2360   // it also makes sense to rewrite terminating conditions to use post-inc
2361   // expressions.
2362   //
2363   // If the loop is not rotated then the latch is not a backedge; the latch
2364   // check is done in the loop head. Adding post-inc expressions before the
2365   // latch will cause overlapping live-ranges of pre-inc and post-inc expressions
2366   // in the loop body. In this case we do *not* want to use post-inc expressions
2367   // in the latch check, and we want to insert post-inc expressions before
2368   // the backedge.
2369   BasicBlock *LatchBlock = L->getLoopLatch();
2370   SmallVector<BasicBlock*, 8> ExitingBlocks;
2371   L->getExitingBlocks(ExitingBlocks);
2372   if (llvm::all_of(ExitingBlocks, [&LatchBlock](const BasicBlock *BB) {
2373         return LatchBlock != BB;
2374       })) {
2375     // The backedge doesn't exit the loop; treat this as a head-tested loop.
2376     IVIncInsertPos = LatchBlock->getTerminator();
2377     return;
2378   }
2379 
2380   // Otherwise treat this as a rotated loop.
2381   for (BasicBlock *ExitingBlock : ExitingBlocks) {
2382     // Get the terminating condition for the loop if possible.  If we
2383     // can, we want to change it to use a post-incremented version of its
2384     // induction variable, to allow coalescing the live ranges for the IV into
2385     // one register value.
2386 
2387     BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2388     if (!TermBr)
2389       continue;
2390     // FIXME: Overly conservative, termination condition could be an 'or' etc..
2391     if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
2392       continue;
2393 
2394     // Search IVUsesByStride to find Cond's IVUse if there is one.
2395     IVStrideUse *CondUse = nullptr;
2396     ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
2397     if (!FindIVUserForCond(Cond, CondUse))
2398       continue;
2399 
2400     // If the trip count is computed in terms of a max (due to ScalarEvolution
2401     // being unable to find a sufficient guard, for example), change the loop
2402     // comparison to use SLT or ULT instead of NE.
2403     // One consequence of doing this now is that it disrupts the count-down
2404     // optimization. That's not always a bad thing though, because in such
2405     // cases it may still be worthwhile to avoid a max.
2406     Cond = OptimizeMax(Cond, CondUse);
2407 
2408     // If this exiting block dominates the latch block, it may also use
2409     // the post-inc value if it won't be shared with other uses.
2410     // Check for dominance.
2411     if (!DT.dominates(ExitingBlock, LatchBlock))
2412       continue;
2413 
2414     // Conservatively avoid trying to use the post-inc value in non-latch
2415     // exits if there may be pre-inc users in intervening blocks.
2416     if (LatchBlock != ExitingBlock)
2417       for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
2418         // Test if the use is reachable from the exiting block. This dominator
2419         // query is a conservative approximation of reachability.
2420         if (&*UI != CondUse &&
2421             !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
2422           // Conservatively assume there may be reuse if the quotient of their
2423           // strides could be a legal scale.
2424           const SCEV *A = IU.getStride(*CondUse, L);
2425           const SCEV *B = IU.getStride(*UI, L);
2426           if (!A || !B) continue;
2427           if (SE.getTypeSizeInBits(A->getType()) !=
2428               SE.getTypeSizeInBits(B->getType())) {
2429             if (SE.getTypeSizeInBits(A->getType()) >
2430                 SE.getTypeSizeInBits(B->getType()))
2431               B = SE.getSignExtendExpr(B, A->getType());
2432             else
2433               A = SE.getSignExtendExpr(A, B->getType());
2434           }
2435           if (const SCEVConstant *D =
2436                 dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {
2437             const ConstantInt *C = D->getValue();
2438             // Stride of one or negative one can have reuse with non-addresses.
2439             if (C->isOne() || C->isMinusOne())
2440               goto decline_post_inc;
2441             // Avoid weird situations.
2442             if (C->getValue().getMinSignedBits() >= 64 ||
2443                 C->getValue().isMinSignedValue())
2444               goto decline_post_inc;
2445             // Check for possible scaled-address reuse.
2446             if (isAddressUse(TTI, UI->getUser(), UI->getOperandValToReplace())) {
2447               MemAccessTy AccessTy = getAccessType(
2448                   TTI, UI->getUser(), UI->getOperandValToReplace());
2449               int64_t Scale = C->getSExtValue();
2450               if (TTI.isLegalAddressingMode(AccessTy.MemTy, /*BaseGV=*/nullptr,
2451                                             /*BaseOffset=*/0,
2452                                             /*HasBaseReg=*/false, Scale,
2453                                             AccessTy.AddrSpace))
2454                 goto decline_post_inc;
2455               Scale = -Scale;
2456               if (TTI.isLegalAddressingMode(AccessTy.MemTy, /*BaseGV=*/nullptr,
2457                                             /*BaseOffset=*/0,
2458                                             /*HasBaseReg=*/false, Scale,
2459                                             AccessTy.AddrSpace))
2460                 goto decline_post_inc;
2461             }
2462           }
2463         }
2464 
2465     LLVM_DEBUG(dbgs() << "  Change loop exiting icmp to use postinc iv: "
2466                       << *Cond << '\n');
2467 
2468     // It's possible for the setcc instruction to be anywhere in the loop, and
2469     // possible for it to have multiple users.  If it is not immediately before
2470     // the exiting block branch, move it.
2471     if (&*++BasicBlock::iterator(Cond) != TermBr) {
2472       if (Cond->hasOneUse()) {
2473         Cond->moveBefore(TermBr);
2474       } else {
2475         // Clone the terminating condition and insert into the loopend.
2476         ICmpInst *OldCond = Cond;
2477         Cond = cast<ICmpInst>(Cond->clone());
2478         Cond->setName(L->getHeader()->getName() + ".termcond");
2479         ExitingBlock->getInstList().insert(TermBr->getIterator(), Cond);
2480 
2481         // Clone the IVUse, as the old use still exists!
2482         CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());
2483         TermBr->replaceUsesOfWith(OldCond, Cond);
2484       }
2485     }
2486 
2487     // If we get to here, we know that we can transform the setcc instruction to
2488     // use the post-incremented version of the IV, allowing us to coalesce the
2489     // live ranges for the IV correctly.
2490     CondUse->transformToPostInc(L);
2491     Changed = true;
2492 
2493     PostIncs.insert(Cond);
2494   decline_post_inc:;
2495   }
2496 
2497   // Determine an insertion point for the loop induction variable increment. It
2498   // must dominate all the post-inc comparisons we just set up, and it must
2499   // dominate the loop latch edge.
2500   IVIncInsertPos = L->getLoopLatch()->getTerminator();
2501   for (Instruction *Inst : PostIncs) {
2502     BasicBlock *BB =
2503       DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
2504                                     Inst->getParent());
2505     if (BB == Inst->getParent())
2506       IVIncInsertPos = Inst;
2507     else if (BB != IVIncInsertPos->getParent())
2508       IVIncInsertPos = BB->getTerminator();
2509   }
2510 }
2511 
2512 /// Determine if the given use can accommodate a fixup at the given offset and
2513 /// other details. If so, update the use and return true.
2514 bool LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
2515                                      bool HasBaseReg, LSRUse::KindType Kind,
2516                                      MemAccessTy AccessTy) {
2517   int64_t NewMinOffset = LU.MinOffset;
2518   int64_t NewMaxOffset = LU.MaxOffset;
2519   MemAccessTy NewAccessTy = AccessTy;
2520 
2521   // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
2522   // something conservative, however this can pessimize in the case that one of
2523   // the uses will have all its uses outside the loop, for example.
2524   if (LU.Kind != Kind)
2525     return false;
2526 
2527   // Check for a mismatched access type, and fall back conservatively as needed.
2528   // TODO: Be less conservative when the type is similar and can use the same
2529   // addressing modes.
2530   if (Kind == LSRUse::Address) {
2531     if (AccessTy.MemTy != LU.AccessTy.MemTy) {
2532       NewAccessTy = MemAccessTy::getUnknown(AccessTy.MemTy->getContext(),
2533                                             AccessTy.AddrSpace);
2534     }
2535   }
2536 
2537   // Conservatively assume HasBaseReg is true for now.
2538   if (NewOffset < LU.MinOffset) {
2539     if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,
2540                           LU.MaxOffset - NewOffset, HasBaseReg))
2541       return false;
2542     NewMinOffset = NewOffset;
2543   } else if (NewOffset > LU.MaxOffset) {
2544     if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,
2545                           NewOffset - LU.MinOffset, HasBaseReg))
2546       return false;
2547     NewMaxOffset = NewOffset;
2548   }
2549 
2550   // Update the use.
2551   LU.MinOffset = NewMinOffset;
2552   LU.MaxOffset = NewMaxOffset;
2553   LU.AccessTy = NewAccessTy;
2554   return true;
2555 }
2556 
2557 /// Return an LSRUse index and an offset value for a fixup which needs the given
2558 /// expression, with the given kind and optional access type.  Either reuse an
2559 /// existing use or create a new one, as needed.
2560 std::pair<size_t, int64_t> LSRInstance::getUse(const SCEV *&Expr,
2561                                                LSRUse::KindType Kind,
2562                                                MemAccessTy AccessTy) {
2563   const SCEV *Copy = Expr;
2564   int64_t Offset = ExtractImmediate(Expr, SE);
2565 
2566   // Basic uses can't accept any offset, for example.
2567   if (!isAlwaysFoldable(TTI, Kind, AccessTy, /*BaseGV=*/ nullptr,
2568                         Offset, /*HasBaseReg=*/ true)) {
2569     Expr = Copy;
2570     Offset = 0;
2571   }
2572 
2573   std::pair<UseMapTy::iterator, bool> P =
2574     UseMap.insert(std::make_pair(LSRUse::SCEVUseKindPair(Expr, Kind), 0));
2575   if (!P.second) {
2576     // A use already existed with this base.
2577     size_t LUIdx = P.first->second;
2578     LSRUse &LU = Uses[LUIdx];
2579     if (reconcileNewOffset(LU, Offset, /*HasBaseReg=*/true, Kind, AccessTy))
2580       // Reuse this use.
2581       return std::make_pair(LUIdx, Offset);
2582   }
2583 
2584   // Create a new use.
2585   size_t LUIdx = Uses.size();
2586   P.first->second = LUIdx;
2587   Uses.push_back(LSRUse(Kind, AccessTy));
2588   LSRUse &LU = Uses[LUIdx];
2589 
2590   LU.MinOffset = Offset;
2591   LU.MaxOffset = Offset;
2592   return std::make_pair(LUIdx, Offset);
2593 }
2594 
2595 /// Delete the given use from the Uses list.
2596 void LSRInstance::DeleteUse(LSRUse &LU, size_t LUIdx) {
2597   if (&LU != &Uses.back())
2598     std::swap(LU, Uses.back());
2599   Uses.pop_back();
2600 
2601   // Update RegUses.
2602   RegUses.swapAndDropUse(LUIdx, Uses.size());
2603 }
2604 
2605 /// Look for a use distinct from OrigLU which is has a formula that has the same
2606 /// registers as the given formula.
2607 LSRUse *
2608 LSRInstance::FindUseWithSimilarFormula(const Formula &OrigF,
2609                                        const LSRUse &OrigLU) {
2610   // Search all uses for the formula. This could be more clever.
2611   for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2612     LSRUse &LU = Uses[LUIdx];
2613     // Check whether this use is close enough to OrigLU, to see whether it's
2614     // worthwhile looking through its formulae.
2615     // Ignore ICmpZero uses because they may contain formulae generated by
2616     // GenerateICmpZeroScales, in which case adding fixup offsets may
2617     // be invalid.
2618     if (&LU != &OrigLU &&
2619         LU.Kind != LSRUse::ICmpZero &&
2620         LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy &&
2621         LU.WidestFixupType == OrigLU.WidestFixupType &&
2622         LU.HasFormulaWithSameRegs(OrigF)) {
2623       // Scan through this use's formulae.
2624       for (const Formula &F : LU.Formulae) {
2625         // Check to see if this formula has the same registers and symbols
2626         // as OrigF.
2627         if (F.BaseRegs == OrigF.BaseRegs &&
2628             F.ScaledReg == OrigF.ScaledReg &&
2629             F.BaseGV == OrigF.BaseGV &&
2630             F.Scale == OrigF.Scale &&
2631             F.UnfoldedOffset == OrigF.UnfoldedOffset) {
2632           if (F.BaseOffset == 0)
2633             return &LU;
2634           // This is the formula where all the registers and symbols matched;
2635           // there aren't going to be any others. Since we declined it, we
2636           // can skip the rest of the formulae and proceed to the next LSRUse.
2637           break;
2638         }
2639       }
2640     }
2641   }
2642 
2643   // Nothing looked good.
2644   return nullptr;
2645 }
2646 
2647 void LSRInstance::CollectInterestingTypesAndFactors() {
2648   SmallSetVector<const SCEV *, 4> Strides;
2649 
2650   // Collect interesting types and strides.
2651   SmallVector<const SCEV *, 4> Worklist;
2652   for (const IVStrideUse &U : IU) {
2653     const SCEV *Expr = IU.getExpr(U);
2654 
2655     // Collect interesting types.
2656     Types.insert(SE.getEffectiveSCEVType(Expr->getType()));
2657 
2658     // Add strides for mentioned loops.
2659     Worklist.push_back(Expr);
2660     do {
2661       const SCEV *S = Worklist.pop_back_val();
2662       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2663         if (AR->getLoop() == L)
2664           Strides.insert(AR->getStepRecurrence(SE));
2665         Worklist.push_back(AR->getStart());
2666       } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2667         Worklist.append(Add->op_begin(), Add->op_end());
2668       }
2669     } while (!Worklist.empty());
2670   }
2671 
2672   // Compute interesting factors from the set of interesting strides.
2673   for (SmallSetVector<const SCEV *, 4>::const_iterator
2674        I = Strides.begin(), E = Strides.end(); I != E; ++I)
2675     for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =
2676          std::next(I); NewStrideIter != E; ++NewStrideIter) {
2677       const SCEV *OldStride = *I;
2678       const SCEV *NewStride = *NewStrideIter;
2679 
2680       if (SE.getTypeSizeInBits(OldStride->getType()) !=
2681           SE.getTypeSizeInBits(NewStride->getType())) {
2682         if (SE.getTypeSizeInBits(OldStride->getType()) >
2683             SE.getTypeSizeInBits(NewStride->getType()))
2684           NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
2685         else
2686           OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
2687       }
2688       if (const SCEVConstant *Factor =
2689             dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,
2690                                                         SE, true))) {
2691         if (Factor->getAPInt().getMinSignedBits() <= 64)
2692           Factors.insert(Factor->getAPInt().getSExtValue());
2693       } else if (const SCEVConstant *Factor =
2694                    dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride,
2695                                                                NewStride,
2696                                                                SE, true))) {
2697         if (Factor->getAPInt().getMinSignedBits() <= 64)
2698           Factors.insert(Factor->getAPInt().getSExtValue());
2699       }
2700     }
2701 
2702   // If all uses use the same type, don't bother looking for truncation-based
2703   // reuse.
2704   if (Types.size() == 1)
2705     Types.clear();
2706 
2707   LLVM_DEBUG(print_factors_and_types(dbgs()));
2708 }
2709 
2710 /// Helper for CollectChains that finds an IV operand (computed by an AddRec in
2711 /// this loop) within [OI,OE) or returns OE. If IVUsers mapped Instructions to
2712 /// IVStrideUses, we could partially skip this.
2713 static User::op_iterator
2714 findIVOperand(User::op_iterator OI, User::op_iterator OE,
2715               Loop *L, ScalarEvolution &SE) {
2716   for(; OI != OE; ++OI) {
2717     if (Instruction *Oper = dyn_cast<Instruction>(*OI)) {
2718       if (!SE.isSCEVable(Oper->getType()))
2719         continue;
2720 
2721       if (const SCEVAddRecExpr *AR =
2722           dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Oper))) {
2723         if (AR->getLoop() == L)
2724           break;
2725       }
2726     }
2727   }
2728   return OI;
2729 }
2730 
2731 /// IVChain logic must consistently peek base TruncInst operands, so wrap it in
2732 /// a convenient helper.
2733 static Value *getWideOperand(Value *Oper) {
2734   if (TruncInst *Trunc = dyn_cast<TruncInst>(Oper))
2735     return Trunc->getOperand(0);
2736   return Oper;
2737 }
2738 
2739 /// Return true if we allow an IV chain to include both types.
2740 static bool isCompatibleIVType(Value *LVal, Value *RVal) {
2741   Type *LType = LVal->getType();
2742   Type *RType = RVal->getType();
2743   return (LType == RType) || (LType->isPointerTy() && RType->isPointerTy() &&
2744                               // Different address spaces means (possibly)
2745                               // different types of the pointer implementation,
2746                               // e.g. i16 vs i32 so disallow that.
2747                               (LType->getPointerAddressSpace() ==
2748                                RType->getPointerAddressSpace()));
2749 }
2750 
2751 /// Return an approximation of this SCEV expression's "base", or NULL for any
2752 /// constant. Returning the expression itself is conservative. Returning a
2753 /// deeper subexpression is more precise and valid as long as it isn't less
2754 /// complex than another subexpression. For expressions involving multiple
2755 /// unscaled values, we need to return the pointer-type SCEVUnknown. This avoids
2756 /// forming chains across objects, such as: PrevOper==a[i], IVOper==b[i],
2757 /// IVInc==b-a.
2758 ///
2759 /// Since SCEVUnknown is the rightmost type, and pointers are the rightmost
2760 /// SCEVUnknown, we simply return the rightmost SCEV operand.
2761 static const SCEV *getExprBase(const SCEV *S) {
2762   switch (S->getSCEVType()) {
2763   default: // uncluding scUnknown.
2764     return S;
2765   case scConstant:
2766     return nullptr;
2767   case scTruncate:
2768     return getExprBase(cast<SCEVTruncateExpr>(S)->getOperand());
2769   case scZeroExtend:
2770     return getExprBase(cast<SCEVZeroExtendExpr>(S)->getOperand());
2771   case scSignExtend:
2772     return getExprBase(cast<SCEVSignExtendExpr>(S)->getOperand());
2773   case scAddExpr: {
2774     // Skip over scaled operands (scMulExpr) to follow add operands as long as
2775     // there's nothing more complex.
2776     // FIXME: not sure if we want to recognize negation.
2777     const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
2778     for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(Add->op_end()),
2779            E(Add->op_begin()); I != E; ++I) {
2780       const SCEV *SubExpr = *I;
2781       if (SubExpr->getSCEVType() == scAddExpr)
2782         return getExprBase(SubExpr);
2783 
2784       if (SubExpr->getSCEVType() != scMulExpr)
2785         return SubExpr;
2786     }
2787     return S; // all operands are scaled, be conservative.
2788   }
2789   case scAddRecExpr:
2790     return getExprBase(cast<SCEVAddRecExpr>(S)->getStart());
2791   }
2792   llvm_unreachable("Unknown SCEV kind!");
2793 }
2794 
2795 /// Return true if the chain increment is profitable to expand into a loop
2796 /// invariant value, which may require its own register. A profitable chain
2797 /// increment will be an offset relative to the same base. We allow such offsets
2798 /// to potentially be used as chain increment as long as it's not obviously
2799 /// expensive to expand using real instructions.
2800 bool IVChain::isProfitableIncrement(const SCEV *OperExpr,
2801                                     const SCEV *IncExpr,
2802                                     ScalarEvolution &SE) {
2803   // Aggressively form chains when -stress-ivchain.
2804   if (StressIVChain)
2805     return true;
2806 
2807   // Do not replace a constant offset from IV head with a nonconstant IV
2808   // increment.
2809   if (!isa<SCEVConstant>(IncExpr)) {
2810     const SCEV *HeadExpr = SE.getSCEV(getWideOperand(Incs[0].IVOperand));
2811     if (isa<SCEVConstant>(SE.getMinusSCEV(OperExpr, HeadExpr)))
2812       return false;
2813   }
2814 
2815   SmallPtrSet<const SCEV*, 8> Processed;
2816   return !isHighCostExpansion(IncExpr, Processed, SE);
2817 }
2818 
2819 /// Return true if the number of registers needed for the chain is estimated to
2820 /// be less than the number required for the individual IV users. First prohibit
2821 /// any IV users that keep the IV live across increments (the Users set should
2822 /// be empty). Next count the number and type of increments in the chain.
2823 ///
2824 /// Chaining IVs can lead to considerable code bloat if ISEL doesn't
2825 /// effectively use postinc addressing modes. Only consider it profitable it the
2826 /// increments can be computed in fewer registers when chained.
2827 ///
2828 /// TODO: Consider IVInc free if it's already used in another chains.
2829 static bool isProfitableChain(IVChain &Chain,
2830                               SmallPtrSetImpl<Instruction *> &Users,
2831                               ScalarEvolution &SE,
2832                               const TargetTransformInfo &TTI) {
2833   if (StressIVChain)
2834     return true;
2835 
2836   if (!Chain.hasIncs())
2837     return false;
2838 
2839   if (!Users.empty()) {
2840     LLVM_DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " users:\n";
2841                for (Instruction *Inst
2842                     : Users) { dbgs() << "  " << *Inst << "\n"; });
2843     return false;
2844   }
2845   assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
2846 
2847   // The chain itself may require a register, so intialize cost to 1.
2848   int cost = 1;
2849 
2850   // A complete chain likely eliminates the need for keeping the original IV in
2851   // a register. LSR does not currently know how to form a complete chain unless
2852   // the header phi already exists.
2853   if (isa<PHINode>(Chain.tailUserInst())
2854       && SE.getSCEV(Chain.tailUserInst()) == Chain.Incs[0].IncExpr) {
2855     --cost;
2856   }
2857   const SCEV *LastIncExpr = nullptr;
2858   unsigned NumConstIncrements = 0;
2859   unsigned NumVarIncrements = 0;
2860   unsigned NumReusedIncrements = 0;
2861 
2862   if (TTI.isProfitableLSRChainElement(Chain.Incs[0].UserInst))
2863     return true;
2864 
2865   for (const IVInc &Inc : Chain) {
2866     if (TTI.isProfitableLSRChainElement(Inc.UserInst))
2867       return true;
2868     if (Inc.IncExpr->isZero())
2869       continue;
2870 
2871     // Incrementing by zero or some constant is neutral. We assume constants can
2872     // be folded into an addressing mode or an add's immediate operand.
2873     if (isa<SCEVConstant>(Inc.IncExpr)) {
2874       ++NumConstIncrements;
2875       continue;
2876     }
2877 
2878     if (Inc.IncExpr == LastIncExpr)
2879       ++NumReusedIncrements;
2880     else
2881       ++NumVarIncrements;
2882 
2883     LastIncExpr = Inc.IncExpr;
2884   }
2885   // An IV chain with a single increment is handled by LSR's postinc
2886   // uses. However, a chain with multiple increments requires keeping the IV's
2887   // value live longer than it needs to be if chained.
2888   if (NumConstIncrements > 1)
2889     --cost;
2890 
2891   // Materializing increment expressions in the preheader that didn't exist in
2892   // the original code may cost a register. For example, sign-extended array
2893   // indices can produce ridiculous increments like this:
2894   // IV + ((sext i32 (2 * %s) to i64) + (-1 * (sext i32 %s to i64)))
2895   cost += NumVarIncrements;
2896 
2897   // Reusing variable increments likely saves a register to hold the multiple of
2898   // the stride.
2899   cost -= NumReusedIncrements;
2900 
2901   LLVM_DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " Cost: " << cost
2902                     << "\n");
2903 
2904   return cost < 0;
2905 }
2906 
2907 /// Add this IV user to an existing chain or make it the head of a new chain.
2908 void LSRInstance::ChainInstruction(Instruction *UserInst, Instruction *IVOper,
2909                                    SmallVectorImpl<ChainUsers> &ChainUsersVec) {
2910   // When IVs are used as types of varying widths, they are generally converted
2911   // to a wider type with some uses remaining narrow under a (free) trunc.
2912   Value *const NextIV = getWideOperand(IVOper);
2913   const SCEV *const OperExpr = SE.getSCEV(NextIV);
2914   const SCEV *const OperExprBase = getExprBase(OperExpr);
2915 
2916   // Visit all existing chains. Check if its IVOper can be computed as a
2917   // profitable loop invariant increment from the last link in the Chain.
2918   unsigned ChainIdx = 0, NChains = IVChainVec.size();
2919   const SCEV *LastIncExpr = nullptr;
2920   for (; ChainIdx < NChains; ++ChainIdx) {
2921     IVChain &Chain = IVChainVec[ChainIdx];
2922 
2923     // Prune the solution space aggressively by checking that both IV operands
2924     // are expressions that operate on the same unscaled SCEVUnknown. This
2925     // "base" will be canceled by the subsequent getMinusSCEV call. Checking
2926     // first avoids creating extra SCEV expressions.
2927     if (!StressIVChain && Chain.ExprBase != OperExprBase)
2928       continue;
2929 
2930     Value *PrevIV = getWideOperand(Chain.Incs.back().IVOperand);
2931     if (!isCompatibleIVType(PrevIV, NextIV))
2932       continue;
2933 
2934     // A phi node terminates a chain.
2935     if (isa<PHINode>(UserInst) && isa<PHINode>(Chain.tailUserInst()))
2936       continue;
2937 
2938     // The increment must be loop-invariant so it can be kept in a register.
2939     const SCEV *PrevExpr = SE.getSCEV(PrevIV);
2940     const SCEV *IncExpr = SE.getMinusSCEV(OperExpr, PrevExpr);
2941     if (!SE.isLoopInvariant(IncExpr, L))
2942       continue;
2943 
2944     if (Chain.isProfitableIncrement(OperExpr, IncExpr, SE)) {
2945       LastIncExpr = IncExpr;
2946       break;
2947     }
2948   }
2949   // If we haven't found a chain, create a new one, unless we hit the max. Don't
2950   // bother for phi nodes, because they must be last in the chain.
2951   if (ChainIdx == NChains) {
2952     if (isa<PHINode>(UserInst))
2953       return;
2954     if (NChains >= MaxChains && !StressIVChain) {
2955       LLVM_DEBUG(dbgs() << "IV Chain Limit\n");
2956       return;
2957     }
2958     LastIncExpr = OperExpr;
2959     // IVUsers may have skipped over sign/zero extensions. We don't currently
2960     // attempt to form chains involving extensions unless they can be hoisted
2961     // into this loop's AddRec.
2962     if (!isa<SCEVAddRecExpr>(LastIncExpr))
2963       return;
2964     ++NChains;
2965     IVChainVec.push_back(IVChain(IVInc(UserInst, IVOper, LastIncExpr),
2966                                  OperExprBase));
2967     ChainUsersVec.resize(NChains);
2968     LLVM_DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Head: (" << *UserInst
2969                       << ") IV=" << *LastIncExpr << "\n");
2970   } else {
2971     LLVM_DEBUG(dbgs() << "IV Chain#" << ChainIdx << "  Inc: (" << *UserInst
2972                       << ") IV+" << *LastIncExpr << "\n");
2973     // Add this IV user to the end of the chain.
2974     IVChainVec[ChainIdx].add(IVInc(UserInst, IVOper, LastIncExpr));
2975   }
2976   IVChain &Chain = IVChainVec[ChainIdx];
2977 
2978   SmallPtrSet<Instruction*,4> &NearUsers = ChainUsersVec[ChainIdx].NearUsers;
2979   // This chain's NearUsers become FarUsers.
2980   if (!LastIncExpr->isZero()) {
2981     ChainUsersVec[ChainIdx].FarUsers.insert(NearUsers.begin(),
2982                                             NearUsers.end());
2983     NearUsers.clear();
2984   }
2985 
2986   // All other uses of IVOperand become near uses of the chain.
2987   // We currently ignore intermediate values within SCEV expressions, assuming
2988   // they will eventually be used be the current chain, or can be computed
2989   // from one of the chain increments. To be more precise we could
2990   // transitively follow its user and only add leaf IV users to the set.
2991   for (User *U : IVOper->users()) {
2992     Instruction *OtherUse = dyn_cast<Instruction>(U);
2993     if (!OtherUse)
2994       continue;
2995     // Uses in the chain will no longer be uses if the chain is formed.
2996     // Include the head of the chain in this iteration (not Chain.begin()).
2997     IVChain::const_iterator IncIter = Chain.Incs.begin();
2998     IVChain::const_iterator IncEnd = Chain.Incs.end();
2999     for( ; IncIter != IncEnd; ++IncIter) {
3000       if (IncIter->UserInst == OtherUse)
3001         break;
3002     }
3003     if (IncIter != IncEnd)
3004       continue;
3005 
3006     if (SE.isSCEVable(OtherUse->getType())
3007         && !isa<SCEVUnknown>(SE.getSCEV(OtherUse))
3008         && IU.isIVUserOrOperand(OtherUse)) {
3009       continue;
3010     }
3011     NearUsers.insert(OtherUse);
3012   }
3013 
3014   // Since this user is part of the chain, it's no longer considered a use
3015   // of the chain.
3016   ChainUsersVec[ChainIdx].FarUsers.erase(UserInst);
3017 }
3018 
3019 /// Populate the vector of Chains.
3020 ///
3021 /// This decreases ILP at the architecture level. Targets with ample registers,
3022 /// multiple memory ports, and no register renaming probably don't want
3023 /// this. However, such targets should probably disable LSR altogether.
3024 ///
3025 /// The job of LSR is to make a reasonable choice of induction variables across
3026 /// the loop. Subsequent passes can easily "unchain" computation exposing more
3027 /// ILP *within the loop* if the target wants it.
3028 ///
3029 /// Finding the best IV chain is potentially a scheduling problem. Since LSR
3030 /// will not reorder memory operations, it will recognize this as a chain, but
3031 /// will generate redundant IV increments. Ideally this would be corrected later
3032 /// by a smart scheduler:
3033 ///        = A[i]
3034 ///        = A[i+x]
3035 /// A[i]   =
3036 /// A[i+x] =
3037 ///
3038 /// TODO: Walk the entire domtree within this loop, not just the path to the
3039 /// loop latch. This will discover chains on side paths, but requires
3040 /// maintaining multiple copies of the Chains state.
3041 void LSRInstance::CollectChains() {
3042   LLVM_DEBUG(dbgs() << "Collecting IV Chains.\n");
3043   SmallVector<ChainUsers, 8> ChainUsersVec;
3044 
3045   SmallVector<BasicBlock *,8> LatchPath;
3046   BasicBlock *LoopHeader = L->getHeader();
3047   for (DomTreeNode *Rung = DT.getNode(L->getLoopLatch());
3048        Rung->getBlock() != LoopHeader; Rung = Rung->getIDom()) {
3049     LatchPath.push_back(Rung->getBlock());
3050   }
3051   LatchPath.push_back(LoopHeader);
3052 
3053   // Walk the instruction stream from the loop header to the loop latch.
3054   for (BasicBlock *BB : reverse(LatchPath)) {
3055     for (Instruction &I : *BB) {
3056       // Skip instructions that weren't seen by IVUsers analysis.
3057       if (isa<PHINode>(I) || !IU.isIVUserOrOperand(&I))
3058         continue;
3059 
3060       // Ignore users that are part of a SCEV expression. This way we only
3061       // consider leaf IV Users. This effectively rediscovers a portion of
3062       // IVUsers analysis but in program order this time.
3063       if (SE.isSCEVable(I.getType()) && !isa<SCEVUnknown>(SE.getSCEV(&I)))
3064           continue;
3065 
3066       // Remove this instruction from any NearUsers set it may be in.
3067       for (unsigned ChainIdx = 0, NChains = IVChainVec.size();
3068            ChainIdx < NChains; ++ChainIdx) {
3069         ChainUsersVec[ChainIdx].NearUsers.erase(&I);
3070       }
3071       // Search for operands that can be chained.
3072       SmallPtrSet<Instruction*, 4> UniqueOperands;
3073       User::op_iterator IVOpEnd = I.op_end();
3074       User::op_iterator IVOpIter = findIVOperand(I.op_begin(), IVOpEnd, L, SE);
3075       while (IVOpIter != IVOpEnd) {
3076         Instruction *IVOpInst = cast<Instruction>(*IVOpIter);
3077         if (UniqueOperands.insert(IVOpInst).second)
3078           ChainInstruction(&I, IVOpInst, ChainUsersVec);
3079         IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
3080       }
3081     } // Continue walking down the instructions.
3082   } // Continue walking down the domtree.
3083   // Visit phi backedges to determine if the chain can generate the IV postinc.
3084   for (PHINode &PN : L->getHeader()->phis()) {
3085     if (!SE.isSCEVable(PN.getType()))
3086       continue;
3087 
3088     Instruction *IncV =
3089         dyn_cast<Instruction>(PN.getIncomingValueForBlock(L->getLoopLatch()));
3090     if (IncV)
3091       ChainInstruction(&PN, IncV, ChainUsersVec);
3092   }
3093   // Remove any unprofitable chains.
3094   unsigned ChainIdx = 0;
3095   for (unsigned UsersIdx = 0, NChains = IVChainVec.size();
3096        UsersIdx < NChains; ++UsersIdx) {
3097     if (!isProfitableChain(IVChainVec[UsersIdx],
3098                            ChainUsersVec[UsersIdx].FarUsers, SE, TTI))
3099       continue;
3100     // Preserve the chain at UsesIdx.
3101     if (ChainIdx != UsersIdx)
3102       IVChainVec[ChainIdx] = IVChainVec[UsersIdx];
3103     FinalizeChain(IVChainVec[ChainIdx]);
3104     ++ChainIdx;
3105   }
3106   IVChainVec.resize(ChainIdx);
3107 }
3108 
3109 void LSRInstance::FinalizeChain(IVChain &Chain) {
3110   assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
3111   LLVM_DEBUG(dbgs() << "Final Chain: " << *Chain.Incs[0].UserInst << "\n");
3112 
3113   for (const IVInc &Inc : Chain) {
3114     LLVM_DEBUG(dbgs() << "        Inc: " << *Inc.UserInst << "\n");
3115     auto UseI = find(Inc.UserInst->operands(), Inc.IVOperand);
3116     assert(UseI != Inc.UserInst->op_end() && "cannot find IV operand");
3117     IVIncSet.insert(UseI);
3118   }
3119 }
3120 
3121 /// Return true if the IVInc can be folded into an addressing mode.
3122 static bool canFoldIVIncExpr(const SCEV *IncExpr, Instruction *UserInst,
3123                              Value *Operand, const TargetTransformInfo &TTI) {
3124   const SCEVConstant *IncConst = dyn_cast<SCEVConstant>(IncExpr);
3125   if (!IncConst || !isAddressUse(TTI, UserInst, Operand))
3126     return false;
3127 
3128   if (IncConst->getAPInt().getMinSignedBits() > 64)
3129     return false;
3130 
3131   MemAccessTy AccessTy = getAccessType(TTI, UserInst, Operand);
3132   int64_t IncOffset = IncConst->getValue()->getSExtValue();
3133   if (!isAlwaysFoldable(TTI, LSRUse::Address, AccessTy, /*BaseGV=*/nullptr,
3134                         IncOffset, /*HasBaseReg=*/false))
3135     return false;
3136 
3137   return true;
3138 }
3139 
3140 /// Generate an add or subtract for each IVInc in a chain to materialize the IV
3141 /// user's operand from the previous IV user's operand.
3142 void LSRInstance::GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter,
3143                                   SmallVectorImpl<WeakTrackingVH> &DeadInsts) {
3144   // Find the new IVOperand for the head of the chain. It may have been replaced
3145   // by LSR.
3146   const IVInc &Head = Chain.Incs[0];
3147   User::op_iterator IVOpEnd = Head.UserInst->op_end();
3148   // findIVOperand returns IVOpEnd if it can no longer find a valid IV user.
3149   User::op_iterator IVOpIter = findIVOperand(Head.UserInst->op_begin(),
3150                                              IVOpEnd, L, SE);
3151   Value *IVSrc = nullptr;
3152   while (IVOpIter != IVOpEnd) {
3153     IVSrc = getWideOperand(*IVOpIter);
3154 
3155     // If this operand computes the expression that the chain needs, we may use
3156     // it. (Check this after setting IVSrc which is used below.)
3157     //
3158     // Note that if Head.IncExpr is wider than IVSrc, then this phi is too
3159     // narrow for the chain, so we can no longer use it. We do allow using a
3160     // wider phi, assuming the LSR checked for free truncation. In that case we
3161     // should already have a truncate on this operand such that
3162     // getSCEV(IVSrc) == IncExpr.
3163     if (SE.getSCEV(*IVOpIter) == Head.IncExpr
3164         || SE.getSCEV(IVSrc) == Head.IncExpr) {
3165       break;
3166     }
3167     IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
3168   }
3169   if (IVOpIter == IVOpEnd) {
3170     // Gracefully give up on this chain.
3171     LLVM_DEBUG(dbgs() << "Concealed chain head: " << *Head.UserInst << "\n");
3172     return;
3173   }
3174   assert(IVSrc && "Failed to find IV chain source");
3175 
3176   LLVM_DEBUG(dbgs() << "Generate chain at: " << *IVSrc << "\n");
3177   Type *IVTy = IVSrc->getType();
3178   Type *IntTy = SE.getEffectiveSCEVType(IVTy);
3179   const SCEV *LeftOverExpr = nullptr;
3180   for (const IVInc &Inc : Chain) {
3181     Instruction *InsertPt = Inc.UserInst;
3182     if (isa<PHINode>(InsertPt))
3183       InsertPt = L->getLoopLatch()->getTerminator();
3184 
3185     // IVOper will replace the current IV User's operand. IVSrc is the IV
3186     // value currently held in a register.
3187     Value *IVOper = IVSrc;
3188     if (!Inc.IncExpr->isZero()) {
3189       // IncExpr was the result of subtraction of two narrow values, so must
3190       // be signed.
3191       const SCEV *IncExpr = SE.getNoopOrSignExtend(Inc.IncExpr, IntTy);
3192       LeftOverExpr = LeftOverExpr ?
3193         SE.getAddExpr(LeftOverExpr, IncExpr) : IncExpr;
3194     }
3195     if (LeftOverExpr && !LeftOverExpr->isZero()) {
3196       // Expand the IV increment.
3197       Rewriter.clearPostInc();
3198       Value *IncV = Rewriter.expandCodeFor(LeftOverExpr, IntTy, InsertPt);
3199       const SCEV *IVOperExpr = SE.getAddExpr(SE.getUnknown(IVSrc),
3200                                              SE.getUnknown(IncV));
3201       IVOper = Rewriter.expandCodeFor(IVOperExpr, IVTy, InsertPt);
3202 
3203       // If an IV increment can't be folded, use it as the next IV value.
3204       if (!canFoldIVIncExpr(LeftOverExpr, Inc.UserInst, Inc.IVOperand, TTI)) {
3205         assert(IVTy == IVOper->getType() && "inconsistent IV increment type");
3206         IVSrc = IVOper;
3207         LeftOverExpr = nullptr;
3208       }
3209     }
3210     Type *OperTy = Inc.IVOperand->getType();
3211     if (IVTy != OperTy) {
3212       assert(SE.getTypeSizeInBits(IVTy) >= SE.getTypeSizeInBits(OperTy) &&
3213              "cannot extend a chained IV");
3214       IRBuilder<> Builder(InsertPt);
3215       IVOper = Builder.CreateTruncOrBitCast(IVOper, OperTy, "lsr.chain");
3216     }
3217     Inc.UserInst->replaceUsesOfWith(Inc.IVOperand, IVOper);
3218     if (auto *OperandIsInstr = dyn_cast<Instruction>(Inc.IVOperand))
3219       DeadInsts.emplace_back(OperandIsInstr);
3220   }
3221   // If LSR created a new, wider phi, we may also replace its postinc. We only
3222   // do this if we also found a wide value for the head of the chain.
3223   if (isa<PHINode>(Chain.tailUserInst())) {
3224     for (PHINode &Phi : L->getHeader()->phis()) {
3225       if (!isCompatibleIVType(&Phi, IVSrc))
3226         continue;
3227       Instruction *PostIncV = dyn_cast<Instruction>(
3228           Phi.getIncomingValueForBlock(L->getLoopLatch()));
3229       if (!PostIncV || (SE.getSCEV(PostIncV) != SE.getSCEV(IVSrc)))
3230         continue;
3231       Value *IVOper = IVSrc;
3232       Type *PostIncTy = PostIncV->getType();
3233       if (IVTy != PostIncTy) {
3234         assert(PostIncTy->isPointerTy() && "mixing int/ptr IV types");
3235         IRBuilder<> Builder(L->getLoopLatch()->getTerminator());
3236         Builder.SetCurrentDebugLocation(PostIncV->getDebugLoc());
3237         IVOper = Builder.CreatePointerCast(IVSrc, PostIncTy, "lsr.chain");
3238       }
3239       Phi.replaceUsesOfWith(PostIncV, IVOper);
3240       DeadInsts.emplace_back(PostIncV);
3241     }
3242   }
3243 }
3244 
3245 void LSRInstance::CollectFixupsAndInitialFormulae() {
3246   BranchInst *ExitBranch = nullptr;
3247   bool SaveCmp = TTI.canSaveCmp(L, &ExitBranch, &SE, &LI, &DT, &AC, &TLI);
3248 
3249   for (const IVStrideUse &U : IU) {
3250     Instruction *UserInst = U.getUser();
3251     // Skip IV users that are part of profitable IV Chains.
3252     User::op_iterator UseI =
3253         find(UserInst->operands(), U.getOperandValToReplace());
3254     assert(UseI != UserInst->op_end() && "cannot find IV operand");
3255     if (IVIncSet.count(UseI)) {
3256       LLVM_DEBUG(dbgs() << "Use is in profitable chain: " << **UseI << '\n');
3257       continue;
3258     }
3259 
3260     LSRUse::KindType Kind = LSRUse::Basic;
3261     MemAccessTy AccessTy;
3262     if (isAddressUse(TTI, UserInst, U.getOperandValToReplace())) {
3263       Kind = LSRUse::Address;
3264       AccessTy = getAccessType(TTI, UserInst, U.getOperandValToReplace());
3265     }
3266 
3267     const SCEV *S = IU.getExpr(U);
3268     PostIncLoopSet TmpPostIncLoops = U.getPostIncLoops();
3269 
3270     // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
3271     // (N - i == 0), and this allows (N - i) to be the expression that we work
3272     // with rather than just N or i, so we can consider the register
3273     // requirements for both N and i at the same time. Limiting this code to
3274     // equality icmps is not a problem because all interesting loops use
3275     // equality icmps, thanks to IndVarSimplify.
3276     if (ICmpInst *CI = dyn_cast<ICmpInst>(UserInst)) {
3277       // If CI can be saved in some target, like replaced inside hardware loop
3278       // in PowerPC, no need to generate initial formulae for it.
3279       if (SaveCmp && CI == dyn_cast<ICmpInst>(ExitBranch->getCondition()))
3280         continue;
3281       if (CI->isEquality()) {
3282         // Swap the operands if needed to put the OperandValToReplace on the
3283         // left, for consistency.
3284         Value *NV = CI->getOperand(1);
3285         if (NV == U.getOperandValToReplace()) {
3286           CI->setOperand(1, CI->getOperand(0));
3287           CI->setOperand(0, NV);
3288           NV = CI->getOperand(1);
3289           Changed = true;
3290         }
3291 
3292         // x == y  -->  x - y == 0
3293         const SCEV *N = SE.getSCEV(NV);
3294         if (SE.isLoopInvariant(N, L) && isSafeToExpand(N, SE)) {
3295           // S is normalized, so normalize N before folding it into S
3296           // to keep the result normalized.
3297           N = normalizeForPostIncUse(N, TmpPostIncLoops, SE);
3298           Kind = LSRUse::ICmpZero;
3299           S = SE.getMinusSCEV(N, S);
3300         }
3301 
3302         // -1 and the negations of all interesting strides (except the negation
3303         // of -1) are now also interesting.
3304         for (size_t i = 0, e = Factors.size(); i != e; ++i)
3305           if (Factors[i] != -1)
3306             Factors.insert(-(uint64_t)Factors[i]);
3307         Factors.insert(-1);
3308       }
3309     }
3310 
3311     // Get or create an LSRUse.
3312     std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
3313     size_t LUIdx = P.first;
3314     int64_t Offset = P.second;
3315     LSRUse &LU = Uses[LUIdx];
3316 
3317     // Record the fixup.
3318     LSRFixup &LF = LU.getNewFixup();
3319     LF.UserInst = UserInst;
3320     LF.OperandValToReplace = U.getOperandValToReplace();
3321     LF.PostIncLoops = TmpPostIncLoops;
3322     LF.Offset = Offset;
3323     LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
3324 
3325     if (!LU.WidestFixupType ||
3326         SE.getTypeSizeInBits(LU.WidestFixupType) <
3327         SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
3328       LU.WidestFixupType = LF.OperandValToReplace->getType();
3329 
3330     // If this is the first use of this LSRUse, give it a formula.
3331     if (LU.Formulae.empty()) {
3332       InsertInitialFormula(S, LU, LUIdx);
3333       CountRegisters(LU.Formulae.back(), LUIdx);
3334     }
3335   }
3336 
3337   LLVM_DEBUG(print_fixups(dbgs()));
3338 }
3339 
3340 /// Insert a formula for the given expression into the given use, separating out
3341 /// loop-variant portions from loop-invariant and loop-computable portions.
3342 void
3343 LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx) {
3344   // Mark uses whose expressions cannot be expanded.
3345   if (!isSafeToExpand(S, SE))
3346     LU.RigidFormula = true;
3347 
3348   Formula F;
3349   F.initialMatch(S, L, SE);
3350   bool Inserted = InsertFormula(LU, LUIdx, F);
3351   assert(Inserted && "Initial formula already exists!"); (void)Inserted;
3352 }
3353 
3354 /// Insert a simple single-register formula for the given expression into the
3355 /// given use.
3356 void
3357 LSRInstance::InsertSupplementalFormula(const SCEV *S,
3358                                        LSRUse &LU, size_t LUIdx) {
3359   Formula F;
3360   F.BaseRegs.push_back(S);
3361   F.HasBaseReg = true;
3362   bool Inserted = InsertFormula(LU, LUIdx, F);
3363   assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
3364 }
3365 
3366 /// Note which registers are used by the given formula, updating RegUses.
3367 void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
3368   if (F.ScaledReg)
3369     RegUses.countRegister(F.ScaledReg, LUIdx);
3370   for (const SCEV *BaseReg : F.BaseRegs)
3371     RegUses.countRegister(BaseReg, LUIdx);
3372 }
3373 
3374 /// If the given formula has not yet been inserted, add it to the list, and
3375 /// return true. Return false otherwise.
3376 bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
3377   // Do not insert formula that we will not be able to expand.
3378   assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F) &&
3379          "Formula is illegal");
3380 
3381   if (!LU.InsertFormula(F, *L))
3382     return false;
3383 
3384   CountRegisters(F, LUIdx);
3385   return true;
3386 }
3387 
3388 /// Check for other uses of loop-invariant values which we're tracking. These
3389 /// other uses will pin these values in registers, making them less profitable
3390 /// for elimination.
3391 /// TODO: This currently misses non-constant addrec step registers.
3392 /// TODO: Should this give more weight to users inside the loop?
3393 void
3394 LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
3395   SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
3396   SmallPtrSet<const SCEV *, 32> Visited;
3397 
3398   while (!Worklist.empty()) {
3399     const SCEV *S = Worklist.pop_back_val();
3400 
3401     // Don't process the same SCEV twice
3402     if (!Visited.insert(S).second)
3403       continue;
3404 
3405     if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
3406       Worklist.append(N->op_begin(), N->op_end());
3407     else if (const SCEVIntegralCastExpr *C = dyn_cast<SCEVIntegralCastExpr>(S))
3408       Worklist.push_back(C->getOperand());
3409     else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
3410       Worklist.push_back(D->getLHS());
3411       Worklist.push_back(D->getRHS());
3412     } else if (const SCEVUnknown *US = dyn_cast<SCEVUnknown>(S)) {
3413       const Value *V = US->getValue();
3414       if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
3415         // Look for instructions defined outside the loop.
3416         if (L->contains(Inst)) continue;
3417       } else if (isa<UndefValue>(V))
3418         // Undef doesn't have a live range, so it doesn't matter.
3419         continue;
3420       for (const Use &U : V->uses()) {
3421         const Instruction *UserInst = dyn_cast<Instruction>(U.getUser());
3422         // Ignore non-instructions.
3423         if (!UserInst)
3424           continue;
3425         // Ignore instructions in other functions (as can happen with
3426         // Constants).
3427         if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
3428           continue;
3429         // Ignore instructions not dominated by the loop.
3430         const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
3431           UserInst->getParent() :
3432           cast<PHINode>(UserInst)->getIncomingBlock(
3433             PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
3434         if (!DT.dominates(L->getHeader(), UseBB))
3435           continue;
3436         // Don't bother if the instruction is in a BB which ends in an EHPad.
3437         if (UseBB->getTerminator()->isEHPad())
3438           continue;
3439         // Don't bother rewriting PHIs in catchswitch blocks.
3440         if (isa<CatchSwitchInst>(UserInst->getParent()->getTerminator()))
3441           continue;
3442         // Ignore uses which are part of other SCEV expressions, to avoid
3443         // analyzing them multiple times.
3444         if (SE.isSCEVable(UserInst->getType())) {
3445           const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst));
3446           // If the user is a no-op, look through to its uses.
3447           if (!isa<SCEVUnknown>(UserS))
3448             continue;
3449           if (UserS == US) {
3450             Worklist.push_back(
3451               SE.getUnknown(const_cast<Instruction *>(UserInst)));
3452             continue;
3453           }
3454         }
3455         // Ignore icmp instructions which are already being analyzed.
3456         if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
3457           unsigned OtherIdx = !U.getOperandNo();
3458           Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
3459           if (SE.hasComputableLoopEvolution(SE.getSCEV(OtherOp), L))
3460             continue;
3461         }
3462 
3463         std::pair<size_t, int64_t> P = getUse(
3464             S, LSRUse::Basic, MemAccessTy());
3465         size_t LUIdx = P.first;
3466         int64_t Offset = P.second;
3467         LSRUse &LU = Uses[LUIdx];
3468         LSRFixup &LF = LU.getNewFixup();
3469         LF.UserInst = const_cast<Instruction *>(UserInst);
3470         LF.OperandValToReplace = U;
3471         LF.Offset = Offset;
3472         LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
3473         if (!LU.WidestFixupType ||
3474             SE.getTypeSizeInBits(LU.WidestFixupType) <
3475             SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
3476           LU.WidestFixupType = LF.OperandValToReplace->getType();
3477         InsertSupplementalFormula(US, LU, LUIdx);
3478         CountRegisters(LU.Formulae.back(), Uses.size() - 1);
3479         break;
3480       }
3481     }
3482   }
3483 }
3484 
3485 /// Split S into subexpressions which can be pulled out into separate
3486 /// registers. If C is non-null, multiply each subexpression by C.
3487 ///
3488 /// Return remainder expression after factoring the subexpressions captured by
3489 /// Ops. If Ops is complete, return NULL.
3490 static const SCEV *CollectSubexprs(const SCEV *S, const SCEVConstant *C,
3491                                    SmallVectorImpl<const SCEV *> &Ops,
3492                                    const Loop *L,
3493                                    ScalarEvolution &SE,
3494                                    unsigned Depth = 0) {
3495   // Arbitrarily cap recursion to protect compile time.
3496   if (Depth >= 3)
3497     return S;
3498 
3499   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3500     // Break out add operands.
3501     for (const SCEV *S : Add->operands()) {
3502       const SCEV *Remainder = CollectSubexprs(S, C, Ops, L, SE, Depth+1);
3503       if (Remainder)
3504         Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
3505     }
3506     return nullptr;
3507   } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
3508     // Split a non-zero base out of an addrec.
3509     if (AR->getStart()->isZero() || !AR->isAffine())
3510       return S;
3511 
3512     const SCEV *Remainder = CollectSubexprs(AR->getStart(),
3513                                             C, Ops, L, SE, Depth+1);
3514     // Split the non-zero AddRec unless it is part of a nested recurrence that
3515     // does not pertain to this loop.
3516     if (Remainder && (AR->getLoop() == L || !isa<SCEVAddRecExpr>(Remainder))) {
3517       Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
3518       Remainder = nullptr;
3519     }
3520     if (Remainder != AR->getStart()) {
3521       if (!Remainder)
3522         Remainder = SE.getConstant(AR->getType(), 0);
3523       return SE.getAddRecExpr(Remainder,
3524                               AR->getStepRecurrence(SE),
3525                               AR->getLoop(),
3526                               //FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
3527                               SCEV::FlagAnyWrap);
3528     }
3529   } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3530     // Break (C * (a + b + c)) into C*a + C*b + C*c.
3531     if (Mul->getNumOperands() != 2)
3532       return S;
3533     if (const SCEVConstant *Op0 =
3534         dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3535       C = C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0;
3536       const SCEV *Remainder =
3537         CollectSubexprs(Mul->getOperand(1), C, Ops, L, SE, Depth+1);
3538       if (Remainder)
3539         Ops.push_back(SE.getMulExpr(C, Remainder));
3540       return nullptr;
3541     }
3542   }
3543   return S;
3544 }
3545 
3546 /// Return true if the SCEV represents a value that may end up as a
3547 /// post-increment operation.
3548 static bool mayUsePostIncMode(const TargetTransformInfo &TTI,
3549                               LSRUse &LU, const SCEV *S, const Loop *L,
3550                               ScalarEvolution &SE) {
3551   if (LU.Kind != LSRUse::Address ||
3552       !LU.AccessTy.getType()->isIntOrIntVectorTy())
3553     return false;
3554   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
3555   if (!AR)
3556     return false;
3557   const SCEV *LoopStep = AR->getStepRecurrence(SE);
3558   if (!isa<SCEVConstant>(LoopStep))
3559     return false;
3560   // Check if a post-indexed load/store can be used.
3561   if (TTI.isIndexedLoadLegal(TTI.MIM_PostInc, AR->getType()) ||
3562       TTI.isIndexedStoreLegal(TTI.MIM_PostInc, AR->getType())) {
3563     const SCEV *LoopStart = AR->getStart();
3564     if (!isa<SCEVConstant>(LoopStart) && SE.isLoopInvariant(LoopStart, L))
3565       return true;
3566   }
3567   return false;
3568 }
3569 
3570 /// Helper function for LSRInstance::GenerateReassociations.
3571 void LSRInstance::GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
3572                                              const Formula &Base,
3573                                              unsigned Depth, size_t Idx,
3574                                              bool IsScaledReg) {
3575   const SCEV *BaseReg = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3576   // Don't generate reassociations for the base register of a value that
3577   // may generate a post-increment operator. The reason is that the
3578   // reassociations cause extra base+register formula to be created,
3579   // and possibly chosen, but the post-increment is more efficient.
3580   if (TTI.shouldFavorPostInc() && mayUsePostIncMode(TTI, LU, BaseReg, L, SE))
3581     return;
3582   SmallVector<const SCEV *, 8> AddOps;
3583   const SCEV *Remainder = CollectSubexprs(BaseReg, nullptr, AddOps, L, SE);
3584   if (Remainder)
3585     AddOps.push_back(Remainder);
3586 
3587   if (AddOps.size() == 1)
3588     return;
3589 
3590   for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),
3591                                                      JE = AddOps.end();
3592        J != JE; ++J) {
3593     // Loop-variant "unknown" values are uninteresting; we won't be able to
3594     // do anything meaningful with them.
3595     if (isa<SCEVUnknown>(*J) && !SE.isLoopInvariant(*J, L))
3596       continue;
3597 
3598     // Don't pull a constant into a register if the constant could be folded
3599     // into an immediate field.
3600     if (isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,
3601                          LU.AccessTy, *J, Base.getNumRegs() > 1))
3602       continue;
3603 
3604     // Collect all operands except *J.
3605     SmallVector<const SCEV *, 8> InnerAddOps(
3606         ((const SmallVector<const SCEV *, 8> &)AddOps).begin(), J);
3607     InnerAddOps.append(std::next(J),
3608                        ((const SmallVector<const SCEV *, 8> &)AddOps).end());
3609 
3610     // Don't leave just a constant behind in a register if the constant could
3611     // be folded into an immediate field.
3612     if (InnerAddOps.size() == 1 &&
3613         isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,
3614                          LU.AccessTy, InnerAddOps[0], Base.getNumRegs() > 1))
3615       continue;
3616 
3617     const SCEV *InnerSum = SE.getAddExpr(InnerAddOps);
3618     if (InnerSum->isZero())
3619       continue;
3620     Formula F = Base;
3621 
3622     // Add the remaining pieces of the add back into the new formula.
3623     const SCEVConstant *InnerSumSC = dyn_cast<SCEVConstant>(InnerSum);
3624     if (InnerSumSC && SE.getTypeSizeInBits(InnerSumSC->getType()) <= 64 &&
3625         TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
3626                                 InnerSumSC->getValue()->getZExtValue())) {
3627       F.UnfoldedOffset =
3628           (uint64_t)F.UnfoldedOffset + InnerSumSC->getValue()->getZExtValue();
3629       if (IsScaledReg)
3630         F.ScaledReg = nullptr;
3631       else
3632         F.BaseRegs.erase(F.BaseRegs.begin() + Idx);
3633     } else if (IsScaledReg)
3634       F.ScaledReg = InnerSum;
3635     else
3636       F.BaseRegs[Idx] = InnerSum;
3637 
3638     // Add J as its own register, or an unfolded immediate.
3639     const SCEVConstant *SC = dyn_cast<SCEVConstant>(*J);
3640     if (SC && SE.getTypeSizeInBits(SC->getType()) <= 64 &&
3641         TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
3642                                 SC->getValue()->getZExtValue()))
3643       F.UnfoldedOffset =
3644           (uint64_t)F.UnfoldedOffset + SC->getValue()->getZExtValue();
3645     else
3646       F.BaseRegs.push_back(*J);
3647     // We may have changed the number of register in base regs, adjust the
3648     // formula accordingly.
3649     F.canonicalize(*L);
3650 
3651     if (InsertFormula(LU, LUIdx, F))
3652       // If that formula hadn't been seen before, recurse to find more like
3653       // it.
3654       // Add check on Log16(AddOps.size()) - same as Log2_32(AddOps.size()) >> 2)
3655       // Because just Depth is not enough to bound compile time.
3656       // This means that every time AddOps.size() is greater 16^x we will add
3657       // x to Depth.
3658       GenerateReassociations(LU, LUIdx, LU.Formulae.back(),
3659                              Depth + 1 + (Log2_32(AddOps.size()) >> 2));
3660   }
3661 }
3662 
3663 /// Split out subexpressions from adds and the bases of addrecs.
3664 void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
3665                                          Formula Base, unsigned Depth) {
3666   assert(Base.isCanonical(*L) && "Input must be in the canonical form");
3667   // Arbitrarily cap recursion to protect compile time.
3668   if (Depth >= 3)
3669     return;
3670 
3671   for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3672     GenerateReassociationsImpl(LU, LUIdx, Base, Depth, i);
3673 
3674   if (Base.Scale == 1)
3675     GenerateReassociationsImpl(LU, LUIdx, Base, Depth,
3676                                /* Idx */ -1, /* IsScaledReg */ true);
3677 }
3678 
3679 ///  Generate a formula consisting of all of the loop-dominating registers added
3680 /// into a single register.
3681 void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
3682                                        Formula Base) {
3683   // This method is only interesting on a plurality of registers.
3684   if (Base.BaseRegs.size() + (Base.Scale == 1) +
3685       (Base.UnfoldedOffset != 0) <= 1)
3686     return;
3687 
3688   // Flatten the representation, i.e., reg1 + 1*reg2 => reg1 + reg2, before
3689   // processing the formula.
3690   Base.unscale();
3691   SmallVector<const SCEV *, 4> Ops;
3692   Formula NewBase = Base;
3693   NewBase.BaseRegs.clear();
3694   Type *CombinedIntegerType = nullptr;
3695   for (const SCEV *BaseReg : Base.BaseRegs) {
3696     if (SE.properlyDominates(BaseReg, L->getHeader()) &&
3697         !SE.hasComputableLoopEvolution(BaseReg, L)) {
3698       if (!CombinedIntegerType)
3699         CombinedIntegerType = SE.getEffectiveSCEVType(BaseReg->getType());
3700       Ops.push_back(BaseReg);
3701     }
3702     else
3703       NewBase.BaseRegs.push_back(BaseReg);
3704   }
3705 
3706   // If no register is relevant, we're done.
3707   if (Ops.size() == 0)
3708     return;
3709 
3710   // Utility function for generating the required variants of the combined
3711   // registers.
3712   auto GenerateFormula = [&](const SCEV *Sum) {
3713     Formula F = NewBase;
3714 
3715     // TODO: If Sum is zero, it probably means ScalarEvolution missed an
3716     // opportunity to fold something. For now, just ignore such cases
3717     // rather than proceed with zero in a register.
3718     if (Sum->isZero())
3719       return;
3720 
3721     F.BaseRegs.push_back(Sum);
3722     F.canonicalize(*L);
3723     (void)InsertFormula(LU, LUIdx, F);
3724   };
3725 
3726   // If we collected at least two registers, generate a formula combining them.
3727   if (Ops.size() > 1) {
3728     SmallVector<const SCEV *, 4> OpsCopy(Ops); // Don't let SE modify Ops.
3729     GenerateFormula(SE.getAddExpr(OpsCopy));
3730   }
3731 
3732   // If we have an unfolded offset, generate a formula combining it with the
3733   // registers collected.
3734   if (NewBase.UnfoldedOffset) {
3735     assert(CombinedIntegerType && "Missing a type for the unfolded offset");
3736     Ops.push_back(SE.getConstant(CombinedIntegerType, NewBase.UnfoldedOffset,
3737                                  true));
3738     NewBase.UnfoldedOffset = 0;
3739     GenerateFormula(SE.getAddExpr(Ops));
3740   }
3741 }
3742 
3743 /// Helper function for LSRInstance::GenerateSymbolicOffsets.
3744 void LSRInstance::GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
3745                                               const Formula &Base, size_t Idx,
3746                                               bool IsScaledReg) {
3747   const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3748   GlobalValue *GV = ExtractSymbol(G, SE);
3749   if (G->isZero() || !GV)
3750     return;
3751   Formula F = Base;
3752   F.BaseGV = GV;
3753   if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
3754     return;
3755   if (IsScaledReg)
3756     F.ScaledReg = G;
3757   else
3758     F.BaseRegs[Idx] = G;
3759   (void)InsertFormula(LU, LUIdx, F);
3760 }
3761 
3762 /// Generate reuse formulae using symbolic offsets.
3763 void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
3764                                           Formula Base) {
3765   // We can't add a symbolic offset if the address already contains one.
3766   if (Base.BaseGV) return;
3767 
3768   for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3769     GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, i);
3770   if (Base.Scale == 1)
3771     GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, /* Idx */ -1,
3772                                 /* IsScaledReg */ true);
3773 }
3774 
3775 /// Helper function for LSRInstance::GenerateConstantOffsets.
3776 void LSRInstance::GenerateConstantOffsetsImpl(
3777     LSRUse &LU, unsigned LUIdx, const Formula &Base,
3778     const SmallVectorImpl<int64_t> &Worklist, size_t Idx, bool IsScaledReg) {
3779 
3780   auto GenerateOffset = [&](const SCEV *G, int64_t Offset) {
3781     Formula F = Base;
3782     F.BaseOffset = (uint64_t)Base.BaseOffset - Offset;
3783 
3784     if (isLegalUse(TTI, LU.MinOffset - Offset, LU.MaxOffset - Offset, LU.Kind,
3785                    LU.AccessTy, F)) {
3786       // Add the offset to the base register.
3787       const SCEV *NewG = SE.getAddExpr(SE.getConstant(G->getType(), Offset), G);
3788       // If it cancelled out, drop the base register, otherwise update it.
3789       if (NewG->isZero()) {
3790         if (IsScaledReg) {
3791           F.Scale = 0;
3792           F.ScaledReg = nullptr;
3793         } else
3794           F.deleteBaseReg(F.BaseRegs[Idx]);
3795         F.canonicalize(*L);
3796       } else if (IsScaledReg)
3797         F.ScaledReg = NewG;
3798       else
3799         F.BaseRegs[Idx] = NewG;
3800 
3801       (void)InsertFormula(LU, LUIdx, F);
3802     }
3803   };
3804 
3805   const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3806 
3807   // With constant offsets and constant steps, we can generate pre-inc
3808   // accesses by having the offset equal the step. So, for access #0 with a
3809   // step of 8, we generate a G - 8 base which would require the first access
3810   // to be ((G - 8) + 8),+,8. The pre-indexed access then updates the pointer
3811   // for itself and hopefully becomes the base for other accesses. This means
3812   // means that a single pre-indexed access can be generated to become the new
3813   // base pointer for each iteration of the loop, resulting in no extra add/sub
3814   // instructions for pointer updating.
3815   if (FavorBackedgeIndex && LU.Kind == LSRUse::Address) {
3816     if (auto *GAR = dyn_cast<SCEVAddRecExpr>(G)) {
3817       if (auto *StepRec =
3818           dyn_cast<SCEVConstant>(GAR->getStepRecurrence(SE))) {
3819         const APInt &StepInt = StepRec->getAPInt();
3820         int64_t Step = StepInt.isNegative() ?
3821           StepInt.getSExtValue() : StepInt.getZExtValue();
3822 
3823         for (int64_t Offset : Worklist) {
3824           Offset -= Step;
3825           GenerateOffset(G, Offset);
3826         }
3827       }
3828     }
3829   }
3830   for (int64_t Offset : Worklist)
3831     GenerateOffset(G, Offset);
3832 
3833   int64_t Imm = ExtractImmediate(G, SE);
3834   if (G->isZero() || Imm == 0)
3835     return;
3836   Formula F = Base;
3837   F.BaseOffset = (uint64_t)F.BaseOffset + Imm;
3838   if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
3839     return;
3840   if (IsScaledReg) {
3841     F.ScaledReg = G;
3842   } else {
3843     F.BaseRegs[Idx] = G;
3844     // We may generate non canonical Formula if G is a recurrent expr reg
3845     // related with current loop while F.ScaledReg is not.
3846     F.canonicalize(*L);
3847   }
3848   (void)InsertFormula(LU, LUIdx, F);
3849 }
3850 
3851 /// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
3852 void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
3853                                           Formula Base) {
3854   // TODO: For now, just add the min and max offset, because it usually isn't
3855   // worthwhile looking at everything inbetween.
3856   SmallVector<int64_t, 2> Worklist;
3857   Worklist.push_back(LU.MinOffset);
3858   if (LU.MaxOffset != LU.MinOffset)
3859     Worklist.push_back(LU.MaxOffset);
3860 
3861   for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3862     GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, i);
3863   if (Base.Scale == 1)
3864     GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, /* Idx */ -1,
3865                                 /* IsScaledReg */ true);
3866 }
3867 
3868 /// For ICmpZero, check to see if we can scale up the comparison. For example, x
3869 /// == y -> x*c == y*c.
3870 void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
3871                                          Formula Base) {
3872   if (LU.Kind != LSRUse::ICmpZero) return;
3873 
3874   // Determine the integer type for the base formula.
3875   Type *IntTy = Base.getType();
3876   if (!IntTy) return;
3877   if (SE.getTypeSizeInBits(IntTy) > 64) return;
3878 
3879   // Don't do this if there is more than one offset.
3880   if (LU.MinOffset != LU.MaxOffset) return;
3881 
3882   // Check if transformation is valid. It is illegal to multiply pointer.
3883   if (Base.ScaledReg && Base.ScaledReg->getType()->isPointerTy())
3884     return;
3885   for (const SCEV *BaseReg : Base.BaseRegs)
3886     if (BaseReg->getType()->isPointerTy())
3887       return;
3888   assert(!Base.BaseGV && "ICmpZero use is not legal!");
3889 
3890   // Check each interesting stride.
3891   for (int64_t Factor : Factors) {
3892     // Check that the multiplication doesn't overflow.
3893     if (Base.BaseOffset == std::numeric_limits<int64_t>::min() && Factor == -1)
3894       continue;
3895     int64_t NewBaseOffset = (uint64_t)Base.BaseOffset * Factor;
3896     if (NewBaseOffset / Factor != Base.BaseOffset)
3897       continue;
3898     // If the offset will be truncated at this use, check that it is in bounds.
3899     if (!IntTy->isPointerTy() &&
3900         !ConstantInt::isValueValidForType(IntTy, NewBaseOffset))
3901       continue;
3902 
3903     // Check that multiplying with the use offset doesn't overflow.
3904     int64_t Offset = LU.MinOffset;
3905     if (Offset == std::numeric_limits<int64_t>::min() && Factor == -1)
3906       continue;
3907     Offset = (uint64_t)Offset * Factor;
3908     if (Offset / Factor != LU.MinOffset)
3909       continue;
3910     // If the offset will be truncated at this use, check that it is in bounds.
3911     if (!IntTy->isPointerTy() &&
3912         !ConstantInt::isValueValidForType(IntTy, Offset))
3913       continue;
3914 
3915     Formula F = Base;
3916     F.BaseOffset = NewBaseOffset;
3917 
3918     // Check that this scale is legal.
3919     if (!isLegalUse(TTI, Offset, Offset, LU.Kind, LU.AccessTy, F))
3920       continue;
3921 
3922     // Compensate for the use having MinOffset built into it.
3923     F.BaseOffset = (uint64_t)F.BaseOffset + Offset - LU.MinOffset;
3924 
3925     const SCEV *FactorS = SE.getConstant(IntTy, Factor);
3926 
3927     // Check that multiplying with each base register doesn't overflow.
3928     for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
3929       F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
3930       if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
3931         goto next;
3932     }
3933 
3934     // Check that multiplying with the scaled register doesn't overflow.
3935     if (F.ScaledReg) {
3936       F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
3937       if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
3938         continue;
3939     }
3940 
3941     // Check that multiplying with the unfolded offset doesn't overflow.
3942     if (F.UnfoldedOffset != 0) {
3943       if (F.UnfoldedOffset == std::numeric_limits<int64_t>::min() &&
3944           Factor == -1)
3945         continue;
3946       F.UnfoldedOffset = (uint64_t)F.UnfoldedOffset * Factor;
3947       if (F.UnfoldedOffset / Factor != Base.UnfoldedOffset)
3948         continue;
3949       // If the offset will be truncated, check that it is in bounds.
3950       if (!IntTy->isPointerTy() &&
3951           !ConstantInt::isValueValidForType(IntTy, F.UnfoldedOffset))
3952         continue;
3953     }
3954 
3955     // If we make it here and it's legal, add it.
3956     (void)InsertFormula(LU, LUIdx, F);
3957   next:;
3958   }
3959 }
3960 
3961 /// Generate stride factor reuse formulae by making use of scaled-offset address
3962 /// modes, for example.
3963 void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base) {
3964   // Determine the integer type for the base formula.
3965   Type *IntTy = Base.getType();
3966   if (!IntTy) return;
3967 
3968   // If this Formula already has a scaled register, we can't add another one.
3969   // Try to unscale the formula to generate a better scale.
3970   if (Base.Scale != 0 && !Base.unscale())
3971     return;
3972 
3973   assert(Base.Scale == 0 && "unscale did not did its job!");
3974 
3975   // Check each interesting stride.
3976   for (int64_t Factor : Factors) {
3977     Base.Scale = Factor;
3978     Base.HasBaseReg = Base.BaseRegs.size() > 1;
3979     // Check whether this scale is going to be legal.
3980     if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
3981                     Base)) {
3982       // As a special-case, handle special out-of-loop Basic users specially.
3983       // TODO: Reconsider this special case.
3984       if (LU.Kind == LSRUse::Basic &&
3985           isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LSRUse::Special,
3986                      LU.AccessTy, Base) &&
3987           LU.AllFixupsOutsideLoop)
3988         LU.Kind = LSRUse::Special;
3989       else
3990         continue;
3991     }
3992     // For an ICmpZero, negating a solitary base register won't lead to
3993     // new solutions.
3994     if (LU.Kind == LSRUse::ICmpZero &&
3995         !Base.HasBaseReg && Base.BaseOffset == 0 && !Base.BaseGV)
3996       continue;
3997     // For each addrec base reg, if its loop is current loop, apply the scale.
3998     for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
3999       const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i]);
4000       if (AR && (AR->getLoop() == L || LU.AllFixupsOutsideLoop)) {
4001         const SCEV *FactorS = SE.getConstant(IntTy, Factor);
4002         if (FactorS->isZero())
4003           continue;
4004         // Divide out the factor, ignoring high bits, since we'll be
4005         // scaling the value back up in the end.
4006         if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) {
4007           // TODO: This could be optimized to avoid all the copying.
4008           Formula F = Base;
4009           F.ScaledReg = Quotient;
4010           F.deleteBaseReg(F.BaseRegs[i]);
4011           // The canonical representation of 1*reg is reg, which is already in
4012           // Base. In that case, do not try to insert the formula, it will be
4013           // rejected anyway.
4014           if (F.Scale == 1 && (F.BaseRegs.empty() ||
4015                                (AR->getLoop() != L && LU.AllFixupsOutsideLoop)))
4016             continue;
4017           // If AllFixupsOutsideLoop is true and F.Scale is 1, we may generate
4018           // non canonical Formula with ScaledReg's loop not being L.
4019           if (F.Scale == 1 && LU.AllFixupsOutsideLoop)
4020             F.canonicalize(*L);
4021           (void)InsertFormula(LU, LUIdx, F);
4022         }
4023       }
4024     }
4025   }
4026 }
4027 
4028 /// Generate reuse formulae from different IV types.
4029 void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base) {
4030   // Don't bother truncating symbolic values.
4031   if (Base.BaseGV) return;
4032 
4033   // Determine the integer type for the base formula.
4034   Type *DstTy = Base.getType();
4035   if (!DstTy) return;
4036   DstTy = SE.getEffectiveSCEVType(DstTy);
4037 
4038   for (Type *SrcTy : Types) {
4039     if (SrcTy != DstTy && TTI.isTruncateFree(SrcTy, DstTy)) {
4040       Formula F = Base;
4041 
4042       // Sometimes SCEV is able to prove zero during ext transform. It may
4043       // happen if SCEV did not do all possible transforms while creating the
4044       // initial node (maybe due to depth limitations), but it can do them while
4045       // taking ext.
4046       if (F.ScaledReg) {
4047         const SCEV *NewScaledReg = SE.getAnyExtendExpr(F.ScaledReg, SrcTy);
4048         if (NewScaledReg->isZero())
4049          continue;
4050         F.ScaledReg = NewScaledReg;
4051       }
4052       bool HasZeroBaseReg = false;
4053       for (const SCEV *&BaseReg : F.BaseRegs) {
4054         const SCEV *NewBaseReg = SE.getAnyExtendExpr(BaseReg, SrcTy);
4055         if (NewBaseReg->isZero()) {
4056           HasZeroBaseReg = true;
4057           break;
4058         }
4059         BaseReg = NewBaseReg;
4060       }
4061       if (HasZeroBaseReg)
4062         continue;
4063 
4064       // TODO: This assumes we've done basic processing on all uses and
4065       // have an idea what the register usage is.
4066       if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
4067         continue;
4068 
4069       F.canonicalize(*L);
4070       (void)InsertFormula(LU, LUIdx, F);
4071     }
4072   }
4073 }
4074 
4075 namespace {
4076 
4077 /// Helper class for GenerateCrossUseConstantOffsets. It's used to defer
4078 /// modifications so that the search phase doesn't have to worry about the data
4079 /// structures moving underneath it.
4080 struct WorkItem {
4081   size_t LUIdx;
4082   int64_t Imm;
4083   const SCEV *OrigReg;
4084 
4085   WorkItem(size_t LI, int64_t I, const SCEV *R)
4086       : LUIdx(LI), Imm(I), OrigReg(R) {}
4087 
4088   void print(raw_ostream &OS) const;
4089   void dump() const;
4090 };
4091 
4092 } // end anonymous namespace
4093 
4094 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4095 void WorkItem::print(raw_ostream &OS) const {
4096   OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
4097      << " , add offset " << Imm;
4098 }
4099 
4100 LLVM_DUMP_METHOD void WorkItem::dump() const {
4101   print(errs()); errs() << '\n';
4102 }
4103 #endif
4104 
4105 /// Look for registers which are a constant distance apart and try to form reuse
4106 /// opportunities between them.
4107 void LSRInstance::GenerateCrossUseConstantOffsets() {
4108   // Group the registers by their value without any added constant offset.
4109   using ImmMapTy = std::map<int64_t, const SCEV *>;
4110 
4111   DenseMap<const SCEV *, ImmMapTy> Map;
4112   DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
4113   SmallVector<const SCEV *, 8> Sequence;
4114   for (const SCEV *Use : RegUses) {
4115     const SCEV *Reg = Use; // Make a copy for ExtractImmediate to modify.
4116     int64_t Imm = ExtractImmediate(Reg, SE);
4117     auto Pair = Map.insert(std::make_pair(Reg, ImmMapTy()));
4118     if (Pair.second)
4119       Sequence.push_back(Reg);
4120     Pair.first->second.insert(std::make_pair(Imm, Use));
4121     UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(Use);
4122   }
4123 
4124   // Now examine each set of registers with the same base value. Build up
4125   // a list of work to do and do the work in a separate step so that we're
4126   // not adding formulae and register counts while we're searching.
4127   SmallVector<WorkItem, 32> WorkItems;
4128   SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems;
4129   for (const SCEV *Reg : Sequence) {
4130     const ImmMapTy &Imms = Map.find(Reg)->second;
4131 
4132     // It's not worthwhile looking for reuse if there's only one offset.
4133     if (Imms.size() == 1)
4134       continue;
4135 
4136     LLVM_DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
4137                for (const auto &Entry
4138                     : Imms) dbgs()
4139                << ' ' << Entry.first;
4140                dbgs() << '\n');
4141 
4142     // Examine each offset.
4143     for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
4144          J != JE; ++J) {
4145       const SCEV *OrigReg = J->second;
4146 
4147       int64_t JImm = J->first;
4148       const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
4149 
4150       if (!isa<SCEVConstant>(OrigReg) &&
4151           UsedByIndicesMap[Reg].count() == 1) {
4152         LLVM_DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg
4153                           << '\n');
4154         continue;
4155       }
4156 
4157       // Conservatively examine offsets between this orig reg a few selected
4158       // other orig regs.
4159       int64_t First = Imms.begin()->first;
4160       int64_t Last = std::prev(Imms.end())->first;
4161       // Compute (First + Last)  / 2 without overflow using the fact that
4162       // First + Last = 2 * (First + Last) + (First ^ Last).
4163       int64_t Avg = (First & Last) + ((First ^ Last) >> 1);
4164       // If the result is negative and First is odd and Last even (or vice versa),
4165       // we rounded towards -inf. Add 1 in that case, to round towards 0.
4166       Avg = Avg + ((First ^ Last) & ((uint64_t)Avg >> 63));
4167       ImmMapTy::const_iterator OtherImms[] = {
4168           Imms.begin(), std::prev(Imms.end()),
4169          Imms.lower_bound(Avg)};
4170       for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) {
4171         ImmMapTy::const_iterator M = OtherImms[i];
4172         if (M == J || M == JE) continue;
4173 
4174         // Compute the difference between the two.
4175         int64_t Imm = (uint64_t)JImm - M->first;
4176         for (unsigned LUIdx : UsedByIndices.set_bits())
4177           // Make a memo of this use, offset, and register tuple.
4178           if (UniqueItems.insert(std::make_pair(LUIdx, Imm)).second)
4179             WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
4180       }
4181     }
4182   }
4183 
4184   Map.clear();
4185   Sequence.clear();
4186   UsedByIndicesMap.clear();
4187   UniqueItems.clear();
4188 
4189   // Now iterate through the worklist and add new formulae.
4190   for (const WorkItem &WI : WorkItems) {
4191     size_t LUIdx = WI.LUIdx;
4192     LSRUse &LU = Uses[LUIdx];
4193     int64_t Imm = WI.Imm;
4194     const SCEV *OrigReg = WI.OrigReg;
4195 
4196     Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
4197     const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
4198     unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
4199 
4200     // TODO: Use a more targeted data structure.
4201     for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
4202       Formula F = LU.Formulae[L];
4203       // FIXME: The code for the scaled and unscaled registers looks
4204       // very similar but slightly different. Investigate if they
4205       // could be merged. That way, we would not have to unscale the
4206       // Formula.
4207       F.unscale();
4208       // Use the immediate in the scaled register.
4209       if (F.ScaledReg == OrigReg) {
4210         int64_t Offset = (uint64_t)F.BaseOffset + Imm * (uint64_t)F.Scale;
4211         // Don't create 50 + reg(-50).
4212         if (F.referencesReg(SE.getSCEV(
4213                    ConstantInt::get(IntTy, -(uint64_t)Offset))))
4214           continue;
4215         Formula NewF = F;
4216         NewF.BaseOffset = Offset;
4217         if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
4218                         NewF))
4219           continue;
4220         NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
4221 
4222         // If the new scale is a constant in a register, and adding the constant
4223         // value to the immediate would produce a value closer to zero than the
4224         // immediate itself, then the formula isn't worthwhile.
4225         if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
4226           if (C->getValue()->isNegative() != (NewF.BaseOffset < 0) &&
4227               (C->getAPInt().abs() * APInt(BitWidth, F.Scale))
4228                   .ule(std::abs(NewF.BaseOffset)))
4229             continue;
4230 
4231         // OK, looks good.
4232         NewF.canonicalize(*this->L);
4233         (void)InsertFormula(LU, LUIdx, NewF);
4234       } else {
4235         // Use the immediate in a base register.
4236         for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
4237           const SCEV *BaseReg = F.BaseRegs[N];
4238           if (BaseReg != OrigReg)
4239             continue;
4240           Formula NewF = F;
4241           NewF.BaseOffset = (uint64_t)NewF.BaseOffset + Imm;
4242           if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset,
4243                           LU.Kind, LU.AccessTy, NewF)) {
4244             if (TTI.shouldFavorPostInc() &&
4245                 mayUsePostIncMode(TTI, LU, OrigReg, this->L, SE))
4246               continue;
4247             if (!TTI.isLegalAddImmediate((uint64_t)NewF.UnfoldedOffset + Imm))
4248               continue;
4249             NewF = F;
4250             NewF.UnfoldedOffset = (uint64_t)NewF.UnfoldedOffset + Imm;
4251           }
4252           NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
4253 
4254           // If the new formula has a constant in a register, and adding the
4255           // constant value to the immediate would produce a value closer to
4256           // zero than the immediate itself, then the formula isn't worthwhile.
4257           for (const SCEV *NewReg : NewF.BaseRegs)
4258             if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewReg))
4259               if ((C->getAPInt() + NewF.BaseOffset)
4260                       .abs()
4261                       .slt(std::abs(NewF.BaseOffset)) &&
4262                   (C->getAPInt() + NewF.BaseOffset).countTrailingZeros() >=
4263                       countTrailingZeros<uint64_t>(NewF.BaseOffset))
4264                 goto skip_formula;
4265 
4266           // Ok, looks good.
4267           NewF.canonicalize(*this->L);
4268           (void)InsertFormula(LU, LUIdx, NewF);
4269           break;
4270         skip_formula:;
4271         }
4272       }
4273     }
4274   }
4275 }
4276 
4277 /// Generate formulae for each use.
4278 void
4279 LSRInstance::GenerateAllReuseFormulae() {
4280   // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
4281   // queries are more precise.
4282   for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4283     LSRUse &LU = Uses[LUIdx];
4284     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4285       GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
4286     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4287       GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
4288   }
4289   for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4290     LSRUse &LU = Uses[LUIdx];
4291     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4292       GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
4293     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4294       GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
4295     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4296       GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
4297     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4298       GenerateScales(LU, LUIdx, LU.Formulae[i]);
4299   }
4300   for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4301     LSRUse &LU = Uses[LUIdx];
4302     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4303       GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
4304   }
4305 
4306   GenerateCrossUseConstantOffsets();
4307 
4308   LLVM_DEBUG(dbgs() << "\n"
4309                        "After generating reuse formulae:\n";
4310              print_uses(dbgs()));
4311 }
4312 
4313 /// If there are multiple formulae with the same set of registers used
4314 /// by other uses, pick the best one and delete the others.
4315 void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
4316   DenseSet<const SCEV *> VisitedRegs;
4317   SmallPtrSet<const SCEV *, 16> Regs;
4318   SmallPtrSet<const SCEV *, 16> LoserRegs;
4319 #ifndef NDEBUG
4320   bool ChangedFormulae = false;
4321 #endif
4322 
4323   // Collect the best formula for each unique set of shared registers. This
4324   // is reset for each use.
4325   using BestFormulaeTy =
4326       DenseMap<SmallVector<const SCEV *, 4>, size_t, UniquifierDenseMapInfo>;
4327 
4328   BestFormulaeTy BestFormulae;
4329 
4330   for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4331     LSRUse &LU = Uses[LUIdx];
4332     LLVM_DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs());
4333                dbgs() << '\n');
4334 
4335     bool Any = false;
4336     for (size_t FIdx = 0, NumForms = LU.Formulae.size();
4337          FIdx != NumForms; ++FIdx) {
4338       Formula &F = LU.Formulae[FIdx];
4339 
4340       // Some formulas are instant losers. For example, they may depend on
4341       // nonexistent AddRecs from other loops. These need to be filtered
4342       // immediately, otherwise heuristics could choose them over others leading
4343       // to an unsatisfactory solution. Passing LoserRegs into RateFormula here
4344       // avoids the need to recompute this information across formulae using the
4345       // same bad AddRec. Passing LoserRegs is also essential unless we remove
4346       // the corresponding bad register from the Regs set.
4347       Cost CostF(L, SE, TTI);
4348       Regs.clear();
4349       CostF.RateFormula(F, Regs, VisitedRegs, LU, &LoserRegs);
4350       if (CostF.isLoser()) {
4351         // During initial formula generation, undesirable formulae are generated
4352         // by uses within other loops that have some non-trivial address mode or
4353         // use the postinc form of the IV. LSR needs to provide these formulae
4354         // as the basis of rediscovering the desired formula that uses an AddRec
4355         // corresponding to the existing phi. Once all formulae have been
4356         // generated, these initial losers may be pruned.
4357         LLVM_DEBUG(dbgs() << "  Filtering loser "; F.print(dbgs());
4358                    dbgs() << "\n");
4359       }
4360       else {
4361         SmallVector<const SCEV *, 4> Key;
4362         for (const SCEV *Reg : F.BaseRegs) {
4363           if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
4364             Key.push_back(Reg);
4365         }
4366         if (F.ScaledReg &&
4367             RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
4368           Key.push_back(F.ScaledReg);
4369         // Unstable sort by host order ok, because this is only used for
4370         // uniquifying.
4371         llvm::sort(Key);
4372 
4373         std::pair<BestFormulaeTy::const_iterator, bool> P =
4374           BestFormulae.insert(std::make_pair(Key, FIdx));
4375         if (P.second)
4376           continue;
4377 
4378         Formula &Best = LU.Formulae[P.first->second];
4379 
4380         Cost CostBest(L, SE, TTI);
4381         Regs.clear();
4382         CostBest.RateFormula(Best, Regs, VisitedRegs, LU);
4383         if (CostF.isLess(CostBest))
4384           std::swap(F, Best);
4385         LLVM_DEBUG(dbgs() << "  Filtering out formula "; F.print(dbgs());
4386                    dbgs() << "\n"
4387                              "    in favor of formula ";
4388                    Best.print(dbgs()); dbgs() << '\n');
4389       }
4390 #ifndef NDEBUG
4391       ChangedFormulae = true;
4392 #endif
4393       LU.DeleteFormula(F);
4394       --FIdx;
4395       --NumForms;
4396       Any = true;
4397     }
4398 
4399     // Now that we've filtered out some formulae, recompute the Regs set.
4400     if (Any)
4401       LU.RecomputeRegs(LUIdx, RegUses);
4402 
4403     // Reset this to prepare for the next use.
4404     BestFormulae.clear();
4405   }
4406 
4407   LLVM_DEBUG(if (ChangedFormulae) {
4408     dbgs() << "\n"
4409               "After filtering out undesirable candidates:\n";
4410     print_uses(dbgs());
4411   });
4412 }
4413 
4414 /// Estimate the worst-case number of solutions the solver might have to
4415 /// consider. It almost never considers this many solutions because it prune the
4416 /// search space, but the pruning isn't always sufficient.
4417 size_t LSRInstance::EstimateSearchSpaceComplexity() const {
4418   size_t Power = 1;
4419   for (const LSRUse &LU : Uses) {
4420     size_t FSize = LU.Formulae.size();
4421     if (FSize >= ComplexityLimit) {
4422       Power = ComplexityLimit;
4423       break;
4424     }
4425     Power *= FSize;
4426     if (Power >= ComplexityLimit)
4427       break;
4428   }
4429   return Power;
4430 }
4431 
4432 /// When one formula uses a superset of the registers of another formula, it
4433 /// won't help reduce register pressure (though it may not necessarily hurt
4434 /// register pressure); remove it to simplify the system.
4435 void LSRInstance::NarrowSearchSpaceByDetectingSupersets() {
4436   if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4437     LLVM_DEBUG(dbgs() << "The search space is too complex.\n");
4438 
4439     LLVM_DEBUG(dbgs() << "Narrowing the search space by eliminating formulae "
4440                          "which use a superset of registers used by other "
4441                          "formulae.\n");
4442 
4443     for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4444       LSRUse &LU = Uses[LUIdx];
4445       bool Any = false;
4446       for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4447         Formula &F = LU.Formulae[i];
4448         // Look for a formula with a constant or GV in a register. If the use
4449         // also has a formula with that same value in an immediate field,
4450         // delete the one that uses a register.
4451         for (SmallVectorImpl<const SCEV *>::const_iterator
4452              I = F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I) {
4453           if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*I)) {
4454             Formula NewF = F;
4455             //FIXME: Formulas should store bitwidth to do wrapping properly.
4456             //       See PR41034.
4457             NewF.BaseOffset += (uint64_t)C->getValue()->getSExtValue();
4458             NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
4459                                 (I - F.BaseRegs.begin()));
4460             if (LU.HasFormulaWithSameRegs(NewF)) {
4461               LLVM_DEBUG(dbgs() << "  Deleting "; F.print(dbgs());
4462                          dbgs() << '\n');
4463               LU.DeleteFormula(F);
4464               --i;
4465               --e;
4466               Any = true;
4467               break;
4468             }
4469           } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) {
4470             if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue()))
4471               if (!F.BaseGV) {
4472                 Formula NewF = F;
4473                 NewF.BaseGV = GV;
4474                 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
4475                                     (I - F.BaseRegs.begin()));
4476                 if (LU.HasFormulaWithSameRegs(NewF)) {
4477                   LLVM_DEBUG(dbgs() << "  Deleting "; F.print(dbgs());
4478                              dbgs() << '\n');
4479                   LU.DeleteFormula(F);
4480                   --i;
4481                   --e;
4482                   Any = true;
4483                   break;
4484                 }
4485               }
4486           }
4487         }
4488       }
4489       if (Any)
4490         LU.RecomputeRegs(LUIdx, RegUses);
4491     }
4492 
4493     LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
4494   }
4495 }
4496 
4497 /// When there are many registers for expressions like A, A+1, A+2, etc.,
4498 /// allocate a single register for them.
4499 void LSRInstance::NarrowSearchSpaceByCollapsingUnrolledCode() {
4500   if (EstimateSearchSpaceComplexity() < ComplexityLimit)
4501     return;
4502 
4503   LLVM_DEBUG(
4504       dbgs() << "The search space is too complex.\n"
4505                 "Narrowing the search space by assuming that uses separated "
4506                 "by a constant offset will use the same registers.\n");
4507 
4508   // This is especially useful for unrolled loops.
4509 
4510   for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4511     LSRUse &LU = Uses[LUIdx];
4512     for (const Formula &F : LU.Formulae) {
4513       if (F.BaseOffset == 0 || (F.Scale != 0 && F.Scale != 1))
4514         continue;
4515 
4516       LSRUse *LUThatHas = FindUseWithSimilarFormula(F, LU);
4517       if (!LUThatHas)
4518         continue;
4519 
4520       if (!reconcileNewOffset(*LUThatHas, F.BaseOffset, /*HasBaseReg=*/ false,
4521                               LU.Kind, LU.AccessTy))
4522         continue;
4523 
4524       LLVM_DEBUG(dbgs() << "  Deleting use "; LU.print(dbgs()); dbgs() << '\n');
4525 
4526       LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop;
4527 
4528       // Transfer the fixups of LU to LUThatHas.
4529       for (LSRFixup &Fixup : LU.Fixups) {
4530         Fixup.Offset += F.BaseOffset;
4531         LUThatHas->pushFixup(Fixup);
4532         LLVM_DEBUG(dbgs() << "New fixup has offset " << Fixup.Offset << '\n');
4533       }
4534 
4535       // Delete formulae from the new use which are no longer legal.
4536       bool Any = false;
4537       for (size_t i = 0, e = LUThatHas->Formulae.size(); i != e; ++i) {
4538         Formula &F = LUThatHas->Formulae[i];
4539         if (!isLegalUse(TTI, LUThatHas->MinOffset, LUThatHas->MaxOffset,
4540                         LUThatHas->Kind, LUThatHas->AccessTy, F)) {
4541           LLVM_DEBUG(dbgs() << "  Deleting "; F.print(dbgs()); dbgs() << '\n');
4542           LUThatHas->DeleteFormula(F);
4543           --i;
4544           --e;
4545           Any = true;
4546         }
4547       }
4548 
4549       if (Any)
4550         LUThatHas->RecomputeRegs(LUThatHas - &Uses.front(), RegUses);
4551 
4552       // Delete the old use.
4553       DeleteUse(LU, LUIdx);
4554       --LUIdx;
4555       --NumUses;
4556       break;
4557     }
4558   }
4559 
4560   LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
4561 }
4562 
4563 /// Call FilterOutUndesirableDedicatedRegisters again, if necessary, now that
4564 /// we've done more filtering, as it may be able to find more formulae to
4565 /// eliminate.
4566 void LSRInstance::NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(){
4567   if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4568     LLVM_DEBUG(dbgs() << "The search space is too complex.\n");
4569 
4570     LLVM_DEBUG(dbgs() << "Narrowing the search space by re-filtering out "
4571                          "undesirable dedicated registers.\n");
4572 
4573     FilterOutUndesirableDedicatedRegisters();
4574 
4575     LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
4576   }
4577 }
4578 
4579 /// If a LSRUse has multiple formulae with the same ScaledReg and Scale.
4580 /// Pick the best one and delete the others.
4581 /// This narrowing heuristic is to keep as many formulae with different
4582 /// Scale and ScaledReg pair as possible while narrowing the search space.
4583 /// The benefit is that it is more likely to find out a better solution
4584 /// from a formulae set with more Scale and ScaledReg variations than
4585 /// a formulae set with the same Scale and ScaledReg. The picking winner
4586 /// reg heuristic will often keep the formulae with the same Scale and
4587 /// ScaledReg and filter others, and we want to avoid that if possible.
4588 void LSRInstance::NarrowSearchSpaceByFilterFormulaWithSameScaledReg() {
4589   if (EstimateSearchSpaceComplexity() < ComplexityLimit)
4590     return;
4591 
4592   LLVM_DEBUG(
4593       dbgs() << "The search space is too complex.\n"
4594                 "Narrowing the search space by choosing the best Formula "
4595                 "from the Formulae with the same Scale and ScaledReg.\n");
4596 
4597   // Map the "Scale * ScaledReg" pair to the best formula of current LSRUse.
4598   using BestFormulaeTy = DenseMap<std::pair<const SCEV *, int64_t>, size_t>;
4599 
4600   BestFormulaeTy BestFormulae;
4601 #ifndef NDEBUG
4602   bool ChangedFormulae = false;
4603 #endif
4604   DenseSet<const SCEV *> VisitedRegs;
4605   SmallPtrSet<const SCEV *, 16> Regs;
4606 
4607   for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4608     LSRUse &LU = Uses[LUIdx];
4609     LLVM_DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs());
4610                dbgs() << '\n');
4611 
4612     // Return true if Formula FA is better than Formula FB.
4613     auto IsBetterThan = [&](Formula &FA, Formula &FB) {
4614       // First we will try to choose the Formula with fewer new registers.
4615       // For a register used by current Formula, the more the register is
4616       // shared among LSRUses, the less we increase the register number
4617       // counter of the formula.
4618       size_t FARegNum = 0;
4619       for (const SCEV *Reg : FA.BaseRegs) {
4620         const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(Reg);
4621         FARegNum += (NumUses - UsedByIndices.count() + 1);
4622       }
4623       size_t FBRegNum = 0;
4624       for (const SCEV *Reg : FB.BaseRegs) {
4625         const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(Reg);
4626         FBRegNum += (NumUses - UsedByIndices.count() + 1);
4627       }
4628       if (FARegNum != FBRegNum)
4629         return FARegNum < FBRegNum;
4630 
4631       // If the new register numbers are the same, choose the Formula with
4632       // less Cost.
4633       Cost CostFA(L, SE, TTI);
4634       Cost CostFB(L, SE, TTI);
4635       Regs.clear();
4636       CostFA.RateFormula(FA, Regs, VisitedRegs, LU);
4637       Regs.clear();
4638       CostFB.RateFormula(FB, Regs, VisitedRegs, LU);
4639       return CostFA.isLess(CostFB);
4640     };
4641 
4642     bool Any = false;
4643     for (size_t FIdx = 0, NumForms = LU.Formulae.size(); FIdx != NumForms;
4644          ++FIdx) {
4645       Formula &F = LU.Formulae[FIdx];
4646       if (!F.ScaledReg)
4647         continue;
4648       auto P = BestFormulae.insert({{F.ScaledReg, F.Scale}, FIdx});
4649       if (P.second)
4650         continue;
4651 
4652       Formula &Best = LU.Formulae[P.first->second];
4653       if (IsBetterThan(F, Best))
4654         std::swap(F, Best);
4655       LLVM_DEBUG(dbgs() << "  Filtering out formula "; F.print(dbgs());
4656                  dbgs() << "\n"
4657                            "    in favor of formula ";
4658                  Best.print(dbgs()); dbgs() << '\n');
4659 #ifndef NDEBUG
4660       ChangedFormulae = true;
4661 #endif
4662       LU.DeleteFormula(F);
4663       --FIdx;
4664       --NumForms;
4665       Any = true;
4666     }
4667     if (Any)
4668       LU.RecomputeRegs(LUIdx, RegUses);
4669 
4670     // Reset this to prepare for the next use.
4671     BestFormulae.clear();
4672   }
4673 
4674   LLVM_DEBUG(if (ChangedFormulae) {
4675     dbgs() << "\n"
4676               "After filtering out undesirable candidates:\n";
4677     print_uses(dbgs());
4678   });
4679 }
4680 
4681 /// If we are over the complexity limit, filter out any post-inc prefering
4682 /// variables to only post-inc values.
4683 void LSRInstance::NarrowSearchSpaceByFilterPostInc() {
4684   if (!TTI.shouldFavorPostInc())
4685     return;
4686   if (EstimateSearchSpaceComplexity() < ComplexityLimit)
4687     return;
4688 
4689   LLVM_DEBUG(dbgs() << "The search space is too complex.\n"
4690                        "Narrowing the search space by choosing the lowest "
4691                        "register Formula for PostInc Uses.\n");
4692 
4693   for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4694     LSRUse &LU = Uses[LUIdx];
4695 
4696     if (LU.Kind != LSRUse::Address)
4697       continue;
4698     if (!TTI.isIndexedLoadLegal(TTI.MIM_PostInc, LU.AccessTy.getType()) &&
4699         !TTI.isIndexedStoreLegal(TTI.MIM_PostInc, LU.AccessTy.getType()))
4700       continue;
4701 
4702     size_t MinRegs = std::numeric_limits<size_t>::max();
4703     for (const Formula &F : LU.Formulae)
4704       MinRegs = std::min(F.getNumRegs(), MinRegs);
4705 
4706     bool Any = false;
4707     for (size_t FIdx = 0, NumForms = LU.Formulae.size(); FIdx != NumForms;
4708          ++FIdx) {
4709       Formula &F = LU.Formulae[FIdx];
4710       if (F.getNumRegs() > MinRegs) {
4711         LLVM_DEBUG(dbgs() << "  Filtering out formula "; F.print(dbgs());
4712                    dbgs() << "\n");
4713         LU.DeleteFormula(F);
4714         --FIdx;
4715         --NumForms;
4716         Any = true;
4717       }
4718     }
4719     if (Any)
4720       LU.RecomputeRegs(LUIdx, RegUses);
4721 
4722     if (EstimateSearchSpaceComplexity() < ComplexityLimit)
4723       break;
4724   }
4725 
4726   LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
4727 }
4728 
4729 /// The function delete formulas with high registers number expectation.
4730 /// Assuming we don't know the value of each formula (already delete
4731 /// all inefficient), generate probability of not selecting for each
4732 /// register.
4733 /// For example,
4734 /// Use1:
4735 ///  reg(a) + reg({0,+,1})
4736 ///  reg(a) + reg({-1,+,1}) + 1
4737 ///  reg({a,+,1})
4738 /// Use2:
4739 ///  reg(b) + reg({0,+,1})
4740 ///  reg(b) + reg({-1,+,1}) + 1
4741 ///  reg({b,+,1})
4742 /// Use3:
4743 ///  reg(c) + reg(b) + reg({0,+,1})
4744 ///  reg(c) + reg({b,+,1})
4745 ///
4746 /// Probability of not selecting
4747 ///                 Use1   Use2    Use3
4748 /// reg(a)         (1/3) *   1   *   1
4749 /// reg(b)           1   * (1/3) * (1/2)
4750 /// reg({0,+,1})   (2/3) * (2/3) * (1/2)
4751 /// reg({-1,+,1})  (2/3) * (2/3) *   1
4752 /// reg({a,+,1})   (2/3) *   1   *   1
4753 /// reg({b,+,1})     1   * (2/3) * (2/3)
4754 /// reg(c)           1   *   1   *   0
4755 ///
4756 /// Now count registers number mathematical expectation for each formula:
4757 /// Note that for each use we exclude probability if not selecting for the use.
4758 /// For example for Use1 probability for reg(a) would be just 1 * 1 (excluding
4759 /// probabilty 1/3 of not selecting for Use1).
4760 /// Use1:
4761 ///  reg(a) + reg({0,+,1})          1 + 1/3       -- to be deleted
4762 ///  reg(a) + reg({-1,+,1}) + 1     1 + 4/9       -- to be deleted
4763 ///  reg({a,+,1})                   1
4764 /// Use2:
4765 ///  reg(b) + reg({0,+,1})          1/2 + 1/3     -- to be deleted
4766 ///  reg(b) + reg({-1,+,1}) + 1     1/2 + 2/3     -- to be deleted
4767 ///  reg({b,+,1})                   2/3
4768 /// Use3:
4769 ///  reg(c) + reg(b) + reg({0,+,1}) 1 + 1/3 + 4/9 -- to be deleted
4770 ///  reg(c) + reg({b,+,1})          1 + 2/3
4771 void LSRInstance::NarrowSearchSpaceByDeletingCostlyFormulas() {
4772   if (EstimateSearchSpaceComplexity() < ComplexityLimit)
4773     return;
4774   // Ok, we have too many of formulae on our hands to conveniently handle.
4775   // Use a rough heuristic to thin out the list.
4776 
4777   // Set of Regs wich will be 100% used in final solution.
4778   // Used in each formula of a solution (in example above this is reg(c)).
4779   // We can skip them in calculations.
4780   SmallPtrSet<const SCEV *, 4> UniqRegs;
4781   LLVM_DEBUG(dbgs() << "The search space is too complex.\n");
4782 
4783   // Map each register to probability of not selecting
4784   DenseMap <const SCEV *, float> RegNumMap;
4785   for (const SCEV *Reg : RegUses) {
4786     if (UniqRegs.count(Reg))
4787       continue;
4788     float PNotSel = 1;
4789     for (const LSRUse &LU : Uses) {
4790       if (!LU.Regs.count(Reg))
4791         continue;
4792       float P = LU.getNotSelectedProbability(Reg);
4793       if (P != 0.0)
4794         PNotSel *= P;
4795       else
4796         UniqRegs.insert(Reg);
4797     }
4798     RegNumMap.insert(std::make_pair(Reg, PNotSel));
4799   }
4800 
4801   LLVM_DEBUG(
4802       dbgs() << "Narrowing the search space by deleting costly formulas\n");
4803 
4804   // Delete formulas where registers number expectation is high.
4805   for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4806     LSRUse &LU = Uses[LUIdx];
4807     // If nothing to delete - continue.
4808     if (LU.Formulae.size() < 2)
4809       continue;
4810     // This is temporary solution to test performance. Float should be
4811     // replaced with round independent type (based on integers) to avoid
4812     // different results for different target builds.
4813     float FMinRegNum = LU.Formulae[0].getNumRegs();
4814     float FMinARegNum = LU.Formulae[0].getNumRegs();
4815     size_t MinIdx = 0;
4816     for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4817       Formula &F = LU.Formulae[i];
4818       float FRegNum = 0;
4819       float FARegNum = 0;
4820       for (const SCEV *BaseReg : F.BaseRegs) {
4821         if (UniqRegs.count(BaseReg))
4822           continue;
4823         FRegNum += RegNumMap[BaseReg] / LU.getNotSelectedProbability(BaseReg);
4824         if (isa<SCEVAddRecExpr>(BaseReg))
4825           FARegNum +=
4826               RegNumMap[BaseReg] / LU.getNotSelectedProbability(BaseReg);
4827       }
4828       if (const SCEV *ScaledReg = F.ScaledReg) {
4829         if (!UniqRegs.count(ScaledReg)) {
4830           FRegNum +=
4831               RegNumMap[ScaledReg] / LU.getNotSelectedProbability(ScaledReg);
4832           if (isa<SCEVAddRecExpr>(ScaledReg))
4833             FARegNum +=
4834                 RegNumMap[ScaledReg] / LU.getNotSelectedProbability(ScaledReg);
4835         }
4836       }
4837       if (FMinRegNum > FRegNum ||
4838           (FMinRegNum == FRegNum && FMinARegNum > FARegNum)) {
4839         FMinRegNum = FRegNum;
4840         FMinARegNum = FARegNum;
4841         MinIdx = i;
4842       }
4843     }
4844     LLVM_DEBUG(dbgs() << "  The formula "; LU.Formulae[MinIdx].print(dbgs());
4845                dbgs() << " with min reg num " << FMinRegNum << '\n');
4846     if (MinIdx != 0)
4847       std::swap(LU.Formulae[MinIdx], LU.Formulae[0]);
4848     while (LU.Formulae.size() != 1) {
4849       LLVM_DEBUG(dbgs() << "  Deleting "; LU.Formulae.back().print(dbgs());
4850                  dbgs() << '\n');
4851       LU.Formulae.pop_back();
4852     }
4853     LU.RecomputeRegs(LUIdx, RegUses);
4854     assert(LU.Formulae.size() == 1 && "Should be exactly 1 min regs formula");
4855     Formula &F = LU.Formulae[0];
4856     LLVM_DEBUG(dbgs() << "  Leaving only "; F.print(dbgs()); dbgs() << '\n');
4857     // When we choose the formula, the regs become unique.
4858     UniqRegs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
4859     if (F.ScaledReg)
4860       UniqRegs.insert(F.ScaledReg);
4861   }
4862   LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
4863 }
4864 
4865 /// Pick a register which seems likely to be profitable, and then in any use
4866 /// which has any reference to that register, delete all formulae which do not
4867 /// reference that register.
4868 void LSRInstance::NarrowSearchSpaceByPickingWinnerRegs() {
4869   // With all other options exhausted, loop until the system is simple
4870   // enough to handle.
4871   SmallPtrSet<const SCEV *, 4> Taken;
4872   while (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4873     // Ok, we have too many of formulae on our hands to conveniently handle.
4874     // Use a rough heuristic to thin out the list.
4875     LLVM_DEBUG(dbgs() << "The search space is too complex.\n");
4876 
4877     // Pick the register which is used by the most LSRUses, which is likely
4878     // to be a good reuse register candidate.
4879     const SCEV *Best = nullptr;
4880     unsigned BestNum = 0;
4881     for (const SCEV *Reg : RegUses) {
4882       if (Taken.count(Reg))
4883         continue;
4884       if (!Best) {
4885         Best = Reg;
4886         BestNum = RegUses.getUsedByIndices(Reg).count();
4887       } else {
4888         unsigned Count = RegUses.getUsedByIndices(Reg).count();
4889         if (Count > BestNum) {
4890           Best = Reg;
4891           BestNum = Count;
4892         }
4893       }
4894     }
4895     assert(Best && "Failed to find best LSRUse candidate");
4896 
4897     LLVM_DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
4898                       << " will yield profitable reuse.\n");
4899     Taken.insert(Best);
4900 
4901     // In any use with formulae which references this register, delete formulae
4902     // which don't reference it.
4903     for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4904       LSRUse &LU = Uses[LUIdx];
4905       if (!LU.Regs.count(Best)) continue;
4906 
4907       bool Any = false;
4908       for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4909         Formula &F = LU.Formulae[i];
4910         if (!F.referencesReg(Best)) {
4911           LLVM_DEBUG(dbgs() << "  Deleting "; F.print(dbgs()); dbgs() << '\n');
4912           LU.DeleteFormula(F);
4913           --e;
4914           --i;
4915           Any = true;
4916           assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?");
4917           continue;
4918         }
4919       }
4920 
4921       if (Any)
4922         LU.RecomputeRegs(LUIdx, RegUses);
4923     }
4924 
4925     LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
4926   }
4927 }
4928 
4929 /// If there are an extraordinary number of formulae to choose from, use some
4930 /// rough heuristics to prune down the number of formulae. This keeps the main
4931 /// solver from taking an extraordinary amount of time in some worst-case
4932 /// scenarios.
4933 void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
4934   NarrowSearchSpaceByDetectingSupersets();
4935   NarrowSearchSpaceByCollapsingUnrolledCode();
4936   NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
4937   if (FilterSameScaledReg)
4938     NarrowSearchSpaceByFilterFormulaWithSameScaledReg();
4939   NarrowSearchSpaceByFilterPostInc();
4940   if (LSRExpNarrow)
4941     NarrowSearchSpaceByDeletingCostlyFormulas();
4942   else
4943     NarrowSearchSpaceByPickingWinnerRegs();
4944 }
4945 
4946 /// This is the recursive solver.
4947 void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
4948                                Cost &SolutionCost,
4949                                SmallVectorImpl<const Formula *> &Workspace,
4950                                const Cost &CurCost,
4951                                const SmallPtrSet<const SCEV *, 16> &CurRegs,
4952                                DenseSet<const SCEV *> &VisitedRegs) const {
4953   // Some ideas:
4954   //  - prune more:
4955   //    - use more aggressive filtering
4956   //    - sort the formula so that the most profitable solutions are found first
4957   //    - sort the uses too
4958   //  - search faster:
4959   //    - don't compute a cost, and then compare. compare while computing a cost
4960   //      and bail early.
4961   //    - track register sets with SmallBitVector
4962 
4963   const LSRUse &LU = Uses[Workspace.size()];
4964 
4965   // If this use references any register that's already a part of the
4966   // in-progress solution, consider it a requirement that a formula must
4967   // reference that register in order to be considered. This prunes out
4968   // unprofitable searching.
4969   SmallSetVector<const SCEV *, 4> ReqRegs;
4970   for (const SCEV *S : CurRegs)
4971     if (LU.Regs.count(S))
4972       ReqRegs.insert(S);
4973 
4974   SmallPtrSet<const SCEV *, 16> NewRegs;
4975   Cost NewCost(L, SE, TTI);
4976   for (const Formula &F : LU.Formulae) {
4977     // Ignore formulae which may not be ideal in terms of register reuse of
4978     // ReqRegs.  The formula should use all required registers before
4979     // introducing new ones.
4980     // This can sometimes (notably when trying to favour postinc) lead to
4981     // sub-optimial decisions. There it is best left to the cost modelling to
4982     // get correct.
4983     if (!TTI.shouldFavorPostInc() || LU.Kind != LSRUse::Address) {
4984       int NumReqRegsToFind = std::min(F.getNumRegs(), ReqRegs.size());
4985       for (const SCEV *Reg : ReqRegs) {
4986         if ((F.ScaledReg && F.ScaledReg == Reg) ||
4987             is_contained(F.BaseRegs, Reg)) {
4988           --NumReqRegsToFind;
4989           if (NumReqRegsToFind == 0)
4990             break;
4991         }
4992       }
4993       if (NumReqRegsToFind != 0) {
4994         // If none of the formulae satisfied the required registers, then we could
4995         // clear ReqRegs and try again. Currently, we simply give up in this case.
4996         continue;
4997       }
4998     }
4999 
5000     // Evaluate the cost of the current formula. If it's already worse than
5001     // the current best, prune the search at that point.
5002     NewCost = CurCost;
5003     NewRegs = CurRegs;
5004     NewCost.RateFormula(F, NewRegs, VisitedRegs, LU);
5005     if (NewCost.isLess(SolutionCost)) {
5006       Workspace.push_back(&F);
5007       if (Workspace.size() != Uses.size()) {
5008         SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
5009                      NewRegs, VisitedRegs);
5010         if (F.getNumRegs() == 1 && Workspace.size() == 1)
5011           VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
5012       } else {
5013         LLVM_DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
5014                    dbgs() << ".\nRegs:\n";
5015                    for (const SCEV *S : NewRegs) dbgs()
5016                       << "- " << *S << "\n";
5017                    dbgs() << '\n');
5018 
5019         SolutionCost = NewCost;
5020         Solution = Workspace;
5021       }
5022       Workspace.pop_back();
5023     }
5024   }
5025 }
5026 
5027 /// Choose one formula from each use. Return the results in the given Solution
5028 /// vector.
5029 void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
5030   SmallVector<const Formula *, 8> Workspace;
5031   Cost SolutionCost(L, SE, TTI);
5032   SolutionCost.Lose();
5033   Cost CurCost(L, SE, TTI);
5034   SmallPtrSet<const SCEV *, 16> CurRegs;
5035   DenseSet<const SCEV *> VisitedRegs;
5036   Workspace.reserve(Uses.size());
5037 
5038   // SolveRecurse does all the work.
5039   SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
5040                CurRegs, VisitedRegs);
5041   if (Solution.empty()) {
5042     LLVM_DEBUG(dbgs() << "\nNo Satisfactory Solution\n");
5043     return;
5044   }
5045 
5046   // Ok, we've now made all our decisions.
5047   LLVM_DEBUG(dbgs() << "\n"
5048                        "The chosen solution requires ";
5049              SolutionCost.print(dbgs()); dbgs() << ":\n";
5050              for (size_t i = 0, e = Uses.size(); i != e; ++i) {
5051                dbgs() << "  ";
5052                Uses[i].print(dbgs());
5053                dbgs() << "\n"
5054                          "    ";
5055                Solution[i]->print(dbgs());
5056                dbgs() << '\n';
5057              });
5058 
5059   assert(Solution.size() == Uses.size() && "Malformed solution!");
5060 }
5061 
5062 /// Helper for AdjustInsertPositionForExpand. Climb up the dominator tree far as
5063 /// we can go while still being dominated by the input positions. This helps
5064 /// canonicalize the insert position, which encourages sharing.
5065 BasicBlock::iterator
5066 LSRInstance::HoistInsertPosition(BasicBlock::iterator IP,
5067                                  const SmallVectorImpl<Instruction *> &Inputs)
5068                                                                          const {
5069   Instruction *Tentative = &*IP;
5070   while (true) {
5071     bool AllDominate = true;
5072     Instruction *BetterPos = nullptr;
5073     // Don't bother attempting to insert before a catchswitch, their basic block
5074     // cannot have other non-PHI instructions.
5075     if (isa<CatchSwitchInst>(Tentative))
5076       return IP;
5077 
5078     for (Instruction *Inst : Inputs) {
5079       if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
5080         AllDominate = false;
5081         break;
5082       }
5083       // Attempt to find an insert position in the middle of the block,
5084       // instead of at the end, so that it can be used for other expansions.
5085       if (Tentative->getParent() == Inst->getParent() &&
5086           (!BetterPos || !DT.dominates(Inst, BetterPos)))
5087         BetterPos = &*std::next(BasicBlock::iterator(Inst));
5088     }
5089     if (!AllDominate)
5090       break;
5091     if (BetterPos)
5092       IP = BetterPos->getIterator();
5093     else
5094       IP = Tentative->getIterator();
5095 
5096     const Loop *IPLoop = LI.getLoopFor(IP->getParent());
5097     unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0;
5098 
5099     BasicBlock *IDom;
5100     for (DomTreeNode *Rung = DT.getNode(IP->getParent()); ; ) {
5101       if (!Rung) return IP;
5102       Rung = Rung->getIDom();
5103       if (!Rung) return IP;
5104       IDom = Rung->getBlock();
5105 
5106       // Don't climb into a loop though.
5107       const Loop *IDomLoop = LI.getLoopFor(IDom);
5108       unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0;
5109       if (IDomDepth <= IPLoopDepth &&
5110           (IDomDepth != IPLoopDepth || IDomLoop == IPLoop))
5111         break;
5112     }
5113 
5114     Tentative = IDom->getTerminator();
5115   }
5116 
5117   return IP;
5118 }
5119 
5120 /// Determine an input position which will be dominated by the operands and
5121 /// which will dominate the result.
5122 BasicBlock::iterator
5123 LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator LowestIP,
5124                                            const LSRFixup &LF,
5125                                            const LSRUse &LU,
5126                                            SCEVExpander &Rewriter) const {
5127   // Collect some instructions which must be dominated by the
5128   // expanding replacement. These must be dominated by any operands that
5129   // will be required in the expansion.
5130   SmallVector<Instruction *, 4> Inputs;
5131   if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
5132     Inputs.push_back(I);
5133   if (LU.Kind == LSRUse::ICmpZero)
5134     if (Instruction *I =
5135           dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
5136       Inputs.push_back(I);
5137   if (LF.PostIncLoops.count(L)) {
5138     if (LF.isUseFullyOutsideLoop(L))
5139       Inputs.push_back(L->getLoopLatch()->getTerminator());
5140     else
5141       Inputs.push_back(IVIncInsertPos);
5142   }
5143   // The expansion must also be dominated by the increment positions of any
5144   // loops it for which it is using post-inc mode.
5145   for (const Loop *PIL : LF.PostIncLoops) {
5146     if (PIL == L) continue;
5147 
5148     // Be dominated by the loop exit.
5149     SmallVector<BasicBlock *, 4> ExitingBlocks;
5150     PIL->getExitingBlocks(ExitingBlocks);
5151     if (!ExitingBlocks.empty()) {
5152       BasicBlock *BB = ExitingBlocks[0];
5153       for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i)
5154         BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]);
5155       Inputs.push_back(BB->getTerminator());
5156     }
5157   }
5158 
5159   assert(!isa<PHINode>(LowestIP) && !LowestIP->isEHPad()
5160          && !isa<DbgInfoIntrinsic>(LowestIP) &&
5161          "Insertion point must be a normal instruction");
5162 
5163   // Then, climb up the immediate dominator tree as far as we can go while
5164   // still being dominated by the input positions.
5165   BasicBlock::iterator IP = HoistInsertPosition(LowestIP, Inputs);
5166 
5167   // Don't insert instructions before PHI nodes.
5168   while (isa<PHINode>(IP)) ++IP;
5169 
5170   // Ignore landingpad instructions.
5171   while (IP->isEHPad()) ++IP;
5172 
5173   // Ignore debug intrinsics.
5174   while (isa<DbgInfoIntrinsic>(IP)) ++IP;
5175 
5176   // Set IP below instructions recently inserted by SCEVExpander. This keeps the
5177   // IP consistent across expansions and allows the previously inserted
5178   // instructions to be reused by subsequent expansion.
5179   while (Rewriter.isInsertedInstruction(&*IP) && IP != LowestIP)
5180     ++IP;
5181 
5182   return IP;
5183 }
5184 
5185 /// Emit instructions for the leading candidate expression for this LSRUse (this
5186 /// is called "expanding").
5187 Value *LSRInstance::Expand(const LSRUse &LU, const LSRFixup &LF,
5188                            const Formula &F, BasicBlock::iterator IP,
5189                            SCEVExpander &Rewriter,
5190                            SmallVectorImpl<WeakTrackingVH> &DeadInsts) const {
5191   if (LU.RigidFormula)
5192     return LF.OperandValToReplace;
5193 
5194   // Determine an input position which will be dominated by the operands and
5195   // which will dominate the result.
5196   IP = AdjustInsertPositionForExpand(IP, LF, LU, Rewriter);
5197   Rewriter.setInsertPoint(&*IP);
5198 
5199   // Inform the Rewriter if we have a post-increment use, so that it can
5200   // perform an advantageous expansion.
5201   Rewriter.setPostInc(LF.PostIncLoops);
5202 
5203   // This is the type that the user actually needs.
5204   Type *OpTy = LF.OperandValToReplace->getType();
5205   // This will be the type that we'll initially expand to.
5206   Type *Ty = F.getType();
5207   if (!Ty)
5208     // No type known; just expand directly to the ultimate type.
5209     Ty = OpTy;
5210   else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
5211     // Expand directly to the ultimate type if it's the right size.
5212     Ty = OpTy;
5213   // This is the type to do integer arithmetic in.
5214   Type *IntTy = SE.getEffectiveSCEVType(Ty);
5215 
5216   // Build up a list of operands to add together to form the full base.
5217   SmallVector<const SCEV *, 8> Ops;
5218 
5219   // Expand the BaseRegs portion.
5220   for (const SCEV *Reg : F.BaseRegs) {
5221     assert(!Reg->isZero() && "Zero allocated in a base register!");
5222 
5223     // If we're expanding for a post-inc user, make the post-inc adjustment.
5224     Reg = denormalizeForPostIncUse(Reg, LF.PostIncLoops, SE);
5225     Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, nullptr)));
5226   }
5227 
5228   // Expand the ScaledReg portion.
5229   Value *ICmpScaledV = nullptr;
5230   if (F.Scale != 0) {
5231     const SCEV *ScaledS = F.ScaledReg;
5232 
5233     // If we're expanding for a post-inc user, make the post-inc adjustment.
5234     PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
5235     ScaledS = denormalizeForPostIncUse(ScaledS, Loops, SE);
5236 
5237     if (LU.Kind == LSRUse::ICmpZero) {
5238       // Expand ScaleReg as if it was part of the base regs.
5239       if (F.Scale == 1)
5240         Ops.push_back(
5241             SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr)));
5242       else {
5243         // An interesting way of "folding" with an icmp is to use a negated
5244         // scale, which we'll implement by inserting it into the other operand
5245         // of the icmp.
5246         assert(F.Scale == -1 &&
5247                "The only scale supported by ICmpZero uses is -1!");
5248         ICmpScaledV = Rewriter.expandCodeFor(ScaledS, nullptr);
5249       }
5250     } else {
5251       // Otherwise just expand the scaled register and an explicit scale,
5252       // which is expected to be matched as part of the address.
5253 
5254       // Flush the operand list to suppress SCEVExpander hoisting address modes.
5255       // Unless the addressing mode will not be folded.
5256       if (!Ops.empty() && LU.Kind == LSRUse::Address &&
5257           isAMCompletelyFolded(TTI, LU, F)) {
5258         Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), nullptr);
5259         Ops.clear();
5260         Ops.push_back(SE.getUnknown(FullV));
5261       }
5262       ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr));
5263       if (F.Scale != 1)
5264         ScaledS =
5265             SE.getMulExpr(ScaledS, SE.getConstant(ScaledS->getType(), F.Scale));
5266       Ops.push_back(ScaledS);
5267     }
5268   }
5269 
5270   // Expand the GV portion.
5271   if (F.BaseGV) {
5272     // Flush the operand list to suppress SCEVExpander hoisting.
5273     if (!Ops.empty()) {
5274       Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty);
5275       Ops.clear();
5276       Ops.push_back(SE.getUnknown(FullV));
5277     }
5278     Ops.push_back(SE.getUnknown(F.BaseGV));
5279   }
5280 
5281   // Flush the operand list to suppress SCEVExpander hoisting of both folded and
5282   // unfolded offsets. LSR assumes they both live next to their uses.
5283   if (!Ops.empty()) {
5284     Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty);
5285     Ops.clear();
5286     Ops.push_back(SE.getUnknown(FullV));
5287   }
5288 
5289   // Expand the immediate portion.
5290   int64_t Offset = (uint64_t)F.BaseOffset + LF.Offset;
5291   if (Offset != 0) {
5292     if (LU.Kind == LSRUse::ICmpZero) {
5293       // The other interesting way of "folding" with an ICmpZero is to use a
5294       // negated immediate.
5295       if (!ICmpScaledV)
5296         ICmpScaledV = ConstantInt::get(IntTy, -(uint64_t)Offset);
5297       else {
5298         Ops.push_back(SE.getUnknown(ICmpScaledV));
5299         ICmpScaledV = ConstantInt::get(IntTy, Offset);
5300       }
5301     } else {
5302       // Just add the immediate values. These again are expected to be matched
5303       // as part of the address.
5304       Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset)));
5305     }
5306   }
5307 
5308   // Expand the unfolded offset portion.
5309   int64_t UnfoldedOffset = F.UnfoldedOffset;
5310   if (UnfoldedOffset != 0) {
5311     // Just add the immediate values.
5312     Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy,
5313                                                        UnfoldedOffset)));
5314   }
5315 
5316   // Emit instructions summing all the operands.
5317   const SCEV *FullS = Ops.empty() ?
5318                       SE.getConstant(IntTy, 0) :
5319                       SE.getAddExpr(Ops);
5320   Value *FullV = Rewriter.expandCodeFor(FullS, Ty);
5321 
5322   // We're done expanding now, so reset the rewriter.
5323   Rewriter.clearPostInc();
5324 
5325   // An ICmpZero Formula represents an ICmp which we're handling as a
5326   // comparison against zero. Now that we've expanded an expression for that
5327   // form, update the ICmp's other operand.
5328   if (LU.Kind == LSRUse::ICmpZero) {
5329     ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
5330     if (auto *OperandIsInstr = dyn_cast<Instruction>(CI->getOperand(1)))
5331       DeadInsts.emplace_back(OperandIsInstr);
5332     assert(!F.BaseGV && "ICmp does not support folding a global value and "
5333                            "a scale at the same time!");
5334     if (F.Scale == -1) {
5335       if (ICmpScaledV->getType() != OpTy) {
5336         Instruction *Cast =
5337           CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
5338                                                    OpTy, false),
5339                            ICmpScaledV, OpTy, "tmp", CI);
5340         ICmpScaledV = Cast;
5341       }
5342       CI->setOperand(1, ICmpScaledV);
5343     } else {
5344       // A scale of 1 means that the scale has been expanded as part of the
5345       // base regs.
5346       assert((F.Scale == 0 || F.Scale == 1) &&
5347              "ICmp does not support folding a global value and "
5348              "a scale at the same time!");
5349       Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),
5350                                            -(uint64_t)Offset);
5351       if (C->getType() != OpTy)
5352         C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
5353                                                           OpTy, false),
5354                                   C, OpTy);
5355 
5356       CI->setOperand(1, C);
5357     }
5358   }
5359 
5360   return FullV;
5361 }
5362 
5363 /// Helper for Rewrite. PHI nodes are special because the use of their operands
5364 /// effectively happens in their predecessor blocks, so the expression may need
5365 /// to be expanded in multiple places.
5366 void LSRInstance::RewriteForPHI(
5367     PHINode *PN, const LSRUse &LU, const LSRFixup &LF, const Formula &F,
5368     SCEVExpander &Rewriter, SmallVectorImpl<WeakTrackingVH> &DeadInsts) const {
5369   DenseMap<BasicBlock *, Value *> Inserted;
5370   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
5371     if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
5372       bool needUpdateFixups = false;
5373       BasicBlock *BB = PN->getIncomingBlock(i);
5374 
5375       // If this is a critical edge, split the edge so that we do not insert
5376       // the code on all predecessor/successor paths.  We do this unless this
5377       // is the canonical backedge for this loop, which complicates post-inc
5378       // users.
5379       if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
5380           !isa<IndirectBrInst>(BB->getTerminator()) &&
5381           !isa<CatchSwitchInst>(BB->getTerminator())) {
5382         BasicBlock *Parent = PN->getParent();
5383         Loop *PNLoop = LI.getLoopFor(Parent);
5384         if (!PNLoop || Parent != PNLoop->getHeader()) {
5385           // Split the critical edge.
5386           BasicBlock *NewBB = nullptr;
5387           if (!Parent->isLandingPad()) {
5388             NewBB =
5389                 SplitCriticalEdge(BB, Parent,
5390                                   CriticalEdgeSplittingOptions(&DT, &LI, MSSAU)
5391                                       .setMergeIdenticalEdges()
5392                                       .setKeepOneInputPHIs());
5393           } else {
5394             SmallVector<BasicBlock*, 2> NewBBs;
5395             SplitLandingPadPredecessors(Parent, BB, "", "", NewBBs, &DT, &LI);
5396             NewBB = NewBBs[0];
5397           }
5398           // If NewBB==NULL, then SplitCriticalEdge refused to split because all
5399           // phi predecessors are identical. The simple thing to do is skip
5400           // splitting in this case rather than complicate the API.
5401           if (NewBB) {
5402             // If PN is outside of the loop and BB is in the loop, we want to
5403             // move the block to be immediately before the PHI block, not
5404             // immediately after BB.
5405             if (L->contains(BB) && !L->contains(PN))
5406               NewBB->moveBefore(PN->getParent());
5407 
5408             // Splitting the edge can reduce the number of PHI entries we have.
5409             e = PN->getNumIncomingValues();
5410             BB = NewBB;
5411             i = PN->getBasicBlockIndex(BB);
5412 
5413             needUpdateFixups = true;
5414           }
5415         }
5416       }
5417 
5418       std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
5419         Inserted.insert(std::make_pair(BB, static_cast<Value *>(nullptr)));
5420       if (!Pair.second)
5421         PN->setIncomingValue(i, Pair.first->second);
5422       else {
5423         Value *FullV = Expand(LU, LF, F, BB->getTerminator()->getIterator(),
5424                               Rewriter, DeadInsts);
5425 
5426         // If this is reuse-by-noop-cast, insert the noop cast.
5427         Type *OpTy = LF.OperandValToReplace->getType();
5428         if (FullV->getType() != OpTy)
5429           FullV =
5430             CastInst::Create(CastInst::getCastOpcode(FullV, false,
5431                                                      OpTy, false),
5432                              FullV, LF.OperandValToReplace->getType(),
5433                              "tmp", BB->getTerminator());
5434 
5435         PN->setIncomingValue(i, FullV);
5436         Pair.first->second = FullV;
5437       }
5438 
5439       // If LSR splits critical edge and phi node has other pending
5440       // fixup operands, we need to update those pending fixups. Otherwise
5441       // formulae will not be implemented completely and some instructions
5442       // will not be eliminated.
5443       if (needUpdateFixups) {
5444         for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx)
5445           for (LSRFixup &Fixup : Uses[LUIdx].Fixups)
5446             // If fixup is supposed to rewrite some operand in the phi
5447             // that was just updated, it may be already moved to
5448             // another phi node. Such fixup requires update.
5449             if (Fixup.UserInst == PN) {
5450               // Check if the operand we try to replace still exists in the
5451               // original phi.
5452               bool foundInOriginalPHI = false;
5453               for (const auto &val : PN->incoming_values())
5454                 if (val == Fixup.OperandValToReplace) {
5455                   foundInOriginalPHI = true;
5456                   break;
5457                 }
5458 
5459               // If fixup operand found in original PHI - nothing to do.
5460               if (foundInOriginalPHI)
5461                 continue;
5462 
5463               // Otherwise it might be moved to another PHI and requires update.
5464               // If fixup operand not found in any of the incoming blocks that
5465               // means we have already rewritten it - nothing to do.
5466               for (const auto &Block : PN->blocks())
5467                 for (BasicBlock::iterator I = Block->begin(); isa<PHINode>(I);
5468                      ++I) {
5469                   PHINode *NewPN = cast<PHINode>(I);
5470                   for (const auto &val : NewPN->incoming_values())
5471                     if (val == Fixup.OperandValToReplace)
5472                       Fixup.UserInst = NewPN;
5473                 }
5474             }
5475       }
5476     }
5477 }
5478 
5479 /// Emit instructions for the leading candidate expression for this LSRUse (this
5480 /// is called "expanding"), and update the UserInst to reference the newly
5481 /// expanded value.
5482 void LSRInstance::Rewrite(const LSRUse &LU, const LSRFixup &LF,
5483                           const Formula &F, SCEVExpander &Rewriter,
5484                           SmallVectorImpl<WeakTrackingVH> &DeadInsts) const {
5485   // First, find an insertion point that dominates UserInst. For PHI nodes,
5486   // find the nearest block which dominates all the relevant uses.
5487   if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
5488     RewriteForPHI(PN, LU, LF, F, Rewriter, DeadInsts);
5489   } else {
5490     Value *FullV =
5491       Expand(LU, LF, F, LF.UserInst->getIterator(), Rewriter, DeadInsts);
5492 
5493     // If this is reuse-by-noop-cast, insert the noop cast.
5494     Type *OpTy = LF.OperandValToReplace->getType();
5495     if (FullV->getType() != OpTy) {
5496       Instruction *Cast =
5497         CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
5498                          FullV, OpTy, "tmp", LF.UserInst);
5499       FullV = Cast;
5500     }
5501 
5502     // Update the user. ICmpZero is handled specially here (for now) because
5503     // Expand may have updated one of the operands of the icmp already, and
5504     // its new value may happen to be equal to LF.OperandValToReplace, in
5505     // which case doing replaceUsesOfWith leads to replacing both operands
5506     // with the same value. TODO: Reorganize this.
5507     if (LU.Kind == LSRUse::ICmpZero)
5508       LF.UserInst->setOperand(0, FullV);
5509     else
5510       LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
5511   }
5512 
5513   if (auto *OperandIsInstr = dyn_cast<Instruction>(LF.OperandValToReplace))
5514     DeadInsts.emplace_back(OperandIsInstr);
5515 }
5516 
5517 /// Rewrite all the fixup locations with new values, following the chosen
5518 /// solution.
5519 void LSRInstance::ImplementSolution(
5520     const SmallVectorImpl<const Formula *> &Solution) {
5521   // Keep track of instructions we may have made dead, so that
5522   // we can remove them after we are done working.
5523   SmallVector<WeakTrackingVH, 16> DeadInsts;
5524 
5525   SCEVExpander Rewriter(SE, L->getHeader()->getModule()->getDataLayout(), "lsr",
5526                         false);
5527 #ifndef NDEBUG
5528   Rewriter.setDebugType(DEBUG_TYPE);
5529 #endif
5530   Rewriter.disableCanonicalMode();
5531   Rewriter.enableLSRMode();
5532   Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
5533 
5534   // Mark phi nodes that terminate chains so the expander tries to reuse them.
5535   for (const IVChain &Chain : IVChainVec) {
5536     if (PHINode *PN = dyn_cast<PHINode>(Chain.tailUserInst()))
5537       Rewriter.setChainedPhi(PN);
5538   }
5539 
5540   // Expand the new value definitions and update the users.
5541   for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx)
5542     for (const LSRFixup &Fixup : Uses[LUIdx].Fixups) {
5543       Rewrite(Uses[LUIdx], Fixup, *Solution[LUIdx], Rewriter, DeadInsts);
5544       Changed = true;
5545     }
5546 
5547   for (const IVChain &Chain : IVChainVec) {
5548     GenerateIVChain(Chain, Rewriter, DeadInsts);
5549     Changed = true;
5550   }
5551   // Clean up after ourselves. This must be done before deleting any
5552   // instructions.
5553   Rewriter.clear();
5554 
5555   Changed |= RecursivelyDeleteTriviallyDeadInstructionsPermissive(DeadInsts,
5556                                                                   &TLI, MSSAU);
5557 }
5558 
5559 LSRInstance::LSRInstance(Loop *L, IVUsers &IU, ScalarEvolution &SE,
5560                          DominatorTree &DT, LoopInfo &LI,
5561                          const TargetTransformInfo &TTI, AssumptionCache &AC,
5562                          TargetLibraryInfo &TLI, MemorySSAUpdater *MSSAU)
5563     : IU(IU), SE(SE), DT(DT), LI(LI), AC(AC), TLI(TLI), TTI(TTI), L(L),
5564       MSSAU(MSSAU), FavorBackedgeIndex(EnableBackedgeIndexing &&
5565                                        TTI.shouldFavorBackedgeIndex(L)) {
5566   // If LoopSimplify form is not available, stay out of trouble.
5567   if (!L->isLoopSimplifyForm())
5568     return;
5569 
5570   // If there's no interesting work to be done, bail early.
5571   if (IU.empty()) return;
5572 
5573   // If there's too much analysis to be done, bail early. We won't be able to
5574   // model the problem anyway.
5575   unsigned NumUsers = 0;
5576   for (const IVStrideUse &U : IU) {
5577     if (++NumUsers > MaxIVUsers) {
5578       (void)U;
5579       LLVM_DEBUG(dbgs() << "LSR skipping loop, too many IV Users in " << U
5580                         << "\n");
5581       return;
5582     }
5583     // Bail out if we have a PHI on an EHPad that gets a value from a
5584     // CatchSwitchInst.  Because the CatchSwitchInst cannot be split, there is
5585     // no good place to stick any instructions.
5586     if (auto *PN = dyn_cast<PHINode>(U.getUser())) {
5587        auto *FirstNonPHI = PN->getParent()->getFirstNonPHI();
5588        if (isa<FuncletPadInst>(FirstNonPHI) ||
5589            isa<CatchSwitchInst>(FirstNonPHI))
5590          for (BasicBlock *PredBB : PN->blocks())
5591            if (isa<CatchSwitchInst>(PredBB->getFirstNonPHI()))
5592              return;
5593     }
5594   }
5595 
5596 #ifndef NDEBUG
5597   // All dominating loops must have preheaders, or SCEVExpander may not be able
5598   // to materialize an AddRecExpr whose Start is an outer AddRecExpr.
5599   //
5600   // IVUsers analysis should only create users that are dominated by simple loop
5601   // headers. Since this loop should dominate all of its users, its user list
5602   // should be empty if this loop itself is not within a simple loop nest.
5603   for (DomTreeNode *Rung = DT.getNode(L->getLoopPreheader());
5604        Rung; Rung = Rung->getIDom()) {
5605     BasicBlock *BB = Rung->getBlock();
5606     const Loop *DomLoop = LI.getLoopFor(BB);
5607     if (DomLoop && DomLoop->getHeader() == BB) {
5608       assert(DomLoop->getLoopPreheader() && "LSR needs a simplified loop nest");
5609     }
5610   }
5611 #endif // DEBUG
5612 
5613   LLVM_DEBUG(dbgs() << "\nLSR on loop ";
5614              L->getHeader()->printAsOperand(dbgs(), /*PrintType=*/false);
5615              dbgs() << ":\n");
5616 
5617   // First, perform some low-level loop optimizations.
5618   OptimizeShadowIV();
5619   OptimizeLoopTermCond();
5620 
5621   // If loop preparation eliminates all interesting IV users, bail.
5622   if (IU.empty()) return;
5623 
5624   // Skip nested loops until we can model them better with formulae.
5625   if (!L->isInnermost()) {
5626     LLVM_DEBUG(dbgs() << "LSR skipping outer loop " << *L << "\n");
5627     return;
5628   }
5629 
5630   // Start collecting data and preparing for the solver.
5631   // If number of registers is not the major cost, we cannot benefit from the
5632   // current profitable chain optimization which is based on number of
5633   // registers.
5634   // FIXME: add profitable chain optimization for other kinds major cost, for
5635   // example number of instructions.
5636   if (TTI.isNumRegsMajorCostOfLSR() || StressIVChain)
5637     CollectChains();
5638   CollectInterestingTypesAndFactors();
5639   CollectFixupsAndInitialFormulae();
5640   CollectLoopInvariantFixupsAndFormulae();
5641 
5642   if (Uses.empty())
5643     return;
5644 
5645   LLVM_DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
5646              print_uses(dbgs()));
5647 
5648   // Now use the reuse data to generate a bunch of interesting ways
5649   // to formulate the values needed for the uses.
5650   GenerateAllReuseFormulae();
5651 
5652   FilterOutUndesirableDedicatedRegisters();
5653   NarrowSearchSpaceUsingHeuristics();
5654 
5655   SmallVector<const Formula *, 8> Solution;
5656   Solve(Solution);
5657 
5658   // Release memory that is no longer needed.
5659   Factors.clear();
5660   Types.clear();
5661   RegUses.clear();
5662 
5663   if (Solution.empty())
5664     return;
5665 
5666 #ifndef NDEBUG
5667   // Formulae should be legal.
5668   for (const LSRUse &LU : Uses) {
5669     for (const Formula &F : LU.Formulae)
5670       assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
5671                         F) && "Illegal formula generated!");
5672   };
5673 #endif
5674 
5675   // Now that we've decided what we want, make it so.
5676   ImplementSolution(Solution);
5677 }
5678 
5679 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5680 void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
5681   if (Factors.empty() && Types.empty()) return;
5682 
5683   OS << "LSR has identified the following interesting factors and types: ";
5684   bool First = true;
5685 
5686   for (int64_t Factor : Factors) {
5687     if (!First) OS << ", ";
5688     First = false;
5689     OS << '*' << Factor;
5690   }
5691 
5692   for (Type *Ty : Types) {
5693     if (!First) OS << ", ";
5694     First = false;
5695     OS << '(' << *Ty << ')';
5696   }
5697   OS << '\n';
5698 }
5699 
5700 void LSRInstance::print_fixups(raw_ostream &OS) const {
5701   OS << "LSR is examining the following fixup sites:\n";
5702   for (const LSRUse &LU : Uses)
5703     for (const LSRFixup &LF : LU.Fixups) {
5704       dbgs() << "  ";
5705       LF.print(OS);
5706       OS << '\n';
5707     }
5708 }
5709 
5710 void LSRInstance::print_uses(raw_ostream &OS) const {
5711   OS << "LSR is examining the following uses:\n";
5712   for (const LSRUse &LU : Uses) {
5713     dbgs() << "  ";
5714     LU.print(OS);
5715     OS << '\n';
5716     for (const Formula &F : LU.Formulae) {
5717       OS << "    ";
5718       F.print(OS);
5719       OS << '\n';
5720     }
5721   }
5722 }
5723 
5724 void LSRInstance::print(raw_ostream &OS) const {
5725   print_factors_and_types(OS);
5726   print_fixups(OS);
5727   print_uses(OS);
5728 }
5729 
5730 LLVM_DUMP_METHOD void LSRInstance::dump() const {
5731   print(errs()); errs() << '\n';
5732 }
5733 #endif
5734 
5735 namespace {
5736 
5737 class LoopStrengthReduce : public LoopPass {
5738 public:
5739   static char ID; // Pass ID, replacement for typeid
5740 
5741   LoopStrengthReduce();
5742 
5743 private:
5744   bool runOnLoop(Loop *L, LPPassManager &LPM) override;
5745   void getAnalysisUsage(AnalysisUsage &AU) const override;
5746 };
5747 
5748 } // end anonymous namespace
5749 
5750 LoopStrengthReduce::LoopStrengthReduce() : LoopPass(ID) {
5751   initializeLoopStrengthReducePass(*PassRegistry::getPassRegistry());
5752 }
5753 
5754 void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
5755   // We split critical edges, so we change the CFG.  However, we do update
5756   // many analyses if they are around.
5757   AU.addPreservedID(LoopSimplifyID);
5758 
5759   AU.addRequired<LoopInfoWrapperPass>();
5760   AU.addPreserved<LoopInfoWrapperPass>();
5761   AU.addRequiredID(LoopSimplifyID);
5762   AU.addRequired<DominatorTreeWrapperPass>();
5763   AU.addPreserved<DominatorTreeWrapperPass>();
5764   AU.addRequired<ScalarEvolutionWrapperPass>();
5765   AU.addPreserved<ScalarEvolutionWrapperPass>();
5766   AU.addRequired<AssumptionCacheTracker>();
5767   AU.addRequired<TargetLibraryInfoWrapperPass>();
5768   // Requiring LoopSimplify a second time here prevents IVUsers from running
5769   // twice, since LoopSimplify was invalidated by running ScalarEvolution.
5770   AU.addRequiredID(LoopSimplifyID);
5771   AU.addRequired<IVUsersWrapperPass>();
5772   AU.addPreserved<IVUsersWrapperPass>();
5773   AU.addRequired<TargetTransformInfoWrapperPass>();
5774   AU.addPreserved<MemorySSAWrapperPass>();
5775 }
5776 
5777 static bool ReduceLoopStrength(Loop *L, IVUsers &IU, ScalarEvolution &SE,
5778                                DominatorTree &DT, LoopInfo &LI,
5779                                const TargetTransformInfo &TTI,
5780                                AssumptionCache &AC, TargetLibraryInfo &TLI,
5781                                MemorySSA *MSSA) {
5782 
5783   bool Changed = false;
5784   std::unique_ptr<MemorySSAUpdater> MSSAU;
5785   if (MSSA)
5786     MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
5787 
5788   // Run the main LSR transformation.
5789   Changed |=
5790       LSRInstance(L, IU, SE, DT, LI, TTI, AC, TLI, MSSAU.get()).getChanged();
5791 
5792   // Remove any extra phis created by processing inner loops.
5793   Changed |= DeleteDeadPHIs(L->getHeader(), &TLI, MSSAU.get());
5794   if (EnablePhiElim && L->isLoopSimplifyForm()) {
5795     SmallVector<WeakTrackingVH, 16> DeadInsts;
5796     const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
5797     SCEVExpander Rewriter(SE, DL, "lsr", false);
5798 #ifndef NDEBUG
5799     Rewriter.setDebugType(DEBUG_TYPE);
5800 #endif
5801     unsigned numFolded = Rewriter.replaceCongruentIVs(L, &DT, DeadInsts, &TTI);
5802     if (numFolded) {
5803       Changed = true;
5804       RecursivelyDeleteTriviallyDeadInstructionsPermissive(DeadInsts, &TLI,
5805                                                            MSSAU.get());
5806       DeleteDeadPHIs(L->getHeader(), &TLI, MSSAU.get());
5807     }
5808   }
5809   return Changed;
5810 }
5811 
5812 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
5813   if (skipLoop(L))
5814     return false;
5815 
5816   auto &IU = getAnalysis<IVUsersWrapperPass>().getIU();
5817   auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5818   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
5819   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5820   const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
5821       *L->getHeader()->getParent());
5822   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
5823       *L->getHeader()->getParent());
5824   auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
5825       *L->getHeader()->getParent());
5826   auto *MSSAAnalysis = getAnalysisIfAvailable<MemorySSAWrapperPass>();
5827   MemorySSA *MSSA = nullptr;
5828   if (MSSAAnalysis)
5829     MSSA = &MSSAAnalysis->getMSSA();
5830   return ReduceLoopStrength(L, IU, SE, DT, LI, TTI, AC, TLI, MSSA);
5831 }
5832 
5833 PreservedAnalyses LoopStrengthReducePass::run(Loop &L, LoopAnalysisManager &AM,
5834                                               LoopStandardAnalysisResults &AR,
5835                                               LPMUpdater &) {
5836   if (!ReduceLoopStrength(&L, AM.getResult<IVUsersAnalysis>(L, AR), AR.SE,
5837                           AR.DT, AR.LI, AR.TTI, AR.AC, AR.TLI, AR.MSSA))
5838     return PreservedAnalyses::all();
5839 
5840   auto PA = getLoopPassPreservedAnalyses();
5841   if (AR.MSSA)
5842     PA.preserve<MemorySSAAnalysis>();
5843   return PA;
5844 }
5845 
5846 char LoopStrengthReduce::ID = 0;
5847 
5848 INITIALIZE_PASS_BEGIN(LoopStrengthReduce, "loop-reduce",
5849                       "Loop Strength Reduction", false, false)
5850 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
5851 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
5852 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
5853 INITIALIZE_PASS_DEPENDENCY(IVUsersWrapperPass)
5854 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
5855 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5856 INITIALIZE_PASS_END(LoopStrengthReduce, "loop-reduce",
5857                     "Loop Strength Reduction", false, false)
5858 
5859 Pass *llvm::createLoopStrengthReducePass() { return new LoopStrengthReduce(); }
5860