1 //===-- RegAllocLinearScan.cpp - Linear Scan register allocator -----------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements a linear scan register allocator.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "regalloc"
15 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
16 #include "PhysRegTracker.h"
17 #include "VirtRegMap.h"
18 #include "llvm/Function.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/CodeGen/RegAllocRegistry.h"
23 #include "llvm/CodeGen/SSARegMap.h"
24 #include "llvm/Target/MRegisterInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/ADT/EquivalenceClasses.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/Compiler.h"
39 static Statistic<double> efficiency
40 ("regalloc", "Ratio of intervals processed over total intervals");
41 static Statistic<> NumBacktracks
42 ("regalloc", "Number of times we had to backtrack");
44 static RegisterRegAlloc
45 linearscanRegAlloc("linearscan", " linear scan register allocator",
46 createLinearScanRegisterAllocator);
48 static unsigned numIterations = 0;
49 static unsigned numIntervals = 0;
51 struct VISIBILITY_HIDDEN RA : public MachineFunctionPass {
52 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
53 typedef std::vector<IntervalPtr> IntervalPtrs;
55 /// RelatedRegClasses - This structure is built the first time a function is
56 /// compiled, and keeps track of which register classes have registers that
57 /// belong to multiple classes or have aliases that are in other classes.
58 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
59 std::map<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
62 const TargetMachine* tm_;
63 const MRegisterInfo* mri_;
67 /// handled_ - Intervals are added to the handled_ set in the order of their
68 /// start value. This is uses for backtracking.
69 std::vector<LiveInterval*> handled_;
71 /// fixed_ - Intervals that correspond to machine registers.
75 /// active_ - Intervals that are currently being processed, and which have a
76 /// live range active for the current point.
79 /// inactive_ - Intervals that are currently being processed, but which have
80 /// a hold at the current point.
81 IntervalPtrs inactive_;
83 typedef std::priority_queue<LiveInterval*,
84 std::vector<LiveInterval*>,
85 greater_ptr<LiveInterval> > IntervalHeap;
86 IntervalHeap unhandled_;
87 std::auto_ptr<PhysRegTracker> prt_;
88 std::auto_ptr<VirtRegMap> vrm_;
89 std::auto_ptr<Spiller> spiller_;
92 virtual const char* getPassName() const {
93 return "Linear Scan Register Allocator";
96 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
97 AU.addRequired<LiveIntervals>();
98 MachineFunctionPass::getAnalysisUsage(AU);
101 /// runOnMachineFunction - register allocate the whole function
102 bool runOnMachineFunction(MachineFunction&);
105 /// linearScan - the linear scan algorithm
108 /// initIntervalSets - initialize the interval sets.
110 void initIntervalSets();
112 /// processActiveIntervals - expire old intervals and move non-overlapping
113 /// ones to the inactive list.
114 void processActiveIntervals(unsigned CurPoint);
116 /// processInactiveIntervals - expire old intervals and move overlapping
117 /// ones to the active list.
118 void processInactiveIntervals(unsigned CurPoint);
120 /// assignRegOrStackSlotAtInterval - assign a register if one
121 /// is available, or spill.
122 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
125 /// register handling helpers
128 /// getFreePhysReg - return a free physical register for this virtual
129 /// register interval if we have one, otherwise return 0.
130 unsigned getFreePhysReg(LiveInterval* cur);
132 /// assignVirt2StackSlot - assigns this virtual register to a
133 /// stack slot. returns the stack slot
134 int assignVirt2StackSlot(unsigned virtReg);
136 void ComputeRelatedRegClasses();
138 template <typename ItTy>
139 void printIntervals(const char* const str, ItTy i, ItTy e) const {
140 if (str) DOUT << str << " intervals:\n";
141 for (; i != e; ++i) {
142 DOUT << "\t" << *i->first << " -> ";
143 unsigned reg = i->first->reg;
144 if (MRegisterInfo::isVirtualRegister(reg)) {
145 reg = vrm_->getPhys(reg);
147 DOUT << mri_->getName(reg) << '\n';
153 void RA::ComputeRelatedRegClasses() {
154 const MRegisterInfo &MRI = *mri_;
156 // First pass, add all reg classes to the union, and determine at least one
157 // reg class that each register is in.
158 bool HasAliases = false;
159 for (MRegisterInfo::regclass_iterator RCI = MRI.regclass_begin(),
160 E = MRI.regclass_end(); RCI != E; ++RCI) {
161 RelatedRegClasses.insert(*RCI);
162 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
164 HasAliases = HasAliases || *MRI.getAliasSet(*I) != 0;
166 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
168 // Already processed this register. Just make sure we know that
169 // multiple register classes share a register.
170 RelatedRegClasses.unionSets(PRC, *RCI);
177 // Second pass, now that we know conservatively what register classes each reg
178 // belongs to, add info about aliases. We don't need to do this for targets
179 // without register aliases.
181 for (std::map<unsigned, const TargetRegisterClass*>::iterator
182 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
184 for (const unsigned *AS = MRI.getAliasSet(I->first); *AS; ++AS)
185 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
188 bool RA::runOnMachineFunction(MachineFunction &fn) {
190 tm_ = &fn.getTarget();
191 mri_ = tm_->getRegisterInfo();
192 li_ = &getAnalysis<LiveIntervals>();
194 // If this is the first function compiled, compute the related reg classes.
195 if (RelatedRegClasses.empty())
196 ComputeRelatedRegClasses();
198 PhysRegsUsed = new bool[mri_->getNumRegs()];
199 std::fill(PhysRegsUsed, PhysRegsUsed+mri_->getNumRegs(), false);
200 fn.setUsedPhysRegs(PhysRegsUsed);
202 if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
203 vrm_.reset(new VirtRegMap(*mf_));
204 if (!spiller_.get()) spiller_.reset(createSpiller());
210 // Rewrite spill code and update the PhysRegsUsed set.
211 spiller_->runOnMachineFunction(*mf_, *vrm_);
213 vrm_.reset(); // Free the VirtRegMap
216 while (!unhandled_.empty()) unhandled_.pop();
225 /// initIntervalSets - initialize the interval sets.
227 void RA::initIntervalSets()
229 assert(unhandled_.empty() && fixed_.empty() &&
230 active_.empty() && inactive_.empty() &&
231 "interval sets should be empty on initialization");
233 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
234 if (MRegisterInfo::isPhysicalRegister(i->second.reg)) {
235 PhysRegsUsed[i->second.reg] = true;
236 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
238 unhandled_.push(&i->second);
242 void RA::linearScan()
244 // linear scan algorithm
245 DOUT << "********** LINEAR SCAN **********\n";
246 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
248 // DEBUG(printIntervals("unhandled", unhandled_.begin(), unhandled_.end()));
249 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
250 DEBUG(printIntervals("active", active_.begin(), active_.end()));
251 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
253 while (!unhandled_.empty()) {
254 // pick the interval with the earliest start point
255 LiveInterval* cur = unhandled_.top();
258 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
260 processActiveIntervals(cur->beginNumber());
261 processInactiveIntervals(cur->beginNumber());
263 assert(MRegisterInfo::isVirtualRegister(cur->reg) &&
264 "Can only allocate virtual registers!");
266 // Allocating a virtual register. try to find a free
267 // physical register or spill an interval (possibly this one) in order to
269 assignRegOrStackSlotAtInterval(cur);
271 DEBUG(printIntervals("active", active_.begin(), active_.end()));
272 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
274 numIntervals += li_->getNumIntervals();
275 efficiency = double(numIterations) / double(numIntervals);
277 // expire any remaining active intervals
278 for (IntervalPtrs::reverse_iterator
279 i = active_.rbegin(); i != active_.rend(); ) {
280 unsigned reg = i->first->reg;
281 DOUT << "\tinterval " << *i->first << " expired\n";
282 assert(MRegisterInfo::isVirtualRegister(reg) &&
283 "Can only allocate virtual registers!");
284 reg = vrm_->getPhys(reg);
285 prt_->delRegUse(reg);
286 i = IntervalPtrs::reverse_iterator(active_.erase(i.base()-1));
289 // expire any remaining inactive intervals
290 for (IntervalPtrs::reverse_iterator
291 i = inactive_.rbegin(); i != inactive_.rend(); ) {
292 DOUT << "\tinterval " << *i->first << " expired\n";
293 i = IntervalPtrs::reverse_iterator(inactive_.erase(i.base()-1));
299 /// processActiveIntervals - expire old intervals and move non-overlapping ones
300 /// to the inactive list.
301 void RA::processActiveIntervals(unsigned CurPoint)
303 DOUT << "\tprocessing active intervals:\n";
305 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
306 LiveInterval *Interval = active_[i].first;
307 LiveInterval::iterator IntervalPos = active_[i].second;
308 unsigned reg = Interval->reg;
310 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
312 if (IntervalPos == Interval->end()) { // Remove expired intervals.
313 DOUT << "\t\tinterval " << *Interval << " expired\n";
314 assert(MRegisterInfo::isVirtualRegister(reg) &&
315 "Can only allocate virtual registers!");
316 reg = vrm_->getPhys(reg);
317 prt_->delRegUse(reg);
319 // Pop off the end of the list.
320 active_[i] = active_.back();
324 } else if (IntervalPos->start > CurPoint) {
325 // Move inactive intervals to inactive list.
326 DOUT << "\t\tinterval " << *Interval << " inactive\n";
327 assert(MRegisterInfo::isVirtualRegister(reg) &&
328 "Can only allocate virtual registers!");
329 reg = vrm_->getPhys(reg);
330 prt_->delRegUse(reg);
332 inactive_.push_back(std::make_pair(Interval, IntervalPos));
334 // Pop off the end of the list.
335 active_[i] = active_.back();
339 // Otherwise, just update the iterator position.
340 active_[i].second = IntervalPos;
345 /// processInactiveIntervals - expire old intervals and move overlapping
346 /// ones to the active list.
347 void RA::processInactiveIntervals(unsigned CurPoint)
349 DOUT << "\tprocessing inactive intervals:\n";
351 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
352 LiveInterval *Interval = inactive_[i].first;
353 LiveInterval::iterator IntervalPos = inactive_[i].second;
354 unsigned reg = Interval->reg;
356 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
358 if (IntervalPos == Interval->end()) { // remove expired intervals.
359 DOUT << "\t\tinterval " << *Interval << " expired\n";
361 // Pop off the end of the list.
362 inactive_[i] = inactive_.back();
363 inactive_.pop_back();
365 } else if (IntervalPos->start <= CurPoint) {
366 // move re-activated intervals in active list
367 DOUT << "\t\tinterval " << *Interval << " active\n";
368 assert(MRegisterInfo::isVirtualRegister(reg) &&
369 "Can only allocate virtual registers!");
370 reg = vrm_->getPhys(reg);
371 prt_->addRegUse(reg);
373 active_.push_back(std::make_pair(Interval, IntervalPos));
375 // Pop off the end of the list.
376 inactive_[i] = inactive_.back();
377 inactive_.pop_back();
380 // Otherwise, just update the iterator position.
381 inactive_[i].second = IntervalPos;
386 /// updateSpillWeights - updates the spill weights of the specifed physical
387 /// register and its weight.
388 static void updateSpillWeights(std::vector<float> &Weights,
389 unsigned reg, float weight,
390 const MRegisterInfo *MRI) {
391 Weights[reg] += weight;
392 for (const unsigned* as = MRI->getAliasSet(reg); *as; ++as)
393 Weights[*as] += weight;
396 static RA::IntervalPtrs::iterator FindIntervalInVector(RA::IntervalPtrs &IP,
398 for (RA::IntervalPtrs::iterator I = IP.begin(), E = IP.end(); I != E; ++I)
399 if (I->first == LI) return I;
403 static void RevertVectorIteratorsTo(RA::IntervalPtrs &V, unsigned Point) {
404 for (unsigned i = 0, e = V.size(); i != e; ++i) {
405 RA::IntervalPtr &IP = V[i];
406 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
408 if (I != IP.first->begin()) --I;
413 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
415 void RA::assignRegOrStackSlotAtInterval(LiveInterval* cur)
417 DOUT << "\tallocating current interval: ";
419 PhysRegTracker backupPrt = *prt_;
421 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
422 unsigned StartPosition = cur->beginNumber();
423 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
424 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
426 // for every interval in inactive we overlap with, mark the
427 // register as not free and update spill weights.
428 for (IntervalPtrs::const_iterator i = inactive_.begin(),
429 e = inactive_.end(); i != e; ++i) {
430 unsigned Reg = i->first->reg;
431 assert(MRegisterInfo::isVirtualRegister(Reg) &&
432 "Can only allocate virtual registers!");
433 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(Reg);
434 // If this is not in a related reg class to the register we're allocating,
436 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
437 cur->overlapsFrom(*i->first, i->second-1)) {
438 Reg = vrm_->getPhys(Reg);
439 prt_->addRegUse(Reg);
440 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
444 // Speculatively check to see if we can get a register right now. If not,
445 // we know we won't be able to by adding more constraints. If so, we can
446 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
447 // is very bad (it contains all callee clobbered registers for any functions
448 // with a call), so we want to avoid doing that if possible.
449 unsigned physReg = getFreePhysReg(cur);
451 // We got a register. However, if it's in the fixed_ list, we might
452 // conflict with it. Check to see if we conflict with it or any of its
454 std::set<unsigned> RegAliases;
455 for (const unsigned *AS = mri_->getAliasSet(physReg); *AS; ++AS)
456 RegAliases.insert(*AS);
458 bool ConflictsWithFixed = false;
459 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
460 IntervalPtr &IP = fixed_[i];
461 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
462 // Okay, this reg is on the fixed list. Check to see if we actually
464 LiveInterval *I = IP.first;
465 if (I->endNumber() > StartPosition) {
466 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
468 if (II != I->begin() && II->start > StartPosition)
470 if (cur->overlapsFrom(*I, II)) {
471 ConflictsWithFixed = true;
478 // Okay, the register picked by our speculative getFreePhysReg call turned
479 // out to be in use. Actually add all of the conflicting fixed registers to
480 // prt so we can do an accurate query.
481 if (ConflictsWithFixed) {
482 // For every interval in fixed we overlap with, mark the register as not
483 // free and update spill weights.
484 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
485 IntervalPtr &IP = fixed_[i];
486 LiveInterval *I = IP.first;
488 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
489 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
490 I->endNumber() > StartPosition) {
491 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
493 if (II != I->begin() && II->start > StartPosition)
495 if (cur->overlapsFrom(*I, II)) {
496 unsigned reg = I->reg;
497 prt_->addRegUse(reg);
498 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
503 // Using the newly updated prt_ object, which includes conflicts in the
504 // future, see if there are any registers available.
505 physReg = getFreePhysReg(cur);
509 // Restore the physical register tracker, removing information about the
513 // if we find a free register, we are done: assign this virtual to
514 // the free physical register and add this interval to the active
517 DOUT << mri_->getName(physReg) << '\n';
518 vrm_->assignVirt2Phys(cur->reg, physReg);
519 prt_->addRegUse(physReg);
520 active_.push_back(std::make_pair(cur, cur->begin()));
521 handled_.push_back(cur);
524 DOUT << "no free registers\n";
526 // Compile the spill weights into an array that is better for scanning.
527 std::vector<float> SpillWeights(mri_->getNumRegs(), 0.0);
528 for (std::vector<std::pair<unsigned, float> >::iterator
529 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
530 updateSpillWeights(SpillWeights, I->first, I->second, mri_);
532 // for each interval in active, update spill weights.
533 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
535 unsigned reg = i->first->reg;
536 assert(MRegisterInfo::isVirtualRegister(reg) &&
537 "Can only allocate virtual registers!");
538 reg = vrm_->getPhys(reg);
539 updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
542 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
544 // Find a register to spill.
545 float minWeight = HUGE_VALF;
547 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
548 e = RC->allocation_order_end(*mf_); i != e; ++i) {
550 if (minWeight > SpillWeights[reg]) {
551 minWeight = SpillWeights[reg];
556 // If we didn't find a register that is spillable, try aliases?
558 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
559 e = RC->allocation_order_end(*mf_); i != e; ++i) {
561 // No need to worry about if the alias register size < regsize of RC.
562 // We are going to spill all registers that alias it anyway.
563 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as) {
564 if (minWeight > SpillWeights[*as]) {
565 minWeight = SpillWeights[*as];
571 // All registers must have inf weight. Just grab one!
573 minReg = *RC->allocation_order_begin(*mf_);
576 DOUT << "\t\tregister with min weight: "
577 << mri_->getName(minReg) << " (" << minWeight << ")\n";
579 // if the current has the minimum weight, we need to spill it and
580 // add any added intervals back to unhandled, and restart
582 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
583 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
584 int slot = vrm_->assignVirt2StackSlot(cur->reg);
585 std::vector<LiveInterval*> added =
586 li_->addIntervalsForSpills(*cur, *vrm_, slot);
588 return; // Early exit if all spills were folded.
590 // Merge added with unhandled. Note that we know that
591 // addIntervalsForSpills returns intervals sorted by their starting
593 for (unsigned i = 0, e = added.size(); i != e; ++i)
594 unhandled_.push(added[i]);
600 // push the current interval back to unhandled since we are going
601 // to re-run at least this iteration. Since we didn't modify it it
602 // should go back right in the front of the list
603 unhandled_.push(cur);
605 // otherwise we spill all intervals aliasing the register with
606 // minimum weight, rollback to the interval with the earliest
607 // start point and let the linear scan algorithm run again
608 std::vector<LiveInterval*> added;
609 assert(MRegisterInfo::isPhysicalRegister(minReg) &&
610 "did not choose a register to spill?");
611 std::vector<bool> toSpill(mri_->getNumRegs(), false);
613 // We are going to spill minReg and all its aliases.
614 toSpill[minReg] = true;
615 for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
618 // the earliest start of a spilled interval indicates up to where
619 // in handled we need to roll back
620 unsigned earliestStart = cur->beginNumber();
622 // set of spilled vregs (used later to rollback properly)
623 std::set<unsigned> spilled;
625 // spill live intervals of virtual regs mapped to the physical register we
626 // want to clear (and its aliases). We only spill those that overlap with the
627 // current interval as the rest do not affect its allocation. we also keep
628 // track of the earliest start of all spilled live intervals since this will
629 // mark our rollback point.
630 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
631 unsigned reg = i->first->reg;
632 if (//MRegisterInfo::isVirtualRegister(reg) &&
633 toSpill[vrm_->getPhys(reg)] &&
634 cur->overlapsFrom(*i->first, i->second)) {
635 DOUT << "\t\t\tspilling(a): " << *i->first << '\n';
636 earliestStart = std::min(earliestStart, i->first->beginNumber());
637 int slot = vrm_->assignVirt2StackSlot(i->first->reg);
638 std::vector<LiveInterval*> newIs =
639 li_->addIntervalsForSpills(*i->first, *vrm_, slot);
640 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
644 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
645 unsigned reg = i->first->reg;
646 if (//MRegisterInfo::isVirtualRegister(reg) &&
647 toSpill[vrm_->getPhys(reg)] &&
648 cur->overlapsFrom(*i->first, i->second-1)) {
649 DOUT << "\t\t\tspilling(i): " << *i->first << '\n';
650 earliestStart = std::min(earliestStart, i->first->beginNumber());
651 int slot = vrm_->assignVirt2StackSlot(reg);
652 std::vector<LiveInterval*> newIs =
653 li_->addIntervalsForSpills(*i->first, *vrm_, slot);
654 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
659 DOUT << "\t\trolling back to: " << earliestStart << '\n';
661 // Scan handled in reverse order up to the earliest start of a
662 // spilled live interval and undo each one, restoring the state of
664 while (!handled_.empty()) {
665 LiveInterval* i = handled_.back();
666 // If this interval starts before t we are done.
667 if (i->beginNumber() < earliestStart)
669 DOUT << "\t\t\tundo changes for: " << *i << '\n';
672 // When undoing a live interval allocation we must know if it is active or
673 // inactive to properly update the PhysRegTracker and the VirtRegMap.
674 IntervalPtrs::iterator it;
675 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
677 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
678 if (!spilled.count(i->reg))
680 prt_->delRegUse(vrm_->getPhys(i->reg));
681 vrm_->clearVirt(i->reg);
682 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
684 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
685 if (!spilled.count(i->reg))
687 vrm_->clearVirt(i->reg);
689 assert(MRegisterInfo::isVirtualRegister(i->reg) &&
690 "Can only allocate virtual registers!");
691 vrm_->clearVirt(i->reg);
696 // Rewind the iterators in the active, inactive, and fixed lists back to the
697 // point we reverted to.
698 RevertVectorIteratorsTo(active_, earliestStart);
699 RevertVectorIteratorsTo(inactive_, earliestStart);
700 RevertVectorIteratorsTo(fixed_, earliestStart);
702 // scan the rest and undo each interval that expired after t and
703 // insert it in active (the next iteration of the algorithm will
704 // put it in inactive if required)
705 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
706 LiveInterval *HI = handled_[i];
707 if (!HI->expiredAt(earliestStart) &&
708 HI->expiredAt(cur->beginNumber())) {
709 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
710 active_.push_back(std::make_pair(HI, HI->begin()));
711 assert(!MRegisterInfo::isPhysicalRegister(HI->reg));
712 prt_->addRegUse(vrm_->getPhys(HI->reg));
716 // merge added with unhandled
717 for (unsigned i = 0, e = added.size(); i != e; ++i)
718 unhandled_.push(added[i]);
721 /// getFreePhysReg - return a free physical register for this virtual register
722 /// interval if we have one, otherwise return 0.
723 unsigned RA::getFreePhysReg(LiveInterval *cur) {
724 std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
725 unsigned MaxInactiveCount = 0;
727 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
728 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
730 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
732 unsigned reg = i->first->reg;
733 assert(MRegisterInfo::isVirtualRegister(reg) &&
734 "Can only allocate virtual registers!");
736 // If this is not in a related reg class to the register we're allocating,
738 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(reg);
739 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
740 reg = vrm_->getPhys(reg);
741 ++inactiveCounts[reg];
742 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
746 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
748 unsigned FreeReg = 0;
749 unsigned FreeRegInactiveCount = 0;
751 // Scan for the first available register.
752 TargetRegisterClass::iterator I = rc->allocation_order_begin(*mf_);
753 TargetRegisterClass::iterator E = rc->allocation_order_end(*mf_);
755 if (prt_->isRegAvail(*I)) {
757 FreeRegInactiveCount = inactiveCounts[FreeReg];
761 // If there are no free regs, or if this reg has the max inactive count,
762 // return this register.
763 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
765 // Continue scanning the registers, looking for the one with the highest
766 // inactive count. Alkis found that this reduced register pressure very
767 // slightly on X86 (in rev 1.94 of this file), though this should probably be
769 for (; I != E; ++I) {
771 if (prt_->isRegAvail(Reg) && FreeRegInactiveCount < inactiveCounts[Reg]) {
773 FreeRegInactiveCount = inactiveCounts[Reg];
774 if (FreeRegInactiveCount == MaxInactiveCount)
775 break; // We found the one with the max inactive count.
782 FunctionPass* llvm::createLinearScanRegisterAllocator() {