Added a new Spiller implementation which wraps LiveIntervals::addIntervalsForSpills.
[oota-llvm.git] / lib / CodeGen / RegAllocLinearScan.cpp
1 //===-- RegAllocLinearScan.cpp - Linear Scan register allocator -----------===//
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 file implements a linear scan register allocator.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "regalloc"
15 #include "VirtRegMap.h"
16 #include "VirtRegRewriter.h"
17 #include "Spiller.h"
18 #include "llvm/Function.h"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/CodeGen/LiveStackAnalysis.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/RegAllocRegistry.h"
27 #include "llvm/CodeGen/RegisterCoalescer.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/ADT/EquivalenceClasses.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include <algorithm>
40 #include <set>
41 #include <queue>
42 #include <memory>
43 #include <cmath>
44
45 using namespace llvm;
46
47 STATISTIC(NumIters     , "Number of iterations performed");
48 STATISTIC(NumBacktracks, "Number of times we had to backtrack");
49 STATISTIC(NumCoalesce,   "Number of copies coalesced");
50 STATISTIC(NumDowngrade,  "Number of registers downgraded");
51
52 static cl::opt<bool>
53 NewHeuristic("new-spilling-heuristic",
54              cl::desc("Use new spilling heuristic"),
55              cl::init(false), cl::Hidden);
56
57 static cl::opt<bool>
58 PreSplitIntervals("pre-alloc-split",
59                   cl::desc("Pre-register allocation live interval splitting"),
60                   cl::init(false), cl::Hidden);
61
62 static RegisterRegAlloc
63 linearscanRegAlloc("linearscan", "linear scan register allocator",
64                    createLinearScanRegisterAllocator);
65
66 namespace {
67   struct RALinScan : public MachineFunctionPass {
68     static char ID;
69     RALinScan() : MachineFunctionPass(&ID) {}
70
71     typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
72     typedef SmallVector<IntervalPtr, 32> IntervalPtrs;
73   private:
74     /// RelatedRegClasses - This structure is built the first time a function is
75     /// compiled, and keeps track of which register classes have registers that
76     /// belong to multiple classes or have aliases that are in other classes.
77     EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
78     DenseMap<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
79
80     // NextReloadMap - For each register in the map, it maps to the another
81     // register which is defined by a reload from the same stack slot and
82     // both reloads are in the same basic block.
83     DenseMap<unsigned, unsigned> NextReloadMap;
84
85     // DowngradedRegs - A set of registers which are being "downgraded", i.e.
86     // un-favored for allocation.
87     SmallSet<unsigned, 8> DowngradedRegs;
88
89     // DowngradeMap - A map from virtual registers to physical registers being
90     // downgraded for the virtual registers.
91     DenseMap<unsigned, unsigned> DowngradeMap;
92
93     MachineFunction* mf_;
94     MachineRegisterInfo* mri_;
95     const TargetMachine* tm_;
96     const TargetRegisterInfo* tri_;
97     const TargetInstrInfo* tii_;
98     BitVector allocatableRegs_;
99     LiveIntervals* li_;
100     LiveStacks* ls_;
101     const MachineLoopInfo *loopInfo;
102
103     /// handled_ - Intervals are added to the handled_ set in the order of their
104     /// start value.  This is uses for backtracking.
105     std::vector<LiveInterval*> handled_;
106
107     /// fixed_ - Intervals that correspond to machine registers.
108     ///
109     IntervalPtrs fixed_;
110
111     /// active_ - Intervals that are currently being processed, and which have a
112     /// live range active for the current point.
113     IntervalPtrs active_;
114
115     /// inactive_ - Intervals that are currently being processed, but which have
116     /// a hold at the current point.
117     IntervalPtrs inactive_;
118
119     typedef std::priority_queue<LiveInterval*,
120                                 SmallVector<LiveInterval*, 64>,
121                                 greater_ptr<LiveInterval> > IntervalHeap;
122     IntervalHeap unhandled_;
123
124     /// regUse_ - Tracks register usage.
125     SmallVector<unsigned, 32> regUse_;
126     SmallVector<unsigned, 32> regUseBackUp_;
127
128     /// vrm_ - Tracks register assignments.
129     VirtRegMap* vrm_;
130
131     std::auto_ptr<VirtRegRewriter> rewriter_;
132
133     std::auto_ptr<Spiller> spiller_;
134
135   public:
136     virtual const char* getPassName() const {
137       return "Linear Scan Register Allocator";
138     }
139
140     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
141       AU.setPreservesCFG();
142       AU.addRequired<LiveIntervals>();
143       AU.addPreserved<SlotIndexes>();
144       if (StrongPHIElim)
145         AU.addRequiredID(StrongPHIEliminationID);
146       // Make sure PassManager knows which analyses to make available
147       // to coalescing and which analyses coalescing invalidates.
148       AU.addRequiredTransitive<RegisterCoalescer>();
149       if (PreSplitIntervals)
150         AU.addRequiredID(PreAllocSplittingID);
151       AU.addRequired<LiveStacks>();
152       AU.addPreserved<LiveStacks>();
153       AU.addRequired<MachineLoopInfo>();
154       AU.addPreserved<MachineLoopInfo>();
155       AU.addRequired<VirtRegMap>();
156       AU.addPreserved<VirtRegMap>();
157       AU.addPreservedID(MachineDominatorsID);
158       MachineFunctionPass::getAnalysisUsage(AU);
159     }
160
161     /// runOnMachineFunction - register allocate the whole function
162     bool runOnMachineFunction(MachineFunction&);
163
164   private:
165     /// linearScan - the linear scan algorithm
166     void linearScan();
167
168     /// initIntervalSets - initialize the interval sets.
169     ///
170     void initIntervalSets();
171
172     /// processActiveIntervals - expire old intervals and move non-overlapping
173     /// ones to the inactive list.
174     void processActiveIntervals(SlotIndex CurPoint);
175
176     /// processInactiveIntervals - expire old intervals and move overlapping
177     /// ones to the active list.
178     void processInactiveIntervals(SlotIndex CurPoint);
179
180     /// hasNextReloadInterval - Return the next liveinterval that's being
181     /// defined by a reload from the same SS as the specified one.
182     LiveInterval *hasNextReloadInterval(LiveInterval *cur);
183
184     /// DowngradeRegister - Downgrade a register for allocation.
185     void DowngradeRegister(LiveInterval *li, unsigned Reg);
186
187     /// UpgradeRegister - Upgrade a register for allocation.
188     void UpgradeRegister(unsigned Reg);
189
190     /// assignRegOrStackSlotAtInterval - assign a register if one
191     /// is available, or spill.
192     void assignRegOrStackSlotAtInterval(LiveInterval* cur);
193
194     void updateSpillWeights(std::vector<float> &Weights,
195                             unsigned reg, float weight,
196                             const TargetRegisterClass *RC);
197
198     /// findIntervalsToSpill - Determine the intervals to spill for the
199     /// specified interval. It's passed the physical registers whose spill
200     /// weight is the lowest among all the registers whose live intervals
201     /// conflict with the interval.
202     void findIntervalsToSpill(LiveInterval *cur,
203                             std::vector<std::pair<unsigned,float> > &Candidates,
204                             unsigned NumCands,
205                             SmallVector<LiveInterval*, 8> &SpillIntervals);
206
207     /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
208     /// try allocate the definition the same register as the source register
209     /// if the register is not defined during live time of the interval. This
210     /// eliminate a copy. This is used to coalesce copies which were not
211     /// coalesced away before allocation either due to dest and src being in
212     /// different register classes or because the coalescer was overly
213     /// conservative.
214     unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
215
216     ///
217     /// Register usage / availability tracking helpers.
218     ///
219
220     void initRegUses() {
221       regUse_.resize(tri_->getNumRegs(), 0);
222       regUseBackUp_.resize(tri_->getNumRegs(), 0);
223     }
224
225     void finalizeRegUses() {
226 #ifndef NDEBUG
227       // Verify all the registers are "freed".
228       bool Error = false;
229       for (unsigned i = 0, e = tri_->getNumRegs(); i != e; ++i) {
230         if (regUse_[i] != 0) {
231           errs() << tri_->getName(i) << " is still in use!\n";
232           Error = true;
233         }
234       }
235       if (Error)
236         llvm_unreachable(0);
237 #endif
238       regUse_.clear();
239       regUseBackUp_.clear();
240     }
241
242     void addRegUse(unsigned physReg) {
243       assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
244              "should be physical register!");
245       ++regUse_[physReg];
246       for (const unsigned* as = tri_->getAliasSet(physReg); *as; ++as)
247         ++regUse_[*as];
248     }
249
250     void delRegUse(unsigned physReg) {
251       assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
252              "should be physical register!");
253       assert(regUse_[physReg] != 0);
254       --regUse_[physReg];
255       for (const unsigned* as = tri_->getAliasSet(physReg); *as; ++as) {
256         assert(regUse_[*as] != 0);
257         --regUse_[*as];
258       }
259     }
260
261     bool isRegAvail(unsigned physReg) const {
262       assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
263              "should be physical register!");
264       return regUse_[physReg] == 0;
265     }
266
267     void backUpRegUses() {
268       regUseBackUp_ = regUse_;
269     }
270
271     void restoreRegUses() {
272       regUse_ = regUseBackUp_;
273     }
274
275     ///
276     /// Register handling helpers.
277     ///
278
279     /// getFreePhysReg - return a free physical register for this virtual
280     /// register interval if we have one, otherwise return 0.
281     unsigned getFreePhysReg(LiveInterval* cur);
282     unsigned getFreePhysReg(LiveInterval* cur,
283                             const TargetRegisterClass *RC,
284                             unsigned MaxInactiveCount,
285                             SmallVector<unsigned, 256> &inactiveCounts,
286                             bool SkipDGRegs);
287
288     /// assignVirt2StackSlot - assigns this virtual register to a
289     /// stack slot. returns the stack slot
290     int assignVirt2StackSlot(unsigned virtReg);
291
292     void ComputeRelatedRegClasses();
293
294     template <typename ItTy>
295     void printIntervals(const char* const str, ItTy i, ItTy e) const {
296       DEBUG({
297           if (str)
298             errs() << str << " intervals:\n";
299
300           for (; i != e; ++i) {
301             errs() << "\t" << *i->first << " -> ";
302
303             unsigned reg = i->first->reg;
304             if (TargetRegisterInfo::isVirtualRegister(reg))
305               reg = vrm_->getPhys(reg);
306
307             errs() << tri_->getName(reg) << '\n';
308           }
309         });
310     }
311   };
312   char RALinScan::ID = 0;
313 }
314
315 static RegisterPass<RALinScan>
316 X("linearscan-regalloc", "Linear Scan Register Allocator");
317
318 void RALinScan::ComputeRelatedRegClasses() {
319   // First pass, add all reg classes to the union, and determine at least one
320   // reg class that each register is in.
321   bool HasAliases = false;
322   for (TargetRegisterInfo::regclass_iterator RCI = tri_->regclass_begin(),
323        E = tri_->regclass_end(); RCI != E; ++RCI) {
324     RelatedRegClasses.insert(*RCI);
325     for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
326          I != E; ++I) {
327       HasAliases = HasAliases || *tri_->getAliasSet(*I) != 0;
328       
329       const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
330       if (PRC) {
331         // Already processed this register.  Just make sure we know that
332         // multiple register classes share a register.
333         RelatedRegClasses.unionSets(PRC, *RCI);
334       } else {
335         PRC = *RCI;
336       }
337     }
338   }
339   
340   // Second pass, now that we know conservatively what register classes each reg
341   // belongs to, add info about aliases.  We don't need to do this for targets
342   // without register aliases.
343   if (HasAliases)
344     for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
345          I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
346          I != E; ++I)
347       for (const unsigned *AS = tri_->getAliasSet(I->first); *AS; ++AS)
348         RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
349 }
350
351 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
352 /// try allocate the definition the same register as the source register
353 /// if the register is not defined during live time of the interval. This
354 /// eliminate a copy. This is used to coalesce copies which were not
355 /// coalesced away before allocation either due to dest and src being in
356 /// different register classes or because the coalescer was overly
357 /// conservative.
358 unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
359   unsigned Preference = vrm_->getRegAllocPref(cur.reg);
360   if ((Preference && Preference == Reg) || !cur.containsOneValue())
361     return Reg;
362
363   VNInfo *vni = cur.begin()->valno;
364   if ((vni->def == SlotIndex()) ||
365       vni->isUnused() || !vni->isDefAccurate())
366     return Reg;
367   MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
368   unsigned SrcReg, DstReg, SrcSubReg, DstSubReg, PhysReg;
369   if (!CopyMI ||
370       !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg))
371     return Reg;
372   PhysReg = SrcReg;
373   if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
374     if (!vrm_->isAssignedReg(SrcReg))
375       return Reg;
376     PhysReg = vrm_->getPhys(SrcReg);
377   }
378   if (Reg == PhysReg)
379     return Reg;
380
381   const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
382   if (!RC->contains(PhysReg))
383     return Reg;
384
385   // Try to coalesce.
386   if (!li_->conflictsWithPhysRegDef(cur, *vrm_, PhysReg)) {
387     DEBUG(errs() << "Coalescing: " << cur << " -> " << tri_->getName(PhysReg)
388                  << '\n');
389     vrm_->clearVirt(cur.reg);
390     vrm_->assignVirt2Phys(cur.reg, PhysReg);
391
392     // Remove unnecessary kills since a copy does not clobber the register.
393     if (li_->hasInterval(SrcReg)) {
394       LiveInterval &SrcLI = li_->getInterval(SrcReg);
395       for (MachineRegisterInfo::use_iterator I = mri_->use_begin(cur.reg),
396              E = mri_->use_end(); I != E; ++I) {
397         MachineOperand &O = I.getOperand();
398         if (!O.isKill())
399           continue;
400         MachineInstr *MI = &*I;
401         if (SrcLI.liveAt(li_->getInstructionIndex(MI).getDefIndex()))
402           O.setIsKill(false);
403       }
404     }
405
406     ++NumCoalesce;
407     return PhysReg;
408   }
409
410   return Reg;
411 }
412
413 bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
414   mf_ = &fn;
415   mri_ = &fn.getRegInfo();
416   tm_ = &fn.getTarget();
417   tri_ = tm_->getRegisterInfo();
418   tii_ = tm_->getInstrInfo();
419   allocatableRegs_ = tri_->getAllocatableSet(fn);
420   li_ = &getAnalysis<LiveIntervals>();
421   ls_ = &getAnalysis<LiveStacks>();
422   loopInfo = &getAnalysis<MachineLoopInfo>();
423
424   // We don't run the coalescer here because we have no reason to
425   // interact with it.  If the coalescer requires interaction, it
426   // won't do anything.  If it doesn't require interaction, we assume
427   // it was run as a separate pass.
428
429   // If this is the first function compiled, compute the related reg classes.
430   if (RelatedRegClasses.empty())
431     ComputeRelatedRegClasses();
432
433   // Also resize register usage trackers.
434   initRegUses();
435
436   vrm_ = &getAnalysis<VirtRegMap>();
437   if (!rewriter_.get()) rewriter_.reset(createVirtRegRewriter());
438   
439   spiller_.reset(createSpiller(mf_, li_, ls_, loopInfo, vrm_));
440   
441   initIntervalSets();
442
443   linearScan();
444
445   // Rewrite spill code and update the PhysRegsUsed set.
446   rewriter_->runOnMachineFunction(*mf_, *vrm_, li_);
447
448   assert(unhandled_.empty() && "Unhandled live intervals remain!");
449
450   finalizeRegUses();
451
452   fixed_.clear();
453   active_.clear();
454   inactive_.clear();
455   handled_.clear();
456   NextReloadMap.clear();
457   DowngradedRegs.clear();
458   DowngradeMap.clear();
459   spiller_.reset(0);
460
461   return true;
462 }
463
464 /// initIntervalSets - initialize the interval sets.
465 ///
466 void RALinScan::initIntervalSets()
467 {
468   assert(unhandled_.empty() && fixed_.empty() &&
469          active_.empty() && inactive_.empty() &&
470          "interval sets should be empty on initialization");
471
472   handled_.reserve(li_->getNumIntervals());
473
474   for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
475     if (TargetRegisterInfo::isPhysicalRegister(i->second->reg)) {
476       if (!i->second->empty()) {
477         mri_->setPhysRegUsed(i->second->reg);
478         fixed_.push_back(std::make_pair(i->second, i->second->begin()));
479       }
480     } else {
481       if (i->second->empty()) {
482         assignRegOrStackSlotAtInterval(i->second);
483       }
484       else
485         unhandled_.push(i->second);
486     }
487   }
488 }
489
490 void RALinScan::linearScan() {
491   // linear scan algorithm
492   DEBUG({
493       errs() << "********** LINEAR SCAN **********\n"
494              << "********** Function: " 
495              << mf_->getFunction()->getName() << '\n';
496       printIntervals("fixed", fixed_.begin(), fixed_.end());
497     });
498
499   while (!unhandled_.empty()) {
500     // pick the interval with the earliest start point
501     LiveInterval* cur = unhandled_.top();
502     unhandled_.pop();
503     ++NumIters;
504     DEBUG(errs() << "\n*** CURRENT ***: " << *cur << '\n');
505
506     assert(!cur->empty() && "Empty interval in unhandled set.");
507
508     processActiveIntervals(cur->beginIndex());
509     processInactiveIntervals(cur->beginIndex());
510
511     assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
512            "Can only allocate virtual registers!");
513
514     // Allocating a virtual register. try to find a free
515     // physical register or spill an interval (possibly this one) in order to
516     // assign it one.
517     assignRegOrStackSlotAtInterval(cur);
518
519     DEBUG({
520         printIntervals("active", active_.begin(), active_.end());
521         printIntervals("inactive", inactive_.begin(), inactive_.end());
522       });
523   }
524
525   // Expire any remaining active intervals
526   while (!active_.empty()) {
527     IntervalPtr &IP = active_.back();
528     unsigned reg = IP.first->reg;
529     DEBUG(errs() << "\tinterval " << *IP.first << " expired\n");
530     assert(TargetRegisterInfo::isVirtualRegister(reg) &&
531            "Can only allocate virtual registers!");
532     reg = vrm_->getPhys(reg);
533     delRegUse(reg);
534     active_.pop_back();
535   }
536
537   // Expire any remaining inactive intervals
538   DEBUG({
539       for (IntervalPtrs::reverse_iterator
540              i = inactive_.rbegin(); i != inactive_.rend(); ++i)
541         errs() << "\tinterval " << *i->first << " expired\n";
542     });
543   inactive_.clear();
544
545   // Add live-ins to every BB except for entry. Also perform trivial coalescing.
546   MachineFunction::iterator EntryMBB = mf_->begin();
547   SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
548   for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
549     LiveInterval &cur = *i->second;
550     unsigned Reg = 0;
551     bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
552     if (isPhys)
553       Reg = cur.reg;
554     else if (vrm_->isAssignedReg(cur.reg))
555       Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
556     if (!Reg)
557       continue;
558     // Ignore splited live intervals.
559     if (!isPhys && vrm_->getPreSplitReg(cur.reg))
560       continue;
561
562     for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
563          I != E; ++I) {
564       const LiveRange &LR = *I;
565       if (li_->findLiveInMBBs(LR.start, LR.end, LiveInMBBs)) {
566         for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
567           if (LiveInMBBs[i] != EntryMBB) {
568             assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
569                    "Adding a virtual register to livein set?");
570             LiveInMBBs[i]->addLiveIn(Reg);
571           }
572         LiveInMBBs.clear();
573       }
574     }
575   }
576
577   DEBUG(errs() << *vrm_);
578
579   // Look for physical registers that end up not being allocated even though
580   // register allocator had to spill other registers in its register class.
581   if (ls_->getNumIntervals() == 0)
582     return;
583   if (!vrm_->FindUnusedRegisters(li_))
584     return;
585 }
586
587 /// processActiveIntervals - expire old intervals and move non-overlapping ones
588 /// to the inactive list.
589 void RALinScan::processActiveIntervals(SlotIndex CurPoint)
590 {
591   DEBUG(errs() << "\tprocessing active intervals:\n");
592
593   for (unsigned i = 0, e = active_.size(); i != e; ++i) {
594     LiveInterval *Interval = active_[i].first;
595     LiveInterval::iterator IntervalPos = active_[i].second;
596     unsigned reg = Interval->reg;
597
598     IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
599
600     if (IntervalPos == Interval->end()) {     // Remove expired intervals.
601       DEBUG(errs() << "\t\tinterval " << *Interval << " expired\n");
602       assert(TargetRegisterInfo::isVirtualRegister(reg) &&
603              "Can only allocate virtual registers!");
604       reg = vrm_->getPhys(reg);
605       delRegUse(reg);
606
607       // Pop off the end of the list.
608       active_[i] = active_.back();
609       active_.pop_back();
610       --i; --e;
611
612     } else if (IntervalPos->start > CurPoint) {
613       // Move inactive intervals to inactive list.
614       DEBUG(errs() << "\t\tinterval " << *Interval << " inactive\n");
615       assert(TargetRegisterInfo::isVirtualRegister(reg) &&
616              "Can only allocate virtual registers!");
617       reg = vrm_->getPhys(reg);
618       delRegUse(reg);
619       // add to inactive.
620       inactive_.push_back(std::make_pair(Interval, IntervalPos));
621
622       // Pop off the end of the list.
623       active_[i] = active_.back();
624       active_.pop_back();
625       --i; --e;
626     } else {
627       // Otherwise, just update the iterator position.
628       active_[i].second = IntervalPos;
629     }
630   }
631 }
632
633 /// processInactiveIntervals - expire old intervals and move overlapping
634 /// ones to the active list.
635 void RALinScan::processInactiveIntervals(SlotIndex CurPoint)
636 {
637   DEBUG(errs() << "\tprocessing inactive intervals:\n");
638
639   for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
640     LiveInterval *Interval = inactive_[i].first;
641     LiveInterval::iterator IntervalPos = inactive_[i].second;
642     unsigned reg = Interval->reg;
643
644     IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
645
646     if (IntervalPos == Interval->end()) {       // remove expired intervals.
647       DEBUG(errs() << "\t\tinterval " << *Interval << " expired\n");
648
649       // Pop off the end of the list.
650       inactive_[i] = inactive_.back();
651       inactive_.pop_back();
652       --i; --e;
653     } else if (IntervalPos->start <= CurPoint) {
654       // move re-activated intervals in active list
655       DEBUG(errs() << "\t\tinterval " << *Interval << " active\n");
656       assert(TargetRegisterInfo::isVirtualRegister(reg) &&
657              "Can only allocate virtual registers!");
658       reg = vrm_->getPhys(reg);
659       addRegUse(reg);
660       // add to active
661       active_.push_back(std::make_pair(Interval, IntervalPos));
662
663       // Pop off the end of the list.
664       inactive_[i] = inactive_.back();
665       inactive_.pop_back();
666       --i; --e;
667     } else {
668       // Otherwise, just update the iterator position.
669       inactive_[i].second = IntervalPos;
670     }
671   }
672 }
673
674 /// updateSpillWeights - updates the spill weights of the specifed physical
675 /// register and its weight.
676 void RALinScan::updateSpillWeights(std::vector<float> &Weights,
677                                    unsigned reg, float weight,
678                                    const TargetRegisterClass *RC) {
679   SmallSet<unsigned, 4> Processed;
680   SmallSet<unsigned, 4> SuperAdded;
681   SmallVector<unsigned, 4> Supers;
682   Weights[reg] += weight;
683   Processed.insert(reg);
684   for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as) {
685     Weights[*as] += weight;
686     Processed.insert(*as);
687     if (tri_->isSubRegister(*as, reg) &&
688         SuperAdded.insert(*as) &&
689         RC->contains(*as)) {
690       Supers.push_back(*as);
691     }
692   }
693
694   // If the alias is a super-register, and the super-register is in the
695   // register class we are trying to allocate. Then add the weight to all
696   // sub-registers of the super-register even if they are not aliases.
697   // e.g. allocating for GR32, bh is not used, updating bl spill weight.
698   //      bl should get the same spill weight otherwise it will be choosen
699   //      as a spill candidate since spilling bh doesn't make ebx available.
700   for (unsigned i = 0, e = Supers.size(); i != e; ++i) {
701     for (const unsigned *sr = tri_->getSubRegisters(Supers[i]); *sr; ++sr)
702       if (!Processed.count(*sr))
703         Weights[*sr] += weight;
704   }
705 }
706
707 static
708 RALinScan::IntervalPtrs::iterator
709 FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
710   for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
711        I != E; ++I)
712     if (I->first == LI) return I;
713   return IP.end();
714 }
715
716 static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, SlotIndex Point){
717   for (unsigned i = 0, e = V.size(); i != e; ++i) {
718     RALinScan::IntervalPtr &IP = V[i];
719     LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
720                                                 IP.second, Point);
721     if (I != IP.first->begin()) --I;
722     IP.second = I;
723   }
724 }
725
726 /// addStackInterval - Create a LiveInterval for stack if the specified live
727 /// interval has been spilled.
728 static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
729                              LiveIntervals *li_,
730                              MachineRegisterInfo* mri_, VirtRegMap &vrm_) {
731   int SS = vrm_.getStackSlot(cur->reg);
732   if (SS == VirtRegMap::NO_STACK_SLOT)
733     return;
734
735   const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
736   LiveInterval &SI = ls_->getOrCreateInterval(SS, RC);
737
738   VNInfo *VNI;
739   if (SI.hasAtLeastOneValue())
740     VNI = SI.getValNumInfo(0);
741   else
742     VNI = SI.getNextValue(SlotIndex(), 0, false,
743                           ls_->getVNInfoAllocator());
744
745   LiveInterval &RI = li_->getInterval(cur->reg);
746   // FIXME: This may be overly conservative.
747   SI.MergeRangesInAsValue(RI, VNI);
748 }
749
750 /// getConflictWeight - Return the number of conflicts between cur
751 /// live interval and defs and uses of Reg weighted by loop depthes.
752 static
753 float getConflictWeight(LiveInterval *cur, unsigned Reg, LiveIntervals *li_,
754                         MachineRegisterInfo *mri_,
755                         const MachineLoopInfo *loopInfo) {
756   float Conflicts = 0;
757   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
758          E = mri_->reg_end(); I != E; ++I) {
759     MachineInstr *MI = &*I;
760     if (cur->liveAt(li_->getInstructionIndex(MI))) {
761       unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
762       Conflicts += powf(10.0f, (float)loopDepth);
763     }
764   }
765   return Conflicts;
766 }
767
768 /// findIntervalsToSpill - Determine the intervals to spill for the
769 /// specified interval. It's passed the physical registers whose spill
770 /// weight is the lowest among all the registers whose live intervals
771 /// conflict with the interval.
772 void RALinScan::findIntervalsToSpill(LiveInterval *cur,
773                             std::vector<std::pair<unsigned,float> > &Candidates,
774                             unsigned NumCands,
775                             SmallVector<LiveInterval*, 8> &SpillIntervals) {
776   // We have figured out the *best* register to spill. But there are other
777   // registers that are pretty good as well (spill weight within 3%). Spill
778   // the one that has fewest defs and uses that conflict with cur.
779   float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
780   SmallVector<LiveInterval*, 8> SLIs[3];
781
782   DEBUG({
783       errs() << "\tConsidering " << NumCands << " candidates: ";
784       for (unsigned i = 0; i != NumCands; ++i)
785         errs() << tri_->getName(Candidates[i].first) << " ";
786       errs() << "\n";
787     });
788   
789   // Calculate the number of conflicts of each candidate.
790   for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
791     unsigned Reg = i->first->reg;
792     unsigned PhysReg = vrm_->getPhys(Reg);
793     if (!cur->overlapsFrom(*i->first, i->second))
794       continue;
795     for (unsigned j = 0; j < NumCands; ++j) {
796       unsigned Candidate = Candidates[j].first;
797       if (tri_->regsOverlap(PhysReg, Candidate)) {
798         if (NumCands > 1)
799           Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
800         SLIs[j].push_back(i->first);
801       }
802     }
803   }
804
805   for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
806     unsigned Reg = i->first->reg;
807     unsigned PhysReg = vrm_->getPhys(Reg);
808     if (!cur->overlapsFrom(*i->first, i->second-1))
809       continue;
810     for (unsigned j = 0; j < NumCands; ++j) {
811       unsigned Candidate = Candidates[j].first;
812       if (tri_->regsOverlap(PhysReg, Candidate)) {
813         if (NumCands > 1)
814           Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
815         SLIs[j].push_back(i->first);
816       }
817     }
818   }
819
820   // Which is the best candidate?
821   unsigned BestCandidate = 0;
822   float MinConflicts = Conflicts[0];
823   for (unsigned i = 1; i != NumCands; ++i) {
824     if (Conflicts[i] < MinConflicts) {
825       BestCandidate = i;
826       MinConflicts = Conflicts[i];
827     }
828   }
829
830   std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
831             std::back_inserter(SpillIntervals));
832 }
833
834 namespace {
835   struct WeightCompare {
836     typedef std::pair<unsigned, float> RegWeightPair;
837     bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
838       return LHS.second < RHS.second;
839     }
840   };
841 }
842
843 static bool weightsAreClose(float w1, float w2) {
844   if (!NewHeuristic)
845     return false;
846
847   float diff = w1 - w2;
848   if (diff <= 0.02f)  // Within 0.02f
849     return true;
850   return (diff / w2) <= 0.05f;  // Within 5%.
851 }
852
853 LiveInterval *RALinScan::hasNextReloadInterval(LiveInterval *cur) {
854   DenseMap<unsigned, unsigned>::iterator I = NextReloadMap.find(cur->reg);
855   if (I == NextReloadMap.end())
856     return 0;
857   return &li_->getInterval(I->second);
858 }
859
860 void RALinScan::DowngradeRegister(LiveInterval *li, unsigned Reg) {
861   bool isNew = DowngradedRegs.insert(Reg);
862   isNew = isNew; // Silence compiler warning.
863   assert(isNew && "Multiple reloads holding the same register?");
864   DowngradeMap.insert(std::make_pair(li->reg, Reg));
865   for (const unsigned *AS = tri_->getAliasSet(Reg); *AS; ++AS) {
866     isNew = DowngradedRegs.insert(*AS);
867     isNew = isNew; // Silence compiler warning.
868     assert(isNew && "Multiple reloads holding the same register?");
869     DowngradeMap.insert(std::make_pair(li->reg, *AS));
870   }
871   ++NumDowngrade;
872 }
873
874 void RALinScan::UpgradeRegister(unsigned Reg) {
875   if (Reg) {
876     DowngradedRegs.erase(Reg);
877     for (const unsigned *AS = tri_->getAliasSet(Reg); *AS; ++AS)
878       DowngradedRegs.erase(*AS);
879   }
880 }
881
882 namespace {
883   struct LISorter {
884     bool operator()(LiveInterval* A, LiveInterval* B) {
885       return A->beginIndex() < B->beginIndex();
886     }
887   };
888 }
889
890 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
891 /// spill.
892 void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur) {
893   DEBUG(errs() << "\tallocating current interval: ");
894
895   // This is an implicitly defined live interval, just assign any register.
896   const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
897   if (cur->empty()) {
898     unsigned physReg = vrm_->getRegAllocPref(cur->reg);
899     if (!physReg)
900       physReg = *RC->allocation_order_begin(*mf_);
901     DEBUG(errs() <<  tri_->getName(physReg) << '\n');
902     // Note the register is not really in use.
903     vrm_->assignVirt2Phys(cur->reg, physReg);
904     return;
905   }
906
907   backUpRegUses();
908
909   std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
910   SlotIndex StartPosition = cur->beginIndex();
911   const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
912
913   // If start of this live interval is defined by a move instruction and its
914   // source is assigned a physical register that is compatible with the target
915   // register class, then we should try to assign it the same register.
916   // This can happen when the move is from a larger register class to a smaller
917   // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
918   if (!vrm_->getRegAllocPref(cur->reg) && cur->hasAtLeastOneValue()) {
919     VNInfo *vni = cur->begin()->valno;
920     if ((vni->def != SlotIndex()) && !vni->isUnused() &&
921          vni->isDefAccurate()) {
922       MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
923       unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
924       if (CopyMI &&
925           tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg)) {
926         unsigned Reg = 0;
927         if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
928           Reg = SrcReg;
929         else if (vrm_->isAssignedReg(SrcReg))
930           Reg = vrm_->getPhys(SrcReg);
931         if (Reg) {
932           if (SrcSubReg)
933             Reg = tri_->getSubReg(Reg, SrcSubReg);
934           if (DstSubReg)
935             Reg = tri_->getMatchingSuperReg(Reg, DstSubReg, RC);
936           if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
937             mri_->setRegAllocationHint(cur->reg, 0, Reg);
938         }
939       }
940     }
941   }
942
943   // For every interval in inactive we overlap with, mark the
944   // register as not free and update spill weights.
945   for (IntervalPtrs::const_iterator i = inactive_.begin(),
946          e = inactive_.end(); i != e; ++i) {
947     unsigned Reg = i->first->reg;
948     assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
949            "Can only allocate virtual registers!");
950     const TargetRegisterClass *RegRC = mri_->getRegClass(Reg);
951     // If this is not in a related reg class to the register we're allocating, 
952     // don't check it.
953     if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
954         cur->overlapsFrom(*i->first, i->second-1)) {
955       Reg = vrm_->getPhys(Reg);
956       addRegUse(Reg);
957       SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
958     }
959   }
960   
961   // Speculatively check to see if we can get a register right now.  If not,
962   // we know we won't be able to by adding more constraints.  If so, we can
963   // check to see if it is valid.  Doing an exhaustive search of the fixed_ list
964   // is very bad (it contains all callee clobbered registers for any functions
965   // with a call), so we want to avoid doing that if possible.
966   unsigned physReg = getFreePhysReg(cur);
967   unsigned BestPhysReg = physReg;
968   if (physReg) {
969     // We got a register.  However, if it's in the fixed_ list, we might
970     // conflict with it.  Check to see if we conflict with it or any of its
971     // aliases.
972     SmallSet<unsigned, 8> RegAliases;
973     for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
974       RegAliases.insert(*AS);
975     
976     bool ConflictsWithFixed = false;
977     for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
978       IntervalPtr &IP = fixed_[i];
979       if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
980         // Okay, this reg is on the fixed list.  Check to see if we actually
981         // conflict.
982         LiveInterval *I = IP.first;
983         if (I->endIndex() > StartPosition) {
984           LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
985           IP.second = II;
986           if (II != I->begin() && II->start > StartPosition)
987             --II;
988           if (cur->overlapsFrom(*I, II)) {
989             ConflictsWithFixed = true;
990             break;
991           }
992         }
993       }
994     }
995     
996     // Okay, the register picked by our speculative getFreePhysReg call turned
997     // out to be in use.  Actually add all of the conflicting fixed registers to
998     // regUse_ so we can do an accurate query.
999     if (ConflictsWithFixed) {
1000       // For every interval in fixed we overlap with, mark the register as not
1001       // free and update spill weights.
1002       for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1003         IntervalPtr &IP = fixed_[i];
1004         LiveInterval *I = IP.first;
1005
1006         const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
1007         if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&       
1008             I->endIndex() > StartPosition) {
1009           LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
1010           IP.second = II;
1011           if (II != I->begin() && II->start > StartPosition)
1012             --II;
1013           if (cur->overlapsFrom(*I, II)) {
1014             unsigned reg = I->reg;
1015             addRegUse(reg);
1016             SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
1017           }
1018         }
1019       }
1020
1021       // Using the newly updated regUse_ object, which includes conflicts in the
1022       // future, see if there are any registers available.
1023       physReg = getFreePhysReg(cur);
1024     }
1025   }
1026     
1027   // Restore the physical register tracker, removing information about the
1028   // future.
1029   restoreRegUses();
1030   
1031   // If we find a free register, we are done: assign this virtual to
1032   // the free physical register and add this interval to the active
1033   // list.
1034   if (physReg) {
1035     DEBUG(errs() <<  tri_->getName(physReg) << '\n');
1036     vrm_->assignVirt2Phys(cur->reg, physReg);
1037     addRegUse(physReg);
1038     active_.push_back(std::make_pair(cur, cur->begin()));
1039     handled_.push_back(cur);
1040
1041     // "Upgrade" the physical register since it has been allocated.
1042     UpgradeRegister(physReg);
1043     if (LiveInterval *NextReloadLI = hasNextReloadInterval(cur)) {
1044       // "Downgrade" physReg to try to keep physReg from being allocated until
1045       // the next reload from the same SS is allocated. 
1046       mri_->setRegAllocationHint(NextReloadLI->reg, 0, physReg);
1047       DowngradeRegister(cur, physReg);
1048     }
1049     return;
1050   }
1051   DEBUG(errs() << "no free registers\n");
1052
1053   // Compile the spill weights into an array that is better for scanning.
1054   std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
1055   for (std::vector<std::pair<unsigned, float> >::iterator
1056        I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
1057     updateSpillWeights(SpillWeights, I->first, I->second, RC);
1058   
1059   // for each interval in active, update spill weights.
1060   for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
1061        i != e; ++i) {
1062     unsigned reg = i->first->reg;
1063     assert(TargetRegisterInfo::isVirtualRegister(reg) &&
1064            "Can only allocate virtual registers!");
1065     reg = vrm_->getPhys(reg);
1066     updateSpillWeights(SpillWeights, reg, i->first->weight, RC);
1067   }
1068  
1069   DEBUG(errs() << "\tassigning stack slot at interval "<< *cur << ":\n");
1070
1071   // Find a register to spill.
1072   float minWeight = HUGE_VALF;
1073   unsigned minReg = 0;
1074
1075   bool Found = false;
1076   std::vector<std::pair<unsigned,float> > RegsWeights;
1077   if (!minReg || SpillWeights[minReg] == HUGE_VALF)
1078     for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
1079            e = RC->allocation_order_end(*mf_); i != e; ++i) {
1080       unsigned reg = *i;
1081       float regWeight = SpillWeights[reg];
1082       if (minWeight > regWeight)
1083         Found = true;
1084       RegsWeights.push_back(std::make_pair(reg, regWeight));
1085     }
1086   
1087   // If we didn't find a register that is spillable, try aliases?
1088   if (!Found) {
1089     for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
1090            e = RC->allocation_order_end(*mf_); i != e; ++i) {
1091       unsigned reg = *i;
1092       // No need to worry about if the alias register size < regsize of RC.
1093       // We are going to spill all registers that alias it anyway.
1094       for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
1095         RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
1096     }
1097   }
1098
1099   // Sort all potential spill candidates by weight.
1100   std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare());
1101   minReg = RegsWeights[0].first;
1102   minWeight = RegsWeights[0].second;
1103   if (minWeight == HUGE_VALF) {
1104     // All registers must have inf weight. Just grab one!
1105     minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
1106     if (cur->weight == HUGE_VALF ||
1107         li_->getApproximateInstructionCount(*cur) == 0) {
1108       // Spill a physical register around defs and uses.
1109       if (li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_)) {
1110         // spillPhysRegAroundRegDefsUses may have invalidated iterator stored
1111         // in fixed_. Reset them.
1112         for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1113           IntervalPtr &IP = fixed_[i];
1114           LiveInterval *I = IP.first;
1115           if (I->reg == minReg || tri_->isSubRegister(minReg, I->reg))
1116             IP.second = I->advanceTo(I->begin(), StartPosition);
1117         }
1118
1119         DowngradedRegs.clear();
1120         assignRegOrStackSlotAtInterval(cur);
1121       } else {
1122         assert(false && "Ran out of registers during register allocation!");
1123         llvm_report_error("Ran out of registers during register allocation!");
1124       }
1125       return;
1126     }
1127   }
1128
1129   // Find up to 3 registers to consider as spill candidates.
1130   unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
1131   while (LastCandidate > 1) {
1132     if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
1133       break;
1134     --LastCandidate;
1135   }
1136
1137   DEBUG({
1138       errs() << "\t\tregister(s) with min weight(s): ";
1139
1140       for (unsigned i = 0; i != LastCandidate; ++i)
1141         errs() << tri_->getName(RegsWeights[i].first)
1142                << " (" << RegsWeights[i].second << ")\n";
1143     });
1144
1145   // If the current has the minimum weight, we need to spill it and
1146   // add any added intervals back to unhandled, and restart
1147   // linearscan.
1148   if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
1149     DEBUG(errs() << "\t\t\tspilling(c): " << *cur << '\n');
1150     SmallVector<LiveInterval*, 8> spillIs;
1151     std::vector<LiveInterval*> added;
1152     
1153     added = spiller_->spill(cur, spillIs); 
1154
1155     std::sort(added.begin(), added.end(), LISorter());
1156     addStackInterval(cur, ls_, li_, mri_, *vrm_);
1157     if (added.empty())
1158       return;  // Early exit if all spills were folded.
1159
1160     // Merge added with unhandled.  Note that we have already sorted
1161     // intervals returned by addIntervalsForSpills by their starting
1162     // point.
1163     // This also update the NextReloadMap. That is, it adds mapping from a
1164     // register defined by a reload from SS to the next reload from SS in the
1165     // same basic block.
1166     MachineBasicBlock *LastReloadMBB = 0;
1167     LiveInterval *LastReload = 0;
1168     int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1169     for (unsigned i = 0, e = added.size(); i != e; ++i) {
1170       LiveInterval *ReloadLi = added[i];
1171       if (ReloadLi->weight == HUGE_VALF &&
1172           li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1173         SlotIndex ReloadIdx = ReloadLi->beginIndex();
1174         MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1175         int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1176         if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1177           // Last reload of same SS is in the same MBB. We want to try to
1178           // allocate both reloads the same register and make sure the reg
1179           // isn't clobbered in between if at all possible.
1180           assert(LastReload->beginIndex() < ReloadIdx);
1181           NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1182         }
1183         LastReloadMBB = ReloadMBB;
1184         LastReload = ReloadLi;
1185         LastReloadSS = ReloadSS;
1186       }
1187       unhandled_.push(ReloadLi);
1188     }
1189     return;
1190   }
1191
1192   ++NumBacktracks;
1193
1194   // Push the current interval back to unhandled since we are going
1195   // to re-run at least this iteration. Since we didn't modify it it
1196   // should go back right in the front of the list
1197   unhandled_.push(cur);
1198
1199   assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
1200          "did not choose a register to spill?");
1201
1202   // We spill all intervals aliasing the register with
1203   // minimum weight, rollback to the interval with the earliest
1204   // start point and let the linear scan algorithm run again
1205   SmallVector<LiveInterval*, 8> spillIs;
1206
1207   // Determine which intervals have to be spilled.
1208   findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
1209
1210   // Set of spilled vregs (used later to rollback properly)
1211   SmallSet<unsigned, 8> spilled;
1212
1213   // The earliest start of a Spilled interval indicates up to where
1214   // in handled we need to roll back
1215   
1216   LiveInterval *earliestStartInterval = cur;
1217
1218   // Spill live intervals of virtual regs mapped to the physical register we
1219   // want to clear (and its aliases).  We only spill those that overlap with the
1220   // current interval as the rest do not affect its allocation. we also keep
1221   // track of the earliest start of all spilled live intervals since this will
1222   // mark our rollback point.
1223   std::vector<LiveInterval*> added;
1224   while (!spillIs.empty()) {
1225     LiveInterval *sli = spillIs.back();
1226     spillIs.pop_back();
1227     DEBUG(errs() << "\t\t\tspilling(a): " << *sli << '\n');
1228     earliestStartInterval =
1229       (earliestStartInterval->beginIndex() < sli->beginIndex()) ?
1230          earliestStartInterval : sli;
1231        
1232     std::vector<LiveInterval*> newIs;
1233     newIs = spiller_->spill(sli, spillIs);
1234     addStackInterval(sli, ls_, li_, mri_, *vrm_);
1235     std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
1236     spilled.insert(sli->reg);
1237   }
1238
1239   SlotIndex earliestStart = earliestStartInterval->beginIndex();
1240
1241   DEBUG(errs() << "\t\trolling back to: " << earliestStart << '\n');
1242
1243   // Scan handled in reverse order up to the earliest start of a
1244   // spilled live interval and undo each one, restoring the state of
1245   // unhandled.
1246   while (!handled_.empty()) {
1247     LiveInterval* i = handled_.back();
1248     // If this interval starts before t we are done.
1249     if (i->beginIndex() < earliestStart)
1250       break;
1251     DEBUG(errs() << "\t\t\tundo changes for: " << *i << '\n');
1252     handled_.pop_back();
1253
1254     // When undoing a live interval allocation we must know if it is active or
1255     // inactive to properly update regUse_ and the VirtRegMap.
1256     IntervalPtrs::iterator it;
1257     if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
1258       active_.erase(it);
1259       assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
1260       if (!spilled.count(i->reg))
1261         unhandled_.push(i);
1262       delRegUse(vrm_->getPhys(i->reg));
1263       vrm_->clearVirt(i->reg);
1264     } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
1265       inactive_.erase(it);
1266       assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
1267       if (!spilled.count(i->reg))
1268         unhandled_.push(i);
1269       vrm_->clearVirt(i->reg);
1270     } else {
1271       assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
1272              "Can only allocate virtual registers!");
1273       vrm_->clearVirt(i->reg);
1274       unhandled_.push(i);
1275     }
1276
1277     DenseMap<unsigned, unsigned>::iterator ii = DowngradeMap.find(i->reg);
1278     if (ii == DowngradeMap.end())
1279       // It interval has a preference, it must be defined by a copy. Clear the
1280       // preference now since the source interval allocation may have been
1281       // undone as well.
1282       mri_->setRegAllocationHint(i->reg, 0, 0);
1283     else {
1284       UpgradeRegister(ii->second);
1285     }
1286   }
1287
1288   // Rewind the iterators in the active, inactive, and fixed lists back to the
1289   // point we reverted to.
1290   RevertVectorIteratorsTo(active_, earliestStart);
1291   RevertVectorIteratorsTo(inactive_, earliestStart);
1292   RevertVectorIteratorsTo(fixed_, earliestStart);
1293
1294   // Scan the rest and undo each interval that expired after t and
1295   // insert it in active (the next iteration of the algorithm will
1296   // put it in inactive if required)
1297   for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
1298     LiveInterval *HI = handled_[i];
1299     if (!HI->expiredAt(earliestStart) &&
1300         HI->expiredAt(cur->beginIndex())) {
1301       DEBUG(errs() << "\t\t\tundo changes for: " << *HI << '\n');
1302       active_.push_back(std::make_pair(HI, HI->begin()));
1303       assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
1304       addRegUse(vrm_->getPhys(HI->reg));
1305     }
1306   }
1307
1308   // Merge added with unhandled.
1309   // This also update the NextReloadMap. That is, it adds mapping from a
1310   // register defined by a reload from SS to the next reload from SS in the
1311   // same basic block.
1312   MachineBasicBlock *LastReloadMBB = 0;
1313   LiveInterval *LastReload = 0;
1314   int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1315   std::sort(added.begin(), added.end(), LISorter());
1316   for (unsigned i = 0, e = added.size(); i != e; ++i) {
1317     LiveInterval *ReloadLi = added[i];
1318     if (ReloadLi->weight == HUGE_VALF &&
1319         li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1320       SlotIndex ReloadIdx = ReloadLi->beginIndex();
1321       MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1322       int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1323       if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1324         // Last reload of same SS is in the same MBB. We want to try to
1325         // allocate both reloads the same register and make sure the reg
1326         // isn't clobbered in between if at all possible.
1327         assert(LastReload->beginIndex() < ReloadIdx);
1328         NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1329       }
1330       LastReloadMBB = ReloadMBB;
1331       LastReload = ReloadLi;
1332       LastReloadSS = ReloadSS;
1333     }
1334     unhandled_.push(ReloadLi);
1335   }
1336 }
1337
1338 unsigned RALinScan::getFreePhysReg(LiveInterval* cur,
1339                                    const TargetRegisterClass *RC,
1340                                    unsigned MaxInactiveCount,
1341                                    SmallVector<unsigned, 256> &inactiveCounts,
1342                                    bool SkipDGRegs) {
1343   unsigned FreeReg = 0;
1344   unsigned FreeRegInactiveCount = 0;
1345
1346   std::pair<unsigned, unsigned> Hint = mri_->getRegAllocationHint(cur->reg);
1347   // Resolve second part of the hint (if possible) given the current allocation.
1348   unsigned physReg = Hint.second;
1349   if (physReg &&
1350       TargetRegisterInfo::isVirtualRegister(physReg) && vrm_->hasPhys(physReg))
1351     physReg = vrm_->getPhys(physReg);
1352
1353   TargetRegisterClass::iterator I, E;
1354   tie(I, E) = tri_->getAllocationOrder(RC, Hint.first, physReg, *mf_);
1355   assert(I != E && "No allocatable register in this register class!");
1356
1357   // Scan for the first available register.
1358   for (; I != E; ++I) {
1359     unsigned Reg = *I;
1360     // Ignore "downgraded" registers.
1361     if (SkipDGRegs && DowngradedRegs.count(Reg))
1362       continue;
1363     if (isRegAvail(Reg)) {
1364       FreeReg = Reg;
1365       if (FreeReg < inactiveCounts.size())
1366         FreeRegInactiveCount = inactiveCounts[FreeReg];
1367       else
1368         FreeRegInactiveCount = 0;
1369       break;
1370     }
1371   }
1372
1373   // If there are no free regs, or if this reg has the max inactive count,
1374   // return this register.
1375   if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount)
1376     return FreeReg;
1377  
1378   // Continue scanning the registers, looking for the one with the highest
1379   // inactive count.  Alkis found that this reduced register pressure very
1380   // slightly on X86 (in rev 1.94 of this file), though this should probably be
1381   // reevaluated now.
1382   for (; I != E; ++I) {
1383     unsigned Reg = *I;
1384     // Ignore "downgraded" registers.
1385     if (SkipDGRegs && DowngradedRegs.count(Reg))
1386       continue;
1387     if (isRegAvail(Reg) && Reg < inactiveCounts.size() &&
1388         FreeRegInactiveCount < inactiveCounts[Reg]) {
1389       FreeReg = Reg;
1390       FreeRegInactiveCount = inactiveCounts[Reg];
1391       if (FreeRegInactiveCount == MaxInactiveCount)
1392         break;    // We found the one with the max inactive count.
1393     }
1394   }
1395
1396   return FreeReg;
1397 }
1398
1399 /// getFreePhysReg - return a free physical register for this virtual register
1400 /// interval if we have one, otherwise return 0.
1401 unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
1402   SmallVector<unsigned, 256> inactiveCounts;
1403   unsigned MaxInactiveCount = 0;
1404   
1405   const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
1406   const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1407  
1408   for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1409        i != e; ++i) {
1410     unsigned reg = i->first->reg;
1411     assert(TargetRegisterInfo::isVirtualRegister(reg) &&
1412            "Can only allocate virtual registers!");
1413
1414     // If this is not in a related reg class to the register we're allocating, 
1415     // don't check it.
1416     const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
1417     if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1418       reg = vrm_->getPhys(reg);
1419       if (inactiveCounts.size() <= reg)
1420         inactiveCounts.resize(reg+1);
1421       ++inactiveCounts[reg];
1422       MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1423     }
1424   }
1425
1426   // If copy coalescer has assigned a "preferred" register, check if it's
1427   // available first.
1428   unsigned Preference = vrm_->getRegAllocPref(cur->reg);
1429   if (Preference) {
1430     DEBUG(errs() << "(preferred: " << tri_->getName(Preference) << ") ");
1431     if (isRegAvail(Preference) && 
1432         RC->contains(Preference))
1433       return Preference;
1434   }
1435
1436   if (!DowngradedRegs.empty()) {
1437     unsigned FreeReg = getFreePhysReg(cur, RC, MaxInactiveCount, inactiveCounts,
1438                                       true);
1439     if (FreeReg)
1440       return FreeReg;
1441   }
1442   return getFreePhysReg(cur, RC, MaxInactiveCount, inactiveCounts, false);
1443 }
1444
1445 FunctionPass* llvm::createLinearScanRegisterAllocator() {
1446   return new RALinScan();
1447 }