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