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