Move SCEV::dominates and properlyDominates to ScalarEvolution.
[oota-llvm.git] / lib / Transforms / Scalar / LoopStrengthReduce.cpp
1 //===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This transformation analyzes and transforms the induction variables (and
11 // computations derived from them) into forms suitable for efficient execution
12 // on the target.
13 //
14 // This pass performs a strength reduction on array references inside loops that
15 // have as one or more of their components the loop induction variable, it
16 // rewrites expressions to take advantage of scaled-index addressing modes
17 // available on the target, and it performs a variety of other optimizations
18 // related to loop induction variables.
19 //
20 // Terminology note: this code has a lot of handling for "post-increment" or
21 // "post-inc" users. This is not talking about post-increment addressing modes;
22 // it is instead talking about code like this:
23 //
24 //   %i = phi [ 0, %entry ], [ %i.next, %latch ]
25 //   ...
26 //   %i.next = add %i, 1
27 //   %c = icmp eq %i.next, %n
28 //
29 // The SCEV for %i is {0,+,1}<%L>. The SCEV for %i.next is {1,+,1}<%L>, however
30 // it's useful to think about these as the same register, with some uses using
31 // the value of the register before the add and some using // it after. In this
32 // example, the icmp is a post-increment user, since it uses %i.next, which is
33 // the value of the induction variable after the increment. The other common
34 // case of post-increment users is users outside the loop.
35 //
36 // TODO: More sophistication in the way Formulae are generated and filtered.
37 //
38 // TODO: Handle multiple loops at a time.
39 //
40 // TODO: Should TargetLowering::AddrMode::BaseGV be changed to a ConstantExpr
41 //       instead 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 #define DEBUG_TYPE "loop-reduce"
57 #include "llvm/Transforms/Scalar.h"
58 #include "llvm/Constants.h"
59 #include "llvm/Instructions.h"
60 #include "llvm/IntrinsicInst.h"
61 #include "llvm/DerivedTypes.h"
62 #include "llvm/Analysis/IVUsers.h"
63 #include "llvm/Analysis/Dominators.h"
64 #include "llvm/Analysis/LoopPass.h"
65 #include "llvm/Analysis/ScalarEvolutionExpander.h"
66 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
67 #include "llvm/Transforms/Utils/Local.h"
68 #include "llvm/ADT/SmallBitVector.h"
69 #include "llvm/ADT/SetVector.h"
70 #include "llvm/ADT/DenseSet.h"
71 #include "llvm/Support/Debug.h"
72 #include "llvm/Support/ValueHandle.h"
73 #include "llvm/Support/raw_ostream.h"
74 #include "llvm/Target/TargetLowering.h"
75 #include <algorithm>
76 using namespace llvm;
77
78 namespace {
79
80 /// RegSortData - This class holds data which is used to order reuse candidates.
81 class RegSortData {
82 public:
83   /// UsedByIndices - This represents the set of LSRUse indices which reference
84   /// a particular register.
85   SmallBitVector UsedByIndices;
86
87   RegSortData() {}
88
89   void print(raw_ostream &OS) const;
90   void dump() const;
91 };
92
93 }
94
95 void RegSortData::print(raw_ostream &OS) const {
96   OS << "[NumUses=" << UsedByIndices.count() << ']';
97 }
98
99 void RegSortData::dump() const {
100   print(errs()); errs() << '\n';
101 }
102
103 namespace {
104
105 /// RegUseTracker - Map register candidates to information about how they are
106 /// used.
107 class RegUseTracker {
108   typedef DenseMap<const SCEV *, RegSortData> RegUsesTy;
109
110   RegUsesTy RegUsesMap;
111   SmallVector<const SCEV *, 16> RegSequence;
112
113 public:
114   void CountRegister(const SCEV *Reg, size_t LUIdx);
115   void DropRegister(const SCEV *Reg, size_t LUIdx);
116   void SwapAndDropUse(size_t LUIdx, size_t LastLUIdx);
117
118   bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const;
119
120   const SmallBitVector &getUsedByIndices(const SCEV *Reg) const;
121
122   void clear();
123
124   typedef SmallVectorImpl<const SCEV *>::iterator iterator;
125   typedef SmallVectorImpl<const SCEV *>::const_iterator const_iterator;
126   iterator begin() { return RegSequence.begin(); }
127   iterator end()   { return RegSequence.end(); }
128   const_iterator begin() const { return RegSequence.begin(); }
129   const_iterator end() const   { return RegSequence.end(); }
130 };
131
132 }
133
134 void
135 RegUseTracker::CountRegister(const SCEV *Reg, size_t LUIdx) {
136   std::pair<RegUsesTy::iterator, bool> Pair =
137     RegUsesMap.insert(std::make_pair(Reg, RegSortData()));
138   RegSortData &RSD = Pair.first->second;
139   if (Pair.second)
140     RegSequence.push_back(Reg);
141   RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1));
142   RSD.UsedByIndices.set(LUIdx);
143 }
144
145 void
146 RegUseTracker::DropRegister(const SCEV *Reg, size_t LUIdx) {
147   RegUsesTy::iterator It = RegUsesMap.find(Reg);
148   assert(It != RegUsesMap.end());
149   RegSortData &RSD = It->second;
150   assert(RSD.UsedByIndices.size() > LUIdx);
151   RSD.UsedByIndices.reset(LUIdx);
152 }
153
154 void
155 RegUseTracker::SwapAndDropUse(size_t LUIdx, size_t LastLUIdx) {
156   assert(LUIdx <= LastLUIdx);
157
158   // Update RegUses. The data structure is not optimized for this purpose;
159   // we must iterate through it and update each of the bit vectors.
160   for (RegUsesTy::iterator I = RegUsesMap.begin(), E = RegUsesMap.end();
161        I != E; ++I) {
162     SmallBitVector &UsedByIndices = I->second.UsedByIndices;
163     if (LUIdx < UsedByIndices.size())
164       UsedByIndices[LUIdx] =
165         LastLUIdx < UsedByIndices.size() ? UsedByIndices[LastLUIdx] : 0;
166     UsedByIndices.resize(std::min(UsedByIndices.size(), LastLUIdx));
167   }
168 }
169
170 bool
171 RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const {
172   RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
173   if (I == RegUsesMap.end())
174     return false;
175   const SmallBitVector &UsedByIndices = I->second.UsedByIndices;
176   int i = UsedByIndices.find_first();
177   if (i == -1) return false;
178   if ((size_t)i != LUIdx) return true;
179   return UsedByIndices.find_next(i) != -1;
180 }
181
182 const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const {
183   RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
184   assert(I != RegUsesMap.end() && "Unknown register!");
185   return I->second.UsedByIndices;
186 }
187
188 void RegUseTracker::clear() {
189   RegUsesMap.clear();
190   RegSequence.clear();
191 }
192
193 namespace {
194
195 /// Formula - This class holds information that describes a formula for
196 /// computing satisfying a use. It may include broken-out immediates and scaled
197 /// registers.
198 struct Formula {
199   /// AM - This is used to represent complex addressing, as well as other kinds
200   /// of interesting uses.
201   TargetLowering::AddrMode AM;
202
203   /// BaseRegs - The list of "base" registers for this use. When this is
204   /// non-empty, AM.HasBaseReg should be set to true.
205   SmallVector<const SCEV *, 2> BaseRegs;
206
207   /// ScaledReg - The 'scaled' register for this use. This should be non-null
208   /// when AM.Scale is not zero.
209   const SCEV *ScaledReg;
210
211   Formula() : ScaledReg(0) {}
212
213   void InitialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE);
214
215   unsigned getNumRegs() const;
216   const Type *getType() const;
217
218   void DeleteBaseReg(const SCEV *&S);
219
220   bool referencesReg(const SCEV *S) const;
221   bool hasRegsUsedByUsesOtherThan(size_t LUIdx,
222                                   const RegUseTracker &RegUses) const;
223
224   void print(raw_ostream &OS) const;
225   void dump() const;
226 };
227
228 }
229
230 /// DoInitialMatch - Recursion helper for InitialMatch.
231 static void DoInitialMatch(const SCEV *S, Loop *L,
232                            SmallVectorImpl<const SCEV *> &Good,
233                            SmallVectorImpl<const SCEV *> &Bad,
234                            ScalarEvolution &SE) {
235   // Collect expressions which properly dominate the loop header.
236   if (SE.properlyDominates(S, L->getHeader())) {
237     Good.push_back(S);
238     return;
239   }
240
241   // Look at add operands.
242   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
243     for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
244          I != E; ++I)
245       DoInitialMatch(*I, L, Good, Bad, SE);
246     return;
247   }
248
249   // Look at addrec operands.
250   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
251     if (!AR->getStart()->isZero()) {
252       DoInitialMatch(AR->getStart(), L, Good, Bad, SE);
253       DoInitialMatch(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
254                                       AR->getStepRecurrence(SE),
255                                       AR->getLoop()),
256                      L, Good, Bad, SE);
257       return;
258     }
259
260   // Handle a multiplication by -1 (negation) if it didn't fold.
261   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S))
262     if (Mul->getOperand(0)->isAllOnesValue()) {
263       SmallVector<const SCEV *, 4> Ops(Mul->op_begin()+1, Mul->op_end());
264       const SCEV *NewMul = SE.getMulExpr(Ops);
265
266       SmallVector<const SCEV *, 4> MyGood;
267       SmallVector<const SCEV *, 4> MyBad;
268       DoInitialMatch(NewMul, L, MyGood, MyBad, SE);
269       const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue(
270         SE.getEffectiveSCEVType(NewMul->getType())));
271       for (SmallVectorImpl<const SCEV *>::const_iterator I = MyGood.begin(),
272            E = MyGood.end(); I != E; ++I)
273         Good.push_back(SE.getMulExpr(NegOne, *I));
274       for (SmallVectorImpl<const SCEV *>::const_iterator I = MyBad.begin(),
275            E = MyBad.end(); I != E; ++I)
276         Bad.push_back(SE.getMulExpr(NegOne, *I));
277       return;
278     }
279
280   // Ok, we can't do anything interesting. Just stuff the whole thing into a
281   // register and hope for the best.
282   Bad.push_back(S);
283 }
284
285 /// InitialMatch - Incorporate loop-variant parts of S into this Formula,
286 /// attempting to keep all loop-invariant and loop-computable values in a
287 /// single base register.
288 void Formula::InitialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE) {
289   SmallVector<const SCEV *, 4> Good;
290   SmallVector<const SCEV *, 4> Bad;
291   DoInitialMatch(S, L, Good, Bad, SE);
292   if (!Good.empty()) {
293     const SCEV *Sum = SE.getAddExpr(Good);
294     if (!Sum->isZero())
295       BaseRegs.push_back(Sum);
296     AM.HasBaseReg = true;
297   }
298   if (!Bad.empty()) {
299     const SCEV *Sum = SE.getAddExpr(Bad);
300     if (!Sum->isZero())
301       BaseRegs.push_back(Sum);
302     AM.HasBaseReg = true;
303   }
304 }
305
306 /// getNumRegs - Return the total number of register operands used by this
307 /// formula. This does not include register uses implied by non-constant
308 /// addrec strides.
309 unsigned Formula::getNumRegs() const {
310   return !!ScaledReg + BaseRegs.size();
311 }
312
313 /// getType - Return the type of this formula, if it has one, or null
314 /// otherwise. This type is meaningless except for the bit size.
315 const Type *Formula::getType() const {
316   return !BaseRegs.empty() ? BaseRegs.front()->getType() :
317          ScaledReg ? ScaledReg->getType() :
318          AM.BaseGV ? AM.BaseGV->getType() :
319          0;
320 }
321
322 /// DeleteBaseReg - Delete the given base reg from the BaseRegs list.
323 void Formula::DeleteBaseReg(const SCEV *&S) {
324   if (&S != &BaseRegs.back())
325     std::swap(S, BaseRegs.back());
326   BaseRegs.pop_back();
327 }
328
329 /// referencesReg - Test if this formula references the given register.
330 bool Formula::referencesReg(const SCEV *S) const {
331   return S == ScaledReg ||
332          std::find(BaseRegs.begin(), BaseRegs.end(), S) != BaseRegs.end();
333 }
334
335 /// hasRegsUsedByUsesOtherThan - Test whether this formula uses registers
336 /// which are used by uses other than the use with the given index.
337 bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,
338                                          const RegUseTracker &RegUses) const {
339   if (ScaledReg)
340     if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
341       return true;
342   for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
343        E = BaseRegs.end(); I != E; ++I)
344     if (RegUses.isRegUsedByUsesOtherThan(*I, LUIdx))
345       return true;
346   return false;
347 }
348
349 void Formula::print(raw_ostream &OS) const {
350   bool First = true;
351   if (AM.BaseGV) {
352     if (!First) OS << " + "; else First = false;
353     WriteAsOperand(OS, AM.BaseGV, /*PrintType=*/false);
354   }
355   if (AM.BaseOffs != 0) {
356     if (!First) OS << " + "; else First = false;
357     OS << AM.BaseOffs;
358   }
359   for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
360        E = BaseRegs.end(); I != E; ++I) {
361     if (!First) OS << " + "; else First = false;
362     OS << "reg(" << **I << ')';
363   }
364   if (AM.HasBaseReg && BaseRegs.empty()) {
365     if (!First) OS << " + "; else First = false;
366     OS << "**error: HasBaseReg**";
367   } else if (!AM.HasBaseReg && !BaseRegs.empty()) {
368     if (!First) OS << " + "; else First = false;
369     OS << "**error: !HasBaseReg**";
370   }
371   if (AM.Scale != 0) {
372     if (!First) OS << " + "; else First = false;
373     OS << AM.Scale << "*reg(";
374     if (ScaledReg)
375       OS << *ScaledReg;
376     else
377       OS << "<unknown>";
378     OS << ')';
379   }
380 }
381
382 void Formula::dump() const {
383   print(errs()); errs() << '\n';
384 }
385
386 /// isAddRecSExtable - Return true if the given addrec can be sign-extended
387 /// without changing its value.
388 static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
389   const Type *WideTy =
390     IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(AR->getType()) + 1);
391   return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
392 }
393
394 /// isAddSExtable - Return true if the given add can be sign-extended
395 /// without changing its value.
396 static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {
397   const Type *WideTy =
398     IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(A->getType()) + 1);
399   return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy));
400 }
401
402 /// isMulSExtable - Return true if the given mul can be sign-extended
403 /// without changing its value.
404 static bool isMulSExtable(const SCEVMulExpr *M, ScalarEvolution &SE) {
405   const Type *WideTy =
406     IntegerType::get(SE.getContext(),
407                      SE.getTypeSizeInBits(M->getType()) * M->getNumOperands());
408   return isa<SCEVMulExpr>(SE.getSignExtendExpr(M, WideTy));
409 }
410
411 /// getExactSDiv - Return an expression for LHS /s RHS, if it can be determined
412 /// and if the remainder is known to be zero,  or null otherwise. If
413 /// IgnoreSignificantBits is true, expressions like (X * Y) /s Y are simplified
414 /// to Y, ignoring that the multiplication may overflow, which is useful when
415 /// the result will be used in a context where the most significant bits are
416 /// ignored.
417 static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,
418                                 ScalarEvolution &SE,
419                                 bool IgnoreSignificantBits = false) {
420   // Handle the trivial case, which works for any SCEV type.
421   if (LHS == RHS)
422     return SE.getConstant(LHS->getType(), 1);
423
424   // Handle a few RHS special cases.
425   const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
426   if (RC) {
427     const APInt &RA = RC->getValue()->getValue();
428     // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do
429     // some folding.
430     if (RA.isAllOnesValue())
431       return SE.getMulExpr(LHS, RC);
432     // Handle x /s 1 as x.
433     if (RA == 1)
434       return LHS;
435   }
436
437   // Check for a division of a constant by a constant.
438   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
439     if (!RC)
440       return 0;
441     const APInt &LA = C->getValue()->getValue();
442     const APInt &RA = RC->getValue()->getValue();
443     if (LA.srem(RA) != 0)
444       return 0;
445     return SE.getConstant(LA.sdiv(RA));
446   }
447
448   // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
449   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
450     if (IgnoreSignificantBits || isAddRecSExtable(AR, SE)) {
451       const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE,
452                                       IgnoreSignificantBits);
453       if (!Step) return 0;
454       const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE,
455                                        IgnoreSignificantBits);
456       if (!Start) return 0;
457       return SE.getAddRecExpr(Start, Step, AR->getLoop());
458     }
459     return 0;
460   }
461
462   // Distribute the sdiv over add operands, if the add doesn't overflow.
463   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
464     if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {
465       SmallVector<const SCEV *, 8> Ops;
466       for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
467            I != E; ++I) {
468         const SCEV *Op = getExactSDiv(*I, RHS, SE,
469                                       IgnoreSignificantBits);
470         if (!Op) return 0;
471         Ops.push_back(Op);
472       }
473       return SE.getAddExpr(Ops);
474     }
475     return 0;
476   }
477
478   // Check for a multiply operand that we can pull RHS out of.
479   if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS)) {
480     if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {
481       SmallVector<const SCEV *, 4> Ops;
482       bool Found = false;
483       for (SCEVMulExpr::op_iterator I = Mul->op_begin(), E = Mul->op_end();
484            I != E; ++I) {
485         const SCEV *S = *I;
486         if (!Found)
487           if (const SCEV *Q = getExactSDiv(S, RHS, SE,
488                                            IgnoreSignificantBits)) {
489             S = Q;
490             Found = true;
491           }
492         Ops.push_back(S);
493       }
494       return Found ? SE.getMulExpr(Ops) : 0;
495     }
496     return 0;
497   }
498
499   // Otherwise we don't know.
500   return 0;
501 }
502
503 /// ExtractImmediate - If S involves the addition of a constant integer value,
504 /// return that integer value, and mutate S to point to a new SCEV with that
505 /// value excluded.
506 static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
507   if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
508     if (C->getValue()->getValue().getMinSignedBits() <= 64) {
509       S = SE.getConstant(C->getType(), 0);
510       return C->getValue()->getSExtValue();
511     }
512   } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
513     SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
514     int64_t Result = ExtractImmediate(NewOps.front(), SE);
515     if (Result != 0)
516       S = SE.getAddExpr(NewOps);
517     return Result;
518   } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
519     SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
520     int64_t Result = ExtractImmediate(NewOps.front(), SE);
521     if (Result != 0)
522       S = SE.getAddRecExpr(NewOps, AR->getLoop());
523     return Result;
524   }
525   return 0;
526 }
527
528 /// ExtractSymbol - If S involves the addition of a GlobalValue address,
529 /// return that symbol, and mutate S to point to a new SCEV with that
530 /// value excluded.
531 static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
532   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
533     if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
534       S = SE.getConstant(GV->getType(), 0);
535       return GV;
536     }
537   } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
538     SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
539     GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
540     if (Result)
541       S = SE.getAddExpr(NewOps);
542     return Result;
543   } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
544     SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
545     GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
546     if (Result)
547       S = SE.getAddRecExpr(NewOps, AR->getLoop());
548     return Result;
549   }
550   return 0;
551 }
552
553 /// isAddressUse - Returns true if the specified instruction is using the
554 /// specified value as an address.
555 static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
556   bool isAddress = isa<LoadInst>(Inst);
557   if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
558     if (SI->getOperand(1) == OperandVal)
559       isAddress = true;
560   } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
561     // Addressing modes can also be folded into prefetches and a variety
562     // of intrinsics.
563     switch (II->getIntrinsicID()) {
564       default: break;
565       case Intrinsic::prefetch:
566       case Intrinsic::x86_sse2_loadu_dq:
567       case Intrinsic::x86_sse2_loadu_pd:
568       case Intrinsic::x86_sse_loadu_ps:
569       case Intrinsic::x86_sse_storeu_ps:
570       case Intrinsic::x86_sse2_storeu_pd:
571       case Intrinsic::x86_sse2_storeu_dq:
572       case Intrinsic::x86_sse2_storel_dq:
573         if (II->getArgOperand(0) == OperandVal)
574           isAddress = true;
575         break;
576     }
577   }
578   return isAddress;
579 }
580
581 /// getAccessType - Return the type of the memory being accessed.
582 static const Type *getAccessType(const Instruction *Inst) {
583   const Type *AccessTy = Inst->getType();
584   if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
585     AccessTy = SI->getOperand(0)->getType();
586   else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
587     // Addressing modes can also be folded into prefetches and a variety
588     // of intrinsics.
589     switch (II->getIntrinsicID()) {
590     default: break;
591     case Intrinsic::x86_sse_storeu_ps:
592     case Intrinsic::x86_sse2_storeu_pd:
593     case Intrinsic::x86_sse2_storeu_dq:
594     case Intrinsic::x86_sse2_storel_dq:
595       AccessTy = II->getArgOperand(0)->getType();
596       break;
597     }
598   }
599
600   // All pointers have the same requirements, so canonicalize them to an
601   // arbitrary pointer type to minimize variation.
602   if (const PointerType *PTy = dyn_cast<PointerType>(AccessTy))
603     AccessTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
604                                 PTy->getAddressSpace());
605
606   return AccessTy;
607 }
608
609 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
610 /// specified set are trivially dead, delete them and see if this makes any of
611 /// their operands subsequently dead.
612 static bool
613 DeleteTriviallyDeadInstructions(SmallVectorImpl<WeakVH> &DeadInsts) {
614   bool Changed = false;
615
616   while (!DeadInsts.empty()) {
617     Instruction *I = dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val());
618
619     if (I == 0 || !isInstructionTriviallyDead(I))
620       continue;
621
622     for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
623       if (Instruction *U = dyn_cast<Instruction>(*OI)) {
624         *OI = 0;
625         if (U->use_empty())
626           DeadInsts.push_back(U);
627       }
628
629     I->eraseFromParent();
630     Changed = true;
631   }
632
633   return Changed;
634 }
635
636 namespace {
637
638 /// Cost - This class is used to measure and compare candidate formulae.
639 class Cost {
640   /// TODO: Some of these could be merged. Also, a lexical ordering
641   /// isn't always optimal.
642   unsigned NumRegs;
643   unsigned AddRecCost;
644   unsigned NumIVMuls;
645   unsigned NumBaseAdds;
646   unsigned ImmCost;
647   unsigned SetupCost;
648
649 public:
650   Cost()
651     : NumRegs(0), AddRecCost(0), NumIVMuls(0), NumBaseAdds(0), ImmCost(0),
652       SetupCost(0) {}
653
654   bool operator<(const Cost &Other) const;
655
656   void Loose();
657
658   void RateFormula(const Formula &F,
659                    SmallPtrSet<const SCEV *, 16> &Regs,
660                    const DenseSet<const SCEV *> &VisitedRegs,
661                    const Loop *L,
662                    const SmallVectorImpl<int64_t> &Offsets,
663                    ScalarEvolution &SE, DominatorTree &DT);
664
665   void print(raw_ostream &OS) const;
666   void dump() const;
667
668 private:
669   void RateRegister(const SCEV *Reg,
670                     SmallPtrSet<const SCEV *, 16> &Regs,
671                     const Loop *L,
672                     ScalarEvolution &SE, DominatorTree &DT);
673   void RatePrimaryRegister(const SCEV *Reg,
674                            SmallPtrSet<const SCEV *, 16> &Regs,
675                            const Loop *L,
676                            ScalarEvolution &SE, DominatorTree &DT);
677 };
678
679 }
680
681 /// RateRegister - Tally up interesting quantities from the given register.
682 void Cost::RateRegister(const SCEV *Reg,
683                         SmallPtrSet<const SCEV *, 16> &Regs,
684                         const Loop *L,
685                         ScalarEvolution &SE, DominatorTree &DT) {
686   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
687     if (AR->getLoop() == L)
688       AddRecCost += 1; /// TODO: This should be a function of the stride.
689
690     // If this is an addrec for a loop that's already been visited by LSR,
691     // don't second-guess its addrec phi nodes. LSR isn't currently smart
692     // enough to reason about more than one loop at a time. Consider these
693     // registers free and leave them alone.
694     else if (L->contains(AR->getLoop()) ||
695              (!AR->getLoop()->contains(L) &&
696               DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))) {
697       for (BasicBlock::iterator I = AR->getLoop()->getHeader()->begin();
698            PHINode *PN = dyn_cast<PHINode>(I); ++I)
699         if (SE.isSCEVable(PN->getType()) &&
700             (SE.getEffectiveSCEVType(PN->getType()) ==
701              SE.getEffectiveSCEVType(AR->getType())) &&
702             SE.getSCEV(PN) == AR)
703           return;
704
705       // If this isn't one of the addrecs that the loop already has, it
706       // would require a costly new phi and add. TODO: This isn't
707       // precisely modeled right now.
708       ++NumBaseAdds;
709       if (!Regs.count(AR->getStart()))
710         RateRegister(AR->getStart(), Regs, L, SE, DT);
711     }
712
713     // Add the step value register, if it needs one.
714     // TODO: The non-affine case isn't precisely modeled here.
715     if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1)))
716       if (!Regs.count(AR->getStart()))
717         RateRegister(AR->getOperand(1), Regs, L, SE, DT);
718   }
719   ++NumRegs;
720
721   // Rough heuristic; favor registers which don't require extra setup
722   // instructions in the preheader.
723   if (!isa<SCEVUnknown>(Reg) &&
724       !isa<SCEVConstant>(Reg) &&
725       !(isa<SCEVAddRecExpr>(Reg) &&
726         (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(Reg)->getStart()) ||
727          isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart()))))
728     ++SetupCost;
729
730     NumIVMuls += isa<SCEVMulExpr>(Reg) &&
731                  SE.hasComputableLoopEvolution(Reg, L);
732 }
733
734 /// RatePrimaryRegister - Record this register in the set. If we haven't seen it
735 /// before, rate it.
736 void Cost::RatePrimaryRegister(const SCEV *Reg,
737                                SmallPtrSet<const SCEV *, 16> &Regs,
738                                const Loop *L,
739                                ScalarEvolution &SE, DominatorTree &DT) {
740   if (Regs.insert(Reg))
741     RateRegister(Reg, Regs, L, SE, DT);
742 }
743
744 void Cost::RateFormula(const Formula &F,
745                        SmallPtrSet<const SCEV *, 16> &Regs,
746                        const DenseSet<const SCEV *> &VisitedRegs,
747                        const Loop *L,
748                        const SmallVectorImpl<int64_t> &Offsets,
749                        ScalarEvolution &SE, DominatorTree &DT) {
750   // Tally up the registers.
751   if (const SCEV *ScaledReg = F.ScaledReg) {
752     if (VisitedRegs.count(ScaledReg)) {
753       Loose();
754       return;
755     }
756     RatePrimaryRegister(ScaledReg, Regs, L, SE, DT);
757   }
758   for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
759        E = F.BaseRegs.end(); I != E; ++I) {
760     const SCEV *BaseReg = *I;
761     if (VisitedRegs.count(BaseReg)) {
762       Loose();
763       return;
764     }
765     RatePrimaryRegister(BaseReg, Regs, L, SE, DT);
766   }
767
768   if (F.BaseRegs.size() > 1)
769     NumBaseAdds += F.BaseRegs.size() - 1;
770
771   // Tally up the non-zero immediates.
772   for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
773        E = Offsets.end(); I != E; ++I) {
774     int64_t Offset = (uint64_t)*I + F.AM.BaseOffs;
775     if (F.AM.BaseGV)
776       ImmCost += 64; // Handle symbolic values conservatively.
777                      // TODO: This should probably be the pointer size.
778     else if (Offset != 0)
779       ImmCost += APInt(64, Offset, true).getMinSignedBits();
780   }
781 }
782
783 /// Loose - Set this cost to a loosing value.
784 void Cost::Loose() {
785   NumRegs = ~0u;
786   AddRecCost = ~0u;
787   NumIVMuls = ~0u;
788   NumBaseAdds = ~0u;
789   ImmCost = ~0u;
790   SetupCost = ~0u;
791 }
792
793 /// operator< - Choose the lower cost.
794 bool Cost::operator<(const Cost &Other) const {
795   if (NumRegs != Other.NumRegs)
796     return NumRegs < Other.NumRegs;
797   if (AddRecCost != Other.AddRecCost)
798     return AddRecCost < Other.AddRecCost;
799   if (NumIVMuls != Other.NumIVMuls)
800     return NumIVMuls < Other.NumIVMuls;
801   if (NumBaseAdds != Other.NumBaseAdds)
802     return NumBaseAdds < Other.NumBaseAdds;
803   if (ImmCost != Other.ImmCost)
804     return ImmCost < Other.ImmCost;
805   if (SetupCost != Other.SetupCost)
806     return SetupCost < Other.SetupCost;
807   return false;
808 }
809
810 void Cost::print(raw_ostream &OS) const {
811   OS << NumRegs << " reg" << (NumRegs == 1 ? "" : "s");
812   if (AddRecCost != 0)
813     OS << ", with addrec cost " << AddRecCost;
814   if (NumIVMuls != 0)
815     OS << ", plus " << NumIVMuls << " IV mul" << (NumIVMuls == 1 ? "" : "s");
816   if (NumBaseAdds != 0)
817     OS << ", plus " << NumBaseAdds << " base add"
818        << (NumBaseAdds == 1 ? "" : "s");
819   if (ImmCost != 0)
820     OS << ", plus " << ImmCost << " imm cost";
821   if (SetupCost != 0)
822     OS << ", plus " << SetupCost << " setup cost";
823 }
824
825 void Cost::dump() const {
826   print(errs()); errs() << '\n';
827 }
828
829 namespace {
830
831 /// LSRFixup - An operand value in an instruction which is to be replaced
832 /// with some equivalent, possibly strength-reduced, replacement.
833 struct LSRFixup {
834   /// UserInst - The instruction which will be updated.
835   Instruction *UserInst;
836
837   /// OperandValToReplace - The operand of the instruction which will
838   /// be replaced. The operand may be used more than once; every instance
839   /// will be replaced.
840   Value *OperandValToReplace;
841
842   /// PostIncLoops - If this user is to use the post-incremented value of an
843   /// induction variable, this variable is non-null and holds the loop
844   /// associated with the induction variable.
845   PostIncLoopSet PostIncLoops;
846
847   /// LUIdx - The index of the LSRUse describing the expression which
848   /// this fixup needs, minus an offset (below).
849   size_t LUIdx;
850
851   /// Offset - A constant offset to be added to the LSRUse expression.
852   /// This allows multiple fixups to share the same LSRUse with different
853   /// offsets, for example in an unrolled loop.
854   int64_t Offset;
855
856   bool isUseFullyOutsideLoop(const Loop *L) const;
857
858   LSRFixup();
859
860   void print(raw_ostream &OS) const;
861   void dump() const;
862 };
863
864 }
865
866 LSRFixup::LSRFixup()
867   : UserInst(0), OperandValToReplace(0), LUIdx(~size_t(0)), Offset(0) {}
868
869 /// isUseFullyOutsideLoop - Test whether this fixup always uses its
870 /// value outside of the given loop.
871 bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const {
872   // PHI nodes use their value in their incoming blocks.
873   if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
874     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
875       if (PN->getIncomingValue(i) == OperandValToReplace &&
876           L->contains(PN->getIncomingBlock(i)))
877         return false;
878     return true;
879   }
880
881   return !L->contains(UserInst);
882 }
883
884 void LSRFixup::print(raw_ostream &OS) const {
885   OS << "UserInst=";
886   // Store is common and interesting enough to be worth special-casing.
887   if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
888     OS << "store ";
889     WriteAsOperand(OS, Store->getOperand(0), /*PrintType=*/false);
890   } else if (UserInst->getType()->isVoidTy())
891     OS << UserInst->getOpcodeName();
892   else
893     WriteAsOperand(OS, UserInst, /*PrintType=*/false);
894
895   OS << ", OperandValToReplace=";
896   WriteAsOperand(OS, OperandValToReplace, /*PrintType=*/false);
897
898   for (PostIncLoopSet::const_iterator I = PostIncLoops.begin(),
899        E = PostIncLoops.end(); I != E; ++I) {
900     OS << ", PostIncLoop=";
901     WriteAsOperand(OS, (*I)->getHeader(), /*PrintType=*/false);
902   }
903
904   if (LUIdx != ~size_t(0))
905     OS << ", LUIdx=" << LUIdx;
906
907   if (Offset != 0)
908     OS << ", Offset=" << Offset;
909 }
910
911 void LSRFixup::dump() const {
912   print(errs()); errs() << '\n';
913 }
914
915 namespace {
916
917 /// UniquifierDenseMapInfo - A DenseMapInfo implementation for holding
918 /// DenseMaps and DenseSets of sorted SmallVectors of const SCEV*.
919 struct UniquifierDenseMapInfo {
920   static SmallVector<const SCEV *, 2> getEmptyKey() {
921     SmallVector<const SCEV *, 2> V;
922     V.push_back(reinterpret_cast<const SCEV *>(-1));
923     return V;
924   }
925
926   static SmallVector<const SCEV *, 2> getTombstoneKey() {
927     SmallVector<const SCEV *, 2> V;
928     V.push_back(reinterpret_cast<const SCEV *>(-2));
929     return V;
930   }
931
932   static unsigned getHashValue(const SmallVector<const SCEV *, 2> &V) {
933     unsigned Result = 0;
934     for (SmallVectorImpl<const SCEV *>::const_iterator I = V.begin(),
935          E = V.end(); I != E; ++I)
936       Result ^= DenseMapInfo<const SCEV *>::getHashValue(*I);
937     return Result;
938   }
939
940   static bool isEqual(const SmallVector<const SCEV *, 2> &LHS,
941                       const SmallVector<const SCEV *, 2> &RHS) {
942     return LHS == RHS;
943   }
944 };
945
946 /// LSRUse - This class holds the state that LSR keeps for each use in
947 /// IVUsers, as well as uses invented by LSR itself. It includes information
948 /// about what kinds of things can be folded into the user, information about
949 /// the user itself, and information about how the use may be satisfied.
950 /// TODO: Represent multiple users of the same expression in common?
951 class LSRUse {
952   DenseSet<SmallVector<const SCEV *, 2>, UniquifierDenseMapInfo> Uniquifier;
953
954 public:
955   /// KindType - An enum for a kind of use, indicating what types of
956   /// scaled and immediate operands it might support.
957   enum KindType {
958     Basic,   ///< A normal use, with no folding.
959     Special, ///< A special case of basic, allowing -1 scales.
960     Address, ///< An address use; folding according to TargetLowering
961     ICmpZero ///< An equality icmp with both operands folded into one.
962     // TODO: Add a generic icmp too?
963   };
964
965   KindType Kind;
966   const Type *AccessTy;
967
968   SmallVector<int64_t, 8> Offsets;
969   int64_t MinOffset;
970   int64_t MaxOffset;
971
972   /// AllFixupsOutsideLoop - This records whether all of the fixups using this
973   /// LSRUse are outside of the loop, in which case some special-case heuristics
974   /// may be used.
975   bool AllFixupsOutsideLoop;
976
977   /// WidestFixupType - This records the widest use type for any fixup using
978   /// this LSRUse. FindUseWithSimilarFormula can't consider uses with different
979   /// max fixup widths to be equivalent, because the narrower one may be relying
980   /// on the implicit truncation to truncate away bogus bits.
981   const Type *WidestFixupType;
982
983   /// Formulae - A list of ways to build a value that can satisfy this user.
984   /// After the list is populated, one of these is selected heuristically and
985   /// used to formulate a replacement for OperandValToReplace in UserInst.
986   SmallVector<Formula, 12> Formulae;
987
988   /// Regs - The set of register candidates used by all formulae in this LSRUse.
989   SmallPtrSet<const SCEV *, 4> Regs;
990
991   LSRUse(KindType K, const Type *T) : Kind(K), AccessTy(T),
992                                       MinOffset(INT64_MAX),
993                                       MaxOffset(INT64_MIN),
994                                       AllFixupsOutsideLoop(true),
995                                       WidestFixupType(0) {}
996
997   bool HasFormulaWithSameRegs(const Formula &F) const;
998   bool InsertFormula(const Formula &F);
999   void DeleteFormula(Formula &F);
1000   void RecomputeRegs(size_t LUIdx, RegUseTracker &Reguses);
1001
1002   void print(raw_ostream &OS) const;
1003   void dump() const;
1004 };
1005
1006 }
1007
1008 /// HasFormula - Test whether this use as a formula which has the same
1009 /// registers as the given formula.
1010 bool LSRUse::HasFormulaWithSameRegs(const Formula &F) const {
1011   SmallVector<const SCEV *, 2> Key = F.BaseRegs;
1012   if (F.ScaledReg) Key.push_back(F.ScaledReg);
1013   // Unstable sort by host order ok, because this is only used for uniquifying.
1014   std::sort(Key.begin(), Key.end());
1015   return Uniquifier.count(Key);
1016 }
1017
1018 /// InsertFormula - If the given formula has not yet been inserted, add it to
1019 /// the list, and return true. Return false otherwise.
1020 bool LSRUse::InsertFormula(const Formula &F) {
1021   SmallVector<const SCEV *, 2> Key = F.BaseRegs;
1022   if (F.ScaledReg) Key.push_back(F.ScaledReg);
1023   // Unstable sort by host order ok, because this is only used for uniquifying.
1024   std::sort(Key.begin(), Key.end());
1025
1026   if (!Uniquifier.insert(Key).second)
1027     return false;
1028
1029   // Using a register to hold the value of 0 is not profitable.
1030   assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
1031          "Zero allocated in a scaled register!");
1032 #ifndef NDEBUG
1033   for (SmallVectorImpl<const SCEV *>::const_iterator I =
1034        F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I)
1035     assert(!(*I)->isZero() && "Zero allocated in a base register!");
1036 #endif
1037
1038   // Add the formula to the list.
1039   Formulae.push_back(F);
1040
1041   // Record registers now being used by this use.
1042   if (F.ScaledReg) Regs.insert(F.ScaledReg);
1043   Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1044
1045   return true;
1046 }
1047
1048 /// DeleteFormula - Remove the given formula from this use's list.
1049 void LSRUse::DeleteFormula(Formula &F) {
1050   if (&F != &Formulae.back())
1051     std::swap(F, Formulae.back());
1052   Formulae.pop_back();
1053   assert(!Formulae.empty() && "LSRUse has no formulae left!");
1054 }
1055
1056 /// RecomputeRegs - Recompute the Regs field, and update RegUses.
1057 void LSRUse::RecomputeRegs(size_t LUIdx, RegUseTracker &RegUses) {
1058   // Now that we've filtered out some formulae, recompute the Regs set.
1059   SmallPtrSet<const SCEV *, 4> OldRegs = Regs;
1060   Regs.clear();
1061   for (SmallVectorImpl<Formula>::const_iterator I = Formulae.begin(),
1062        E = Formulae.end(); I != E; ++I) {
1063     const Formula &F = *I;
1064     if (F.ScaledReg) Regs.insert(F.ScaledReg);
1065     Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1066   }
1067
1068   // Update the RegTracker.
1069   for (SmallPtrSet<const SCEV *, 4>::iterator I = OldRegs.begin(),
1070        E = OldRegs.end(); I != E; ++I)
1071     if (!Regs.count(*I))
1072       RegUses.DropRegister(*I, LUIdx);
1073 }
1074
1075 void LSRUse::print(raw_ostream &OS) const {
1076   OS << "LSR Use: Kind=";
1077   switch (Kind) {
1078   case Basic:    OS << "Basic"; break;
1079   case Special:  OS << "Special"; break;
1080   case ICmpZero: OS << "ICmpZero"; break;
1081   case Address:
1082     OS << "Address of ";
1083     if (AccessTy->isPointerTy())
1084       OS << "pointer"; // the full pointer type could be really verbose
1085     else
1086       OS << *AccessTy;
1087   }
1088
1089   OS << ", Offsets={";
1090   for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
1091        E = Offsets.end(); I != E; ++I) {
1092     OS << *I;
1093     if (llvm::next(I) != E)
1094       OS << ',';
1095   }
1096   OS << '}';
1097
1098   if (AllFixupsOutsideLoop)
1099     OS << ", all-fixups-outside-loop";
1100
1101   if (WidestFixupType)
1102     OS << ", widest fixup type: " << *WidestFixupType;
1103 }
1104
1105 void LSRUse::dump() const {
1106   print(errs()); errs() << '\n';
1107 }
1108
1109 /// isLegalUse - Test whether the use described by AM is "legal", meaning it can
1110 /// be completely folded into the user instruction at isel time. This includes
1111 /// address-mode folding and special icmp tricks.
1112 static bool isLegalUse(const TargetLowering::AddrMode &AM,
1113                        LSRUse::KindType Kind, const Type *AccessTy,
1114                        const TargetLowering *TLI) {
1115   switch (Kind) {
1116   case LSRUse::Address:
1117     // If we have low-level target information, ask the target if it can
1118     // completely fold this address.
1119     if (TLI) return TLI->isLegalAddressingMode(AM, AccessTy);
1120
1121     // Otherwise, just guess that reg+reg addressing is legal.
1122     return !AM.BaseGV && AM.BaseOffs == 0 && AM.Scale <= 1;
1123
1124   case LSRUse::ICmpZero:
1125     // There's not even a target hook for querying whether it would be legal to
1126     // fold a GV into an ICmp.
1127     if (AM.BaseGV)
1128       return false;
1129
1130     // ICmp only has two operands; don't allow more than two non-trivial parts.
1131     if (AM.Scale != 0 && AM.HasBaseReg && AM.BaseOffs != 0)
1132       return false;
1133
1134     // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
1135     // putting the scaled register in the other operand of the icmp.
1136     if (AM.Scale != 0 && AM.Scale != -1)
1137       return false;
1138
1139     // If we have low-level target information, ask the target if it can fold an
1140     // integer immediate on an icmp.
1141     if (AM.BaseOffs != 0) {
1142       if (TLI) return TLI->isLegalICmpImmediate(-AM.BaseOffs);
1143       return false;
1144     }
1145
1146     return true;
1147
1148   case LSRUse::Basic:
1149     // Only handle single-register values.
1150     return !AM.BaseGV && AM.Scale == 0 && AM.BaseOffs == 0;
1151
1152   case LSRUse::Special:
1153     // Only handle -1 scales, or no scale.
1154     return AM.Scale == 0 || AM.Scale == -1;
1155   }
1156
1157   return false;
1158 }
1159
1160 static bool isLegalUse(TargetLowering::AddrMode AM,
1161                        int64_t MinOffset, int64_t MaxOffset,
1162                        LSRUse::KindType Kind, const Type *AccessTy,
1163                        const TargetLowering *TLI) {
1164   // Check for overflow.
1165   if (((int64_t)((uint64_t)AM.BaseOffs + MinOffset) > AM.BaseOffs) !=
1166       (MinOffset > 0))
1167     return false;
1168   AM.BaseOffs = (uint64_t)AM.BaseOffs + MinOffset;
1169   if (isLegalUse(AM, Kind, AccessTy, TLI)) {
1170     AM.BaseOffs = (uint64_t)AM.BaseOffs - MinOffset;
1171     // Check for overflow.
1172     if (((int64_t)((uint64_t)AM.BaseOffs + MaxOffset) > AM.BaseOffs) !=
1173         (MaxOffset > 0))
1174       return false;
1175     AM.BaseOffs = (uint64_t)AM.BaseOffs + MaxOffset;
1176     return isLegalUse(AM, Kind, AccessTy, TLI);
1177   }
1178   return false;
1179 }
1180
1181 static bool isAlwaysFoldable(int64_t BaseOffs,
1182                              GlobalValue *BaseGV,
1183                              bool HasBaseReg,
1184                              LSRUse::KindType Kind, const Type *AccessTy,
1185                              const TargetLowering *TLI) {
1186   // Fast-path: zero is always foldable.
1187   if (BaseOffs == 0 && !BaseGV) return true;
1188
1189   // Conservatively, create an address with an immediate and a
1190   // base and a scale.
1191   TargetLowering::AddrMode AM;
1192   AM.BaseOffs = BaseOffs;
1193   AM.BaseGV = BaseGV;
1194   AM.HasBaseReg = HasBaseReg;
1195   AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1196
1197   // Canonicalize a scale of 1 to a base register if the formula doesn't
1198   // already have a base register.
1199   if (!AM.HasBaseReg && AM.Scale == 1) {
1200     AM.Scale = 0;
1201     AM.HasBaseReg = true;
1202   }
1203
1204   return isLegalUse(AM, Kind, AccessTy, TLI);
1205 }
1206
1207 static bool isAlwaysFoldable(const SCEV *S,
1208                              int64_t MinOffset, int64_t MaxOffset,
1209                              bool HasBaseReg,
1210                              LSRUse::KindType Kind, const Type *AccessTy,
1211                              const TargetLowering *TLI,
1212                              ScalarEvolution &SE) {
1213   // Fast-path: zero is always foldable.
1214   if (S->isZero()) return true;
1215
1216   // Conservatively, create an address with an immediate and a
1217   // base and a scale.
1218   int64_t BaseOffs = ExtractImmediate(S, SE);
1219   GlobalValue *BaseGV = ExtractSymbol(S, SE);
1220
1221   // If there's anything else involved, it's not foldable.
1222   if (!S->isZero()) return false;
1223
1224   // Fast-path: zero is always foldable.
1225   if (BaseOffs == 0 && !BaseGV) return true;
1226
1227   // Conservatively, create an address with an immediate and a
1228   // base and a scale.
1229   TargetLowering::AddrMode AM;
1230   AM.BaseOffs = BaseOffs;
1231   AM.BaseGV = BaseGV;
1232   AM.HasBaseReg = HasBaseReg;
1233   AM.Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1234
1235   return isLegalUse(AM, MinOffset, MaxOffset, Kind, AccessTy, TLI);
1236 }
1237
1238 namespace {
1239
1240 /// UseMapDenseMapInfo - A DenseMapInfo implementation for holding
1241 /// DenseMaps and DenseSets of pairs of const SCEV* and LSRUse::Kind.
1242 struct UseMapDenseMapInfo {
1243   static std::pair<const SCEV *, LSRUse::KindType> getEmptyKey() {
1244     return std::make_pair(reinterpret_cast<const SCEV *>(-1), LSRUse::Basic);
1245   }
1246
1247   static std::pair<const SCEV *, LSRUse::KindType> getTombstoneKey() {
1248     return std::make_pair(reinterpret_cast<const SCEV *>(-2), LSRUse::Basic);
1249   }
1250
1251   static unsigned
1252   getHashValue(const std::pair<const SCEV *, LSRUse::KindType> &V) {
1253     unsigned Result = DenseMapInfo<const SCEV *>::getHashValue(V.first);
1254     Result ^= DenseMapInfo<unsigned>::getHashValue(unsigned(V.second));
1255     return Result;
1256   }
1257
1258   static bool isEqual(const std::pair<const SCEV *, LSRUse::KindType> &LHS,
1259                       const std::pair<const SCEV *, LSRUse::KindType> &RHS) {
1260     return LHS == RHS;
1261   }
1262 };
1263
1264 /// LSRInstance - This class holds state for the main loop strength reduction
1265 /// logic.
1266 class LSRInstance {
1267   IVUsers &IU;
1268   ScalarEvolution &SE;
1269   DominatorTree &DT;
1270   LoopInfo &LI;
1271   const TargetLowering *const TLI;
1272   Loop *const L;
1273   bool Changed;
1274
1275   /// IVIncInsertPos - This is the insert position that the current loop's
1276   /// induction variable increment should be placed. In simple loops, this is
1277   /// the latch block's terminator. But in more complicated cases, this is a
1278   /// position which will dominate all the in-loop post-increment users.
1279   Instruction *IVIncInsertPos;
1280
1281   /// Factors - Interesting factors between use strides.
1282   SmallSetVector<int64_t, 8> Factors;
1283
1284   /// Types - Interesting use types, to facilitate truncation reuse.
1285   SmallSetVector<const Type *, 4> Types;
1286
1287   /// Fixups - The list of operands which are to be replaced.
1288   SmallVector<LSRFixup, 16> Fixups;
1289
1290   /// Uses - The list of interesting uses.
1291   SmallVector<LSRUse, 16> Uses;
1292
1293   /// RegUses - Track which uses use which register candidates.
1294   RegUseTracker RegUses;
1295
1296   void OptimizeShadowIV();
1297   bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
1298   ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
1299   void OptimizeLoopTermCond();
1300
1301   void CollectInterestingTypesAndFactors();
1302   void CollectFixupsAndInitialFormulae();
1303
1304   LSRFixup &getNewFixup() {
1305     Fixups.push_back(LSRFixup());
1306     return Fixups.back();
1307   }
1308
1309   // Support for sharing of LSRUses between LSRFixups.
1310   typedef DenseMap<std::pair<const SCEV *, LSRUse::KindType>,
1311                    size_t,
1312                    UseMapDenseMapInfo> UseMapTy;
1313   UseMapTy UseMap;
1314
1315   bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
1316                           LSRUse::KindType Kind, const Type *AccessTy);
1317
1318   std::pair<size_t, int64_t> getUse(const SCEV *&Expr,
1319                                     LSRUse::KindType Kind,
1320                                     const Type *AccessTy);
1321
1322   void DeleteUse(LSRUse &LU, size_t LUIdx);
1323
1324   LSRUse *FindUseWithSimilarFormula(const Formula &F, const LSRUse &OrigLU);
1325
1326 public:
1327   void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1328   void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1329   void CountRegisters(const Formula &F, size_t LUIdx);
1330   bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
1331
1332   void CollectLoopInvariantFixupsAndFormulae();
1333
1334   void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
1335                               unsigned Depth = 0);
1336   void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
1337   void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1338   void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1339   void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1340   void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1341   void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
1342   void GenerateCrossUseConstantOffsets();
1343   void GenerateAllReuseFormulae();
1344
1345   void FilterOutUndesirableDedicatedRegisters();
1346
1347   size_t EstimateSearchSpaceComplexity() const;
1348   void NarrowSearchSpaceByDetectingSupersets();
1349   void NarrowSearchSpaceByCollapsingUnrolledCode();
1350   void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
1351   void NarrowSearchSpaceByPickingWinnerRegs();
1352   void NarrowSearchSpaceUsingHeuristics();
1353
1354   void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
1355                     Cost &SolutionCost,
1356                     SmallVectorImpl<const Formula *> &Workspace,
1357                     const Cost &CurCost,
1358                     const SmallPtrSet<const SCEV *, 16> &CurRegs,
1359                     DenseSet<const SCEV *> &VisitedRegs) const;
1360   void Solve(SmallVectorImpl<const Formula *> &Solution) const;
1361
1362   BasicBlock::iterator
1363     HoistInsertPosition(BasicBlock::iterator IP,
1364                         const SmallVectorImpl<Instruction *> &Inputs) const;
1365   BasicBlock::iterator AdjustInsertPositionForExpand(BasicBlock::iterator IP,
1366                                                      const LSRFixup &LF,
1367                                                      const LSRUse &LU) const;
1368
1369   Value *Expand(const LSRFixup &LF,
1370                 const Formula &F,
1371                 BasicBlock::iterator IP,
1372                 SCEVExpander &Rewriter,
1373                 SmallVectorImpl<WeakVH> &DeadInsts) const;
1374   void RewriteForPHI(PHINode *PN, const LSRFixup &LF,
1375                      const Formula &F,
1376                      SCEVExpander &Rewriter,
1377                      SmallVectorImpl<WeakVH> &DeadInsts,
1378                      Pass *P) const;
1379   void Rewrite(const LSRFixup &LF,
1380                const Formula &F,
1381                SCEVExpander &Rewriter,
1382                SmallVectorImpl<WeakVH> &DeadInsts,
1383                Pass *P) const;
1384   void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
1385                          Pass *P);
1386
1387   LSRInstance(const TargetLowering *tli, Loop *l, Pass *P);
1388
1389   bool getChanged() const { return Changed; }
1390
1391   void print_factors_and_types(raw_ostream &OS) const;
1392   void print_fixups(raw_ostream &OS) const;
1393   void print_uses(raw_ostream &OS) const;
1394   void print(raw_ostream &OS) const;
1395   void dump() const;
1396 };
1397
1398 }
1399
1400 /// OptimizeShadowIV - If IV is used in a int-to-float cast
1401 /// inside the loop then try to eliminate the cast operation.
1402 void LSRInstance::OptimizeShadowIV() {
1403   const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1404   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1405     return;
1406
1407   for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
1408        UI != E; /* empty */) {
1409     IVUsers::const_iterator CandidateUI = UI;
1410     ++UI;
1411     Instruction *ShadowUse = CandidateUI->getUser();
1412     const Type *DestTy = NULL;
1413
1414     /* If shadow use is a int->float cast then insert a second IV
1415        to eliminate this cast.
1416
1417          for (unsigned i = 0; i < n; ++i)
1418            foo((double)i);
1419
1420        is transformed into
1421
1422          double d = 0.0;
1423          for (unsigned i = 0; i < n; ++i, ++d)
1424            foo(d);
1425     */
1426     if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser()))
1427       DestTy = UCast->getDestTy();
1428     else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser()))
1429       DestTy = SCast->getDestTy();
1430     if (!DestTy) continue;
1431
1432     if (TLI) {
1433       // If target does not support DestTy natively then do not apply
1434       // this transformation.
1435       EVT DVT = TLI->getValueType(DestTy);
1436       if (!TLI->isTypeLegal(DVT)) continue;
1437     }
1438
1439     PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
1440     if (!PH) continue;
1441     if (PH->getNumIncomingValues() != 2) continue;
1442
1443     const Type *SrcTy = PH->getType();
1444     int Mantissa = DestTy->getFPMantissaWidth();
1445     if (Mantissa == -1) continue;
1446     if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
1447       continue;
1448
1449     unsigned Entry, Latch;
1450     if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
1451       Entry = 0;
1452       Latch = 1;
1453     } else {
1454       Entry = 1;
1455       Latch = 0;
1456     }
1457
1458     ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
1459     if (!Init) continue;
1460     Constant *NewInit = ConstantFP::get(DestTy, Init->getZExtValue());
1461
1462     BinaryOperator *Incr =
1463       dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
1464     if (!Incr) continue;
1465     if (Incr->getOpcode() != Instruction::Add
1466         && Incr->getOpcode() != Instruction::Sub)
1467       continue;
1468
1469     /* Initialize new IV, double d = 0.0 in above example. */
1470     ConstantInt *C = NULL;
1471     if (Incr->getOperand(0) == PH)
1472       C = dyn_cast<ConstantInt>(Incr->getOperand(1));
1473     else if (Incr->getOperand(1) == PH)
1474       C = dyn_cast<ConstantInt>(Incr->getOperand(0));
1475     else
1476       continue;
1477
1478     if (!C) continue;
1479
1480     // Ignore negative constants, as the code below doesn't handle them
1481     // correctly. TODO: Remove this restriction.
1482     if (!C->getValue().isStrictlyPositive()) continue;
1483
1484     /* Add new PHINode. */
1485     PHINode *NewPH = PHINode::Create(DestTy, "IV.S.", PH);
1486
1487     /* create new increment. '++d' in above example. */
1488     Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
1489     BinaryOperator *NewIncr =
1490       BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
1491                                Instruction::FAdd : Instruction::FSub,
1492                              NewPH, CFP, "IV.S.next.", Incr);
1493
1494     NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
1495     NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
1496
1497     /* Remove cast operation */
1498     ShadowUse->replaceAllUsesWith(NewPH);
1499     ShadowUse->eraseFromParent();
1500     Changed = true;
1501     break;
1502   }
1503 }
1504
1505 /// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1506 /// set the IV user and stride information and return true, otherwise return
1507 /// false.
1508 bool LSRInstance::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse) {
1509   for (IVUsers::iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1510     if (UI->getUser() == Cond) {
1511       // NOTE: we could handle setcc instructions with multiple uses here, but
1512       // InstCombine does it as well for simple uses, it's not clear that it
1513       // occurs enough in real life to handle.
1514       CondUse = UI;
1515       return true;
1516     }
1517   return false;
1518 }
1519
1520 /// OptimizeMax - Rewrite the loop's terminating condition if it uses
1521 /// a max computation.
1522 ///
1523 /// This is a narrow solution to a specific, but acute, problem. For loops
1524 /// like this:
1525 ///
1526 ///   i = 0;
1527 ///   do {
1528 ///     p[i] = 0.0;
1529 ///   } while (++i < n);
1530 ///
1531 /// the trip count isn't just 'n', because 'n' might not be positive. And
1532 /// unfortunately this can come up even for loops where the user didn't use
1533 /// a C do-while loop. For example, seemingly well-behaved top-test loops
1534 /// will commonly be lowered like this:
1535 //
1536 ///   if (n > 0) {
1537 ///     i = 0;
1538 ///     do {
1539 ///       p[i] = 0.0;
1540 ///     } while (++i < n);
1541 ///   }
1542 ///
1543 /// and then it's possible for subsequent optimization to obscure the if
1544 /// test in such a way that indvars can't find it.
1545 ///
1546 /// When indvars can't find the if test in loops like this, it creates a
1547 /// max expression, which allows it to give the loop a canonical
1548 /// induction variable:
1549 ///
1550 ///   i = 0;
1551 ///   max = n < 1 ? 1 : n;
1552 ///   do {
1553 ///     p[i] = 0.0;
1554 ///   } while (++i != max);
1555 ///
1556 /// Canonical induction variables are necessary because the loop passes
1557 /// are designed around them. The most obvious example of this is the
1558 /// LoopInfo analysis, which doesn't remember trip count values. It
1559 /// expects to be able to rediscover the trip count each time it is
1560 /// needed, and it does this using a simple analysis that only succeeds if
1561 /// the loop has a canonical induction variable.
1562 ///
1563 /// However, when it comes time to generate code, the maximum operation
1564 /// can be quite costly, especially if it's inside of an outer loop.
1565 ///
1566 /// This function solves this problem by detecting this type of loop and
1567 /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
1568 /// the instructions for the maximum computation.
1569 ///
1570 ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
1571   // Check that the loop matches the pattern we're looking for.
1572   if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
1573       Cond->getPredicate() != CmpInst::ICMP_NE)
1574     return Cond;
1575
1576   SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
1577   if (!Sel || !Sel->hasOneUse()) return Cond;
1578
1579   const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1580   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1581     return Cond;
1582   const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1);
1583
1584   // Add one to the backedge-taken count to get the trip count.
1585   const SCEV *IterationCount = SE.getAddExpr(One, BackedgeTakenCount);
1586   if (IterationCount != SE.getSCEV(Sel)) return Cond;
1587
1588   // Check for a max calculation that matches the pattern. There's no check
1589   // for ICMP_ULE here because the comparison would be with zero, which
1590   // isn't interesting.
1591   CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1592   const SCEVNAryExpr *Max = 0;
1593   if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) {
1594     Pred = ICmpInst::ICMP_SLE;
1595     Max = S;
1596   } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) {
1597     Pred = ICmpInst::ICMP_SLT;
1598     Max = S;
1599   } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) {
1600     Pred = ICmpInst::ICMP_ULT;
1601     Max = U;
1602   } else {
1603     // No match; bail.
1604     return Cond;
1605   }
1606
1607   // To handle a max with more than two operands, this optimization would
1608   // require additional checking and setup.
1609   if (Max->getNumOperands() != 2)
1610     return Cond;
1611
1612   const SCEV *MaxLHS = Max->getOperand(0);
1613   const SCEV *MaxRHS = Max->getOperand(1);
1614
1615   // ScalarEvolution canonicalizes constants to the left. For < and >, look
1616   // for a comparison with 1. For <= and >=, a comparison with zero.
1617   if (!MaxLHS ||
1618       (ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One)))
1619     return Cond;
1620
1621   // Check the relevant induction variable for conformance to
1622   // the pattern.
1623   const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
1624   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
1625   if (!AR || !AR->isAffine() ||
1626       AR->getStart() != One ||
1627       AR->getStepRecurrence(SE) != One)
1628     return Cond;
1629
1630   assert(AR->getLoop() == L &&
1631          "Loop condition operand is an addrec in a different loop!");
1632
1633   // Check the right operand of the select, and remember it, as it will
1634   // be used in the new comparison instruction.
1635   Value *NewRHS = 0;
1636   if (ICmpInst::isTrueWhenEqual(Pred)) {
1637     // Look for n+1, and grab n.
1638     if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1)))
1639       if (isa<ConstantInt>(BO->getOperand(1)) &&
1640           cast<ConstantInt>(BO->getOperand(1))->isOne() &&
1641           SE.getSCEV(BO->getOperand(0)) == MaxRHS)
1642         NewRHS = BO->getOperand(0);
1643     if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2)))
1644       if (isa<ConstantInt>(BO->getOperand(1)) &&
1645           cast<ConstantInt>(BO->getOperand(1))->isOne() &&
1646           SE.getSCEV(BO->getOperand(0)) == MaxRHS)
1647         NewRHS = BO->getOperand(0);
1648     if (!NewRHS)
1649       return Cond;
1650   } else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
1651     NewRHS = Sel->getOperand(1);
1652   else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
1653     NewRHS = Sel->getOperand(2);
1654   else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(MaxRHS))
1655     NewRHS = SU->getValue();
1656   else
1657     // Max doesn't match expected pattern.
1658     return Cond;
1659
1660   // Determine the new comparison opcode. It may be signed or unsigned,
1661   // and the original comparison may be either equality or inequality.
1662   if (Cond->getPredicate() == CmpInst::ICMP_EQ)
1663     Pred = CmpInst::getInversePredicate(Pred);
1664
1665   // Ok, everything looks ok to change the condition into an SLT or SGE and
1666   // delete the max calculation.
1667   ICmpInst *NewCond =
1668     new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
1669
1670   // Delete the max calculation instructions.
1671   Cond->replaceAllUsesWith(NewCond);
1672   CondUse->setUser(NewCond);
1673   Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
1674   Cond->eraseFromParent();
1675   Sel->eraseFromParent();
1676   if (Cmp->use_empty())
1677     Cmp->eraseFromParent();
1678   return NewCond;
1679 }
1680
1681 /// OptimizeLoopTermCond - Change loop terminating condition to use the
1682 /// postinc iv when possible.
1683 void
1684 LSRInstance::OptimizeLoopTermCond() {
1685   SmallPtrSet<Instruction *, 4> PostIncs;
1686
1687   BasicBlock *LatchBlock = L->getLoopLatch();
1688   SmallVector<BasicBlock*, 8> ExitingBlocks;
1689   L->getExitingBlocks(ExitingBlocks);
1690
1691   for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
1692     BasicBlock *ExitingBlock = ExitingBlocks[i];
1693
1694     // Get the terminating condition for the loop if possible.  If we
1695     // can, we want to change it to use a post-incremented version of its
1696     // induction variable, to allow coalescing the live ranges for the IV into
1697     // one register value.
1698
1699     BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1700     if (!TermBr)
1701       continue;
1702     // FIXME: Overly conservative, termination condition could be an 'or' etc..
1703     if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
1704       continue;
1705
1706     // Search IVUsesByStride to find Cond's IVUse if there is one.
1707     IVStrideUse *CondUse = 0;
1708     ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
1709     if (!FindIVUserForCond(Cond, CondUse))
1710       continue;
1711
1712     // If the trip count is computed in terms of a max (due to ScalarEvolution
1713     // being unable to find a sufficient guard, for example), change the loop
1714     // comparison to use SLT or ULT instead of NE.
1715     // One consequence of doing this now is that it disrupts the count-down
1716     // optimization. That's not always a bad thing though, because in such
1717     // cases it may still be worthwhile to avoid a max.
1718     Cond = OptimizeMax(Cond, CondUse);
1719
1720     // If this exiting block dominates the latch block, it may also use
1721     // the post-inc value if it won't be shared with other uses.
1722     // Check for dominance.
1723     if (!DT.dominates(ExitingBlock, LatchBlock))
1724       continue;
1725
1726     // Conservatively avoid trying to use the post-inc value in non-latch
1727     // exits if there may be pre-inc users in intervening blocks.
1728     if (LatchBlock != ExitingBlock)
1729       for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1730         // Test if the use is reachable from the exiting block. This dominator
1731         // query is a conservative approximation of reachability.
1732         if (&*UI != CondUse &&
1733             !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
1734           // Conservatively assume there may be reuse if the quotient of their
1735           // strides could be a legal scale.
1736           const SCEV *A = IU.getStride(*CondUse, L);
1737           const SCEV *B = IU.getStride(*UI, L);
1738           if (!A || !B) continue;
1739           if (SE.getTypeSizeInBits(A->getType()) !=
1740               SE.getTypeSizeInBits(B->getType())) {
1741             if (SE.getTypeSizeInBits(A->getType()) >
1742                 SE.getTypeSizeInBits(B->getType()))
1743               B = SE.getSignExtendExpr(B, A->getType());
1744             else
1745               A = SE.getSignExtendExpr(A, B->getType());
1746           }
1747           if (const SCEVConstant *D =
1748                 dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {
1749             const ConstantInt *C = D->getValue();
1750             // Stride of one or negative one can have reuse with non-addresses.
1751             if (C->isOne() || C->isAllOnesValue())
1752               goto decline_post_inc;
1753             // Avoid weird situations.
1754             if (C->getValue().getMinSignedBits() >= 64 ||
1755                 C->getValue().isMinSignedValue())
1756               goto decline_post_inc;
1757             // Without TLI, assume that any stride might be valid, and so any
1758             // use might be shared.
1759             if (!TLI)
1760               goto decline_post_inc;
1761             // Check for possible scaled-address reuse.
1762             const Type *AccessTy = getAccessType(UI->getUser());
1763             TargetLowering::AddrMode AM;
1764             AM.Scale = C->getSExtValue();
1765             if (TLI->isLegalAddressingMode(AM, AccessTy))
1766               goto decline_post_inc;
1767             AM.Scale = -AM.Scale;
1768             if (TLI->isLegalAddressingMode(AM, AccessTy))
1769               goto decline_post_inc;
1770           }
1771         }
1772
1773     DEBUG(dbgs() << "  Change loop exiting icmp to use postinc iv: "
1774                  << *Cond << '\n');
1775
1776     // It's possible for the setcc instruction to be anywhere in the loop, and
1777     // possible for it to have multiple users.  If it is not immediately before
1778     // the exiting block branch, move it.
1779     if (&*++BasicBlock::iterator(Cond) != TermBr) {
1780       if (Cond->hasOneUse()) {
1781         Cond->moveBefore(TermBr);
1782       } else {
1783         // Clone the terminating condition and insert into the loopend.
1784         ICmpInst *OldCond = Cond;
1785         Cond = cast<ICmpInst>(Cond->clone());
1786         Cond->setName(L->getHeader()->getName() + ".termcond");
1787         ExitingBlock->getInstList().insert(TermBr, Cond);
1788
1789         // Clone the IVUse, as the old use still exists!
1790         CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());
1791         TermBr->replaceUsesOfWith(OldCond, Cond);
1792       }
1793     }
1794
1795     // If we get to here, we know that we can transform the setcc instruction to
1796     // use the post-incremented version of the IV, allowing us to coalesce the
1797     // live ranges for the IV correctly.
1798     CondUse->transformToPostInc(L);
1799     Changed = true;
1800
1801     PostIncs.insert(Cond);
1802   decline_post_inc:;
1803   }
1804
1805   // Determine an insertion point for the loop induction variable increment. It
1806   // must dominate all the post-inc comparisons we just set up, and it must
1807   // dominate the loop latch edge.
1808   IVIncInsertPos = L->getLoopLatch()->getTerminator();
1809   for (SmallPtrSet<Instruction *, 4>::const_iterator I = PostIncs.begin(),
1810        E = PostIncs.end(); I != E; ++I) {
1811     BasicBlock *BB =
1812       DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
1813                                     (*I)->getParent());
1814     if (BB == (*I)->getParent())
1815       IVIncInsertPos = *I;
1816     else if (BB != IVIncInsertPos->getParent())
1817       IVIncInsertPos = BB->getTerminator();
1818   }
1819 }
1820
1821 /// reconcileNewOffset - Determine if the given use can accomodate a fixup
1822 /// at the given offset and other details. If so, update the use and
1823 /// return true.
1824 bool
1825 LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
1826                                 LSRUse::KindType Kind, const Type *AccessTy) {
1827   int64_t NewMinOffset = LU.MinOffset;
1828   int64_t NewMaxOffset = LU.MaxOffset;
1829   const Type *NewAccessTy = AccessTy;
1830
1831   // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
1832   // something conservative, however this can pessimize in the case that one of
1833   // the uses will have all its uses outside the loop, for example.
1834   if (LU.Kind != Kind)
1835     return false;
1836   // Conservatively assume HasBaseReg is true for now.
1837   if (NewOffset < LU.MinOffset) {
1838     if (!isAlwaysFoldable(LU.MaxOffset - NewOffset, 0, HasBaseReg,
1839                           Kind, AccessTy, TLI))
1840       return false;
1841     NewMinOffset = NewOffset;
1842   } else if (NewOffset > LU.MaxOffset) {
1843     if (!isAlwaysFoldable(NewOffset - LU.MinOffset, 0, HasBaseReg,
1844                           Kind, AccessTy, TLI))
1845       return false;
1846     NewMaxOffset = NewOffset;
1847   }
1848   // Check for a mismatched access type, and fall back conservatively as needed.
1849   // TODO: Be less conservative when the type is similar and can use the same
1850   // addressing modes.
1851   if (Kind == LSRUse::Address && AccessTy != LU.AccessTy)
1852     NewAccessTy = Type::getVoidTy(AccessTy->getContext());
1853
1854   // Update the use.
1855   LU.MinOffset = NewMinOffset;
1856   LU.MaxOffset = NewMaxOffset;
1857   LU.AccessTy = NewAccessTy;
1858   if (NewOffset != LU.Offsets.back())
1859     LU.Offsets.push_back(NewOffset);
1860   return true;
1861 }
1862
1863 /// getUse - Return an LSRUse index and an offset value for a fixup which
1864 /// needs the given expression, with the given kind and optional access type.
1865 /// Either reuse an existing use or create a new one, as needed.
1866 std::pair<size_t, int64_t>
1867 LSRInstance::getUse(const SCEV *&Expr,
1868                     LSRUse::KindType Kind, const Type *AccessTy) {
1869   const SCEV *Copy = Expr;
1870   int64_t Offset = ExtractImmediate(Expr, SE);
1871
1872   // Basic uses can't accept any offset, for example.
1873   if (!isAlwaysFoldable(Offset, 0, /*HasBaseReg=*/true, Kind, AccessTy, TLI)) {
1874     Expr = Copy;
1875     Offset = 0;
1876   }
1877
1878   std::pair<UseMapTy::iterator, bool> P =
1879     UseMap.insert(std::make_pair(std::make_pair(Expr, Kind), 0));
1880   if (!P.second) {
1881     // A use already existed with this base.
1882     size_t LUIdx = P.first->second;
1883     LSRUse &LU = Uses[LUIdx];
1884     if (reconcileNewOffset(LU, Offset, /*HasBaseReg=*/true, Kind, AccessTy))
1885       // Reuse this use.
1886       return std::make_pair(LUIdx, Offset);
1887   }
1888
1889   // Create a new use.
1890   size_t LUIdx = Uses.size();
1891   P.first->second = LUIdx;
1892   Uses.push_back(LSRUse(Kind, AccessTy));
1893   LSRUse &LU = Uses[LUIdx];
1894
1895   // We don't need to track redundant offsets, but we don't need to go out
1896   // of our way here to avoid them.
1897   if (LU.Offsets.empty() || Offset != LU.Offsets.back())
1898     LU.Offsets.push_back(Offset);
1899
1900   LU.MinOffset = Offset;
1901   LU.MaxOffset = Offset;
1902   return std::make_pair(LUIdx, Offset);
1903 }
1904
1905 /// DeleteUse - Delete the given use from the Uses list.
1906 void LSRInstance::DeleteUse(LSRUse &LU, size_t LUIdx) {
1907   if (&LU != &Uses.back())
1908     std::swap(LU, Uses.back());
1909   Uses.pop_back();
1910
1911   // Update RegUses.
1912   RegUses.SwapAndDropUse(LUIdx, Uses.size());
1913 }
1914
1915 /// FindUseWithFormula - Look for a use distinct from OrigLU which is has
1916 /// a formula that has the same registers as the given formula.
1917 LSRUse *
1918 LSRInstance::FindUseWithSimilarFormula(const Formula &OrigF,
1919                                        const LSRUse &OrigLU) {
1920   // Search all uses for the formula. This could be more clever.
1921   for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
1922     LSRUse &LU = Uses[LUIdx];
1923     // Check whether this use is close enough to OrigLU, to see whether it's
1924     // worthwhile looking through its formulae.
1925     // Ignore ICmpZero uses because they may contain formulae generated by
1926     // GenerateICmpZeroScales, in which case adding fixup offsets may
1927     // be invalid.
1928     if (&LU != &OrigLU &&
1929         LU.Kind != LSRUse::ICmpZero &&
1930         LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy &&
1931         LU.WidestFixupType == OrigLU.WidestFixupType &&
1932         LU.HasFormulaWithSameRegs(OrigF)) {
1933       // Scan through this use's formulae.
1934       for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
1935            E = LU.Formulae.end(); I != E; ++I) {
1936         const Formula &F = *I;
1937         // Check to see if this formula has the same registers and symbols
1938         // as OrigF.
1939         if (F.BaseRegs == OrigF.BaseRegs &&
1940             F.ScaledReg == OrigF.ScaledReg &&
1941             F.AM.BaseGV == OrigF.AM.BaseGV &&
1942             F.AM.Scale == OrigF.AM.Scale) {
1943           if (F.AM.BaseOffs == 0)
1944             return &LU;
1945           // This is the formula where all the registers and symbols matched;
1946           // there aren't going to be any others. Since we declined it, we
1947           // can skip the rest of the formulae and procede to the next LSRUse.
1948           break;
1949         }
1950       }
1951     }
1952   }
1953
1954   // Nothing looked good.
1955   return 0;
1956 }
1957
1958 void LSRInstance::CollectInterestingTypesAndFactors() {
1959   SmallSetVector<const SCEV *, 4> Strides;
1960
1961   // Collect interesting types and strides.
1962   SmallVector<const SCEV *, 4> Worklist;
1963   for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
1964     const SCEV *Expr = IU.getExpr(*UI);
1965
1966     // Collect interesting types.
1967     Types.insert(SE.getEffectiveSCEVType(Expr->getType()));
1968
1969     // Add strides for mentioned loops.
1970     Worklist.push_back(Expr);
1971     do {
1972       const SCEV *S = Worklist.pop_back_val();
1973       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
1974         Strides.insert(AR->getStepRecurrence(SE));
1975         Worklist.push_back(AR->getStart());
1976       } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
1977         Worklist.append(Add->op_begin(), Add->op_end());
1978       }
1979     } while (!Worklist.empty());
1980   }
1981
1982   // Compute interesting factors from the set of interesting strides.
1983   for (SmallSetVector<const SCEV *, 4>::const_iterator
1984        I = Strides.begin(), E = Strides.end(); I != E; ++I)
1985     for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =
1986          llvm::next(I); NewStrideIter != E; ++NewStrideIter) {
1987       const SCEV *OldStride = *I;
1988       const SCEV *NewStride = *NewStrideIter;
1989
1990       if (SE.getTypeSizeInBits(OldStride->getType()) !=
1991           SE.getTypeSizeInBits(NewStride->getType())) {
1992         if (SE.getTypeSizeInBits(OldStride->getType()) >
1993             SE.getTypeSizeInBits(NewStride->getType()))
1994           NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
1995         else
1996           OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
1997       }
1998       if (const SCEVConstant *Factor =
1999             dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,
2000                                                         SE, true))) {
2001         if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
2002           Factors.insert(Factor->getValue()->getValue().getSExtValue());
2003       } else if (const SCEVConstant *Factor =
2004                    dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride,
2005                                                                NewStride,
2006                                                                SE, true))) {
2007         if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
2008           Factors.insert(Factor->getValue()->getValue().getSExtValue());
2009       }
2010     }
2011
2012   // If all uses use the same type, don't bother looking for truncation-based
2013   // reuse.
2014   if (Types.size() == 1)
2015     Types.clear();
2016
2017   DEBUG(print_factors_and_types(dbgs()));
2018 }
2019
2020 void LSRInstance::CollectFixupsAndInitialFormulae() {
2021   for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
2022     // Record the uses.
2023     LSRFixup &LF = getNewFixup();
2024     LF.UserInst = UI->getUser();
2025     LF.OperandValToReplace = UI->getOperandValToReplace();
2026     LF.PostIncLoops = UI->getPostIncLoops();
2027
2028     LSRUse::KindType Kind = LSRUse::Basic;
2029     const Type *AccessTy = 0;
2030     if (isAddressUse(LF.UserInst, LF.OperandValToReplace)) {
2031       Kind = LSRUse::Address;
2032       AccessTy = getAccessType(LF.UserInst);
2033     }
2034
2035     const SCEV *S = IU.getExpr(*UI);
2036
2037     // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
2038     // (N - i == 0), and this allows (N - i) to be the expression that we work
2039     // with rather than just N or i, so we can consider the register
2040     // requirements for both N and i at the same time. Limiting this code to
2041     // equality icmps is not a problem because all interesting loops use
2042     // equality icmps, thanks to IndVarSimplify.
2043     if (ICmpInst *CI = dyn_cast<ICmpInst>(LF.UserInst))
2044       if (CI->isEquality()) {
2045         // Swap the operands if needed to put the OperandValToReplace on the
2046         // left, for consistency.
2047         Value *NV = CI->getOperand(1);
2048         if (NV == LF.OperandValToReplace) {
2049           CI->setOperand(1, CI->getOperand(0));
2050           CI->setOperand(0, NV);
2051           NV = CI->getOperand(1);
2052           Changed = true;
2053         }
2054
2055         // x == y  -->  x - y == 0
2056         const SCEV *N = SE.getSCEV(NV);
2057         if (SE.isLoopInvariant(N, L)) {
2058           Kind = LSRUse::ICmpZero;
2059           S = SE.getMinusSCEV(N, S);
2060         }
2061
2062         // -1 and the negations of all interesting strides (except the negation
2063         // of -1) are now also interesting.
2064         for (size_t i = 0, e = Factors.size(); i != e; ++i)
2065           if (Factors[i] != -1)
2066             Factors.insert(-(uint64_t)Factors[i]);
2067         Factors.insert(-1);
2068       }
2069
2070     // Set up the initial formula for this use.
2071     std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
2072     LF.LUIdx = P.first;
2073     LF.Offset = P.second;
2074     LSRUse &LU = Uses[LF.LUIdx];
2075     LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
2076     if (!LU.WidestFixupType ||
2077         SE.getTypeSizeInBits(LU.WidestFixupType) <
2078         SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
2079       LU.WidestFixupType = LF.OperandValToReplace->getType();
2080
2081     // If this is the first use of this LSRUse, give it a formula.
2082     if (LU.Formulae.empty()) {
2083       InsertInitialFormula(S, LU, LF.LUIdx);
2084       CountRegisters(LU.Formulae.back(), LF.LUIdx);
2085     }
2086   }
2087
2088   DEBUG(print_fixups(dbgs()));
2089 }
2090
2091 /// InsertInitialFormula - Insert a formula for the given expression into
2092 /// the given use, separating out loop-variant portions from loop-invariant
2093 /// and loop-computable portions.
2094 void
2095 LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx) {
2096   Formula F;
2097   F.InitialMatch(S, L, SE);
2098   bool Inserted = InsertFormula(LU, LUIdx, F);
2099   assert(Inserted && "Initial formula already exists!"); (void)Inserted;
2100 }
2101
2102 /// InsertSupplementalFormula - Insert a simple single-register formula for
2103 /// the given expression into the given use.
2104 void
2105 LSRInstance::InsertSupplementalFormula(const SCEV *S,
2106                                        LSRUse &LU, size_t LUIdx) {
2107   Formula F;
2108   F.BaseRegs.push_back(S);
2109   F.AM.HasBaseReg = true;
2110   bool Inserted = InsertFormula(LU, LUIdx, F);
2111   assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
2112 }
2113
2114 /// CountRegisters - Note which registers are used by the given formula,
2115 /// updating RegUses.
2116 void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
2117   if (F.ScaledReg)
2118     RegUses.CountRegister(F.ScaledReg, LUIdx);
2119   for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
2120        E = F.BaseRegs.end(); I != E; ++I)
2121     RegUses.CountRegister(*I, LUIdx);
2122 }
2123
2124 /// InsertFormula - If the given formula has not yet been inserted, add it to
2125 /// the list, and return true. Return false otherwise.
2126 bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
2127   if (!LU.InsertFormula(F))
2128     return false;
2129
2130   CountRegisters(F, LUIdx);
2131   return true;
2132 }
2133
2134 /// CollectLoopInvariantFixupsAndFormulae - Check for other uses of
2135 /// loop-invariant values which we're tracking. These other uses will pin these
2136 /// values in registers, making them less profitable for elimination.
2137 /// TODO: This currently misses non-constant addrec step registers.
2138 /// TODO: Should this give more weight to users inside the loop?
2139 void
2140 LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
2141   SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
2142   SmallPtrSet<const SCEV *, 8> Inserted;
2143
2144   while (!Worklist.empty()) {
2145     const SCEV *S = Worklist.pop_back_val();
2146
2147     if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
2148       Worklist.append(N->op_begin(), N->op_end());
2149     else if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
2150       Worklist.push_back(C->getOperand());
2151     else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
2152       Worklist.push_back(D->getLHS());
2153       Worklist.push_back(D->getRHS());
2154     } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2155       if (!Inserted.insert(U)) continue;
2156       const Value *V = U->getValue();
2157       if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
2158         // Look for instructions defined outside the loop.
2159         if (L->contains(Inst)) continue;
2160       } else if (isa<UndefValue>(V))
2161         // Undef doesn't have a live range, so it doesn't matter.
2162         continue;
2163       for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
2164            UI != UE; ++UI) {
2165         const Instruction *UserInst = dyn_cast<Instruction>(*UI);
2166         // Ignore non-instructions.
2167         if (!UserInst)
2168           continue;
2169         // Ignore instructions in other functions (as can happen with
2170         // Constants).
2171         if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
2172           continue;
2173         // Ignore instructions not dominated by the loop.
2174         const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
2175           UserInst->getParent() :
2176           cast<PHINode>(UserInst)->getIncomingBlock(
2177             PHINode::getIncomingValueNumForOperand(UI.getOperandNo()));
2178         if (!DT.dominates(L->getHeader(), UseBB))
2179           continue;
2180         // Ignore uses which are part of other SCEV expressions, to avoid
2181         // analyzing them multiple times.
2182         if (SE.isSCEVable(UserInst->getType())) {
2183           const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst));
2184           // If the user is a no-op, look through to its uses.
2185           if (!isa<SCEVUnknown>(UserS))
2186             continue;
2187           if (UserS == U) {
2188             Worklist.push_back(
2189               SE.getUnknown(const_cast<Instruction *>(UserInst)));
2190             continue;
2191           }
2192         }
2193         // Ignore icmp instructions which are already being analyzed.
2194         if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
2195           unsigned OtherIdx = !UI.getOperandNo();
2196           Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
2197           if (SE.hasComputableLoopEvolution(SE.getSCEV(OtherOp), L))
2198             continue;
2199         }
2200
2201         LSRFixup &LF = getNewFixup();
2202         LF.UserInst = const_cast<Instruction *>(UserInst);
2203         LF.OperandValToReplace = UI.getUse();
2204         std::pair<size_t, int64_t> P = getUse(S, LSRUse::Basic, 0);
2205         LF.LUIdx = P.first;
2206         LF.Offset = P.second;
2207         LSRUse &LU = Uses[LF.LUIdx];
2208         LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
2209         if (!LU.WidestFixupType ||
2210             SE.getTypeSizeInBits(LU.WidestFixupType) <
2211             SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
2212           LU.WidestFixupType = LF.OperandValToReplace->getType();
2213         InsertSupplementalFormula(U, LU, LF.LUIdx);
2214         CountRegisters(LU.Formulae.back(), Uses.size() - 1);
2215         break;
2216       }
2217     }
2218   }
2219 }
2220
2221 /// CollectSubexprs - Split S into subexpressions which can be pulled out into
2222 /// separate registers. If C is non-null, multiply each subexpression by C.
2223 static void CollectSubexprs(const SCEV *S, const SCEVConstant *C,
2224                             SmallVectorImpl<const SCEV *> &Ops,
2225                             const Loop *L,
2226                             ScalarEvolution &SE) {
2227   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2228     // Break out add operands.
2229     for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
2230          I != E; ++I)
2231       CollectSubexprs(*I, C, Ops, L, SE);
2232     return;
2233   } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
2234     // Split a non-zero base out of an addrec.
2235     if (!AR->getStart()->isZero()) {
2236       CollectSubexprs(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
2237                                        AR->getStepRecurrence(SE),
2238                                        AR->getLoop()),
2239                       C, Ops, L, SE);
2240       CollectSubexprs(AR->getStart(), C, Ops, L, SE);
2241       return;
2242     }
2243   } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2244     // Break (C * (a + b + c)) into C*a + C*b + C*c.
2245     if (Mul->getNumOperands() == 2)
2246       if (const SCEVConstant *Op0 =
2247             dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2248         CollectSubexprs(Mul->getOperand(1),
2249                         C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0,
2250                         Ops, L, SE);
2251         return;
2252       }
2253   }
2254
2255   // Otherwise use the value itself, optionally with a scale applied.
2256   Ops.push_back(C ? SE.getMulExpr(C, S) : S);
2257 }
2258
2259 /// GenerateReassociations - Split out subexpressions from adds and the bases of
2260 /// addrecs.
2261 void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
2262                                          Formula Base,
2263                                          unsigned Depth) {
2264   // Arbitrarily cap recursion to protect compile time.
2265   if (Depth >= 3) return;
2266
2267   for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2268     const SCEV *BaseReg = Base.BaseRegs[i];
2269
2270     SmallVector<const SCEV *, 8> AddOps;
2271     CollectSubexprs(BaseReg, 0, AddOps, L, SE);
2272
2273     if (AddOps.size() == 1) continue;
2274
2275     for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),
2276          JE = AddOps.end(); J != JE; ++J) {
2277
2278       // Loop-variant "unknown" values are uninteresting; we won't be able to
2279       // do anything meaningful with them.
2280       if (isa<SCEVUnknown>(*J) && !SE.isLoopInvariant(*J, L))
2281         continue;
2282
2283       // Don't pull a constant into a register if the constant could be folded
2284       // into an immediate field.
2285       if (isAlwaysFoldable(*J, LU.MinOffset, LU.MaxOffset,
2286                            Base.getNumRegs() > 1,
2287                            LU.Kind, LU.AccessTy, TLI, SE))
2288         continue;
2289
2290       // Collect all operands except *J.
2291       SmallVector<const SCEV *, 8> InnerAddOps
2292         (((const SmallVector<const SCEV *, 8> &)AddOps).begin(), J);
2293       InnerAddOps.append
2294         (llvm::next(J), ((const SmallVector<const SCEV *, 8> &)AddOps).end());
2295
2296       // Don't leave just a constant behind in a register if the constant could
2297       // be folded into an immediate field.
2298       if (InnerAddOps.size() == 1 &&
2299           isAlwaysFoldable(InnerAddOps[0], LU.MinOffset, LU.MaxOffset,
2300                            Base.getNumRegs() > 1,
2301                            LU.Kind, LU.AccessTy, TLI, SE))
2302         continue;
2303
2304       const SCEV *InnerSum = SE.getAddExpr(InnerAddOps);
2305       if (InnerSum->isZero())
2306         continue;
2307       Formula F = Base;
2308       F.BaseRegs[i] = InnerSum;
2309       F.BaseRegs.push_back(*J);
2310       if (InsertFormula(LU, LUIdx, F))
2311         // If that formula hadn't been seen before, recurse to find more like
2312         // it.
2313         GenerateReassociations(LU, LUIdx, LU.Formulae.back(), Depth+1);
2314     }
2315   }
2316 }
2317
2318 /// GenerateCombinations - Generate a formula consisting of all of the
2319 /// loop-dominating registers added into a single register.
2320 void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
2321                                        Formula Base) {
2322   // This method is only interesting on a plurality of registers.
2323   if (Base.BaseRegs.size() <= 1) return;
2324
2325   Formula F = Base;
2326   F.BaseRegs.clear();
2327   SmallVector<const SCEV *, 4> Ops;
2328   for (SmallVectorImpl<const SCEV *>::const_iterator
2329        I = Base.BaseRegs.begin(), E = Base.BaseRegs.end(); I != E; ++I) {
2330     const SCEV *BaseReg = *I;
2331     if (SE.properlyDominates(BaseReg, L->getHeader()) &&
2332         !SE.hasComputableLoopEvolution(BaseReg, L))
2333       Ops.push_back(BaseReg);
2334     else
2335       F.BaseRegs.push_back(BaseReg);
2336   }
2337   if (Ops.size() > 1) {
2338     const SCEV *Sum = SE.getAddExpr(Ops);
2339     // TODO: If Sum is zero, it probably means ScalarEvolution missed an
2340     // opportunity to fold something. For now, just ignore such cases
2341     // rather than proceed with zero in a register.
2342     if (!Sum->isZero()) {
2343       F.BaseRegs.push_back(Sum);
2344       (void)InsertFormula(LU, LUIdx, F);
2345     }
2346   }
2347 }
2348
2349 /// GenerateSymbolicOffsets - Generate reuse formulae using symbolic offsets.
2350 void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
2351                                           Formula Base) {
2352   // We can't add a symbolic offset if the address already contains one.
2353   if (Base.AM.BaseGV) return;
2354
2355   for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2356     const SCEV *G = Base.BaseRegs[i];
2357     GlobalValue *GV = ExtractSymbol(G, SE);
2358     if (G->isZero() || !GV)
2359       continue;
2360     Formula F = Base;
2361     F.AM.BaseGV = GV;
2362     if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2363                     LU.Kind, LU.AccessTy, TLI))
2364       continue;
2365     F.BaseRegs[i] = G;
2366     (void)InsertFormula(LU, LUIdx, F);
2367   }
2368 }
2369
2370 /// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
2371 void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
2372                                           Formula Base) {
2373   // TODO: For now, just add the min and max offset, because it usually isn't
2374   // worthwhile looking at everything inbetween.
2375   SmallVector<int64_t, 2> Worklist;
2376   Worklist.push_back(LU.MinOffset);
2377   if (LU.MaxOffset != LU.MinOffset)
2378     Worklist.push_back(LU.MaxOffset);
2379
2380   for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
2381     const SCEV *G = Base.BaseRegs[i];
2382
2383     for (SmallVectorImpl<int64_t>::const_iterator I = Worklist.begin(),
2384          E = Worklist.end(); I != E; ++I) {
2385       Formula F = Base;
2386       F.AM.BaseOffs = (uint64_t)Base.AM.BaseOffs - *I;
2387       if (isLegalUse(F.AM, LU.MinOffset - *I, LU.MaxOffset - *I,
2388                      LU.Kind, LU.AccessTy, TLI)) {
2389         // Add the offset to the base register.
2390         const SCEV *NewG = SE.getAddExpr(SE.getConstant(G->getType(), *I), G);
2391         // If it cancelled out, drop the base register, otherwise update it.
2392         if (NewG->isZero()) {
2393           std::swap(F.BaseRegs[i], F.BaseRegs.back());
2394           F.BaseRegs.pop_back();
2395         } else
2396           F.BaseRegs[i] = NewG;
2397
2398         (void)InsertFormula(LU, LUIdx, F);
2399       }
2400     }
2401
2402     int64_t Imm = ExtractImmediate(G, SE);
2403     if (G->isZero() || Imm == 0)
2404       continue;
2405     Formula F = Base;
2406     F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Imm;
2407     if (!isLegalUse(F.AM, LU.MinOffset, LU.MaxOffset,
2408                     LU.Kind, LU.AccessTy, TLI))
2409       continue;
2410     F.BaseRegs[i] = G;
2411     (void)InsertFormula(LU, LUIdx, F);
2412   }
2413 }
2414
2415 /// GenerateICmpZeroScales - For ICmpZero, check to see if we can scale up
2416 /// the comparison. For example, x == y -> x*c == y*c.
2417 void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
2418                                          Formula Base) {
2419   if (LU.Kind != LSRUse::ICmpZero) return;
2420
2421   // Determine the integer type for the base formula.
2422   const Type *IntTy = Base.getType();
2423   if (!IntTy) return;
2424   if (SE.getTypeSizeInBits(IntTy) > 64) return;
2425
2426   // Don't do this if there is more than one offset.
2427   if (LU.MinOffset != LU.MaxOffset) return;
2428
2429   assert(!Base.AM.BaseGV && "ICmpZero use is not legal!");
2430
2431   // Check each interesting stride.
2432   for (SmallSetVector<int64_t, 8>::const_iterator
2433        I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2434     int64_t Factor = *I;
2435
2436     // Check that the multiplication doesn't overflow.
2437     if (Base.AM.BaseOffs == INT64_MIN && Factor == -1)
2438       continue;
2439     int64_t NewBaseOffs = (uint64_t)Base.AM.BaseOffs * Factor;
2440     if (NewBaseOffs / Factor != Base.AM.BaseOffs)
2441       continue;
2442
2443     // Check that multiplying with the use offset doesn't overflow.
2444     int64_t Offset = LU.MinOffset;
2445     if (Offset == INT64_MIN && Factor == -1)
2446       continue;
2447     Offset = (uint64_t)Offset * Factor;
2448     if (Offset / Factor != LU.MinOffset)
2449       continue;
2450
2451     Formula F = Base;
2452     F.AM.BaseOffs = NewBaseOffs;
2453
2454     // Check that this scale is legal.
2455     if (!isLegalUse(F.AM, Offset, Offset, LU.Kind, LU.AccessTy, TLI))
2456       continue;
2457
2458     // Compensate for the use having MinOffset built into it.
2459     F.AM.BaseOffs = (uint64_t)F.AM.BaseOffs + Offset - LU.MinOffset;
2460
2461     const SCEV *FactorS = SE.getConstant(IntTy, Factor);
2462
2463     // Check that multiplying with each base register doesn't overflow.
2464     for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
2465       F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
2466       if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
2467         goto next;
2468     }
2469
2470     // Check that multiplying with the scaled register doesn't overflow.
2471     if (F.ScaledReg) {
2472       F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
2473       if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
2474         continue;
2475     }
2476
2477     // If we make it here and it's legal, add it.
2478     (void)InsertFormula(LU, LUIdx, F);
2479   next:;
2480   }
2481 }
2482
2483 /// GenerateScales - Generate stride factor reuse formulae by making use of
2484 /// scaled-offset address modes, for example.
2485 void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base) {
2486   // Determine the integer type for the base formula.
2487   const Type *IntTy = Base.getType();
2488   if (!IntTy) return;
2489
2490   // If this Formula already has a scaled register, we can't add another one.
2491   if (Base.AM.Scale != 0) return;
2492
2493   // Check each interesting stride.
2494   for (SmallSetVector<int64_t, 8>::const_iterator
2495        I = Factors.begin(), E = Factors.end(); I != E; ++I) {
2496     int64_t Factor = *I;
2497
2498     Base.AM.Scale = Factor;
2499     Base.AM.HasBaseReg = Base.BaseRegs.size() > 1;
2500     // Check whether this scale is going to be legal.
2501     if (!isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2502                     LU.Kind, LU.AccessTy, TLI)) {
2503       // As a special-case, handle special out-of-loop Basic users specially.
2504       // TODO: Reconsider this special case.
2505       if (LU.Kind == LSRUse::Basic &&
2506           isLegalUse(Base.AM, LU.MinOffset, LU.MaxOffset,
2507                      LSRUse::Special, LU.AccessTy, TLI) &&
2508           LU.AllFixupsOutsideLoop)
2509         LU.Kind = LSRUse::Special;
2510       else
2511         continue;
2512     }
2513     // For an ICmpZero, negating a solitary base register won't lead to
2514     // new solutions.
2515     if (LU.Kind == LSRUse::ICmpZero &&
2516         !Base.AM.HasBaseReg && Base.AM.BaseOffs == 0 && !Base.AM.BaseGV)
2517       continue;
2518     // For each addrec base reg, apply the scale, if possible.
2519     for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
2520       if (const SCEVAddRecExpr *AR =
2521             dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i])) {
2522         const SCEV *FactorS = SE.getConstant(IntTy, Factor);
2523         if (FactorS->isZero())
2524           continue;
2525         // Divide out the factor, ignoring high bits, since we'll be
2526         // scaling the value back up in the end.
2527         if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) {
2528           // TODO: This could be optimized to avoid all the copying.
2529           Formula F = Base;
2530           F.ScaledReg = Quotient;
2531           F.DeleteBaseReg(F.BaseRegs[i]);
2532           (void)InsertFormula(LU, LUIdx, F);
2533         }
2534       }
2535   }
2536 }
2537
2538 /// GenerateTruncates - Generate reuse formulae from different IV types.
2539 void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base) {
2540   // This requires TargetLowering to tell us which truncates are free.
2541   if (!TLI) return;
2542
2543   // Don't bother truncating symbolic values.
2544   if (Base.AM.BaseGV) return;
2545
2546   // Determine the integer type for the base formula.
2547   const Type *DstTy = Base.getType();
2548   if (!DstTy) return;
2549   DstTy = SE.getEffectiveSCEVType(DstTy);
2550
2551   for (SmallSetVector<const Type *, 4>::const_iterator
2552        I = Types.begin(), E = Types.end(); I != E; ++I) {
2553     const Type *SrcTy = *I;
2554     if (SrcTy != DstTy && TLI->isTruncateFree(SrcTy, DstTy)) {
2555       Formula F = Base;
2556
2557       if (F.ScaledReg) F.ScaledReg = SE.getAnyExtendExpr(F.ScaledReg, *I);
2558       for (SmallVectorImpl<const SCEV *>::iterator J = F.BaseRegs.begin(),
2559            JE = F.BaseRegs.end(); J != JE; ++J)
2560         *J = SE.getAnyExtendExpr(*J, SrcTy);
2561
2562       // TODO: This assumes we've done basic processing on all uses and
2563       // have an idea what the register usage is.
2564       if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
2565         continue;
2566
2567       (void)InsertFormula(LU, LUIdx, F);
2568     }
2569   }
2570 }
2571
2572 namespace {
2573
2574 /// WorkItem - Helper class for GenerateCrossUseConstantOffsets. It's used to
2575 /// defer modifications so that the search phase doesn't have to worry about
2576 /// the data structures moving underneath it.
2577 struct WorkItem {
2578   size_t LUIdx;
2579   int64_t Imm;
2580   const SCEV *OrigReg;
2581
2582   WorkItem(size_t LI, int64_t I, const SCEV *R)
2583     : LUIdx(LI), Imm(I), OrigReg(R) {}
2584
2585   void print(raw_ostream &OS) const;
2586   void dump() const;
2587 };
2588
2589 }
2590
2591 void WorkItem::print(raw_ostream &OS) const {
2592   OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
2593      << " , add offset " << Imm;
2594 }
2595
2596 void WorkItem::dump() const {
2597   print(errs()); errs() << '\n';
2598 }
2599
2600 /// GenerateCrossUseConstantOffsets - Look for registers which are a constant
2601 /// distance apart and try to form reuse opportunities between them.
2602 void LSRInstance::GenerateCrossUseConstantOffsets() {
2603   // Group the registers by their value without any added constant offset.
2604   typedef std::map<int64_t, const SCEV *> ImmMapTy;
2605   typedef DenseMap<const SCEV *, ImmMapTy> RegMapTy;
2606   RegMapTy Map;
2607   DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
2608   SmallVector<const SCEV *, 8> Sequence;
2609   for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
2610        I != E; ++I) {
2611     const SCEV *Reg = *I;
2612     int64_t Imm = ExtractImmediate(Reg, SE);
2613     std::pair<RegMapTy::iterator, bool> Pair =
2614       Map.insert(std::make_pair(Reg, ImmMapTy()));
2615     if (Pair.second)
2616       Sequence.push_back(Reg);
2617     Pair.first->second.insert(std::make_pair(Imm, *I));
2618     UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(*I);
2619   }
2620
2621   // Now examine each set of registers with the same base value. Build up
2622   // a list of work to do and do the work in a separate step so that we're
2623   // not adding formulae and register counts while we're searching.
2624   SmallVector<WorkItem, 32> WorkItems;
2625   SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems;
2626   for (SmallVectorImpl<const SCEV *>::const_iterator I = Sequence.begin(),
2627        E = Sequence.end(); I != E; ++I) {
2628     const SCEV *Reg = *I;
2629     const ImmMapTy &Imms = Map.find(Reg)->second;
2630
2631     // It's not worthwhile looking for reuse if there's only one offset.
2632     if (Imms.size() == 1)
2633       continue;
2634
2635     DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
2636           for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2637                J != JE; ++J)
2638             dbgs() << ' ' << J->first;
2639           dbgs() << '\n');
2640
2641     // Examine each offset.
2642     for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
2643          J != JE; ++J) {
2644       const SCEV *OrigReg = J->second;
2645
2646       int64_t JImm = J->first;
2647       const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
2648
2649       if (!isa<SCEVConstant>(OrigReg) &&
2650           UsedByIndicesMap[Reg].count() == 1) {
2651         DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg << '\n');
2652         continue;
2653       }
2654
2655       // Conservatively examine offsets between this orig reg a few selected
2656       // other orig regs.
2657       ImmMapTy::const_iterator OtherImms[] = {
2658         Imms.begin(), prior(Imms.end()),
2659         Imms.upper_bound((Imms.begin()->first + prior(Imms.end())->first) / 2)
2660       };
2661       for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) {
2662         ImmMapTy::const_iterator M = OtherImms[i];
2663         if (M == J || M == JE) continue;
2664
2665         // Compute the difference between the two.
2666         int64_t Imm = (uint64_t)JImm - M->first;
2667         for (int LUIdx = UsedByIndices.find_first(); LUIdx != -1;
2668              LUIdx = UsedByIndices.find_next(LUIdx))
2669           // Make a memo of this use, offset, and register tuple.
2670           if (UniqueItems.insert(std::make_pair(LUIdx, Imm)))
2671             WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
2672       }
2673     }
2674   }
2675
2676   Map.clear();
2677   Sequence.clear();
2678   UsedByIndicesMap.clear();
2679   UniqueItems.clear();
2680
2681   // Now iterate through the worklist and add new formulae.
2682   for (SmallVectorImpl<WorkItem>::const_iterator I = WorkItems.begin(),
2683        E = WorkItems.end(); I != E; ++I) {
2684     const WorkItem &WI = *I;
2685     size_t LUIdx = WI.LUIdx;
2686     LSRUse &LU = Uses[LUIdx];
2687     int64_t Imm = WI.Imm;
2688     const SCEV *OrigReg = WI.OrigReg;
2689
2690     const Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
2691     const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
2692     unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
2693
2694     // TODO: Use a more targeted data structure.
2695     for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
2696       const Formula &F = LU.Formulae[L];
2697       // Use the immediate in the scaled register.
2698       if (F.ScaledReg == OrigReg) {
2699         int64_t Offs = (uint64_t)F.AM.BaseOffs +
2700                        Imm * (uint64_t)F.AM.Scale;
2701         // Don't create 50 + reg(-50).
2702         if (F.referencesReg(SE.getSCEV(
2703                    ConstantInt::get(IntTy, -(uint64_t)Offs))))
2704           continue;
2705         Formula NewF = F;
2706         NewF.AM.BaseOffs = Offs;
2707         if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
2708                         LU.Kind, LU.AccessTy, TLI))
2709           continue;
2710         NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
2711
2712         // If the new scale is a constant in a register, and adding the constant
2713         // value to the immediate would produce a value closer to zero than the
2714         // immediate itself, then the formula isn't worthwhile.
2715         if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
2716           if (C->getValue()->getValue().isNegative() !=
2717                 (NewF.AM.BaseOffs < 0) &&
2718               (C->getValue()->getValue().abs() * APInt(BitWidth, F.AM.Scale))
2719                 .ule(abs64(NewF.AM.BaseOffs)))
2720             continue;
2721
2722         // OK, looks good.
2723         (void)InsertFormula(LU, LUIdx, NewF);
2724       } else {
2725         // Use the immediate in a base register.
2726         for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
2727           const SCEV *BaseReg = F.BaseRegs[N];
2728           if (BaseReg != OrigReg)
2729             continue;
2730           Formula NewF = F;
2731           NewF.AM.BaseOffs = (uint64_t)NewF.AM.BaseOffs + Imm;
2732           if (!isLegalUse(NewF.AM, LU.MinOffset, LU.MaxOffset,
2733                           LU.Kind, LU.AccessTy, TLI))
2734             continue;
2735           NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
2736
2737           // If the new formula has a constant in a register, and adding the
2738           // constant value to the immediate would produce a value closer to
2739           // zero than the immediate itself, then the formula isn't worthwhile.
2740           for (SmallVectorImpl<const SCEV *>::const_iterator
2741                J = NewF.BaseRegs.begin(), JE = NewF.BaseRegs.end();
2742                J != JE; ++J)
2743             if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*J))
2744               if ((C->getValue()->getValue() + NewF.AM.BaseOffs).abs().slt(
2745                    abs64(NewF.AM.BaseOffs)) &&
2746                   (C->getValue()->getValue() +
2747                    NewF.AM.BaseOffs).countTrailingZeros() >=
2748                    CountTrailingZeros_64(NewF.AM.BaseOffs))
2749                 goto skip_formula;
2750
2751           // Ok, looks good.
2752           (void)InsertFormula(LU, LUIdx, NewF);
2753           break;
2754         skip_formula:;
2755         }
2756       }
2757     }
2758   }
2759 }
2760
2761 /// GenerateAllReuseFormulae - Generate formulae for each use.
2762 void
2763 LSRInstance::GenerateAllReuseFormulae() {
2764   // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
2765   // queries are more precise.
2766   for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2767     LSRUse &LU = Uses[LUIdx];
2768     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2769       GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
2770     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2771       GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
2772   }
2773   for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2774     LSRUse &LU = Uses[LUIdx];
2775     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2776       GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
2777     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2778       GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
2779     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2780       GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
2781     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2782       GenerateScales(LU, LUIdx, LU.Formulae[i]);
2783   }
2784   for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2785     LSRUse &LU = Uses[LUIdx];
2786     for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
2787       GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
2788   }
2789
2790   GenerateCrossUseConstantOffsets();
2791
2792   DEBUG(dbgs() << "\n"
2793                   "After generating reuse formulae:\n";
2794         print_uses(dbgs()));
2795 }
2796
2797 /// If there are multiple formulae with the same set of registers used
2798 /// by other uses, pick the best one and delete the others.
2799 void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
2800   DenseSet<const SCEV *> VisitedRegs;
2801   SmallPtrSet<const SCEV *, 16> Regs;
2802 #ifndef NDEBUG
2803   bool ChangedFormulae = false;
2804 #endif
2805
2806   // Collect the best formula for each unique set of shared registers. This
2807   // is reset for each use.
2808   typedef DenseMap<SmallVector<const SCEV *, 2>, size_t, UniquifierDenseMapInfo>
2809     BestFormulaeTy;
2810   BestFormulaeTy BestFormulae;
2811
2812   for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2813     LSRUse &LU = Uses[LUIdx];
2814     DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs()); dbgs() << '\n');
2815
2816     bool Any = false;
2817     for (size_t FIdx = 0, NumForms = LU.Formulae.size();
2818          FIdx != NumForms; ++FIdx) {
2819       Formula &F = LU.Formulae[FIdx];
2820
2821       SmallVector<const SCEV *, 2> Key;
2822       for (SmallVectorImpl<const SCEV *>::const_iterator J = F.BaseRegs.begin(),
2823            JE = F.BaseRegs.end(); J != JE; ++J) {
2824         const SCEV *Reg = *J;
2825         if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
2826           Key.push_back(Reg);
2827       }
2828       if (F.ScaledReg &&
2829           RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
2830         Key.push_back(F.ScaledReg);
2831       // Unstable sort by host order ok, because this is only used for
2832       // uniquifying.
2833       std::sort(Key.begin(), Key.end());
2834
2835       std::pair<BestFormulaeTy::const_iterator, bool> P =
2836         BestFormulae.insert(std::make_pair(Key, FIdx));
2837       if (!P.second) {
2838         Formula &Best = LU.Formulae[P.first->second];
2839
2840         Cost CostF;
2841         CostF.RateFormula(F, Regs, VisitedRegs, L, LU.Offsets, SE, DT);
2842         Regs.clear();
2843         Cost CostBest;
2844         CostBest.RateFormula(Best, Regs, VisitedRegs, L, LU.Offsets, SE, DT);
2845         Regs.clear();
2846         if (CostF < CostBest)
2847           std::swap(F, Best);
2848         DEBUG(dbgs() << "  Filtering out formula "; F.print(dbgs());
2849               dbgs() << "\n"
2850                         "    in favor of formula "; Best.print(dbgs());
2851               dbgs() << '\n');
2852 #ifndef NDEBUG
2853         ChangedFormulae = true;
2854 #endif
2855         LU.DeleteFormula(F);
2856         --FIdx;
2857         --NumForms;
2858         Any = true;
2859         continue;
2860       }
2861     }
2862
2863     // Now that we've filtered out some formulae, recompute the Regs set.
2864     if (Any)
2865       LU.RecomputeRegs(LUIdx, RegUses);
2866
2867     // Reset this to prepare for the next use.
2868     BestFormulae.clear();
2869   }
2870
2871   DEBUG(if (ChangedFormulae) {
2872           dbgs() << "\n"
2873                     "After filtering out undesirable candidates:\n";
2874           print_uses(dbgs());
2875         });
2876 }
2877
2878 // This is a rough guess that seems to work fairly well.
2879 static const size_t ComplexityLimit = UINT16_MAX;
2880
2881 /// EstimateSearchSpaceComplexity - Estimate the worst-case number of
2882 /// solutions the solver might have to consider. It almost never considers
2883 /// this many solutions because it prune the search space, but the pruning
2884 /// isn't always sufficient.
2885 size_t LSRInstance::EstimateSearchSpaceComplexity() const {
2886   size_t Power = 1;
2887   for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
2888        E = Uses.end(); I != E; ++I) {
2889     size_t FSize = I->Formulae.size();
2890     if (FSize >= ComplexityLimit) {
2891       Power = ComplexityLimit;
2892       break;
2893     }
2894     Power *= FSize;
2895     if (Power >= ComplexityLimit)
2896       break;
2897   }
2898   return Power;
2899 }
2900
2901 /// NarrowSearchSpaceByDetectingSupersets - When one formula uses a superset
2902 /// of the registers of another formula, it won't help reduce register
2903 /// pressure (though it may not necessarily hurt register pressure); remove
2904 /// it to simplify the system.
2905 void LSRInstance::NarrowSearchSpaceByDetectingSupersets() {
2906   if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
2907     DEBUG(dbgs() << "The search space is too complex.\n");
2908
2909     DEBUG(dbgs() << "Narrowing the search space by eliminating formulae "
2910                     "which use a superset of registers used by other "
2911                     "formulae.\n");
2912
2913     for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2914       LSRUse &LU = Uses[LUIdx];
2915       bool Any = false;
2916       for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
2917         Formula &F = LU.Formulae[i];
2918         // Look for a formula with a constant or GV in a register. If the use
2919         // also has a formula with that same value in an immediate field,
2920         // delete the one that uses a register.
2921         for (SmallVectorImpl<const SCEV *>::const_iterator
2922              I = F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I) {
2923           if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*I)) {
2924             Formula NewF = F;
2925             NewF.AM.BaseOffs += C->getValue()->getSExtValue();
2926             NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
2927                                 (I - F.BaseRegs.begin()));
2928             if (LU.HasFormulaWithSameRegs(NewF)) {
2929               DEBUG(dbgs() << "  Deleting "; F.print(dbgs()); dbgs() << '\n');
2930               LU.DeleteFormula(F);
2931               --i;
2932               --e;
2933               Any = true;
2934               break;
2935             }
2936           } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) {
2937             if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue()))
2938               if (!F.AM.BaseGV) {
2939                 Formula NewF = F;
2940                 NewF.AM.BaseGV = GV;
2941                 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
2942                                     (I - F.BaseRegs.begin()));
2943                 if (LU.HasFormulaWithSameRegs(NewF)) {
2944                   DEBUG(dbgs() << "  Deleting "; F.print(dbgs());
2945                         dbgs() << '\n');
2946                   LU.DeleteFormula(F);
2947                   --i;
2948                   --e;
2949                   Any = true;
2950                   break;
2951                 }
2952               }
2953           }
2954         }
2955       }
2956       if (Any)
2957         LU.RecomputeRegs(LUIdx, RegUses);
2958     }
2959
2960     DEBUG(dbgs() << "After pre-selection:\n";
2961           print_uses(dbgs()));
2962   }
2963 }
2964
2965 /// NarrowSearchSpaceByCollapsingUnrolledCode - When there are many registers
2966 /// for expressions like A, A+1, A+2, etc., allocate a single register for
2967 /// them.
2968 void LSRInstance::NarrowSearchSpaceByCollapsingUnrolledCode() {
2969   if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
2970     DEBUG(dbgs() << "The search space is too complex.\n");
2971
2972     DEBUG(dbgs() << "Narrowing the search space by assuming that uses "
2973                     "separated by a constant offset will use the same "
2974                     "registers.\n");
2975
2976     // This is especially useful for unrolled loops.
2977
2978     for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2979       LSRUse &LU = Uses[LUIdx];
2980       for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
2981            E = LU.Formulae.end(); I != E; ++I) {
2982         const Formula &F = *I;
2983         if (F.AM.BaseOffs != 0 && F.AM.Scale == 0) {
2984           if (LSRUse *LUThatHas = FindUseWithSimilarFormula(F, LU)) {
2985             if (reconcileNewOffset(*LUThatHas, F.AM.BaseOffs,
2986                                    /*HasBaseReg=*/false,
2987                                    LU.Kind, LU.AccessTy)) {
2988               DEBUG(dbgs() << "  Deleting use "; LU.print(dbgs());
2989                     dbgs() << '\n');
2990
2991               LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop;
2992
2993               // Update the relocs to reference the new use.
2994               for (SmallVectorImpl<LSRFixup>::iterator I = Fixups.begin(),
2995                    E = Fixups.end(); I != E; ++I) {
2996                 LSRFixup &Fixup = *I;
2997                 if (Fixup.LUIdx == LUIdx) {
2998                   Fixup.LUIdx = LUThatHas - &Uses.front();
2999                   Fixup.Offset += F.AM.BaseOffs;
3000                   // Add the new offset to LUThatHas' offset list.
3001                   if (LUThatHas->Offsets.back() != Fixup.Offset) {
3002                     LUThatHas->Offsets.push_back(Fixup.Offset);
3003                     if (Fixup.Offset > LUThatHas->MaxOffset)
3004                       LUThatHas->MaxOffset = Fixup.Offset;
3005                     if (Fixup.Offset < LUThatHas->MinOffset)
3006                       LUThatHas->MinOffset = Fixup.Offset;
3007                   }
3008                   DEBUG(dbgs() << "New fixup has offset "
3009                                << Fixup.Offset << '\n');
3010                 }
3011                 if (Fixup.LUIdx == NumUses-1)
3012                   Fixup.LUIdx = LUIdx;
3013               }
3014
3015               // Delete formulae from the new use which are no longer legal.
3016               bool Any = false;
3017               for (size_t i = 0, e = LUThatHas->Formulae.size(); i != e; ++i) {
3018                 Formula &F = LUThatHas->Formulae[i];
3019                 if (!isLegalUse(F.AM,
3020                                 LUThatHas->MinOffset, LUThatHas->MaxOffset,
3021                                 LUThatHas->Kind, LUThatHas->AccessTy, TLI)) {
3022                   DEBUG(dbgs() << "  Deleting "; F.print(dbgs());
3023                         dbgs() << '\n');
3024                   LUThatHas->DeleteFormula(F);
3025                   --i;
3026                   --e;
3027                   Any = true;
3028                 }
3029               }
3030               if (Any)
3031                 LUThatHas->RecomputeRegs(LUThatHas - &Uses.front(), RegUses);
3032
3033               // Delete the old use.
3034               DeleteUse(LU, LUIdx);
3035               --LUIdx;
3036               --NumUses;
3037               break;
3038             }
3039           }
3040         }
3041       }
3042     }
3043
3044     DEBUG(dbgs() << "After pre-selection:\n";
3045           print_uses(dbgs()));
3046   }
3047 }
3048
3049 /// NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters - Call 
3050 /// FilterOutUndesirableDedicatedRegisters again, if necessary, now that
3051 /// we've done more filtering, as it may be able to find more formulae to
3052 /// eliminate.
3053 void LSRInstance::NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(){
3054   if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
3055     DEBUG(dbgs() << "The search space is too complex.\n");
3056
3057     DEBUG(dbgs() << "Narrowing the search space by re-filtering out "
3058                     "undesirable dedicated registers.\n");
3059
3060     FilterOutUndesirableDedicatedRegisters();
3061
3062     DEBUG(dbgs() << "After pre-selection:\n";
3063           print_uses(dbgs()));
3064   }
3065 }
3066
3067 /// NarrowSearchSpaceByPickingWinnerRegs - Pick a register which seems likely
3068 /// to be profitable, and then in any use which has any reference to that
3069 /// register, delete all formulae which do not reference that register.
3070 void LSRInstance::NarrowSearchSpaceByPickingWinnerRegs() {
3071   // With all other options exhausted, loop until the system is simple
3072   // enough to handle.
3073   SmallPtrSet<const SCEV *, 4> Taken;
3074   while (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
3075     // Ok, we have too many of formulae on our hands to conveniently handle.
3076     // Use a rough heuristic to thin out the list.
3077     DEBUG(dbgs() << "The search space is too complex.\n");
3078
3079     // Pick the register which is used by the most LSRUses, which is likely
3080     // to be a good reuse register candidate.
3081     const SCEV *Best = 0;
3082     unsigned BestNum = 0;
3083     for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
3084          I != E; ++I) {
3085       const SCEV *Reg = *I;
3086       if (Taken.count(Reg))
3087         continue;
3088       if (!Best)
3089         Best = Reg;
3090       else {
3091         unsigned Count = RegUses.getUsedByIndices(Reg).count();
3092         if (Count > BestNum) {
3093           Best = Reg;
3094           BestNum = Count;
3095         }
3096       }
3097     }
3098
3099     DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
3100                  << " will yield profitable reuse.\n");
3101     Taken.insert(Best);
3102
3103     // In any use with formulae which references this register, delete formulae
3104     // which don't reference it.
3105     for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3106       LSRUse &LU = Uses[LUIdx];
3107       if (!LU.Regs.count(Best)) continue;
3108
3109       bool Any = false;
3110       for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
3111         Formula &F = LU.Formulae[i];
3112         if (!F.referencesReg(Best)) {
3113           DEBUG(dbgs() << "  Deleting "; F.print(dbgs()); dbgs() << '\n');
3114           LU.DeleteFormula(F);
3115           --e;
3116           --i;
3117           Any = true;
3118           assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?");
3119           continue;
3120         }
3121       }
3122
3123       if (Any)
3124         LU.RecomputeRegs(LUIdx, RegUses);
3125     }
3126
3127     DEBUG(dbgs() << "After pre-selection:\n";
3128           print_uses(dbgs()));
3129   }
3130 }
3131
3132 /// NarrowSearchSpaceUsingHeuristics - If there are an extraordinary number of
3133 /// formulae to choose from, use some rough heuristics to prune down the number
3134 /// of formulae. This keeps the main solver from taking an extraordinary amount
3135 /// of time in some worst-case scenarios.
3136 void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
3137   NarrowSearchSpaceByDetectingSupersets();
3138   NarrowSearchSpaceByCollapsingUnrolledCode();
3139   NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
3140   NarrowSearchSpaceByPickingWinnerRegs();
3141 }
3142
3143 /// SolveRecurse - This is the recursive solver.
3144 void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
3145                                Cost &SolutionCost,
3146                                SmallVectorImpl<const Formula *> &Workspace,
3147                                const Cost &CurCost,
3148                                const SmallPtrSet<const SCEV *, 16> &CurRegs,
3149                                DenseSet<const SCEV *> &VisitedRegs) const {
3150   // Some ideas:
3151   //  - prune more:
3152   //    - use more aggressive filtering
3153   //    - sort the formula so that the most profitable solutions are found first
3154   //    - sort the uses too
3155   //  - search faster:
3156   //    - don't compute a cost, and then compare. compare while computing a cost
3157   //      and bail early.
3158   //    - track register sets with SmallBitVector
3159
3160   const LSRUse &LU = Uses[Workspace.size()];
3161
3162   // If this use references any register that's already a part of the
3163   // in-progress solution, consider it a requirement that a formula must
3164   // reference that register in order to be considered. This prunes out
3165   // unprofitable searching.
3166   SmallSetVector<const SCEV *, 4> ReqRegs;
3167   for (SmallPtrSet<const SCEV *, 16>::const_iterator I = CurRegs.begin(),
3168        E = CurRegs.end(); I != E; ++I)
3169     if (LU.Regs.count(*I))
3170       ReqRegs.insert(*I);
3171
3172   bool AnySatisfiedReqRegs = false;
3173   SmallPtrSet<const SCEV *, 16> NewRegs;
3174   Cost NewCost;
3175 retry:
3176   for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
3177        E = LU.Formulae.end(); I != E; ++I) {
3178     const Formula &F = *I;
3179
3180     // Ignore formulae which do not use any of the required registers.
3181     for (SmallSetVector<const SCEV *, 4>::const_iterator J = ReqRegs.begin(),
3182          JE = ReqRegs.end(); J != JE; ++J) {
3183       const SCEV *Reg = *J;
3184       if ((!F.ScaledReg || F.ScaledReg != Reg) &&
3185           std::find(F.BaseRegs.begin(), F.BaseRegs.end(), Reg) ==
3186           F.BaseRegs.end())
3187         goto skip;
3188     }
3189     AnySatisfiedReqRegs = true;
3190
3191     // Evaluate the cost of the current formula. If it's already worse than
3192     // the current best, prune the search at that point.
3193     NewCost = CurCost;
3194     NewRegs = CurRegs;
3195     NewCost.RateFormula(F, NewRegs, VisitedRegs, L, LU.Offsets, SE, DT);
3196     if (NewCost < SolutionCost) {
3197       Workspace.push_back(&F);
3198       if (Workspace.size() != Uses.size()) {
3199         SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
3200                      NewRegs, VisitedRegs);
3201         if (F.getNumRegs() == 1 && Workspace.size() == 1)
3202           VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
3203       } else {
3204         DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
3205               dbgs() << ". Regs:";
3206               for (SmallPtrSet<const SCEV *, 16>::const_iterator
3207                    I = NewRegs.begin(), E = NewRegs.end(); I != E; ++I)
3208                 dbgs() << ' ' << **I;
3209               dbgs() << '\n');
3210
3211         SolutionCost = NewCost;
3212         Solution = Workspace;
3213       }
3214       Workspace.pop_back();
3215     }
3216   skip:;
3217   }
3218
3219   // If none of the formulae had all of the required registers, relax the
3220   // constraint so that we don't exclude all formulae.
3221   if (!AnySatisfiedReqRegs) {
3222     assert(!ReqRegs.empty() && "Solver failed even without required registers");
3223     ReqRegs.clear();
3224     goto retry;
3225   }
3226 }
3227
3228 /// Solve - Choose one formula from each use. Return the results in the given
3229 /// Solution vector.
3230 void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
3231   SmallVector<const Formula *, 8> Workspace;
3232   Cost SolutionCost;
3233   SolutionCost.Loose();
3234   Cost CurCost;
3235   SmallPtrSet<const SCEV *, 16> CurRegs;
3236   DenseSet<const SCEV *> VisitedRegs;
3237   Workspace.reserve(Uses.size());
3238
3239   // SolveRecurse does all the work.
3240   SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
3241                CurRegs, VisitedRegs);
3242
3243   // Ok, we've now made all our decisions.
3244   DEBUG(dbgs() << "\n"
3245                   "The chosen solution requires "; SolutionCost.print(dbgs());
3246         dbgs() << ":\n";
3247         for (size_t i = 0, e = Uses.size(); i != e; ++i) {
3248           dbgs() << "  ";
3249           Uses[i].print(dbgs());
3250           dbgs() << "\n"
3251                     "    ";
3252           Solution[i]->print(dbgs());
3253           dbgs() << '\n';
3254         });
3255
3256   assert(Solution.size() == Uses.size() && "Malformed solution!");
3257 }
3258
3259 /// HoistInsertPosition - Helper for AdjustInsertPositionForExpand. Climb up
3260 /// the dominator tree far as we can go while still being dominated by the
3261 /// input positions. This helps canonicalize the insert position, which
3262 /// encourages sharing.
3263 BasicBlock::iterator
3264 LSRInstance::HoistInsertPosition(BasicBlock::iterator IP,
3265                                  const SmallVectorImpl<Instruction *> &Inputs)
3266                                                                          const {
3267   for (;;) {
3268     const Loop *IPLoop = LI.getLoopFor(IP->getParent());
3269     unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0;
3270
3271     BasicBlock *IDom;
3272     for (DomTreeNode *Rung = DT.getNode(IP->getParent()); ; ) {
3273       if (!Rung) return IP;
3274       Rung = Rung->getIDom();
3275       if (!Rung) return IP;
3276       IDom = Rung->getBlock();
3277
3278       // Don't climb into a loop though.
3279       const Loop *IDomLoop = LI.getLoopFor(IDom);
3280       unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0;
3281       if (IDomDepth <= IPLoopDepth &&
3282           (IDomDepth != IPLoopDepth || IDomLoop == IPLoop))
3283         break;
3284     }
3285
3286     bool AllDominate = true;
3287     Instruction *BetterPos = 0;
3288     Instruction *Tentative = IDom->getTerminator();
3289     for (SmallVectorImpl<Instruction *>::const_iterator I = Inputs.begin(),
3290          E = Inputs.end(); I != E; ++I) {
3291       Instruction *Inst = *I;
3292       if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
3293         AllDominate = false;
3294         break;
3295       }
3296       // Attempt to find an insert position in the middle of the block,
3297       // instead of at the end, so that it can be used for other expansions.
3298       if (IDom == Inst->getParent() &&
3299           (!BetterPos || DT.dominates(BetterPos, Inst)))
3300         BetterPos = llvm::next(BasicBlock::iterator(Inst));
3301     }
3302     if (!AllDominate)
3303       break;
3304     if (BetterPos)
3305       IP = BetterPos;
3306     else
3307       IP = Tentative;
3308   }
3309
3310   return IP;
3311 }
3312
3313 /// AdjustInsertPositionForExpand - Determine an input position which will be
3314 /// dominated by the operands and which will dominate the result.
3315 BasicBlock::iterator
3316 LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator IP,
3317                                            const LSRFixup &LF,
3318                                            const LSRUse &LU) const {
3319   // Collect some instructions which must be dominated by the
3320   // expanding replacement. These must be dominated by any operands that
3321   // will be required in the expansion.
3322   SmallVector<Instruction *, 4> Inputs;
3323   if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
3324     Inputs.push_back(I);
3325   if (LU.Kind == LSRUse::ICmpZero)
3326     if (Instruction *I =
3327           dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
3328       Inputs.push_back(I);
3329   if (LF.PostIncLoops.count(L)) {
3330     if (LF.isUseFullyOutsideLoop(L))
3331       Inputs.push_back(L->getLoopLatch()->getTerminator());
3332     else
3333       Inputs.push_back(IVIncInsertPos);
3334   }
3335   // The expansion must also be dominated by the increment positions of any
3336   // loops it for which it is using post-inc mode.
3337   for (PostIncLoopSet::const_iterator I = LF.PostIncLoops.begin(),
3338        E = LF.PostIncLoops.end(); I != E; ++I) {
3339     const Loop *PIL = *I;
3340     if (PIL == L) continue;
3341
3342     // Be dominated by the loop exit.
3343     SmallVector<BasicBlock *, 4> ExitingBlocks;
3344     PIL->getExitingBlocks(ExitingBlocks);
3345     if (!ExitingBlocks.empty()) {
3346       BasicBlock *BB = ExitingBlocks[0];
3347       for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i)
3348         BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]);
3349       Inputs.push_back(BB->getTerminator());
3350     }
3351   }
3352
3353   // Then, climb up the immediate dominator tree as far as we can go while
3354   // still being dominated by the input positions.
3355   IP = HoistInsertPosition(IP, Inputs);
3356
3357   // Don't insert instructions before PHI nodes.
3358   while (isa<PHINode>(IP)) ++IP;
3359
3360   // Ignore debug intrinsics.
3361   while (isa<DbgInfoIntrinsic>(IP)) ++IP;
3362
3363   return IP;
3364 }
3365
3366 /// Expand - Emit instructions for the leading candidate expression for this
3367 /// LSRUse (this is called "expanding").
3368 Value *LSRInstance::Expand(const LSRFixup &LF,
3369                            const Formula &F,
3370                            BasicBlock::iterator IP,
3371                            SCEVExpander &Rewriter,
3372                            SmallVectorImpl<WeakVH> &DeadInsts) const {
3373   const LSRUse &LU = Uses[LF.LUIdx];
3374
3375   // Determine an input position which will be dominated by the operands and
3376   // which will dominate the result.
3377   IP = AdjustInsertPositionForExpand(IP, LF, LU);
3378
3379   // Inform the Rewriter if we have a post-increment use, so that it can
3380   // perform an advantageous expansion.
3381   Rewriter.setPostInc(LF.PostIncLoops);
3382
3383   // This is the type that the user actually needs.
3384   const Type *OpTy = LF.OperandValToReplace->getType();
3385   // This will be the type that we'll initially expand to.
3386   const Type *Ty = F.getType();
3387   if (!Ty)
3388     // No type known; just expand directly to the ultimate type.
3389     Ty = OpTy;
3390   else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
3391     // Expand directly to the ultimate type if it's the right size.
3392     Ty = OpTy;
3393   // This is the type to do integer arithmetic in.
3394   const Type *IntTy = SE.getEffectiveSCEVType(Ty);
3395
3396   // Build up a list of operands to add together to form the full base.
3397   SmallVector<const SCEV *, 8> Ops;
3398
3399   // Expand the BaseRegs portion.
3400   for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
3401        E = F.BaseRegs.end(); I != E; ++I) {
3402     const SCEV *Reg = *I;
3403     assert(!Reg->isZero() && "Zero allocated in a base register!");
3404
3405     // If we're expanding for a post-inc user, make the post-inc adjustment.
3406     PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
3407     Reg = TransformForPostIncUse(Denormalize, Reg,
3408                                  LF.UserInst, LF.OperandValToReplace,
3409                                  Loops, SE, DT);
3410
3411     Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, 0, IP)));
3412   }
3413
3414   // Flush the operand list to suppress SCEVExpander hoisting.
3415   if (!Ops.empty()) {
3416     Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3417     Ops.clear();
3418     Ops.push_back(SE.getUnknown(FullV));
3419   }
3420
3421   // Expand the ScaledReg portion.
3422   Value *ICmpScaledV = 0;
3423   if (F.AM.Scale != 0) {
3424     const SCEV *ScaledS = F.ScaledReg;
3425
3426     // If we're expanding for a post-inc user, make the post-inc adjustment.
3427     PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
3428     ScaledS = TransformForPostIncUse(Denormalize, ScaledS,
3429                                      LF.UserInst, LF.OperandValToReplace,
3430                                      Loops, SE, DT);
3431
3432     if (LU.Kind == LSRUse::ICmpZero) {
3433       // An interesting way of "folding" with an icmp is to use a negated
3434       // scale, which we'll implement by inserting it into the other operand
3435       // of the icmp.
3436       assert(F.AM.Scale == -1 &&
3437              "The only scale supported by ICmpZero uses is -1!");
3438       ICmpScaledV = Rewriter.expandCodeFor(ScaledS, 0, IP);
3439     } else {
3440       // Otherwise just expand the scaled register and an explicit scale,
3441       // which is expected to be matched as part of the address.
3442       ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, 0, IP));
3443       ScaledS = SE.getMulExpr(ScaledS,
3444                               SE.getConstant(ScaledS->getType(), F.AM.Scale));
3445       Ops.push_back(ScaledS);
3446
3447       // Flush the operand list to suppress SCEVExpander hoisting.
3448       Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3449       Ops.clear();
3450       Ops.push_back(SE.getUnknown(FullV));
3451     }
3452   }
3453
3454   // Expand the GV portion.
3455   if (F.AM.BaseGV) {
3456     Ops.push_back(SE.getUnknown(F.AM.BaseGV));
3457
3458     // Flush the operand list to suppress SCEVExpander hoisting.
3459     Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
3460     Ops.clear();
3461     Ops.push_back(SE.getUnknown(FullV));
3462   }
3463
3464   // Expand the immediate portion.
3465   int64_t Offset = (uint64_t)F.AM.BaseOffs + LF.Offset;
3466   if (Offset != 0) {
3467     if (LU.Kind == LSRUse::ICmpZero) {
3468       // The other interesting way of "folding" with an ICmpZero is to use a
3469       // negated immediate.
3470       if (!ICmpScaledV)
3471         ICmpScaledV = ConstantInt::get(IntTy, -Offset);
3472       else {
3473         Ops.push_back(SE.getUnknown(ICmpScaledV));
3474         ICmpScaledV = ConstantInt::get(IntTy, Offset);
3475       }
3476     } else {
3477       // Just add the immediate values. These again are expected to be matched
3478       // as part of the address.
3479       Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset)));
3480     }
3481   }
3482
3483   // Emit instructions summing all the operands.
3484   const SCEV *FullS = Ops.empty() ?
3485                       SE.getConstant(IntTy, 0) :
3486                       SE.getAddExpr(Ops);
3487   Value *FullV = Rewriter.expandCodeFor(FullS, Ty, IP);
3488
3489   // We're done expanding now, so reset the rewriter.
3490   Rewriter.clearPostInc();
3491
3492   // An ICmpZero Formula represents an ICmp which we're handling as a
3493   // comparison against zero. Now that we've expanded an expression for that
3494   // form, update the ICmp's other operand.
3495   if (LU.Kind == LSRUse::ICmpZero) {
3496     ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
3497     DeadInsts.push_back(CI->getOperand(1));
3498     assert(!F.AM.BaseGV && "ICmp does not support folding a global value and "
3499                            "a scale at the same time!");
3500     if (F.AM.Scale == -1) {
3501       if (ICmpScaledV->getType() != OpTy) {
3502         Instruction *Cast =
3503           CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
3504                                                    OpTy, false),
3505                            ICmpScaledV, OpTy, "tmp", CI);
3506         ICmpScaledV = Cast;
3507       }
3508       CI->setOperand(1, ICmpScaledV);
3509     } else {
3510       assert(F.AM.Scale == 0 &&
3511              "ICmp does not support folding a global value and "
3512              "a scale at the same time!");
3513       Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),
3514                                            -(uint64_t)Offset);
3515       if (C->getType() != OpTy)
3516         C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3517                                                           OpTy, false),
3518                                   C, OpTy);
3519
3520       CI->setOperand(1, C);
3521     }
3522   }
3523
3524   return FullV;
3525 }
3526
3527 /// RewriteForPHI - Helper for Rewrite. PHI nodes are special because the use
3528 /// of their operands effectively happens in their predecessor blocks, so the
3529 /// expression may need to be expanded in multiple places.
3530 void LSRInstance::RewriteForPHI(PHINode *PN,
3531                                 const LSRFixup &LF,
3532                                 const Formula &F,
3533                                 SCEVExpander &Rewriter,
3534                                 SmallVectorImpl<WeakVH> &DeadInsts,
3535                                 Pass *P) const {
3536   DenseMap<BasicBlock *, Value *> Inserted;
3537   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
3538     if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
3539       BasicBlock *BB = PN->getIncomingBlock(i);
3540
3541       // If this is a critical edge, split the edge so that we do not insert
3542       // the code on all predecessor/successor paths.  We do this unless this
3543       // is the canonical backedge for this loop, which complicates post-inc
3544       // users.
3545       if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
3546           !isa<IndirectBrInst>(BB->getTerminator()) &&
3547           (PN->getParent() != L->getHeader() || !L->contains(BB))) {
3548         // Split the critical edge.
3549         BasicBlock *NewBB = SplitCriticalEdge(BB, PN->getParent(), P);
3550
3551         // If PN is outside of the loop and BB is in the loop, we want to
3552         // move the block to be immediately before the PHI block, not
3553         // immediately after BB.
3554         if (L->contains(BB) && !L->contains(PN))
3555           NewBB->moveBefore(PN->getParent());
3556
3557         // Splitting the edge can reduce the number of PHI entries we have.
3558         e = PN->getNumIncomingValues();
3559         BB = NewBB;
3560         i = PN->getBasicBlockIndex(BB);
3561       }
3562
3563       std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
3564         Inserted.insert(std::make_pair(BB, static_cast<Value *>(0)));
3565       if (!Pair.second)
3566         PN->setIncomingValue(i, Pair.first->second);
3567       else {
3568         Value *FullV = Expand(LF, F, BB->getTerminator(), Rewriter, DeadInsts);
3569
3570         // If this is reuse-by-noop-cast, insert the noop cast.
3571         const Type *OpTy = LF.OperandValToReplace->getType();
3572         if (FullV->getType() != OpTy)
3573           FullV =
3574             CastInst::Create(CastInst::getCastOpcode(FullV, false,
3575                                                      OpTy, false),
3576                              FullV, LF.OperandValToReplace->getType(),
3577                              "tmp", BB->getTerminator());
3578
3579         PN->setIncomingValue(i, FullV);
3580         Pair.first->second = FullV;
3581       }
3582     }
3583 }
3584
3585 /// Rewrite - Emit instructions for the leading candidate expression for this
3586 /// LSRUse (this is called "expanding"), and update the UserInst to reference
3587 /// the newly expanded value.
3588 void LSRInstance::Rewrite(const LSRFixup &LF,
3589                           const Formula &F,
3590                           SCEVExpander &Rewriter,
3591                           SmallVectorImpl<WeakVH> &DeadInsts,
3592                           Pass *P) const {
3593   // First, find an insertion point that dominates UserInst. For PHI nodes,
3594   // find the nearest block which dominates all the relevant uses.
3595   if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
3596     RewriteForPHI(PN, LF, F, Rewriter, DeadInsts, P);
3597   } else {
3598     Value *FullV = Expand(LF, F, LF.UserInst, Rewriter, DeadInsts);
3599
3600     // If this is reuse-by-noop-cast, insert the noop cast.
3601     const Type *OpTy = LF.OperandValToReplace->getType();
3602     if (FullV->getType() != OpTy) {
3603       Instruction *Cast =
3604         CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
3605                          FullV, OpTy, "tmp", LF.UserInst);
3606       FullV = Cast;
3607     }
3608
3609     // Update the user. ICmpZero is handled specially here (for now) because
3610     // Expand may have updated one of the operands of the icmp already, and
3611     // its new value may happen to be equal to LF.OperandValToReplace, in
3612     // which case doing replaceUsesOfWith leads to replacing both operands
3613     // with the same value. TODO: Reorganize this.
3614     if (Uses[LF.LUIdx].Kind == LSRUse::ICmpZero)
3615       LF.UserInst->setOperand(0, FullV);
3616     else
3617       LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
3618   }
3619
3620   DeadInsts.push_back(LF.OperandValToReplace);
3621 }
3622
3623 /// ImplementSolution - Rewrite all the fixup locations with new values,
3624 /// following the chosen solution.
3625 void
3626 LSRInstance::ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
3627                                Pass *P) {
3628   // Keep track of instructions we may have made dead, so that
3629   // we can remove them after we are done working.
3630   SmallVector<WeakVH, 16> DeadInsts;
3631
3632   SCEVExpander Rewriter(SE);
3633   Rewriter.disableCanonicalMode();
3634   Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
3635
3636   // Expand the new value definitions and update the users.
3637   for (SmallVectorImpl<LSRFixup>::const_iterator I = Fixups.begin(),
3638        E = Fixups.end(); I != E; ++I) {
3639     const LSRFixup &Fixup = *I;
3640
3641     Rewrite(Fixup, *Solution[Fixup.LUIdx], Rewriter, DeadInsts, P);
3642
3643     Changed = true;
3644   }
3645
3646   // Clean up after ourselves. This must be done before deleting any
3647   // instructions.
3648   Rewriter.clear();
3649
3650   Changed |= DeleteTriviallyDeadInstructions(DeadInsts);
3651 }
3652
3653 LSRInstance::LSRInstance(const TargetLowering *tli, Loop *l, Pass *P)
3654   : IU(P->getAnalysis<IVUsers>()),
3655     SE(P->getAnalysis<ScalarEvolution>()),
3656     DT(P->getAnalysis<DominatorTree>()),
3657     LI(P->getAnalysis<LoopInfo>()),
3658     TLI(tli), L(l), Changed(false), IVIncInsertPos(0) {
3659
3660   // If LoopSimplify form is not available, stay out of trouble.
3661   if (!L->isLoopSimplifyForm()) return;
3662
3663   // If there's no interesting work to be done, bail early.
3664   if (IU.empty()) return;
3665
3666   DEBUG(dbgs() << "\nLSR on loop ";
3667         WriteAsOperand(dbgs(), L->getHeader(), /*PrintType=*/false);
3668         dbgs() << ":\n");
3669
3670   // First, perform some low-level loop optimizations.
3671   OptimizeShadowIV();
3672   OptimizeLoopTermCond();
3673
3674   // Start collecting data and preparing for the solver.
3675   CollectInterestingTypesAndFactors();
3676   CollectFixupsAndInitialFormulae();
3677   CollectLoopInvariantFixupsAndFormulae();
3678
3679   DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
3680         print_uses(dbgs()));
3681
3682   // Now use the reuse data to generate a bunch of interesting ways
3683   // to formulate the values needed for the uses.
3684   GenerateAllReuseFormulae();
3685
3686   FilterOutUndesirableDedicatedRegisters();
3687   NarrowSearchSpaceUsingHeuristics();
3688
3689   SmallVector<const Formula *, 8> Solution;
3690   Solve(Solution);
3691
3692   // Release memory that is no longer needed.
3693   Factors.clear();
3694   Types.clear();
3695   RegUses.clear();
3696
3697 #ifndef NDEBUG
3698   // Formulae should be legal.
3699   for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3700        E = Uses.end(); I != E; ++I) {
3701      const LSRUse &LU = *I;
3702      for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3703           JE = LU.Formulae.end(); J != JE; ++J)
3704         assert(isLegalUse(J->AM, LU.MinOffset, LU.MaxOffset,
3705                           LU.Kind, LU.AccessTy, TLI) &&
3706                "Illegal formula generated!");
3707   };
3708 #endif
3709
3710   // Now that we've decided what we want, make it so.
3711   ImplementSolution(Solution, P);
3712 }
3713
3714 void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
3715   if (Factors.empty() && Types.empty()) return;
3716
3717   OS << "LSR has identified the following interesting factors and types: ";
3718   bool First = true;
3719
3720   for (SmallSetVector<int64_t, 8>::const_iterator
3721        I = Factors.begin(), E = Factors.end(); I != E; ++I) {
3722     if (!First) OS << ", ";
3723     First = false;
3724     OS << '*' << *I;
3725   }
3726
3727   for (SmallSetVector<const Type *, 4>::const_iterator
3728        I = Types.begin(), E = Types.end(); I != E; ++I) {
3729     if (!First) OS << ", ";
3730     First = false;
3731     OS << '(' << **I << ')';
3732   }
3733   OS << '\n';
3734 }
3735
3736 void LSRInstance::print_fixups(raw_ostream &OS) const {
3737   OS << "LSR is examining the following fixup sites:\n";
3738   for (SmallVectorImpl<LSRFixup>::const_iterator I = Fixups.begin(),
3739        E = Fixups.end(); I != E; ++I) {
3740     dbgs() << "  ";
3741     I->print(OS);
3742     OS << '\n';
3743   }
3744 }
3745
3746 void LSRInstance::print_uses(raw_ostream &OS) const {
3747   OS << "LSR is examining the following uses:\n";
3748   for (SmallVectorImpl<LSRUse>::const_iterator I = Uses.begin(),
3749        E = Uses.end(); I != E; ++I) {
3750     const LSRUse &LU = *I;
3751     dbgs() << "  ";
3752     LU.print(OS);
3753     OS << '\n';
3754     for (SmallVectorImpl<Formula>::const_iterator J = LU.Formulae.begin(),
3755          JE = LU.Formulae.end(); J != JE; ++J) {
3756       OS << "    ";
3757       J->print(OS);
3758       OS << '\n';
3759     }
3760   }
3761 }
3762
3763 void LSRInstance::print(raw_ostream &OS) const {
3764   print_factors_and_types(OS);
3765   print_fixups(OS);
3766   print_uses(OS);
3767 }
3768
3769 void LSRInstance::dump() const {
3770   print(errs()); errs() << '\n';
3771 }
3772
3773 namespace {
3774
3775 class LoopStrengthReduce : public LoopPass {
3776   /// TLI - Keep a pointer of a TargetLowering to consult for determining
3777   /// transformation profitability.
3778   const TargetLowering *const TLI;
3779
3780 public:
3781   static char ID; // Pass ID, replacement for typeid
3782   explicit LoopStrengthReduce(const TargetLowering *tli = 0);
3783
3784 private:
3785   bool runOnLoop(Loop *L, LPPassManager &LPM);
3786   void getAnalysisUsage(AnalysisUsage &AU) const;
3787 };
3788
3789 }
3790
3791 char LoopStrengthReduce::ID = 0;
3792 INITIALIZE_PASS_BEGIN(LoopStrengthReduce, "loop-reduce",
3793                 "Loop Strength Reduction", false, false)
3794 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3795 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3796 INITIALIZE_PASS_DEPENDENCY(IVUsers)
3797 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
3798 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3799 INITIALIZE_PASS_END(LoopStrengthReduce, "loop-reduce",
3800                 "Loop Strength Reduction", false, false)
3801
3802
3803 Pass *llvm::createLoopStrengthReducePass(const TargetLowering *TLI) {
3804   return new LoopStrengthReduce(TLI);
3805 }
3806
3807 LoopStrengthReduce::LoopStrengthReduce(const TargetLowering *tli)
3808   : LoopPass(ID), TLI(tli) {
3809     initializeLoopStrengthReducePass(*PassRegistry::getPassRegistry());
3810   }
3811
3812 void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
3813   // We split critical edges, so we change the CFG.  However, we do update
3814   // many analyses if they are around.
3815   AU.addPreservedID(LoopSimplifyID);
3816   AU.addPreserved("domfrontier");
3817
3818   AU.addRequired<LoopInfo>();
3819   AU.addPreserved<LoopInfo>();
3820   AU.addRequiredID(LoopSimplifyID);
3821   AU.addRequired<DominatorTree>();
3822   AU.addPreserved<DominatorTree>();
3823   AU.addRequired<ScalarEvolution>();
3824   AU.addPreserved<ScalarEvolution>();
3825   AU.addRequired<IVUsers>();
3826   AU.addPreserved<IVUsers>();
3827 }
3828
3829 bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
3830   bool Changed = false;
3831
3832   // Run the main LSR transformation.
3833   Changed |= LSRInstance(TLI, L, this).getChanged();
3834
3835   // At this point, it is worth checking to see if any recurrence PHIs are also
3836   // dead, so that we can remove them as well.
3837   Changed |= DeleteDeadPHIs(L->getHeader());
3838
3839   return Changed;
3840 }