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