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 "LiveIntervalAnalysis.h"
16 #include "PhysRegTracker.h"
17 #include "VirtRegMap.h"
18 #include "llvm/Function.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/CodeGen/SSARegMap.h"
23 #include "llvm/Target/MRegisterInfo.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/ADT/EquivalenceClasses.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/Support/Debug.h"
37 Statistic<double> efficiency
38 ("regalloc", "Ratio of intervals processed over total intervals");
39 Statistic<> NumBacktracks("regalloc", "Number of times we had to backtrack");
41 static unsigned numIterations = 0;
42 static unsigned numIntervals = 0;
44 struct RA : public MachineFunctionPass {
45 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
46 typedef std::vector<IntervalPtr> IntervalPtrs;
48 /// RelatedRegClasses - This structure is built the first time a function is
49 /// compiled, and keeps track of which register classes have registers that
50 /// belong to multiple classes or have aliases that are in other classes.
51 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
52 std::map<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
55 const TargetMachine* tm_;
56 const MRegisterInfo* mri_;
60 /// handled_ - Intervals are added to the handled_ set in the order of their
61 /// start value. This is uses for backtracking.
62 std::vector<LiveInterval*> handled_;
64 /// fixed_ - Intervals that correspond to machine registers.
68 /// active_ - Intervals that are currently being processed, and which have a
69 /// live range active for the current point.
72 /// inactive_ - Intervals that are currently being processed, but which have
73 /// a hold at the current point.
74 IntervalPtrs inactive_;
76 typedef std::priority_queue<LiveInterval*,
77 std::vector<LiveInterval*>,
78 greater_ptr<LiveInterval> > IntervalHeap;
79 IntervalHeap unhandled_;
80 std::auto_ptr<PhysRegTracker> prt_;
81 std::auto_ptr<VirtRegMap> vrm_;
82 std::auto_ptr<Spiller> spiller_;
85 virtual const char* getPassName() const {
86 return "Linear Scan Register Allocator";
89 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
90 AU.addRequired<LiveIntervals>();
91 MachineFunctionPass::getAnalysisUsage(AU);
94 /// runOnMachineFunction - register allocate the whole function
95 bool runOnMachineFunction(MachineFunction&);
98 /// linearScan - the linear scan algorithm
101 /// initIntervalSets - initialize the interval sets.
103 void initIntervalSets();
105 /// processActiveIntervals - expire old intervals and move non-overlapping
106 /// ones to the inactive list.
107 void processActiveIntervals(unsigned CurPoint);
109 /// processInactiveIntervals - expire old intervals and move overlapping
110 /// ones to the active list.
111 void processInactiveIntervals(unsigned CurPoint);
113 /// assignRegOrStackSlotAtInterval - assign a register if one
114 /// is available, or spill.
115 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
118 /// register handling helpers
121 /// getFreePhysReg - return a free physical register for this virtual
122 /// register interval if we have one, otherwise return 0.
123 unsigned getFreePhysReg(LiveInterval* cur);
125 /// assignVirt2StackSlot - assigns this virtual register to a
126 /// stack slot. returns the stack slot
127 int assignVirt2StackSlot(unsigned virtReg);
129 void ComputeRelatedRegClasses();
131 template <typename ItTy>
132 void printIntervals(const char* const str, ItTy i, ItTy e) const {
133 if (str) std::cerr << str << " intervals:\n";
134 for (; i != e; ++i) {
135 std::cerr << "\t" << *i->first << " -> ";
136 unsigned reg = i->first->reg;
137 if (MRegisterInfo::isVirtualRegister(reg)) {
138 reg = vrm_->getPhys(reg);
140 std::cerr << mri_->getName(reg) << '\n';
146 void RA::ComputeRelatedRegClasses() {
147 const MRegisterInfo &MRI = *mri_;
149 // First pass, add all reg classes to the union, and determine at least one
150 // reg class that each register is in.
151 bool HasAliases = false;
152 for (MRegisterInfo::regclass_iterator RCI = MRI.regclass_begin(),
153 E = MRI.regclass_end(); RCI != E; ++RCI) {
154 RelatedRegClasses.insert(*RCI);
155 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
157 HasAliases = HasAliases || *MRI.getAliasSet(*I) != 0;
159 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
161 // Already processed this register. Just make sure we know that
162 // multiple register classes share a register.
163 RelatedRegClasses.unionSets(PRC, *RCI);
170 // Second pass, now that we know conservatively what register classes each reg
171 // belongs to, add info about aliases. We don't need to do this for targets
172 // without register aliases.
174 for (std::map<unsigned, const TargetRegisterClass*>::iterator
175 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
177 for (const unsigned *AS = MRI.getAliasSet(I->first); *AS; ++AS)
178 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
181 bool RA::runOnMachineFunction(MachineFunction &fn) {
183 tm_ = &fn.getTarget();
184 mri_ = tm_->getRegisterInfo();
185 li_ = &getAnalysis<LiveIntervals>();
187 // If this is the first function compiled, compute the related reg classes.
188 if (RelatedRegClasses.empty())
189 ComputeRelatedRegClasses();
191 PhysRegsUsed = new bool[mri_->getNumRegs()];
192 std::fill(PhysRegsUsed, PhysRegsUsed+mri_->getNumRegs(), false);
193 fn.setUsedPhysRegs(PhysRegsUsed);
195 if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
196 vrm_.reset(new VirtRegMap(*mf_));
197 if (!spiller_.get()) spiller_.reset(createSpiller());
203 // Rewrite spill code and update the PhysRegsUsed set.
204 spiller_->runOnMachineFunction(*mf_, *vrm_);
206 vrm_.reset(); // Free the VirtRegMap
209 while (!unhandled_.empty()) unhandled_.pop();
218 /// initIntervalSets - initialize the interval sets.
220 void RA::initIntervalSets()
222 assert(unhandled_.empty() && fixed_.empty() &&
223 active_.empty() && inactive_.empty() &&
224 "interval sets should be empty on initialization");
226 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
227 if (MRegisterInfo::isPhysicalRegister(i->second.reg)) {
228 PhysRegsUsed[i->second.reg] = true;
229 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
231 unhandled_.push(&i->second);
235 void RA::linearScan()
237 // linear scan algorithm
238 DEBUG(std::cerr << "********** LINEAR SCAN **********\n");
239 DEBUG(std::cerr << "********** Function: "
240 << mf_->getFunction()->getName() << '\n');
242 // DEBUG(printIntervals("unhandled", unhandled_.begin(), unhandled_.end()));
243 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
244 DEBUG(printIntervals("active", active_.begin(), active_.end()));
245 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
247 while (!unhandled_.empty()) {
248 // pick the interval with the earliest start point
249 LiveInterval* cur = unhandled_.top();
252 DEBUG(std::cerr << "\n*** CURRENT ***: " << *cur << '\n');
254 processActiveIntervals(cur->beginNumber());
255 processInactiveIntervals(cur->beginNumber());
257 assert(MRegisterInfo::isVirtualRegister(cur->reg) &&
258 "Can only allocate virtual registers!");
260 // Allocating a virtual register. try to find a free
261 // physical register or spill an interval (possibly this one) in order to
263 assignRegOrStackSlotAtInterval(cur);
265 DEBUG(printIntervals("active", active_.begin(), active_.end()));
266 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
268 numIntervals += li_->getNumIntervals();
269 efficiency = double(numIterations) / double(numIntervals);
271 // expire any remaining active intervals
272 for (IntervalPtrs::reverse_iterator
273 i = active_.rbegin(); i != active_.rend(); ) {
274 unsigned reg = i->first->reg;
275 DEBUG(std::cerr << "\tinterval " << *i->first << " expired\n");
276 assert(MRegisterInfo::isVirtualRegister(reg) &&
277 "Can only allocate virtual registers!");
278 reg = vrm_->getPhys(reg);
279 prt_->delRegUse(reg);
280 i = IntervalPtrs::reverse_iterator(active_.erase(i.base()-1));
283 // expire any remaining inactive intervals
284 for (IntervalPtrs::reverse_iterator
285 i = inactive_.rbegin(); i != inactive_.rend(); ) {
286 DEBUG(std::cerr << "\tinterval " << *i->first << " expired\n");
287 i = IntervalPtrs::reverse_iterator(inactive_.erase(i.base()-1));
290 DEBUG(std::cerr << *vrm_);
293 /// processActiveIntervals - expire old intervals and move non-overlapping ones
294 /// to the inactive list.
295 void RA::processActiveIntervals(unsigned CurPoint)
297 DEBUG(std::cerr << "\tprocessing active intervals:\n");
299 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
300 LiveInterval *Interval = active_[i].first;
301 LiveInterval::iterator IntervalPos = active_[i].second;
302 unsigned reg = Interval->reg;
304 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
306 if (IntervalPos == Interval->end()) { // Remove expired intervals.
307 DEBUG(std::cerr << "\t\tinterval " << *Interval << " expired\n");
308 assert(MRegisterInfo::isVirtualRegister(reg) &&
309 "Can only allocate virtual registers!");
310 reg = vrm_->getPhys(reg);
311 prt_->delRegUse(reg);
313 // Pop off the end of the list.
314 active_[i] = active_.back();
318 } else if (IntervalPos->start > CurPoint) {
319 // Move inactive intervals to inactive list.
320 DEBUG(std::cerr << "\t\tinterval " << *Interval << " inactive\n");
321 assert(MRegisterInfo::isVirtualRegister(reg) &&
322 "Can only allocate virtual registers!");
323 reg = vrm_->getPhys(reg);
324 prt_->delRegUse(reg);
326 inactive_.push_back(std::make_pair(Interval, IntervalPos));
328 // Pop off the end of the list.
329 active_[i] = active_.back();
333 // Otherwise, just update the iterator position.
334 active_[i].second = IntervalPos;
339 /// processInactiveIntervals - expire old intervals and move overlapping
340 /// ones to the active list.
341 void RA::processInactiveIntervals(unsigned CurPoint)
343 DEBUG(std::cerr << "\tprocessing inactive intervals:\n");
345 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
346 LiveInterval *Interval = inactive_[i].first;
347 LiveInterval::iterator IntervalPos = inactive_[i].second;
348 unsigned reg = Interval->reg;
350 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
352 if (IntervalPos == Interval->end()) { // remove expired intervals.
353 DEBUG(std::cerr << "\t\tinterval " << *Interval << " expired\n");
355 // Pop off the end of the list.
356 inactive_[i] = inactive_.back();
357 inactive_.pop_back();
359 } else if (IntervalPos->start <= CurPoint) {
360 // move re-activated intervals in active list
361 DEBUG(std::cerr << "\t\tinterval " << *Interval << " active\n");
362 assert(MRegisterInfo::isVirtualRegister(reg) &&
363 "Can only allocate virtual registers!");
364 reg = vrm_->getPhys(reg);
365 prt_->addRegUse(reg);
367 active_.push_back(std::make_pair(Interval, IntervalPos));
369 // Pop off the end of the list.
370 inactive_[i] = inactive_.back();
371 inactive_.pop_back();
374 // Otherwise, just update the iterator position.
375 inactive_[i].second = IntervalPos;
380 /// updateSpillWeights - updates the spill weights of the specifed physical
381 /// register and its weight.
382 static void updateSpillWeights(std::vector<float> &Weights,
383 unsigned reg, float weight,
384 const MRegisterInfo *MRI) {
385 Weights[reg] += weight;
386 for (const unsigned* as = MRI->getAliasSet(reg); *as; ++as)
387 Weights[*as] += weight;
390 static RA::IntervalPtrs::iterator FindIntervalInVector(RA::IntervalPtrs &IP,
392 for (RA::IntervalPtrs::iterator I = IP.begin(), E = IP.end(); I != E; ++I)
393 if (I->first == LI) return I;
397 static void RevertVectorIteratorsTo(RA::IntervalPtrs &V, unsigned Point) {
398 for (unsigned i = 0, e = V.size(); i != e; ++i) {
399 RA::IntervalPtr &IP = V[i];
400 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
402 if (I != IP.first->begin()) --I;
408 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
410 void RA::assignRegOrStackSlotAtInterval(LiveInterval* cur)
412 DEBUG(std::cerr << "\tallocating current interval: ");
414 PhysRegTracker backupPrt = *prt_;
416 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
417 unsigned StartPosition = cur->beginNumber();
418 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
419 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
421 // for every interval in inactive we overlap with, mark the
422 // register as not free and update spill weights.
423 for (IntervalPtrs::const_iterator i = inactive_.begin(),
424 e = inactive_.end(); i != e; ++i) {
425 unsigned Reg = i->first->reg;
426 assert(MRegisterInfo::isVirtualRegister(Reg) &&
427 "Can only allocate virtual registers!");
428 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(Reg);
429 // If this is not in a related reg class to the register we're allocating,
431 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
432 cur->overlapsFrom(*i->first, i->second-1)) {
433 Reg = vrm_->getPhys(Reg);
434 prt_->addRegUse(Reg);
435 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
439 // Speculatively check to see if we can get a register right now. If not,
440 // we know we won't be able to by adding more constraints. If so, we can
441 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
442 // is very bad (it contains all callee clobbered registers for any functions
443 // with a call), so we want to avoid doing that if possible.
444 unsigned physReg = getFreePhysReg(cur);
446 // We got a register. However, if it's in the fixed_ list, we might
447 // conflict with it. Check to see if we conflict with it.
448 bool ConflictsWithFixed = false;
449 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
450 if (physReg == fixed_[i].first->reg) {
451 // Okay, this reg is on the fixed list. Check to see if we actually
453 IntervalPtr &IP = fixed_[i];
454 LiveInterval *I = IP.first;
455 if (I->endNumber() > StartPosition) {
456 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
458 if (II != I->begin() && II->start > StartPosition)
460 if (cur->overlapsFrom(*I, II))
461 ConflictsWithFixed = true;
468 // Okay, the register picked by our speculative getFreePhysReg call turned
469 // out to be in use. Actually add all of the conflicting fixed registers to
470 // prt so we can do an accurate query.
471 if (ConflictsWithFixed) {
472 // For every interval in fixed we overlap with, mark the register as not
473 // free and update spill weights.
474 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
475 IntervalPtr &IP = fixed_[i];
476 LiveInterval *I = IP.first;
478 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
479 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
480 I->endNumber() > StartPosition) {
481 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
483 if (II != I->begin() && II->start > StartPosition)
485 if (cur->overlapsFrom(*I, II)) {
486 unsigned reg = I->reg;
487 prt_->addRegUse(reg);
488 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
493 // Using the newly updated prt_ object, which includes conflicts in the
494 // future, see if there are any registers available.
495 physReg = getFreePhysReg(cur);
499 // Restore the physical register tracker, removing information about the
503 // if we find a free register, we are done: assign this virtual to
504 // the free physical register and add this interval to the active
507 DEBUG(std::cerr << mri_->getName(physReg) << '\n');
508 vrm_->assignVirt2Phys(cur->reg, physReg);
509 prt_->addRegUse(physReg);
510 active_.push_back(std::make_pair(cur, cur->begin()));
511 handled_.push_back(cur);
514 DEBUG(std::cerr << "no free registers\n");
516 // Compile the spill weights into an array that is better for scanning.
517 std::vector<float> SpillWeights(mri_->getNumRegs(), 0.0);
518 for (std::vector<std::pair<unsigned, float> >::iterator
519 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
520 updateSpillWeights(SpillWeights, I->first, I->second, mri_);
522 // for each interval in active, update spill weights.
523 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
525 unsigned reg = i->first->reg;
526 assert(MRegisterInfo::isVirtualRegister(reg) &&
527 "Can only allocate virtual registers!");
528 reg = vrm_->getPhys(reg);
529 updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
532 DEBUG(std::cerr << "\tassigning stack slot at interval "<< *cur << ":\n");
534 float minWeight = float(HUGE_VAL);
536 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
537 e = RC->allocation_order_end(*mf_); i != e; ++i) {
539 if (minWeight > SpillWeights[reg]) {
540 minWeight = SpillWeights[reg];
544 DEBUG(std::cerr << "\t\tregister with min weight: "
545 << mri_->getName(minReg) << " (" << minWeight << ")\n");
547 // if the current has the minimum weight, we need to spill it and
548 // add any added intervals back to unhandled, and restart
550 if (cur->weight <= minWeight) {
551 DEBUG(std::cerr << "\t\t\tspilling(c): " << *cur << '\n';);
552 int slot = vrm_->assignVirt2StackSlot(cur->reg);
553 std::vector<LiveInterval*> added =
554 li_->addIntervalsForSpills(*cur, *vrm_, slot);
556 return; // Early exit if all spills were folded.
558 // Merge added with unhandled. Note that we know that
559 // addIntervalsForSpills returns intervals sorted by their starting
561 for (unsigned i = 0, e = added.size(); i != e; ++i)
562 unhandled_.push(added[i]);
568 // push the current interval back to unhandled since we are going
569 // to re-run at least this iteration. Since we didn't modify it it
570 // should go back right in the front of the list
571 unhandled_.push(cur);
573 // otherwise we spill all intervals aliasing the register with
574 // minimum weight, rollback to the interval with the earliest
575 // start point and let the linear scan algorithm run again
576 std::vector<LiveInterval*> added;
577 assert(MRegisterInfo::isPhysicalRegister(minReg) &&
578 "did not choose a register to spill?");
579 std::vector<bool> toSpill(mri_->getNumRegs(), false);
581 // We are going to spill minReg and all its aliases.
582 toSpill[minReg] = true;
583 for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
586 // the earliest start of a spilled interval indicates up to where
587 // in handled we need to roll back
588 unsigned earliestStart = cur->beginNumber();
590 // set of spilled vregs (used later to rollback properly)
591 std::set<unsigned> spilled;
593 // spill live intervals of virtual regs mapped to the physical register we
594 // want to clear (and its aliases). We only spill those that overlap with the
595 // current interval as the rest do not affect its allocation. we also keep
596 // track of the earliest start of all spilled live intervals since this will
597 // mark our rollback point.
598 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
599 unsigned reg = i->first->reg;
600 if (//MRegisterInfo::isVirtualRegister(reg) &&
601 toSpill[vrm_->getPhys(reg)] &&
602 cur->overlapsFrom(*i->first, i->second)) {
603 DEBUG(std::cerr << "\t\t\tspilling(a): " << *i->first << '\n');
604 earliestStart = std::min(earliestStart, i->first->beginNumber());
605 int slot = vrm_->assignVirt2StackSlot(i->first->reg);
606 std::vector<LiveInterval*> newIs =
607 li_->addIntervalsForSpills(*i->first, *vrm_, slot);
608 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
612 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
613 unsigned reg = i->first->reg;
614 if (//MRegisterInfo::isVirtualRegister(reg) &&
615 toSpill[vrm_->getPhys(reg)] &&
616 cur->overlapsFrom(*i->first, i->second-1)) {
617 DEBUG(std::cerr << "\t\t\tspilling(i): " << *i->first << '\n');
618 earliestStart = std::min(earliestStart, i->first->beginNumber());
619 int slot = vrm_->assignVirt2StackSlot(reg);
620 std::vector<LiveInterval*> newIs =
621 li_->addIntervalsForSpills(*i->first, *vrm_, slot);
622 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
627 DEBUG(std::cerr << "\t\trolling back to: " << earliestStart << '\n');
629 // Scan handled in reverse order up to the earliest start of a
630 // spilled live interval and undo each one, restoring the state of
632 while (!handled_.empty()) {
633 LiveInterval* i = handled_.back();
634 // If this interval starts before t we are done.
635 if (i->beginNumber() < earliestStart)
637 DEBUG(std::cerr << "\t\t\tundo changes for: " << *i << '\n');
640 // When undoing a live interval allocation we must know if it is active or
641 // inactive to properly update the PhysRegTracker and the VirtRegMap.
642 IntervalPtrs::iterator it;
643 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
645 if (MRegisterInfo::isPhysicalRegister(i->reg)) {
646 assert(0 && "daksjlfd");
647 prt_->delRegUse(i->reg);
650 if (!spilled.count(i->reg))
652 prt_->delRegUse(vrm_->getPhys(i->reg));
653 vrm_->clearVirt(i->reg);
655 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
657 if (MRegisterInfo::isPhysicalRegister(i->reg)) {
658 assert(0 && "daksjlfd");
661 if (!spilled.count(i->reg))
663 vrm_->clearVirt(i->reg);
666 assert(MRegisterInfo::isVirtualRegister(i->reg) &&
667 "Can only allocate virtual registers!");
668 vrm_->clearVirt(i->reg);
673 // Rewind the iterators in the active, inactive, and fixed lists back to the
674 // point we reverted to.
675 RevertVectorIteratorsTo(active_, earliestStart);
676 RevertVectorIteratorsTo(inactive_, earliestStart);
677 RevertVectorIteratorsTo(fixed_, earliestStart);
679 // scan the rest and undo each interval that expired after t and
680 // insert it in active (the next iteration of the algorithm will
681 // put it in inactive if required)
682 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
683 LiveInterval *HI = handled_[i];
684 if (!HI->expiredAt(earliestStart) &&
685 HI->expiredAt(cur->beginNumber())) {
686 DEBUG(std::cerr << "\t\t\tundo changes for: " << *HI << '\n');
687 active_.push_back(std::make_pair(HI, HI->begin()));
688 if (MRegisterInfo::isPhysicalRegister(HI->reg)) {
689 assert(0 &&"sdflkajsdf");
690 prt_->addRegUse(HI->reg);
692 prt_->addRegUse(vrm_->getPhys(HI->reg));
696 // merge added with unhandled
697 for (unsigned i = 0, e = added.size(); i != e; ++i)
698 unhandled_.push(added[i]);
701 /// getFreePhysReg - return a free physical register for this virtual register
702 /// interval if we have one, otherwise return 0.
703 unsigned RA::getFreePhysReg(LiveInterval* cur)
705 std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
706 unsigned MaxInactiveCount = 0;
708 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
709 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
711 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
713 unsigned reg = i->first->reg;
714 assert(MRegisterInfo::isVirtualRegister(reg) &&
715 "Can only allocate virtual registers!");
717 // If this is not in a related reg class to the register we're allocating,
719 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(reg);
720 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
721 reg = vrm_->getPhys(reg);
722 ++inactiveCounts[reg];
723 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
727 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
729 unsigned FreeReg = 0;
730 unsigned FreeRegInactiveCount = 0;
732 // Scan for the first available register.
733 TargetRegisterClass::iterator I = rc->allocation_order_begin(*mf_);
734 TargetRegisterClass::iterator E = rc->allocation_order_end(*mf_);
736 if (prt_->isRegAvail(*I)) {
738 FreeRegInactiveCount = inactiveCounts[FreeReg];
742 // If there are no free regs, or if this reg has the max inactive count,
743 // return this register.
744 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
746 // Continue scanning the registers, looking for the one with the highest
747 // inactive count. Alkis found that this reduced register pressure very
748 // slightly on X86 (in rev 1.94 of this file), though this should probably be
750 for (; I != E; ++I) {
752 if (prt_->isRegAvail(Reg) && FreeRegInactiveCount < inactiveCounts[Reg]) {
754 FreeRegInactiveCount = inactiveCounts[Reg];
755 if (FreeRegInactiveCount == MaxInactiveCount)
756 break; // We found the one with the max inactive count.
763 FunctionPass* llvm::createLinearScanRegisterAllocator() {