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"
40 static Statistic<double> efficiency
41 ("regalloc", "Ratio of intervals processed over total intervals");
42 static Statistic<> NumBacktracks
43 ("regalloc", "Number of times we had to backtrack");
45 static RegisterRegAlloc
46 linearscanRegAlloc("linearscan", " linear scan register allocator",
47 createLinearScanRegisterAllocator);
49 static unsigned numIterations = 0;
50 static unsigned numIntervals = 0;
52 struct VISIBILITY_HIDDEN RA : public MachineFunctionPass {
53 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
54 typedef std::vector<IntervalPtr> IntervalPtrs;
56 /// RelatedRegClasses - This structure is built the first time a function is
57 /// compiled, and keeps track of which register classes have registers that
58 /// belong to multiple classes or have aliases that are in other classes.
59 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
60 std::map<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
63 const TargetMachine* tm_;
64 const MRegisterInfo* mri_;
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_;
72 /// fixed_ - Intervals that correspond to machine registers.
76 /// active_ - Intervals that are currently being processed, and which have a
77 /// live range active for the current point.
80 /// inactive_ - Intervals that are currently being processed, but which have
81 /// a hold at the current point.
82 IntervalPtrs inactive_;
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_;
93 virtual const char* getPassName() const {
94 return "Linear Scan Register Allocator";
97 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
98 AU.addRequired<LiveIntervals>();
99 MachineFunctionPass::getAnalysisUsage(AU);
102 /// runOnMachineFunction - register allocate the whole function
103 bool runOnMachineFunction(MachineFunction&);
106 /// linearScan - the linear scan algorithm
109 /// initIntervalSets - initialize the interval sets.
111 void initIntervalSets();
113 /// processActiveIntervals - expire old intervals and move non-overlapping
114 /// ones to the inactive list.
115 void processActiveIntervals(unsigned CurPoint);
117 /// processInactiveIntervals - expire old intervals and move overlapping
118 /// ones to the active list.
119 void processInactiveIntervals(unsigned CurPoint);
121 /// assignRegOrStackSlotAtInterval - assign a register if one
122 /// is available, or spill.
123 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
126 /// register handling helpers
129 /// getFreePhysReg - return a free physical register for this virtual
130 /// register interval if we have one, otherwise return 0.
131 unsigned getFreePhysReg(LiveInterval* cur);
133 /// assignVirt2StackSlot - assigns this virtual register to a
134 /// stack slot. returns the stack slot
135 int assignVirt2StackSlot(unsigned virtReg);
137 void ComputeRelatedRegClasses();
139 template <typename ItTy>
140 void printIntervals(const char* const str, ItTy i, ItTy e) const {
141 if (str) std::cerr << str << " intervals:\n";
142 for (; i != e; ++i) {
143 std::cerr << "\t" << *i->first << " -> ";
144 unsigned reg = i->first->reg;
145 if (MRegisterInfo::isVirtualRegister(reg)) {
146 reg = vrm_->getPhys(reg);
148 std::cerr << mri_->getName(reg) << '\n';
154 void RA::ComputeRelatedRegClasses() {
155 const MRegisterInfo &MRI = *mri_;
157 // First pass, add all reg classes to the union, and determine at least one
158 // reg class that each register is in.
159 bool HasAliases = false;
160 for (MRegisterInfo::regclass_iterator RCI = MRI.regclass_begin(),
161 E = MRI.regclass_end(); RCI != E; ++RCI) {
162 RelatedRegClasses.insert(*RCI);
163 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
165 HasAliases = HasAliases || *MRI.getAliasSet(*I) != 0;
167 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
169 // Already processed this register. Just make sure we know that
170 // multiple register classes share a register.
171 RelatedRegClasses.unionSets(PRC, *RCI);
178 // Second pass, now that we know conservatively what register classes each reg
179 // belongs to, add info about aliases. We don't need to do this for targets
180 // without register aliases.
182 for (std::map<unsigned, const TargetRegisterClass*>::iterator
183 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
185 for (const unsigned *AS = MRI.getAliasSet(I->first); *AS; ++AS)
186 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
189 bool RA::runOnMachineFunction(MachineFunction &fn) {
191 tm_ = &fn.getTarget();
192 mri_ = tm_->getRegisterInfo();
193 li_ = &getAnalysis<LiveIntervals>();
195 // If this is the first function compiled, compute the related reg classes.
196 if (RelatedRegClasses.empty())
197 ComputeRelatedRegClasses();
199 PhysRegsUsed = new bool[mri_->getNumRegs()];
200 std::fill(PhysRegsUsed, PhysRegsUsed+mri_->getNumRegs(), false);
201 fn.setUsedPhysRegs(PhysRegsUsed);
203 if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
204 vrm_.reset(new VirtRegMap(*mf_));
205 if (!spiller_.get()) spiller_.reset(createSpiller());
211 // Rewrite spill code and update the PhysRegsUsed set.
212 spiller_->runOnMachineFunction(*mf_, *vrm_);
214 vrm_.reset(); // Free the VirtRegMap
217 while (!unhandled_.empty()) unhandled_.pop();
226 /// initIntervalSets - initialize the interval sets.
228 void RA::initIntervalSets()
230 assert(unhandled_.empty() && fixed_.empty() &&
231 active_.empty() && inactive_.empty() &&
232 "interval sets should be empty on initialization");
234 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
235 if (MRegisterInfo::isPhysicalRegister(i->second.reg)) {
236 PhysRegsUsed[i->second.reg] = true;
237 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
239 unhandled_.push(&i->second);
243 void RA::linearScan()
245 // linear scan algorithm
246 DEBUG(std::cerr << "********** LINEAR SCAN **********\n");
247 DEBUG(std::cerr << "********** Function: "
248 << mf_->getFunction()->getName() << '\n');
250 // DEBUG(printIntervals("unhandled", unhandled_.begin(), unhandled_.end()));
251 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
252 DEBUG(printIntervals("active", active_.begin(), active_.end()));
253 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
255 while (!unhandled_.empty()) {
256 // pick the interval with the earliest start point
257 LiveInterval* cur = unhandled_.top();
260 DEBUG(std::cerr << "\n*** CURRENT ***: " << *cur << '\n');
262 processActiveIntervals(cur->beginNumber());
263 processInactiveIntervals(cur->beginNumber());
265 assert(MRegisterInfo::isVirtualRegister(cur->reg) &&
266 "Can only allocate virtual registers!");
268 // Allocating a virtual register. try to find a free
269 // physical register or spill an interval (possibly this one) in order to
271 assignRegOrStackSlotAtInterval(cur);
273 DEBUG(printIntervals("active", active_.begin(), active_.end()));
274 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
276 numIntervals += li_->getNumIntervals();
277 efficiency = double(numIterations) / double(numIntervals);
279 // expire any remaining active intervals
280 for (IntervalPtrs::reverse_iterator
281 i = active_.rbegin(); i != active_.rend(); ) {
282 unsigned reg = i->first->reg;
283 DEBUG(std::cerr << "\tinterval " << *i->first << " expired\n");
284 assert(MRegisterInfo::isVirtualRegister(reg) &&
285 "Can only allocate virtual registers!");
286 reg = vrm_->getPhys(reg);
287 prt_->delRegUse(reg);
288 i = IntervalPtrs::reverse_iterator(active_.erase(i.base()-1));
291 // expire any remaining inactive intervals
292 for (IntervalPtrs::reverse_iterator
293 i = inactive_.rbegin(); i != inactive_.rend(); ) {
294 DEBUG(std::cerr << "\tinterval " << *i->first << " expired\n");
295 i = IntervalPtrs::reverse_iterator(inactive_.erase(i.base()-1));
298 DEBUG(std::cerr << *vrm_);
301 /// processActiveIntervals - expire old intervals and move non-overlapping ones
302 /// to the inactive list.
303 void RA::processActiveIntervals(unsigned CurPoint)
305 DEBUG(std::cerr << "\tprocessing active intervals:\n");
307 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
308 LiveInterval *Interval = active_[i].first;
309 LiveInterval::iterator IntervalPos = active_[i].second;
310 unsigned reg = Interval->reg;
312 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
314 if (IntervalPos == Interval->end()) { // Remove expired intervals.
315 DEBUG(std::cerr << "\t\tinterval " << *Interval << " expired\n");
316 assert(MRegisterInfo::isVirtualRegister(reg) &&
317 "Can only allocate virtual registers!");
318 reg = vrm_->getPhys(reg);
319 prt_->delRegUse(reg);
321 // Pop off the end of the list.
322 active_[i] = active_.back();
326 } else if (IntervalPos->start > CurPoint) {
327 // Move inactive intervals to inactive list.
328 DEBUG(std::cerr << "\t\tinterval " << *Interval << " inactive\n");
329 assert(MRegisterInfo::isVirtualRegister(reg) &&
330 "Can only allocate virtual registers!");
331 reg = vrm_->getPhys(reg);
332 prt_->delRegUse(reg);
334 inactive_.push_back(std::make_pair(Interval, IntervalPos));
336 // Pop off the end of the list.
337 active_[i] = active_.back();
341 // Otherwise, just update the iterator position.
342 active_[i].second = IntervalPos;
347 /// processInactiveIntervals - expire old intervals and move overlapping
348 /// ones to the active list.
349 void RA::processInactiveIntervals(unsigned CurPoint)
351 DEBUG(std::cerr << "\tprocessing inactive intervals:\n");
353 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
354 LiveInterval *Interval = inactive_[i].first;
355 LiveInterval::iterator IntervalPos = inactive_[i].second;
356 unsigned reg = Interval->reg;
358 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
360 if (IntervalPos == Interval->end()) { // remove expired intervals.
361 DEBUG(std::cerr << "\t\tinterval " << *Interval << " expired\n");
363 // Pop off the end of the list.
364 inactive_[i] = inactive_.back();
365 inactive_.pop_back();
367 } else if (IntervalPos->start <= CurPoint) {
368 // move re-activated intervals in active list
369 DEBUG(std::cerr << "\t\tinterval " << *Interval << " active\n");
370 assert(MRegisterInfo::isVirtualRegister(reg) &&
371 "Can only allocate virtual registers!");
372 reg = vrm_->getPhys(reg);
373 prt_->addRegUse(reg);
375 active_.push_back(std::make_pair(Interval, IntervalPos));
377 // Pop off the end of the list.
378 inactive_[i] = inactive_.back();
379 inactive_.pop_back();
382 // Otherwise, just update the iterator position.
383 inactive_[i].second = IntervalPos;
388 /// updateSpillWeights - updates the spill weights of the specifed physical
389 /// register and its weight.
390 static void updateSpillWeights(std::vector<float> &Weights,
391 unsigned reg, float weight,
392 const MRegisterInfo *MRI) {
393 Weights[reg] += weight;
394 for (const unsigned* as = MRI->getAliasSet(reg); *as; ++as)
395 Weights[*as] += weight;
398 static RA::IntervalPtrs::iterator FindIntervalInVector(RA::IntervalPtrs &IP,
400 for (RA::IntervalPtrs::iterator I = IP.begin(), E = IP.end(); I != E; ++I)
401 if (I->first == LI) return I;
405 static void RevertVectorIteratorsTo(RA::IntervalPtrs &V, unsigned Point) {
406 for (unsigned i = 0, e = V.size(); i != e; ++i) {
407 RA::IntervalPtr &IP = V[i];
408 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
410 if (I != IP.first->begin()) --I;
415 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
417 void RA::assignRegOrStackSlotAtInterval(LiveInterval* cur)
419 DEBUG(std::cerr << "\tallocating current interval: ");
421 PhysRegTracker backupPrt = *prt_;
423 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
424 unsigned StartPosition = cur->beginNumber();
425 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
426 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
428 // for every interval in inactive we overlap with, mark the
429 // register as not free and update spill weights.
430 for (IntervalPtrs::const_iterator i = inactive_.begin(),
431 e = inactive_.end(); i != e; ++i) {
432 unsigned Reg = i->first->reg;
433 assert(MRegisterInfo::isVirtualRegister(Reg) &&
434 "Can only allocate virtual registers!");
435 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(Reg);
436 // If this is not in a related reg class to the register we're allocating,
438 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
439 cur->overlapsFrom(*i->first, i->second-1)) {
440 Reg = vrm_->getPhys(Reg);
441 prt_->addRegUse(Reg);
442 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
446 // Speculatively check to see if we can get a register right now. If not,
447 // we know we won't be able to by adding more constraints. If so, we can
448 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
449 // is very bad (it contains all callee clobbered registers for any functions
450 // with a call), so we want to avoid doing that if possible.
451 unsigned physReg = getFreePhysReg(cur);
453 // We got a register. However, if it's in the fixed_ list, we might
454 // conflict with it. Check to see if we conflict with it or any of its
456 std::set<unsigned> RegAliases;
457 for (const unsigned *AS = mri_->getAliasSet(physReg); *AS; ++AS)
458 RegAliases.insert(*AS);
460 bool ConflictsWithFixed = false;
461 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
462 IntervalPtr &IP = fixed_[i];
463 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
464 // Okay, this reg is on the fixed list. Check to see if we actually
466 LiveInterval *I = IP.first;
467 if (I->endNumber() > StartPosition) {
468 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
470 if (II != I->begin() && II->start > StartPosition)
472 if (cur->overlapsFrom(*I, II)) {
473 ConflictsWithFixed = true;
480 // Okay, the register picked by our speculative getFreePhysReg call turned
481 // out to be in use. Actually add all of the conflicting fixed registers to
482 // prt so we can do an accurate query.
483 if (ConflictsWithFixed) {
484 // For every interval in fixed we overlap with, mark the register as not
485 // free and update spill weights.
486 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
487 IntervalPtr &IP = fixed_[i];
488 LiveInterval *I = IP.first;
490 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
491 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
492 I->endNumber() > StartPosition) {
493 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
495 if (II != I->begin() && II->start > StartPosition)
497 if (cur->overlapsFrom(*I, II)) {
498 unsigned reg = I->reg;
499 prt_->addRegUse(reg);
500 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
505 // Using the newly updated prt_ object, which includes conflicts in the
506 // future, see if there are any registers available.
507 physReg = getFreePhysReg(cur);
511 // Restore the physical register tracker, removing information about the
515 // if we find a free register, we are done: assign this virtual to
516 // the free physical register and add this interval to the active
519 DEBUG(std::cerr << mri_->getName(physReg) << '\n');
520 vrm_->assignVirt2Phys(cur->reg, physReg);
521 prt_->addRegUse(physReg);
522 active_.push_back(std::make_pair(cur, cur->begin()));
523 handled_.push_back(cur);
526 DEBUG(std::cerr << "no free registers\n");
528 // Compile the spill weights into an array that is better for scanning.
529 std::vector<float> SpillWeights(mri_->getNumRegs(), 0.0);
530 for (std::vector<std::pair<unsigned, float> >::iterator
531 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
532 updateSpillWeights(SpillWeights, I->first, I->second, mri_);
534 // for each interval in active, update spill weights.
535 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
537 unsigned reg = i->first->reg;
538 assert(MRegisterInfo::isVirtualRegister(reg) &&
539 "Can only allocate virtual registers!");
540 reg = vrm_->getPhys(reg);
541 updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
544 DEBUG(std::cerr << "\tassigning stack slot at interval "<< *cur << ":\n");
546 // Find a register to spill.
547 float minWeight = HUGE_VALF;
549 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
550 e = RC->allocation_order_end(*mf_); i != e; ++i) {
552 if (minWeight > SpillWeights[reg]) {
553 minWeight = SpillWeights[reg];
558 // If we didn't find a register that is spillable, try aliases?
560 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
561 e = RC->allocation_order_end(*mf_); i != e; ++i) {
563 // No need to worry about if the alias register size < regsize of RC.
564 // We are going to spill all registers that alias it anyway.
565 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as) {
566 if (minWeight > SpillWeights[*as]) {
567 minWeight = SpillWeights[*as];
573 // All registers must have inf weight. Just grab one!
575 minReg = *RC->allocation_order_begin(*mf_);
578 DEBUG(std::cerr << "\t\tregister with min weight: "
579 << mri_->getName(minReg) << " (" << minWeight << ")\n");
581 // if the current has the minimum weight, we need to spill it and
582 // add any added intervals back to unhandled, and restart
584 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
585 DEBUG(std::cerr << "\t\t\tspilling(c): " << *cur << '\n';);
586 int slot = vrm_->assignVirt2StackSlot(cur->reg);
587 std::vector<LiveInterval*> added =
588 li_->addIntervalsForSpills(*cur, *vrm_, slot);
590 return; // Early exit if all spills were folded.
592 // Merge added with unhandled. Note that we know that
593 // addIntervalsForSpills returns intervals sorted by their starting
595 for (unsigned i = 0, e = added.size(); i != e; ++i)
596 unhandled_.push(added[i]);
602 // push the current interval back to unhandled since we are going
603 // to re-run at least this iteration. Since we didn't modify it it
604 // should go back right in the front of the list
605 unhandled_.push(cur);
607 // otherwise we spill all intervals aliasing the register with
608 // minimum weight, rollback to the interval with the earliest
609 // start point and let the linear scan algorithm run again
610 std::vector<LiveInterval*> added;
611 assert(MRegisterInfo::isPhysicalRegister(minReg) &&
612 "did not choose a register to spill?");
613 std::vector<bool> toSpill(mri_->getNumRegs(), false);
615 // We are going to spill minReg and all its aliases.
616 toSpill[minReg] = true;
617 for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
620 // the earliest start of a spilled interval indicates up to where
621 // in handled we need to roll back
622 unsigned earliestStart = cur->beginNumber();
624 // set of spilled vregs (used later to rollback properly)
625 std::set<unsigned> spilled;
627 // spill live intervals of virtual regs mapped to the physical register we
628 // want to clear (and its aliases). We only spill those that overlap with the
629 // current interval as the rest do not affect its allocation. we also keep
630 // track of the earliest start of all spilled live intervals since this will
631 // mark our rollback point.
632 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
633 unsigned reg = i->first->reg;
634 if (//MRegisterInfo::isVirtualRegister(reg) &&
635 toSpill[vrm_->getPhys(reg)] &&
636 cur->overlapsFrom(*i->first, i->second)) {
637 DEBUG(std::cerr << "\t\t\tspilling(a): " << *i->first << '\n');
638 earliestStart = std::min(earliestStart, i->first->beginNumber());
639 int slot = vrm_->assignVirt2StackSlot(i->first->reg);
640 std::vector<LiveInterval*> newIs =
641 li_->addIntervalsForSpills(*i->first, *vrm_, slot);
642 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
646 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
647 unsigned reg = i->first->reg;
648 if (//MRegisterInfo::isVirtualRegister(reg) &&
649 toSpill[vrm_->getPhys(reg)] &&
650 cur->overlapsFrom(*i->first, i->second-1)) {
651 DEBUG(std::cerr << "\t\t\tspilling(i): " << *i->first << '\n');
652 earliestStart = std::min(earliestStart, i->first->beginNumber());
653 int slot = vrm_->assignVirt2StackSlot(reg);
654 std::vector<LiveInterval*> newIs =
655 li_->addIntervalsForSpills(*i->first, *vrm_, slot);
656 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
661 DEBUG(std::cerr << "\t\trolling back to: " << earliestStart << '\n');
663 // Scan handled in reverse order up to the earliest start of a
664 // spilled live interval and undo each one, restoring the state of
666 while (!handled_.empty()) {
667 LiveInterval* i = handled_.back();
668 // If this interval starts before t we are done.
669 if (i->beginNumber() < earliestStart)
671 DEBUG(std::cerr << "\t\t\tundo changes for: " << *i << '\n');
674 // When undoing a live interval allocation we must know if it is active or
675 // inactive to properly update the PhysRegTracker and the VirtRegMap.
676 IntervalPtrs::iterator it;
677 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
679 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
680 if (!spilled.count(i->reg))
682 prt_->delRegUse(vrm_->getPhys(i->reg));
683 vrm_->clearVirt(i->reg);
684 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
686 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
687 if (!spilled.count(i->reg))
689 vrm_->clearVirt(i->reg);
691 assert(MRegisterInfo::isVirtualRegister(i->reg) &&
692 "Can only allocate virtual registers!");
693 vrm_->clearVirt(i->reg);
698 // Rewind the iterators in the active, inactive, and fixed lists back to the
699 // point we reverted to.
700 RevertVectorIteratorsTo(active_, earliestStart);
701 RevertVectorIteratorsTo(inactive_, earliestStart);
702 RevertVectorIteratorsTo(fixed_, earliestStart);
704 // scan the rest and undo each interval that expired after t and
705 // insert it in active (the next iteration of the algorithm will
706 // put it in inactive if required)
707 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
708 LiveInterval *HI = handled_[i];
709 if (!HI->expiredAt(earliestStart) &&
710 HI->expiredAt(cur->beginNumber())) {
711 DEBUG(std::cerr << "\t\t\tundo changes for: " << *HI << '\n');
712 active_.push_back(std::make_pair(HI, HI->begin()));
713 assert(!MRegisterInfo::isPhysicalRegister(HI->reg));
714 prt_->addRegUse(vrm_->getPhys(HI->reg));
718 // merge added with unhandled
719 for (unsigned i = 0, e = added.size(); i != e; ++i)
720 unhandled_.push(added[i]);
723 /// getFreePhysReg - return a free physical register for this virtual register
724 /// interval if we have one, otherwise return 0.
725 unsigned RA::getFreePhysReg(LiveInterval *cur) {
726 std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
727 unsigned MaxInactiveCount = 0;
729 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
730 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
732 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
734 unsigned reg = i->first->reg;
735 assert(MRegisterInfo::isVirtualRegister(reg) &&
736 "Can only allocate virtual registers!");
738 // If this is not in a related reg class to the register we're allocating,
740 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(reg);
741 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
742 reg = vrm_->getPhys(reg);
743 ++inactiveCounts[reg];
744 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
748 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
750 unsigned FreeReg = 0;
751 unsigned FreeRegInactiveCount = 0;
753 // Scan for the first available register.
754 TargetRegisterClass::iterator I = rc->allocation_order_begin(*mf_);
755 TargetRegisterClass::iterator E = rc->allocation_order_end(*mf_);
757 if (prt_->isRegAvail(*I)) {
759 FreeRegInactiveCount = inactiveCounts[FreeReg];
763 // If there are no free regs, or if this reg has the max inactive count,
764 // return this register.
765 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
767 // Continue scanning the registers, looking for the one with the highest
768 // inactive count. Alkis found that this reduced register pressure very
769 // slightly on X86 (in rev 1.94 of this file), though this should probably be
771 for (; I != E; ++I) {
773 if (prt_->isRegAvail(Reg) && FreeRegInactiveCount < inactiveCounts[Reg]) {
775 FreeRegInactiveCount = inactiveCounts[Reg];
776 if (FreeRegInactiveCount == MaxInactiveCount)
777 break; // We found the one with the max inactive count.
784 FunctionPass* llvm::createLinearScanRegisterAllocator() {