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