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