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