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