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