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