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"
41 static Statistic<double> efficiency
42 ("regalloc", "Ratio of intervals processed over total intervals");
43 static Statistic<> NumBacktracks
44 ("regalloc", "Number of times we had to backtrack");
46 static RegisterRegAlloc
47 linearscanRegAlloc("linearscan", " linear scan register allocator",
48 createLinearScanRegisterAllocator);
50 static unsigned numIterations = 0;
51 static unsigned numIntervals = 0;
53 struct VISIBILITY_HIDDEN RA : public MachineFunctionPass {
54 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
55 typedef std::vector<IntervalPtr> IntervalPtrs;
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;
64 const TargetMachine* tm_;
65 const MRegisterInfo* mri_;
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_;
73 /// fixed_ - Intervals that correspond to machine registers.
77 /// active_ - Intervals that are currently being processed, and which have a
78 /// live range active for the current point.
81 /// inactive_ - Intervals that are currently being processed, but which have
82 /// a hold at the current point.
83 IntervalPtrs inactive_;
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_;
94 virtual const char* getPassName() const {
95 return "Linear Scan Register Allocator";
98 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
99 AU.addRequired<LiveIntervals>();
100 MachineFunctionPass::getAnalysisUsage(AU);
103 /// runOnMachineFunction - register allocate the whole function
104 bool runOnMachineFunction(MachineFunction&);
107 /// linearScan - the linear scan algorithm
110 /// initIntervalSets - initialize the interval sets.
112 void initIntervalSets();
114 /// processActiveIntervals - expire old intervals and move non-overlapping
115 /// ones to the inactive list.
116 void processActiveIntervals(unsigned CurPoint);
118 /// processInactiveIntervals - expire old intervals and move overlapping
119 /// ones to the active list.
120 void processInactiveIntervals(unsigned CurPoint);
122 /// assignRegOrStackSlotAtInterval - assign a register if one
123 /// is available, or spill.
124 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
127 /// register handling helpers
130 /// getFreePhysReg - return a free physical register for this virtual
131 /// register interval if we have one, otherwise return 0.
132 unsigned getFreePhysReg(LiveInterval* cur);
134 /// assignVirt2StackSlot - assigns this virtual register to a
135 /// stack slot. returns the stack slot
136 int assignVirt2StackSlot(unsigned virtReg);
138 void ComputeRelatedRegClasses();
140 template <typename ItTy>
141 void printIntervals(const char* const str, ItTy i, ItTy e) const {
142 if (str) std::cerr << str << " intervals:\n";
143 for (; i != e; ++i) {
144 std::cerr << "\t" << *i->first << " -> ";
145 unsigned reg = i->first->reg;
146 if (MRegisterInfo::isVirtualRegister(reg)) {
147 reg = vrm_->getPhys(reg);
149 std::cerr << mri_->getName(reg) << '\n';
155 void RA::ComputeRelatedRegClasses() {
156 const MRegisterInfo &MRI = *mri_;
158 // First pass, add all reg classes to the union, and determine at least one
159 // reg class that each register is in.
160 bool HasAliases = false;
161 for (MRegisterInfo::regclass_iterator RCI = MRI.regclass_begin(),
162 E = MRI.regclass_end(); RCI != E; ++RCI) {
163 RelatedRegClasses.insert(*RCI);
164 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
166 HasAliases = HasAliases || *MRI.getAliasSet(*I) != 0;
168 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
170 // Already processed this register. Just make sure we know that
171 // multiple register classes share a register.
172 RelatedRegClasses.unionSets(PRC, *RCI);
179 // Second pass, now that we know conservatively what register classes each reg
180 // belongs to, add info about aliases. We don't need to do this for targets
181 // without register aliases.
183 for (std::map<unsigned, const TargetRegisterClass*>::iterator
184 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
186 for (const unsigned *AS = MRI.getAliasSet(I->first); *AS; ++AS)
187 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
190 bool RA::runOnMachineFunction(MachineFunction &fn) {
192 tm_ = &fn.getTarget();
193 mri_ = tm_->getRegisterInfo();
194 li_ = &getAnalysis<LiveIntervals>();
196 // If this is the first function compiled, compute the related reg classes.
197 if (RelatedRegClasses.empty())
198 ComputeRelatedRegClasses();
200 PhysRegsUsed = new bool[mri_->getNumRegs()];
201 std::fill(PhysRegsUsed, PhysRegsUsed+mri_->getNumRegs(), false);
202 fn.setUsedPhysRegs(PhysRegsUsed);
204 if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
205 vrm_.reset(new VirtRegMap(*mf_));
206 if (!spiller_.get()) spiller_.reset(createSpiller());
212 // Rewrite spill code and update the PhysRegsUsed set.
213 spiller_->runOnMachineFunction(*mf_, *vrm_);
215 vrm_.reset(); // Free the VirtRegMap
218 while (!unhandled_.empty()) unhandled_.pop();
227 /// initIntervalSets - initialize the interval sets.
229 void RA::initIntervalSets()
231 assert(unhandled_.empty() && fixed_.empty() &&
232 active_.empty() && inactive_.empty() &&
233 "interval sets should be empty on initialization");
235 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
236 if (MRegisterInfo::isPhysicalRegister(i->second.reg)) {
237 PhysRegsUsed[i->second.reg] = true;
238 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
240 unhandled_.push(&i->second);
244 void RA::linearScan()
246 // linear scan algorithm
247 DEBUG(std::cerr << "********** LINEAR SCAN **********\n");
248 DEBUG(std::cerr << "********** Function: "
249 << mf_->getFunction()->getName() << '\n');
251 // DEBUG(printIntervals("unhandled", unhandled_.begin(), unhandled_.end()));
252 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
253 DEBUG(printIntervals("active", active_.begin(), active_.end()));
254 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
256 while (!unhandled_.empty()) {
257 // pick the interval with the earliest start point
258 LiveInterval* cur = unhandled_.top();
261 DEBUG(std::cerr << "\n*** CURRENT ***: " << *cur << '\n');
263 processActiveIntervals(cur->beginNumber());
264 processInactiveIntervals(cur->beginNumber());
266 assert(MRegisterInfo::isVirtualRegister(cur->reg) &&
267 "Can only allocate virtual registers!");
269 // Allocating a virtual register. try to find a free
270 // physical register or spill an interval (possibly this one) in order to
272 assignRegOrStackSlotAtInterval(cur);
274 DEBUG(printIntervals("active", active_.begin(), active_.end()));
275 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
277 numIntervals += li_->getNumIntervals();
278 efficiency = double(numIterations) / double(numIntervals);
280 // expire any remaining active intervals
281 for (IntervalPtrs::reverse_iterator
282 i = active_.rbegin(); i != active_.rend(); ) {
283 unsigned reg = i->first->reg;
284 DEBUG(std::cerr << "\tinterval " << *i->first << " expired\n");
285 assert(MRegisterInfo::isVirtualRegister(reg) &&
286 "Can only allocate virtual registers!");
287 reg = vrm_->getPhys(reg);
288 prt_->delRegUse(reg);
289 i = IntervalPtrs::reverse_iterator(active_.erase(i.base()-1));
292 // expire any remaining inactive intervals
293 for (IntervalPtrs::reverse_iterator
294 i = inactive_.rbegin(); i != inactive_.rend(); ) {
295 DEBUG(std::cerr << "\tinterval " << *i->first << " expired\n");
296 i = IntervalPtrs::reverse_iterator(inactive_.erase(i.base()-1));
299 DEBUG(std::cerr << *vrm_);
302 /// processActiveIntervals - expire old intervals and move non-overlapping ones
303 /// to the inactive list.
304 void RA::processActiveIntervals(unsigned CurPoint)
306 DEBUG(std::cerr << "\tprocessing active intervals:\n");
308 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
309 LiveInterval *Interval = active_[i].first;
310 LiveInterval::iterator IntervalPos = active_[i].second;
311 unsigned reg = Interval->reg;
313 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
315 if (IntervalPos == Interval->end()) { // Remove expired intervals.
316 DEBUG(std::cerr << "\t\tinterval " << *Interval << " expired\n");
317 assert(MRegisterInfo::isVirtualRegister(reg) &&
318 "Can only allocate virtual registers!");
319 reg = vrm_->getPhys(reg);
320 prt_->delRegUse(reg);
322 // Pop off the end of the list.
323 active_[i] = active_.back();
327 } else if (IntervalPos->start > CurPoint) {
328 // Move inactive intervals to inactive list.
329 DEBUG(std::cerr << "\t\tinterval " << *Interval << " inactive\n");
330 assert(MRegisterInfo::isVirtualRegister(reg) &&
331 "Can only allocate virtual registers!");
332 reg = vrm_->getPhys(reg);
333 prt_->delRegUse(reg);
335 inactive_.push_back(std::make_pair(Interval, IntervalPos));
337 // Pop off the end of the list.
338 active_[i] = active_.back();
342 // Otherwise, just update the iterator position.
343 active_[i].second = IntervalPos;
348 /// processInactiveIntervals - expire old intervals and move overlapping
349 /// ones to the active list.
350 void RA::processInactiveIntervals(unsigned CurPoint)
352 DEBUG(std::cerr << "\tprocessing inactive intervals:\n");
354 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
355 LiveInterval *Interval = inactive_[i].first;
356 LiveInterval::iterator IntervalPos = inactive_[i].second;
357 unsigned reg = Interval->reg;
359 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
361 if (IntervalPos == Interval->end()) { // remove expired intervals.
362 DEBUG(std::cerr << "\t\tinterval " << *Interval << " expired\n");
364 // Pop off the end of the list.
365 inactive_[i] = inactive_.back();
366 inactive_.pop_back();
368 } else if (IntervalPos->start <= CurPoint) {
369 // move re-activated intervals in active list
370 DEBUG(std::cerr << "\t\tinterval " << *Interval << " active\n");
371 assert(MRegisterInfo::isVirtualRegister(reg) &&
372 "Can only allocate virtual registers!");
373 reg = vrm_->getPhys(reg);
374 prt_->addRegUse(reg);
376 active_.push_back(std::make_pair(Interval, IntervalPos));
378 // Pop off the end of the list.
379 inactive_[i] = inactive_.back();
380 inactive_.pop_back();
383 // Otherwise, just update the iterator position.
384 inactive_[i].second = IntervalPos;
389 /// updateSpillWeights - updates the spill weights of the specifed physical
390 /// register and its weight.
391 static void updateSpillWeights(std::vector<float> &Weights,
392 unsigned reg, float weight,
393 const MRegisterInfo *MRI) {
394 Weights[reg] += weight;
395 for (const unsigned* as = MRI->getAliasSet(reg); *as; ++as)
396 Weights[*as] += weight;
399 static RA::IntervalPtrs::iterator FindIntervalInVector(RA::IntervalPtrs &IP,
401 for (RA::IntervalPtrs::iterator I = IP.begin(), E = IP.end(); I != E; ++I)
402 if (I->first == LI) return I;
406 static void RevertVectorIteratorsTo(RA::IntervalPtrs &V, unsigned Point) {
407 for (unsigned i = 0, e = V.size(); i != e; ++i) {
408 RA::IntervalPtr &IP = V[i];
409 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
411 if (I != IP.first->begin()) --I;
416 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
418 void RA::assignRegOrStackSlotAtInterval(LiveInterval* cur)
420 DEBUG(std::cerr << "\tallocating current interval: ");
422 PhysRegTracker backupPrt = *prt_;
424 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
425 unsigned StartPosition = cur->beginNumber();
426 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
427 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
429 // for every interval in inactive we overlap with, mark the
430 // register as not free and update spill weights.
431 for (IntervalPtrs::const_iterator i = inactive_.begin(),
432 e = inactive_.end(); i != e; ++i) {
433 unsigned Reg = i->first->reg;
434 assert(MRegisterInfo::isVirtualRegister(Reg) &&
435 "Can only allocate virtual registers!");
436 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(Reg);
437 // If this is not in a related reg class to the register we're allocating,
439 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
440 cur->overlapsFrom(*i->first, i->second-1)) {
441 Reg = vrm_->getPhys(Reg);
442 prt_->addRegUse(Reg);
443 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
447 // Speculatively check to see if we can get a register right now. If not,
448 // we know we won't be able to by adding more constraints. If so, we can
449 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
450 // is very bad (it contains all callee clobbered registers for any functions
451 // with a call), so we want to avoid doing that if possible.
452 unsigned physReg = getFreePhysReg(cur);
454 // We got a register. However, if it's in the fixed_ list, we might
455 // conflict with it. Check to see if we conflict with it or any of its
457 std::set<unsigned> RegAliases;
458 for (const unsigned *AS = mri_->getAliasSet(physReg); *AS; ++AS)
459 RegAliases.insert(*AS);
461 bool ConflictsWithFixed = false;
462 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
463 IntervalPtr &IP = fixed_[i];
464 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
465 // Okay, this reg is on the fixed list. Check to see if we actually
467 LiveInterval *I = IP.first;
468 if (I->endNumber() > StartPosition) {
469 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
471 if (II != I->begin() && II->start > StartPosition)
473 if (cur->overlapsFrom(*I, II)) {
474 ConflictsWithFixed = true;
481 // Okay, the register picked by our speculative getFreePhysReg call turned
482 // out to be in use. Actually add all of the conflicting fixed registers to
483 // prt so we can do an accurate query.
484 if (ConflictsWithFixed) {
485 // For every interval in fixed we overlap with, mark the register as not
486 // free and update spill weights.
487 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
488 IntervalPtr &IP = fixed_[i];
489 LiveInterval *I = IP.first;
491 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
492 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
493 I->endNumber() > StartPosition) {
494 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
496 if (II != I->begin() && II->start > StartPosition)
498 if (cur->overlapsFrom(*I, II)) {
499 unsigned reg = I->reg;
500 prt_->addRegUse(reg);
501 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
506 // Using the newly updated prt_ object, which includes conflicts in the
507 // future, see if there are any registers available.
508 physReg = getFreePhysReg(cur);
512 // Restore the physical register tracker, removing information about the
516 // if we find a free register, we are done: assign this virtual to
517 // the free physical register and add this interval to the active
520 DEBUG(std::cerr << mri_->getName(physReg) << '\n');
521 vrm_->assignVirt2Phys(cur->reg, physReg);
522 prt_->addRegUse(physReg);
523 active_.push_back(std::make_pair(cur, cur->begin()));
524 handled_.push_back(cur);
527 DEBUG(std::cerr << "no free registers\n");
529 // Compile the spill weights into an array that is better for scanning.
530 std::vector<float> SpillWeights(mri_->getNumRegs(), 0.0);
531 for (std::vector<std::pair<unsigned, float> >::iterator
532 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
533 updateSpillWeights(SpillWeights, I->first, I->second, mri_);
535 // for each interval in active, update spill weights.
536 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
538 unsigned reg = i->first->reg;
539 assert(MRegisterInfo::isVirtualRegister(reg) &&
540 "Can only allocate virtual registers!");
541 reg = vrm_->getPhys(reg);
542 updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
545 DEBUG(std::cerr << "\tassigning stack slot at interval "<< *cur << ":\n");
547 // Find a register to spill.
548 float minWeight = float(HUGE_VAL);
550 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
551 e = RC->allocation_order_end(*mf_); i != e; ++i) {
553 if (minWeight > SpillWeights[reg]) {
554 minWeight = SpillWeights[reg];
559 // If we didn't find a register that is spillable, try aliases?
561 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
562 e = RC->allocation_order_end(*mf_); i != e; ++i) {
564 // No need to worry about if the alias register size < regsize of RC.
565 // We are going to spill all registers that alias it anyway.
566 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as) {
567 if (minWeight > SpillWeights[*as]) {
568 minWeight = SpillWeights[*as];
574 // All registers must have inf weight. Just grab one!
576 minReg = *RC->allocation_order_begin(*mf_);
579 DEBUG(std::cerr << "\t\tregister with min weight: "
580 << mri_->getName(minReg) << " (" << minWeight << ")\n");
582 // if the current has the minimum weight, we need to spill it and
583 // add any added intervals back to unhandled, and restart
585 if (cur->weight != float(HUGE_VAL) && cur->weight <= minWeight) {
586 DEBUG(std::cerr << "\t\t\tspilling(c): " << *cur << '\n';);
587 int slot = vrm_->assignVirt2StackSlot(cur->reg);
588 std::vector<LiveInterval*> added =
589 li_->addIntervalsForSpills(*cur, *vrm_, slot);
591 return; // Early exit if all spills were folded.
593 // Merge added with unhandled. Note that we know that
594 // addIntervalsForSpills returns intervals sorted by their starting
596 for (unsigned i = 0, e = added.size(); i != e; ++i)
597 unhandled_.push(added[i]);
603 // push the current interval back to unhandled since we are going
604 // to re-run at least this iteration. Since we didn't modify it it
605 // should go back right in the front of the list
606 unhandled_.push(cur);
608 // otherwise we spill all intervals aliasing the register with
609 // minimum weight, rollback to the interval with the earliest
610 // start point and let the linear scan algorithm run again
611 std::vector<LiveInterval*> added;
612 assert(MRegisterInfo::isPhysicalRegister(minReg) &&
613 "did not choose a register to spill?");
614 std::vector<bool> toSpill(mri_->getNumRegs(), false);
616 // We are going to spill minReg and all its aliases.
617 toSpill[minReg] = true;
618 for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
621 // the earliest start of a spilled interval indicates up to where
622 // in handled we need to roll back
623 unsigned earliestStart = cur->beginNumber();
625 // set of spilled vregs (used later to rollback properly)
626 std::set<unsigned> spilled;
628 // spill live intervals of virtual regs mapped to the physical register we
629 // want to clear (and its aliases). We only spill those that overlap with the
630 // current interval as the rest do not affect its allocation. we also keep
631 // track of the earliest start of all spilled live intervals since this will
632 // mark our rollback point.
633 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
634 unsigned reg = i->first->reg;
635 if (//MRegisterInfo::isVirtualRegister(reg) &&
636 toSpill[vrm_->getPhys(reg)] &&
637 cur->overlapsFrom(*i->first, i->second)) {
638 DEBUG(std::cerr << "\t\t\tspilling(a): " << *i->first << '\n');
639 earliestStart = std::min(earliestStart, i->first->beginNumber());
640 int slot = vrm_->assignVirt2StackSlot(i->first->reg);
641 std::vector<LiveInterval*> newIs =
642 li_->addIntervalsForSpills(*i->first, *vrm_, slot);
643 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
647 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
648 unsigned reg = i->first->reg;
649 if (//MRegisterInfo::isVirtualRegister(reg) &&
650 toSpill[vrm_->getPhys(reg)] &&
651 cur->overlapsFrom(*i->first, i->second-1)) {
652 DEBUG(std::cerr << "\t\t\tspilling(i): " << *i->first << '\n');
653 earliestStart = std::min(earliestStart, i->first->beginNumber());
654 int slot = vrm_->assignVirt2StackSlot(reg);
655 std::vector<LiveInterval*> newIs =
656 li_->addIntervalsForSpills(*i->first, *vrm_, slot);
657 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
662 DEBUG(std::cerr << "\t\trolling back to: " << earliestStart << '\n');
664 // Scan handled in reverse order up to the earliest start of a
665 // spilled live interval and undo each one, restoring the state of
667 while (!handled_.empty()) {
668 LiveInterval* i = handled_.back();
669 // If this interval starts before t we are done.
670 if (i->beginNumber() < earliestStart)
672 DEBUG(std::cerr << "\t\t\tundo changes for: " << *i << '\n');
675 // When undoing a live interval allocation we must know if it is active or
676 // inactive to properly update the PhysRegTracker and the VirtRegMap.
677 IntervalPtrs::iterator it;
678 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
680 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
681 if (!spilled.count(i->reg))
683 prt_->delRegUse(vrm_->getPhys(i->reg));
684 vrm_->clearVirt(i->reg);
685 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
687 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
688 if (!spilled.count(i->reg))
690 vrm_->clearVirt(i->reg);
692 assert(MRegisterInfo::isVirtualRegister(i->reg) &&
693 "Can only allocate virtual registers!");
694 vrm_->clearVirt(i->reg);
699 // Rewind the iterators in the active, inactive, and fixed lists back to the
700 // point we reverted to.
701 RevertVectorIteratorsTo(active_, earliestStart);
702 RevertVectorIteratorsTo(inactive_, earliestStart);
703 RevertVectorIteratorsTo(fixed_, earliestStart);
705 // scan the rest and undo each interval that expired after t and
706 // insert it in active (the next iteration of the algorithm will
707 // put it in inactive if required)
708 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
709 LiveInterval *HI = handled_[i];
710 if (!HI->expiredAt(earliestStart) &&
711 HI->expiredAt(cur->beginNumber())) {
712 DEBUG(std::cerr << "\t\t\tundo changes for: " << *HI << '\n');
713 active_.push_back(std::make_pair(HI, HI->begin()));
714 assert(!MRegisterInfo::isPhysicalRegister(HI->reg));
715 prt_->addRegUse(vrm_->getPhys(HI->reg));
719 // merge added with unhandled
720 for (unsigned i = 0, e = added.size(); i != e; ++i)
721 unhandled_.push(added[i]);
724 /// getFreePhysReg - return a free physical register for this virtual register
725 /// interval if we have one, otherwise return 0.
726 unsigned RA::getFreePhysReg(LiveInterval *cur) {
727 std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
728 unsigned MaxInactiveCount = 0;
730 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
731 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
733 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
735 unsigned reg = i->first->reg;
736 assert(MRegisterInfo::isVirtualRegister(reg) &&
737 "Can only allocate virtual registers!");
739 // If this is not in a related reg class to the register we're allocating,
741 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(reg);
742 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
743 reg = vrm_->getPhys(reg);
744 ++inactiveCounts[reg];
745 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
749 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
751 unsigned FreeReg = 0;
752 unsigned FreeRegInactiveCount = 0;
754 // Scan for the first available register.
755 TargetRegisterClass::iterator I = rc->allocation_order_begin(*mf_);
756 TargetRegisterClass::iterator E = rc->allocation_order_end(*mf_);
758 if (prt_->isRegAvail(*I)) {
760 FreeRegInactiveCount = inactiveCounts[FreeReg];
764 // If there are no free regs, or if this reg has the max inactive count,
765 // return this register.
766 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
768 // Continue scanning the registers, looking for the one with the highest
769 // inactive count. Alkis found that this reduced register pressure very
770 // slightly on X86 (in rev 1.94 of this file), though this should probably be
772 for (; I != E; ++I) {
774 if (prt_->isRegAvail(Reg) && FreeRegInactiveCount < inactiveCounts[Reg]) {
776 FreeRegInactiveCount = inactiveCounts[Reg];
777 if (FreeRegInactiveCount == MaxInactiveCount)
778 break; // We found the one with the max inactive count.
785 FunctionPass* llvm::createLinearScanRegisterAllocator() {