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