170febcc50be7183d28fc088695791bb7459fc7d
[oota-llvm.git] / lib / CodeGen / RegAllocLinearScan.cpp
1 //===-- RegAllocLinearScan.cpp - Linear Scan register allocator -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 "llvm/CodeGen/LiveIntervalAnalysis.h"
16 #include "PhysRegTracker.h"
17 #include "VirtRegMap.h"
18 #include "llvm/Function.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/CodeGen/RegAllocRegistry.h"
23 #include "llvm/CodeGen/SSARegMap.h"
24 #include "llvm/Target/MRegisterInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/ADT/EquivalenceClasses.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/Compiler.h"
31 #include <algorithm>
32 #include <set>
33 #include <queue>
34 #include <memory>
35 #include <cmath>
36 using namespace llvm;
37
38 namespace {
39
40   static Statistic<> NumIters
41   ("regalloc", "Number of iterations performed");
42   static Statistic<> NumBacktracks
43   ("regalloc", "Number of times we had to backtrack");
44
45   static RegisterRegAlloc
46     linearscanRegAlloc("linearscan", "  linear scan register allocator",
47                        createLinearScanRegisterAllocator);
48
49   static unsigned numIterations = 0;
50   static unsigned numIntervals = 0;
51
52   struct VISIBILITY_HIDDEN RA : public MachineFunctionPass {
53     typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
54     typedef std::vector<IntervalPtr> IntervalPtrs;
55   private:
56     /// RelatedRegClasses - This structure is built the first time a function is
57     /// compiled, and keeps track of which register classes have registers that
58     /// belong to multiple classes or have aliases that are in other classes.
59     EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
60     std::map<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
61
62     MachineFunction* mf_;
63     const TargetMachine* tm_;
64     const MRegisterInfo* mri_;
65     LiveIntervals* li_;
66     bool *PhysRegsUsed;
67
68     /// handled_ - Intervals are added to the handled_ set in the order of their
69     /// start value.  This is uses for backtracking.
70     std::vector<LiveInterval*> handled_;
71
72     /// fixed_ - Intervals that correspond to machine registers.
73     ///
74     IntervalPtrs fixed_;
75
76     /// active_ - Intervals that are currently being processed, and which have a
77     /// live range active for the current point.
78     IntervalPtrs active_;
79
80     /// inactive_ - Intervals that are currently being processed, but which have
81     /// a hold at the current point.
82     IntervalPtrs inactive_;
83
84     typedef std::priority_queue<LiveInterval*,
85                                 std::vector<LiveInterval*>,
86                                 greater_ptr<LiveInterval> > IntervalHeap;
87     IntervalHeap unhandled_;
88     std::auto_ptr<PhysRegTracker> prt_;
89     std::auto_ptr<VirtRegMap> vrm_;
90     std::auto_ptr<Spiller> spiller_;
91
92   public:
93     virtual const char* getPassName() const {
94       return "Linear Scan Register Allocator";
95     }
96
97     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
98       AU.addRequired<LiveIntervals>();
99       MachineFunctionPass::getAnalysisUsage(AU);
100     }
101
102     /// runOnMachineFunction - register allocate the whole function
103     bool runOnMachineFunction(MachineFunction&);
104
105   private:
106     /// linearScan - the linear scan algorithm
107     void linearScan();
108
109     /// initIntervalSets - initialize the interval sets.
110     ///
111     void initIntervalSets();
112
113     /// processActiveIntervals - expire old intervals and move non-overlapping
114     /// ones to the inactive list.
115     void processActiveIntervals(unsigned CurPoint);
116
117     /// processInactiveIntervals - expire old intervals and move overlapping
118     /// ones to the active list.
119     void processInactiveIntervals(unsigned CurPoint);
120
121     /// assignRegOrStackSlotAtInterval - assign a register if one
122     /// is available, or spill.
123     void assignRegOrStackSlotAtInterval(LiveInterval* cur);
124
125     ///
126     /// register handling helpers
127     ///
128
129     /// getFreePhysReg - return a free physical register for this virtual
130     /// register interval if we have one, otherwise return 0.
131     unsigned getFreePhysReg(LiveInterval* cur);
132
133     /// assignVirt2StackSlot - assigns this virtual register to a
134     /// stack slot. returns the stack slot
135     int assignVirt2StackSlot(unsigned virtReg);
136
137     void ComputeRelatedRegClasses();
138
139     template <typename ItTy>
140     void printIntervals(const char* const str, ItTy i, ItTy e) const {
141       if (str) DOUT << str << " intervals:\n";
142       for (; i != e; ++i) {
143         DOUT << "\t" << *i->first << " -> ";
144         unsigned reg = i->first->reg;
145         if (MRegisterInfo::isVirtualRegister(reg)) {
146           reg = vrm_->getPhys(reg);
147         }
148         DOUT << mri_->getName(reg) << '\n';
149       }
150     }
151   };
152 }
153
154 void RA::ComputeRelatedRegClasses() {
155   const MRegisterInfo &MRI = *mri_;
156   
157   // First pass, add all reg classes to the union, and determine at least one
158   // reg class that each register is in.
159   bool HasAliases = false;
160   for (MRegisterInfo::regclass_iterator RCI = MRI.regclass_begin(),
161        E = MRI.regclass_end(); RCI != E; ++RCI) {
162     RelatedRegClasses.insert(*RCI);
163     for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
164          I != E; ++I) {
165       HasAliases = HasAliases || *MRI.getAliasSet(*I) != 0;
166       
167       const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
168       if (PRC) {
169         // Already processed this register.  Just make sure we know that
170         // multiple register classes share a register.
171         RelatedRegClasses.unionSets(PRC, *RCI);
172       } else {
173         PRC = *RCI;
174       }
175     }
176   }
177   
178   // Second pass, now that we know conservatively what register classes each reg
179   // belongs to, add info about aliases.  We don't need to do this for targets
180   // without register aliases.
181   if (HasAliases)
182     for (std::map<unsigned, const TargetRegisterClass*>::iterator
183          I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
184          I != E; ++I)
185       for (const unsigned *AS = MRI.getAliasSet(I->first); *AS; ++AS)
186         RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
187 }
188
189 bool RA::runOnMachineFunction(MachineFunction &fn) {
190   mf_ = &fn;
191   tm_ = &fn.getTarget();
192   mri_ = tm_->getRegisterInfo();
193   li_ = &getAnalysis<LiveIntervals>();
194
195   // If this is the first function compiled, compute the related reg classes.
196   if (RelatedRegClasses.empty())
197     ComputeRelatedRegClasses();
198   
199   PhysRegsUsed = new bool[mri_->getNumRegs()];
200   std::fill(PhysRegsUsed, PhysRegsUsed+mri_->getNumRegs(), false);
201   fn.setUsedPhysRegs(PhysRegsUsed);
202
203   if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
204   vrm_.reset(new VirtRegMap(*mf_));
205   if (!spiller_.get()) spiller_.reset(createSpiller());
206
207   initIntervalSets();
208
209   linearScan();
210
211   // Rewrite spill code and update the PhysRegsUsed set.
212   spiller_->runOnMachineFunction(*mf_, *vrm_);
213
214   vrm_.reset();  // Free the VirtRegMap
215
216
217   while (!unhandled_.empty()) unhandled_.pop();
218   fixed_.clear();
219   active_.clear();
220   inactive_.clear();
221   handled_.clear();
222
223   return true;
224 }
225
226 /// initIntervalSets - initialize the interval sets.
227 ///
228 void RA::initIntervalSets()
229 {
230   assert(unhandled_.empty() && fixed_.empty() &&
231          active_.empty() && inactive_.empty() &&
232          "interval sets should be empty on initialization");
233
234   for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
235     if (MRegisterInfo::isPhysicalRegister(i->second.reg)) {
236       PhysRegsUsed[i->second.reg] = true;
237       fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
238     } else
239       unhandled_.push(&i->second);
240   }
241 }
242
243 void RA::linearScan()
244 {
245   // linear scan algorithm
246   DOUT << "********** LINEAR SCAN **********\n";
247   DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
248
249   // DEBUG(printIntervals("unhandled", unhandled_.begin(), unhandled_.end()));
250   DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
251   DEBUG(printIntervals("active", active_.begin(), active_.end()));
252   DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
253
254   while (!unhandled_.empty()) {
255     // pick the interval with the earliest start point
256     LiveInterval* cur = unhandled_.top();
257     unhandled_.pop();
258     ++numIterations;
259     DOUT << "\n*** CURRENT ***: " << *cur << '\n';
260
261     processActiveIntervals(cur->beginNumber());
262     processInactiveIntervals(cur->beginNumber());
263
264     assert(MRegisterInfo::isVirtualRegister(cur->reg) &&
265            "Can only allocate virtual registers!");
266
267     // Allocating a virtual register. try to find a free
268     // physical register or spill an interval (possibly this one) in order to
269     // assign it one.
270     assignRegOrStackSlotAtInterval(cur);
271
272     DEBUG(printIntervals("active", active_.begin(), active_.end()));
273     DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
274   }
275   numIntervals += li_->getNumIntervals();
276   NumIters += numIterations;
277
278   // expire any remaining active intervals
279   for (IntervalPtrs::reverse_iterator
280          i = active_.rbegin(); i != active_.rend(); ) {
281     unsigned reg = i->first->reg;
282     DOUT << "\tinterval " << *i->first << " expired\n";
283     assert(MRegisterInfo::isVirtualRegister(reg) &&
284            "Can only allocate virtual registers!");
285     reg = vrm_->getPhys(reg);
286     prt_->delRegUse(reg);
287     i = IntervalPtrs::reverse_iterator(active_.erase(i.base()-1));
288   }
289
290   // expire any remaining inactive intervals
291   for (IntervalPtrs::reverse_iterator
292          i = inactive_.rbegin(); i != inactive_.rend(); ) {
293     DOUT << "\tinterval " << *i->first << " expired\n";
294     i = IntervalPtrs::reverse_iterator(inactive_.erase(i.base()-1));
295   }
296
297   DOUT << *vrm_;
298 }
299
300 /// processActiveIntervals - expire old intervals and move non-overlapping ones
301 /// to the inactive list.
302 void RA::processActiveIntervals(unsigned CurPoint)
303 {
304   DOUT << "\tprocessing active intervals:\n";
305
306   for (unsigned i = 0, e = active_.size(); i != e; ++i) {
307     LiveInterval *Interval = active_[i].first;
308     LiveInterval::iterator IntervalPos = active_[i].second;
309     unsigned reg = Interval->reg;
310
311     IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
312
313     if (IntervalPos == Interval->end()) {     // Remove expired intervals.
314       DOUT << "\t\tinterval " << *Interval << " expired\n";
315       assert(MRegisterInfo::isVirtualRegister(reg) &&
316              "Can only allocate virtual registers!");
317       reg = vrm_->getPhys(reg);
318       prt_->delRegUse(reg);
319
320       // Pop off the end of the list.
321       active_[i] = active_.back();
322       active_.pop_back();
323       --i; --e;
324
325     } else if (IntervalPos->start > CurPoint) {
326       // Move inactive intervals to inactive list.
327       DOUT << "\t\tinterval " << *Interval << " inactive\n";
328       assert(MRegisterInfo::isVirtualRegister(reg) &&
329              "Can only allocate virtual registers!");
330       reg = vrm_->getPhys(reg);
331       prt_->delRegUse(reg);
332       // add to inactive.
333       inactive_.push_back(std::make_pair(Interval, IntervalPos));
334
335       // Pop off the end of the list.
336       active_[i] = active_.back();
337       active_.pop_back();
338       --i; --e;
339     } else {
340       // Otherwise, just update the iterator position.
341       active_[i].second = IntervalPos;
342     }
343   }
344 }
345
346 /// processInactiveIntervals - expire old intervals and move overlapping
347 /// ones to the active list.
348 void RA::processInactiveIntervals(unsigned CurPoint)
349 {
350   DOUT << "\tprocessing inactive intervals:\n";
351
352   for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
353     LiveInterval *Interval = inactive_[i].first;
354     LiveInterval::iterator IntervalPos = inactive_[i].second;
355     unsigned reg = Interval->reg;
356
357     IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
358
359     if (IntervalPos == Interval->end()) {       // remove expired intervals.
360       DOUT << "\t\tinterval " << *Interval << " expired\n";
361
362       // Pop off the end of the list.
363       inactive_[i] = inactive_.back();
364       inactive_.pop_back();
365       --i; --e;
366     } else if (IntervalPos->start <= CurPoint) {
367       // move re-activated intervals in active list
368       DOUT << "\t\tinterval " << *Interval << " active\n";
369       assert(MRegisterInfo::isVirtualRegister(reg) &&
370              "Can only allocate virtual registers!");
371       reg = vrm_->getPhys(reg);
372       prt_->addRegUse(reg);
373       // add to active
374       active_.push_back(std::make_pair(Interval, IntervalPos));
375
376       // Pop off the end of the list.
377       inactive_[i] = inactive_.back();
378       inactive_.pop_back();
379       --i; --e;
380     } else {
381       // Otherwise, just update the iterator position.
382       inactive_[i].second = IntervalPos;
383     }
384   }
385 }
386
387 /// updateSpillWeights - updates the spill weights of the specifed physical
388 /// register and its weight.
389 static void updateSpillWeights(std::vector<float> &Weights,
390                                unsigned reg, float weight,
391                                const MRegisterInfo *MRI) {
392   Weights[reg] += weight;
393   for (const unsigned* as = MRI->getAliasSet(reg); *as; ++as)
394     Weights[*as] += weight;
395 }
396
397 static RA::IntervalPtrs::iterator FindIntervalInVector(RA::IntervalPtrs &IP,
398                                                        LiveInterval *LI) {
399   for (RA::IntervalPtrs::iterator I = IP.begin(), E = IP.end(); I != E; ++I)
400     if (I->first == LI) return I;
401   return IP.end();
402 }
403
404 static void RevertVectorIteratorsTo(RA::IntervalPtrs &V, unsigned Point) {
405   for (unsigned i = 0, e = V.size(); i != e; ++i) {
406     RA::IntervalPtr &IP = V[i];
407     LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
408                                                 IP.second, Point);
409     if (I != IP.first->begin()) --I;
410     IP.second = I;
411   }
412 }
413
414 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
415 /// spill.
416 void RA::assignRegOrStackSlotAtInterval(LiveInterval* cur)
417 {
418   DOUT << "\tallocating current interval: ";
419
420   PhysRegTracker backupPrt = *prt_;
421
422   std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
423   unsigned StartPosition = cur->beginNumber();
424   const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
425   const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
426       
427   // for every interval in inactive we overlap with, mark the
428   // register as not free and update spill weights.
429   for (IntervalPtrs::const_iterator i = inactive_.begin(),
430          e = inactive_.end(); i != e; ++i) {
431     unsigned Reg = i->first->reg;
432     assert(MRegisterInfo::isVirtualRegister(Reg) &&
433            "Can only allocate virtual registers!");
434     const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(Reg);
435     // If this is not in a related reg class to the register we're allocating, 
436     // don't check it.
437     if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
438         cur->overlapsFrom(*i->first, i->second-1)) {
439       Reg = vrm_->getPhys(Reg);
440       prt_->addRegUse(Reg);
441       SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
442     }
443   }
444   
445   // Speculatively check to see if we can get a register right now.  If not,
446   // we know we won't be able to by adding more constraints.  If so, we can
447   // check to see if it is valid.  Doing an exhaustive search of the fixed_ list
448   // is very bad (it contains all callee clobbered registers for any functions
449   // with a call), so we want to avoid doing that if possible.
450   unsigned physReg = getFreePhysReg(cur);
451   if (physReg) {
452     // We got a register.  However, if it's in the fixed_ list, we might
453     // conflict with it.  Check to see if we conflict with it or any of its
454     // aliases.
455     std::set<unsigned> RegAliases;
456     for (const unsigned *AS = mri_->getAliasSet(physReg); *AS; ++AS)
457       RegAliases.insert(*AS);
458     
459     bool ConflictsWithFixed = false;
460     for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
461       IntervalPtr &IP = fixed_[i];
462       if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
463         // Okay, this reg is on the fixed list.  Check to see if we actually
464         // conflict.
465         LiveInterval *I = IP.first;
466         if (I->endNumber() > StartPosition) {
467           LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
468           IP.second = II;
469           if (II != I->begin() && II->start > StartPosition)
470             --II;
471           if (cur->overlapsFrom(*I, II)) {
472             ConflictsWithFixed = true;
473             break;
474           }
475         }
476       }
477     }
478     
479     // Okay, the register picked by our speculative getFreePhysReg call turned
480     // out to be in use.  Actually add all of the conflicting fixed registers to
481     // prt so we can do an accurate query.
482     if (ConflictsWithFixed) {
483       // For every interval in fixed we overlap with, mark the register as not
484       // free and update spill weights.
485       for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
486         IntervalPtr &IP = fixed_[i];
487         LiveInterval *I = IP.first;
488
489         const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
490         if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&       
491             I->endNumber() > StartPosition) {
492           LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
493           IP.second = II;
494           if (II != I->begin() && II->start > StartPosition)
495             --II;
496           if (cur->overlapsFrom(*I, II)) {
497             unsigned reg = I->reg;
498             prt_->addRegUse(reg);
499             SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
500           }
501         }
502       }
503
504       // Using the newly updated prt_ object, which includes conflicts in the
505       // future, see if there are any registers available.
506       physReg = getFreePhysReg(cur);
507     }
508   }
509     
510   // Restore the physical register tracker, removing information about the
511   // future.
512   *prt_ = backupPrt;
513   
514   // if we find a free register, we are done: assign this virtual to
515   // the free physical register and add this interval to the active
516   // list.
517   if (physReg) {
518     DOUT <<  mri_->getName(physReg) << '\n';
519     vrm_->assignVirt2Phys(cur->reg, physReg);
520     prt_->addRegUse(physReg);
521     active_.push_back(std::make_pair(cur, cur->begin()));
522     handled_.push_back(cur);
523     return;
524   }
525   DOUT << "no free registers\n";
526
527   // Compile the spill weights into an array that is better for scanning.
528   std::vector<float> SpillWeights(mri_->getNumRegs(), 0.0);
529   for (std::vector<std::pair<unsigned, float> >::iterator
530        I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
531     updateSpillWeights(SpillWeights, I->first, I->second, mri_);
532   
533   // for each interval in active, update spill weights.
534   for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
535        i != e; ++i) {
536     unsigned reg = i->first->reg;
537     assert(MRegisterInfo::isVirtualRegister(reg) &&
538            "Can only allocate virtual registers!");
539     reg = vrm_->getPhys(reg);
540     updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
541   }
542  
543   DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
544
545   // Find a register to spill.
546   float minWeight = HUGE_VALF;
547   unsigned minReg = 0;
548   for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
549        e = RC->allocation_order_end(*mf_); i != e; ++i) {
550     unsigned reg = *i;
551     if (minWeight > SpillWeights[reg]) {
552       minWeight = SpillWeights[reg];
553       minReg = reg;
554     }
555   }
556   
557   // If we didn't find a register that is spillable, try aliases?
558   if (!minReg) {
559     for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
560            e = RC->allocation_order_end(*mf_); i != e; ++i) {
561       unsigned reg = *i;
562       // No need to worry about if the alias register size < regsize of RC.
563       // We are going to spill all registers that alias it anyway.
564       for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as) {
565         if (minWeight > SpillWeights[*as]) {
566           minWeight = SpillWeights[*as];
567           minReg = *as;
568         }
569       }
570     }
571
572     // All registers must have inf weight. Just grab one!
573     if (!minReg)
574       minReg = *RC->allocation_order_begin(*mf_);
575   }
576   
577   DOUT << "\t\tregister with min weight: "
578        << mri_->getName(minReg) << " (" << minWeight << ")\n";
579
580   // if the current has the minimum weight, we need to spill it and
581   // add any added intervals back to unhandled, and restart
582   // linearscan.
583   if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
584     DOUT << "\t\t\tspilling(c): " << *cur << '\n';
585     int slot = vrm_->assignVirt2StackSlot(cur->reg);
586     std::vector<LiveInterval*> added =
587       li_->addIntervalsForSpills(*cur, *vrm_, slot);
588     if (added.empty())
589       return;  // Early exit if all spills were folded.
590
591     // Merge added with unhandled.  Note that we know that
592     // addIntervalsForSpills returns intervals sorted by their starting
593     // point.
594     for (unsigned i = 0, e = added.size(); i != e; ++i)
595       unhandled_.push(added[i]);
596     return;
597   }
598
599   ++NumBacktracks;
600
601   // push the current interval back to unhandled since we are going
602   // to re-run at least this iteration. Since we didn't modify it it
603   // should go back right in the front of the list
604   unhandled_.push(cur);
605
606   // otherwise we spill all intervals aliasing the register with
607   // minimum weight, rollback to the interval with the earliest
608   // start point and let the linear scan algorithm run again
609   std::vector<LiveInterval*> added;
610   assert(MRegisterInfo::isPhysicalRegister(minReg) &&
611          "did not choose a register to spill?");
612   std::vector<bool> toSpill(mri_->getNumRegs(), false);
613
614   // We are going to spill minReg and all its aliases.
615   toSpill[minReg] = true;
616   for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
617     toSpill[*as] = true;
618
619   // the earliest start of a spilled interval indicates up to where
620   // in handled we need to roll back
621   unsigned earliestStart = cur->beginNumber();
622
623   // set of spilled vregs (used later to rollback properly)
624   std::set<unsigned> spilled;
625
626   // spill live intervals of virtual regs mapped to the physical register we
627   // want to clear (and its aliases).  We only spill those that overlap with the
628   // current interval as the rest do not affect its allocation. we also keep
629   // track of the earliest start of all spilled live intervals since this will
630   // mark our rollback point.
631   for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
632     unsigned reg = i->first->reg;
633     if (//MRegisterInfo::isVirtualRegister(reg) &&
634         toSpill[vrm_->getPhys(reg)] &&
635         cur->overlapsFrom(*i->first, i->second)) {
636       DOUT << "\t\t\tspilling(a): " << *i->first << '\n';
637       earliestStart = std::min(earliestStart, i->first->beginNumber());
638       int slot = vrm_->assignVirt2StackSlot(i->first->reg);
639       std::vector<LiveInterval*> newIs =
640         li_->addIntervalsForSpills(*i->first, *vrm_, slot);
641       std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
642       spilled.insert(reg);
643     }
644   }
645   for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
646     unsigned reg = i->first->reg;
647     if (//MRegisterInfo::isVirtualRegister(reg) &&
648         toSpill[vrm_->getPhys(reg)] &&
649         cur->overlapsFrom(*i->first, i->second-1)) {
650       DOUT << "\t\t\tspilling(i): " << *i->first << '\n';
651       earliestStart = std::min(earliestStart, i->first->beginNumber());
652       int slot = vrm_->assignVirt2StackSlot(reg);
653       std::vector<LiveInterval*> newIs =
654         li_->addIntervalsForSpills(*i->first, *vrm_, slot);
655       std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
656       spilled.insert(reg);
657     }
658   }
659
660   DOUT << "\t\trolling back to: " << earliestStart << '\n';
661
662   // Scan handled in reverse order up to the earliest start of a
663   // spilled live interval and undo each one, restoring the state of
664   // unhandled.
665   while (!handled_.empty()) {
666     LiveInterval* i = handled_.back();
667     // If this interval starts before t we are done.
668     if (i->beginNumber() < earliestStart)
669       break;
670     DOUT << "\t\t\tundo changes for: " << *i << '\n';
671     handled_.pop_back();
672
673     // When undoing a live interval allocation we must know if it is active or
674     // inactive to properly update the PhysRegTracker and the VirtRegMap.
675     IntervalPtrs::iterator it;
676     if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
677       active_.erase(it);
678       assert(!MRegisterInfo::isPhysicalRegister(i->reg));
679       if (!spilled.count(i->reg))
680         unhandled_.push(i);
681       prt_->delRegUse(vrm_->getPhys(i->reg));
682       vrm_->clearVirt(i->reg);
683     } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
684       inactive_.erase(it);
685       assert(!MRegisterInfo::isPhysicalRegister(i->reg));
686       if (!spilled.count(i->reg))
687         unhandled_.push(i);
688       vrm_->clearVirt(i->reg);
689     } else {
690       assert(MRegisterInfo::isVirtualRegister(i->reg) &&
691              "Can only allocate virtual registers!");
692       vrm_->clearVirt(i->reg);
693       unhandled_.push(i);
694     }
695   }
696
697   // Rewind the iterators in the active, inactive, and fixed lists back to the
698   // point we reverted to.
699   RevertVectorIteratorsTo(active_, earliestStart);
700   RevertVectorIteratorsTo(inactive_, earliestStart);
701   RevertVectorIteratorsTo(fixed_, earliestStart);
702
703   // scan the rest and undo each interval that expired after t and
704   // insert it in active (the next iteration of the algorithm will
705   // put it in inactive if required)
706   for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
707     LiveInterval *HI = handled_[i];
708     if (!HI->expiredAt(earliestStart) &&
709         HI->expiredAt(cur->beginNumber())) {
710       DOUT << "\t\t\tundo changes for: " << *HI << '\n';
711       active_.push_back(std::make_pair(HI, HI->begin()));
712       assert(!MRegisterInfo::isPhysicalRegister(HI->reg));
713       prt_->addRegUse(vrm_->getPhys(HI->reg));
714     }
715   }
716
717   // merge added with unhandled
718   for (unsigned i = 0, e = added.size(); i != e; ++i)
719     unhandled_.push(added[i]);
720 }
721
722 /// getFreePhysReg - return a free physical register for this virtual register
723 /// interval if we have one, otherwise return 0.
724 unsigned RA::getFreePhysReg(LiveInterval *cur) {
725   std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
726   unsigned MaxInactiveCount = 0;
727   
728   const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
729   const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
730  
731   for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
732        i != e; ++i) {
733     unsigned reg = i->first->reg;
734     assert(MRegisterInfo::isVirtualRegister(reg) &&
735            "Can only allocate virtual registers!");
736
737     // If this is not in a related reg class to the register we're allocating, 
738     // don't check it.
739     const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(reg);
740     if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
741       reg = vrm_->getPhys(reg);
742       ++inactiveCounts[reg];
743       MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
744     }
745   }
746
747   const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
748
749   unsigned FreeReg = 0;
750   unsigned FreeRegInactiveCount = 0;
751   
752   // Scan for the first available register.
753   TargetRegisterClass::iterator I = rc->allocation_order_begin(*mf_);
754   TargetRegisterClass::iterator E = rc->allocation_order_end(*mf_);
755   for (; I != E; ++I)
756     if (prt_->isRegAvail(*I)) {
757       FreeReg = *I;
758       FreeRegInactiveCount = inactiveCounts[FreeReg];
759       break;
760     }
761   
762   // If there are no free regs, or if this reg has the max inactive count,
763   // return this register.
764   if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
765   
766   // Continue scanning the registers, looking for the one with the highest
767   // inactive count.  Alkis found that this reduced register pressure very
768   // slightly on X86 (in rev 1.94 of this file), though this should probably be
769   // reevaluated now.
770   for (; I != E; ++I) {
771     unsigned Reg = *I;
772     if (prt_->isRegAvail(Reg) && FreeRegInactiveCount < inactiveCounts[Reg]) {
773       FreeReg = Reg;
774       FreeRegInactiveCount = inactiveCounts[Reg];
775       if (FreeRegInactiveCount == MaxInactiveCount)
776         break;    // We found the one with the max inactive count.
777     }
778   }
779   
780   return FreeReg;
781 }
782
783 FunctionPass* llvm::createLinearScanRegisterAllocator() {
784   return new RA();
785 }