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