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 NumIters
41 ("regalloc", "Number of iterations performed");
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) DOUT << str << " intervals:\n";
142 for (; i != e; ++i) {
143 DOUT << "\t" << *i->first << " -> ";
144 unsigned reg = i->first->reg;
145 if (MRegisterInfo::isVirtualRegister(reg)) {
146 reg = vrm_->getPhys(reg);
148 DOUT << 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 DOUT << "********** LINEAR SCAN **********\n";
247 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
249 // DEBUG(printIntervals("unhandled", unhandled_.begin(), unhandled_.end()));
250 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
251 DEBUG(printIntervals("active", active_.begin(), active_.end()));
252 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
254 while (!unhandled_.empty()) {
255 // pick the interval with the earliest start point
256 LiveInterval* cur = unhandled_.top();
259 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
261 processActiveIntervals(cur->beginNumber());
262 processInactiveIntervals(cur->beginNumber());
264 assert(MRegisterInfo::isVirtualRegister(cur->reg) &&
265 "Can only allocate virtual registers!");
267 // Allocating a virtual register. try to find a free
268 // physical register or spill an interval (possibly this one) in order to
270 assignRegOrStackSlotAtInterval(cur);
272 DEBUG(printIntervals("active", active_.begin(), active_.end()));
273 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
275 numIntervals += li_->getNumIntervals();
276 NumIters += numIterations;
278 // expire any remaining active intervals
279 for (IntervalPtrs::reverse_iterator
280 i = active_.rbegin(); i != active_.rend(); ) {
281 unsigned reg = i->first->reg;
282 DOUT << "\tinterval " << *i->first << " expired\n";
283 assert(MRegisterInfo::isVirtualRegister(reg) &&
284 "Can only allocate virtual registers!");
285 reg = vrm_->getPhys(reg);
286 prt_->delRegUse(reg);
287 i = IntervalPtrs::reverse_iterator(active_.erase(i.base()-1));
290 // expire any remaining inactive intervals
291 for (IntervalPtrs::reverse_iterator
292 i = inactive_.rbegin(); i != inactive_.rend(); ) {
293 DOUT << "\tinterval " << *i->first << " expired\n";
294 i = IntervalPtrs::reverse_iterator(inactive_.erase(i.base()-1));
300 /// processActiveIntervals - expire old intervals and move non-overlapping ones
301 /// to the inactive list.
302 void RA::processActiveIntervals(unsigned CurPoint)
304 DOUT << "\tprocessing active intervals:\n";
306 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
307 LiveInterval *Interval = active_[i].first;
308 LiveInterval::iterator IntervalPos = active_[i].second;
309 unsigned reg = Interval->reg;
311 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
313 if (IntervalPos == Interval->end()) { // Remove expired intervals.
314 DOUT << "\t\tinterval " << *Interval << " expired\n";
315 assert(MRegisterInfo::isVirtualRegister(reg) &&
316 "Can only allocate virtual registers!");
317 reg = vrm_->getPhys(reg);
318 prt_->delRegUse(reg);
320 // Pop off the end of the list.
321 active_[i] = active_.back();
325 } else if (IntervalPos->start > CurPoint) {
326 // Move inactive intervals to inactive list.
327 DOUT << "\t\tinterval " << *Interval << " inactive\n";
328 assert(MRegisterInfo::isVirtualRegister(reg) &&
329 "Can only allocate virtual registers!");
330 reg = vrm_->getPhys(reg);
331 prt_->delRegUse(reg);
333 inactive_.push_back(std::make_pair(Interval, IntervalPos));
335 // Pop off the end of the list.
336 active_[i] = active_.back();
340 // Otherwise, just update the iterator position.
341 active_[i].second = IntervalPos;
346 /// processInactiveIntervals - expire old intervals and move overlapping
347 /// ones to the active list.
348 void RA::processInactiveIntervals(unsigned CurPoint)
350 DOUT << "\tprocessing inactive intervals:\n";
352 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
353 LiveInterval *Interval = inactive_[i].first;
354 LiveInterval::iterator IntervalPos = inactive_[i].second;
355 unsigned reg = Interval->reg;
357 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
359 if (IntervalPos == Interval->end()) { // remove expired intervals.
360 DOUT << "\t\tinterval " << *Interval << " expired\n";
362 // Pop off the end of the list.
363 inactive_[i] = inactive_.back();
364 inactive_.pop_back();
366 } else if (IntervalPos->start <= CurPoint) {
367 // move re-activated intervals in active list
368 DOUT << "\t\tinterval " << *Interval << " active\n";
369 assert(MRegisterInfo::isVirtualRegister(reg) &&
370 "Can only allocate virtual registers!");
371 reg = vrm_->getPhys(reg);
372 prt_->addRegUse(reg);
374 active_.push_back(std::make_pair(Interval, IntervalPos));
376 // Pop off the end of the list.
377 inactive_[i] = inactive_.back();
378 inactive_.pop_back();
381 // Otherwise, just update the iterator position.
382 inactive_[i].second = IntervalPos;
387 /// updateSpillWeights - updates the spill weights of the specifed physical
388 /// register and its weight.
389 static void updateSpillWeights(std::vector<float> &Weights,
390 unsigned reg, float weight,
391 const MRegisterInfo *MRI) {
392 Weights[reg] += weight;
393 for (const unsigned* as = MRI->getAliasSet(reg); *as; ++as)
394 Weights[*as] += weight;
397 static RA::IntervalPtrs::iterator FindIntervalInVector(RA::IntervalPtrs &IP,
399 for (RA::IntervalPtrs::iterator I = IP.begin(), E = IP.end(); I != E; ++I)
400 if (I->first == LI) return I;
404 static void RevertVectorIteratorsTo(RA::IntervalPtrs &V, unsigned Point) {
405 for (unsigned i = 0, e = V.size(); i != e; ++i) {
406 RA::IntervalPtr &IP = V[i];
407 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
409 if (I != IP.first->begin()) --I;
414 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
416 void RA::assignRegOrStackSlotAtInterval(LiveInterval* cur)
418 DOUT << "\tallocating current interval: ";
420 PhysRegTracker backupPrt = *prt_;
422 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
423 unsigned StartPosition = cur->beginNumber();
424 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
425 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
427 // for every interval in inactive we overlap with, mark the
428 // register as not free and update spill weights.
429 for (IntervalPtrs::const_iterator i = inactive_.begin(),
430 e = inactive_.end(); i != e; ++i) {
431 unsigned Reg = i->first->reg;
432 assert(MRegisterInfo::isVirtualRegister(Reg) &&
433 "Can only allocate virtual registers!");
434 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(Reg);
435 // If this is not in a related reg class to the register we're allocating,
437 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
438 cur->overlapsFrom(*i->first, i->second-1)) {
439 Reg = vrm_->getPhys(Reg);
440 prt_->addRegUse(Reg);
441 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
445 // Speculatively check to see if we can get a register right now. If not,
446 // we know we won't be able to by adding more constraints. If so, we can
447 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
448 // is very bad (it contains all callee clobbered registers for any functions
449 // with a call), so we want to avoid doing that if possible.
450 unsigned physReg = getFreePhysReg(cur);
452 // We got a register. However, if it's in the fixed_ list, we might
453 // conflict with it. Check to see if we conflict with it or any of its
455 std::set<unsigned> RegAliases;
456 for (const unsigned *AS = mri_->getAliasSet(physReg); *AS; ++AS)
457 RegAliases.insert(*AS);
459 bool ConflictsWithFixed = false;
460 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
461 IntervalPtr &IP = fixed_[i];
462 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
463 // Okay, this reg is on the fixed list. Check to see if we actually
465 LiveInterval *I = IP.first;
466 if (I->endNumber() > StartPosition) {
467 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
469 if (II != I->begin() && II->start > StartPosition)
471 if (cur->overlapsFrom(*I, II)) {
472 ConflictsWithFixed = true;
479 // Okay, the register picked by our speculative getFreePhysReg call turned
480 // out to be in use. Actually add all of the conflicting fixed registers to
481 // prt so we can do an accurate query.
482 if (ConflictsWithFixed) {
483 // For every interval in fixed we overlap with, mark the register as not
484 // free and update spill weights.
485 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
486 IntervalPtr &IP = fixed_[i];
487 LiveInterval *I = IP.first;
489 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
490 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
491 I->endNumber() > StartPosition) {
492 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
494 if (II != I->begin() && II->start > StartPosition)
496 if (cur->overlapsFrom(*I, II)) {
497 unsigned reg = I->reg;
498 prt_->addRegUse(reg);
499 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
504 // Using the newly updated prt_ object, which includes conflicts in the
505 // future, see if there are any registers available.
506 physReg = getFreePhysReg(cur);
510 // Restore the physical register tracker, removing information about the
514 // if we find a free register, we are done: assign this virtual to
515 // the free physical register and add this interval to the active
518 DOUT << mri_->getName(physReg) << '\n';
519 vrm_->assignVirt2Phys(cur->reg, physReg);
520 prt_->addRegUse(physReg);
521 active_.push_back(std::make_pair(cur, cur->begin()));
522 handled_.push_back(cur);
525 DOUT << "no free registers\n";
527 // Compile the spill weights into an array that is better for scanning.
528 std::vector<float> SpillWeights(mri_->getNumRegs(), 0.0);
529 for (std::vector<std::pair<unsigned, float> >::iterator
530 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
531 updateSpillWeights(SpillWeights, I->first, I->second, mri_);
533 // for each interval in active, update spill weights.
534 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
536 unsigned reg = i->first->reg;
537 assert(MRegisterInfo::isVirtualRegister(reg) &&
538 "Can only allocate virtual registers!");
539 reg = vrm_->getPhys(reg);
540 updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
543 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
545 // Find a register to spill.
546 float minWeight = HUGE_VALF;
548 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
549 e = RC->allocation_order_end(*mf_); i != e; ++i) {
551 if (minWeight > SpillWeights[reg]) {
552 minWeight = SpillWeights[reg];
557 // If we didn't find a register that is spillable, try aliases?
559 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
560 e = RC->allocation_order_end(*mf_); i != e; ++i) {
562 // No need to worry about if the alias register size < regsize of RC.
563 // We are going to spill all registers that alias it anyway.
564 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as) {
565 if (minWeight > SpillWeights[*as]) {
566 minWeight = SpillWeights[*as];
572 // All registers must have inf weight. Just grab one!
574 minReg = *RC->allocation_order_begin(*mf_);
577 DOUT << "\t\tregister with min weight: "
578 << mri_->getName(minReg) << " (" << minWeight << ")\n";
580 // if the current has the minimum weight, we need to spill it and
581 // add any added intervals back to unhandled, and restart
583 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
584 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
585 int slot = vrm_->assignVirt2StackSlot(cur->reg);
586 std::vector<LiveInterval*> added =
587 li_->addIntervalsForSpills(*cur, *vrm_, slot);
589 return; // Early exit if all spills were folded.
591 // Merge added with unhandled. Note that we know that
592 // addIntervalsForSpills returns intervals sorted by their starting
594 for (unsigned i = 0, e = added.size(); i != e; ++i)
595 unhandled_.push(added[i]);
601 // push the current interval back to unhandled since we are going
602 // to re-run at least this iteration. Since we didn't modify it it
603 // should go back right in the front of the list
604 unhandled_.push(cur);
606 // otherwise we spill all intervals aliasing the register with
607 // minimum weight, rollback to the interval with the earliest
608 // start point and let the linear scan algorithm run again
609 std::vector<LiveInterval*> added;
610 assert(MRegisterInfo::isPhysicalRegister(minReg) &&
611 "did not choose a register to spill?");
612 std::vector<bool> toSpill(mri_->getNumRegs(), false);
614 // We are going to spill minReg and all its aliases.
615 toSpill[minReg] = true;
616 for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
619 // the earliest start of a spilled interval indicates up to where
620 // in handled we need to roll back
621 unsigned earliestStart = cur->beginNumber();
623 // set of spilled vregs (used later to rollback properly)
624 std::set<unsigned> spilled;
626 // spill live intervals of virtual regs mapped to the physical register we
627 // want to clear (and its aliases). We only spill those that overlap with the
628 // current interval as the rest do not affect its allocation. we also keep
629 // track of the earliest start of all spilled live intervals since this will
630 // mark our rollback point.
631 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
632 unsigned reg = i->first->reg;
633 if (//MRegisterInfo::isVirtualRegister(reg) &&
634 toSpill[vrm_->getPhys(reg)] &&
635 cur->overlapsFrom(*i->first, i->second)) {
636 DOUT << "\t\t\tspilling(a): " << *i->first << '\n';
637 earliestStart = std::min(earliestStart, i->first->beginNumber());
638 int slot = vrm_->assignVirt2StackSlot(i->first->reg);
639 std::vector<LiveInterval*> newIs =
640 li_->addIntervalsForSpills(*i->first, *vrm_, slot);
641 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
645 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
646 unsigned reg = i->first->reg;
647 if (//MRegisterInfo::isVirtualRegister(reg) &&
648 toSpill[vrm_->getPhys(reg)] &&
649 cur->overlapsFrom(*i->first, i->second-1)) {
650 DOUT << "\t\t\tspilling(i): " << *i->first << '\n';
651 earliestStart = std::min(earliestStart, i->first->beginNumber());
652 int slot = vrm_->assignVirt2StackSlot(reg);
653 std::vector<LiveInterval*> newIs =
654 li_->addIntervalsForSpills(*i->first, *vrm_, slot);
655 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
660 DOUT << "\t\trolling back to: " << earliestStart << '\n';
662 // Scan handled in reverse order up to the earliest start of a
663 // spilled live interval and undo each one, restoring the state of
665 while (!handled_.empty()) {
666 LiveInterval* i = handled_.back();
667 // If this interval starts before t we are done.
668 if (i->beginNumber() < earliestStart)
670 DOUT << "\t\t\tundo changes for: " << *i << '\n';
673 // When undoing a live interval allocation we must know if it is active or
674 // inactive to properly update the PhysRegTracker and the VirtRegMap.
675 IntervalPtrs::iterator it;
676 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
678 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
679 if (!spilled.count(i->reg))
681 prt_->delRegUse(vrm_->getPhys(i->reg));
682 vrm_->clearVirt(i->reg);
683 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
685 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
686 if (!spilled.count(i->reg))
688 vrm_->clearVirt(i->reg);
690 assert(MRegisterInfo::isVirtualRegister(i->reg) &&
691 "Can only allocate virtual registers!");
692 vrm_->clearVirt(i->reg);
697 // Rewind the iterators in the active, inactive, and fixed lists back to the
698 // point we reverted to.
699 RevertVectorIteratorsTo(active_, earliestStart);
700 RevertVectorIteratorsTo(inactive_, earliestStart);
701 RevertVectorIteratorsTo(fixed_, earliestStart);
703 // scan the rest and undo each interval that expired after t and
704 // insert it in active (the next iteration of the algorithm will
705 // put it in inactive if required)
706 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
707 LiveInterval *HI = handled_[i];
708 if (!HI->expiredAt(earliestStart) &&
709 HI->expiredAt(cur->beginNumber())) {
710 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
711 active_.push_back(std::make_pair(HI, HI->begin()));
712 assert(!MRegisterInfo::isPhysicalRegister(HI->reg));
713 prt_->addRegUse(vrm_->getPhys(HI->reg));
717 // merge added with unhandled
718 for (unsigned i = 0, e = added.size(); i != e; ++i)
719 unhandled_.push(added[i]);
722 /// getFreePhysReg - return a free physical register for this virtual register
723 /// interval if we have one, otherwise return 0.
724 unsigned RA::getFreePhysReg(LiveInterval *cur) {
725 std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
726 unsigned MaxInactiveCount = 0;
728 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
729 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
731 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
733 unsigned reg = i->first->reg;
734 assert(MRegisterInfo::isVirtualRegister(reg) &&
735 "Can only allocate virtual registers!");
737 // If this is not in a related reg class to the register we're allocating,
739 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(reg);
740 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
741 reg = vrm_->getPhys(reg);
742 ++inactiveCounts[reg];
743 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
747 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(cur->reg);
749 unsigned FreeReg = 0;
750 unsigned FreeRegInactiveCount = 0;
752 // Scan for the first available register.
753 TargetRegisterClass::iterator I = rc->allocation_order_begin(*mf_);
754 TargetRegisterClass::iterator E = rc->allocation_order_end(*mf_);
756 if (prt_->isRegAvail(*I)) {
758 FreeRegInactiveCount = inactiveCounts[FreeReg];
762 // If there are no free regs, or if this reg has the max inactive count,
763 // return this register.
764 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
766 // Continue scanning the registers, looking for the one with the highest
767 // inactive count. Alkis found that this reduced register pressure very
768 // slightly on X86 (in rev 1.94 of this file), though this should probably be
770 for (; I != E; ++I) {
772 if (prt_->isRegAvail(Reg) && FreeRegInactiveCount < inactiveCounts[Reg]) {
774 FreeRegInactiveCount = inactiveCounts[Reg];
775 if (FreeRegInactiveCount == MaxInactiveCount)
776 break; // We found the one with the max inactive count.
783 FunctionPass* llvm::createLinearScanRegisterAllocator() {