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/RegisterCoalescer.h"
24 #include "llvm/CodeGen/SSARegMap.h"
25 #include "llvm/Target/MRegisterInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/ADT/EquivalenceClasses.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/Compiler.h"
39 STATISTIC(NumIters , "Number of iterations performed");
40 STATISTIC(NumBacktracks, "Number of times we had to backtrack");
42 static RegisterRegAlloc
43 linearscanRegAlloc("linearscan", " linear scan register allocator",
44 createLinearScanRegisterAllocator);
47 static unsigned numIterations = 0;
48 static unsigned numIntervals = 0;
50 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
52 RALinScan() : MachineFunctionPass((intptr_t)&ID) {}
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_;
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 // Make sure PassManager knows which analyses to make available
100 // to coalescing and which analyses coalescing invalidates.
101 AU.addRequiredTransitive<RegisterCoalescer>();
102 MachineFunctionPass::getAnalysisUsage(AU);
105 /// runOnMachineFunction - register allocate the whole function
106 bool runOnMachineFunction(MachineFunction&);
109 /// linearScan - the linear scan algorithm
112 /// initIntervalSets - initialize the interval sets.
114 void initIntervalSets();
116 /// processActiveIntervals - expire old intervals and move non-overlapping
117 /// ones to the inactive list.
118 void processActiveIntervals(unsigned CurPoint);
120 /// processInactiveIntervals - expire old intervals and move overlapping
121 /// ones to the active list.
122 void processInactiveIntervals(unsigned CurPoint);
124 /// assignRegOrStackSlotAtInterval - assign a register if one
125 /// is available, or spill.
126 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
129 /// register handling helpers
132 /// getFreePhysReg - return a free physical register for this virtual
133 /// register interval if we have one, otherwise return 0.
134 unsigned getFreePhysReg(LiveInterval* cur);
136 /// assignVirt2StackSlot - assigns this virtual register to a
137 /// stack slot. returns the stack slot
138 int assignVirt2StackSlot(unsigned virtReg);
140 void ComputeRelatedRegClasses();
142 template <typename ItTy>
143 void printIntervals(const char* const str, ItTy i, ItTy e) const {
144 if (str) DOUT << str << " intervals:\n";
145 for (; i != e; ++i) {
146 DOUT << "\t" << *i->first << " -> ";
147 unsigned reg = i->first->reg;
148 if (MRegisterInfo::isVirtualRegister(reg)) {
149 reg = vrm_->getPhys(reg);
151 DOUT << mri_->getName(reg) << '\n';
155 char RALinScan::ID = 0;
158 void RALinScan::ComputeRelatedRegClasses() {
159 const MRegisterInfo &MRI = *mri_;
161 // First pass, add all reg classes to the union, and determine at least one
162 // reg class that each register is in.
163 bool HasAliases = false;
164 for (MRegisterInfo::regclass_iterator RCI = MRI.regclass_begin(),
165 E = MRI.regclass_end(); RCI != E; ++RCI) {
166 RelatedRegClasses.insert(*RCI);
167 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
169 HasAliases = HasAliases || *MRI.getAliasSet(*I) != 0;
171 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
173 // Already processed this register. Just make sure we know that
174 // multiple register classes share a register.
175 RelatedRegClasses.unionSets(PRC, *RCI);
182 // Second pass, now that we know conservatively what register classes each reg
183 // belongs to, add info about aliases. We don't need to do this for targets
184 // without register aliases.
186 for (std::map<unsigned, const TargetRegisterClass*>::iterator
187 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
189 for (const unsigned *AS = MRI.getAliasSet(I->first); *AS; ++AS)
190 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
193 bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
195 tm_ = &fn.getTarget();
196 mri_ = tm_->getRegisterInfo();
197 li_ = &getAnalysis<LiveIntervals>();
199 // We don't run the coalescer here because we have no reason to
200 // interact with it. If the coalescer requires interaction, it
201 // won't do anything. If it doesn't require interaction, we assume
202 // it was run as a separate pass.
204 // If this is the first function compiled, compute the related reg classes.
205 if (RelatedRegClasses.empty())
206 ComputeRelatedRegClasses();
208 if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
209 vrm_.reset(new VirtRegMap(*mf_));
210 if (!spiller_.get()) spiller_.reset(createSpiller());
216 // Rewrite spill code and update the PhysRegsUsed set.
217 spiller_->runOnMachineFunction(*mf_, *vrm_);
218 vrm_.reset(); // Free the VirtRegMap
220 while (!unhandled_.empty()) unhandled_.pop();
229 /// initIntervalSets - initialize the interval sets.
231 void RALinScan::initIntervalSets()
233 assert(unhandled_.empty() && fixed_.empty() &&
234 active_.empty() && inactive_.empty() &&
235 "interval sets should be empty on initialization");
237 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
238 if (MRegisterInfo::isPhysicalRegister(i->second.reg)) {
239 mf_->setPhysRegUsed(i->second.reg);
240 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
242 unhandled_.push(&i->second);
246 void RALinScan::linearScan()
248 // linear scan algorithm
249 DOUT << "********** LINEAR SCAN **********\n";
250 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
252 // DEBUG(printIntervals("unhandled", unhandled_.begin(), unhandled_.end()));
253 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
254 DEBUG(printIntervals("active", active_.begin(), active_.end()));
255 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
257 while (!unhandled_.empty()) {
258 // pick the interval with the earliest start point
259 LiveInterval* cur = unhandled_.top();
262 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
264 processActiveIntervals(cur->beginNumber());
265 processInactiveIntervals(cur->beginNumber());
267 assert(MRegisterInfo::isVirtualRegister(cur->reg) &&
268 "Can only allocate virtual registers!");
270 // Allocating a virtual register. try to find a free
271 // physical register or spill an interval (possibly this one) in order to
273 assignRegOrStackSlotAtInterval(cur);
275 DEBUG(printIntervals("active", active_.begin(), active_.end()));
276 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
278 numIntervals += li_->getNumIntervals();
279 NumIters += numIterations;
281 // expire any remaining active intervals
282 for (IntervalPtrs::reverse_iterator
283 i = active_.rbegin(); i != active_.rend(); ) {
284 unsigned reg = i->first->reg;
285 DOUT << "\tinterval " << *i->first << " expired\n";
286 assert(MRegisterInfo::isVirtualRegister(reg) &&
287 "Can only allocate virtual registers!");
288 reg = vrm_->getPhys(reg);
289 prt_->delRegUse(reg);
290 i = IntervalPtrs::reverse_iterator(active_.erase(i.base()-1));
293 // expire any remaining inactive intervals
294 for (IntervalPtrs::reverse_iterator
295 i = inactive_.rbegin(); i != inactive_.rend(); ) {
296 DOUT << "\tinterval " << *i->first << " expired\n";
297 i = IntervalPtrs::reverse_iterator(inactive_.erase(i.base()-1));
300 // A brute force way of adding live-ins to every BB.
301 MachineFunction::iterator MBB = mf_->begin();
302 ++MBB; // Skip entry MBB.
303 for (MachineFunction::iterator E = mf_->end(); MBB != E; ++MBB) {
304 unsigned StartIdx = li_->getMBBStartIdx(MBB->getNumber());
305 for (IntervalPtrs::iterator i = fixed_.begin(), e = fixed_.end();
307 if (i->first->liveAt(StartIdx))
308 MBB->addLiveIn(i->first->reg);
310 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
311 LiveInterval *HI = handled_[i];
312 unsigned Reg = HI->reg;
313 if (vrm_->isAssignedReg(Reg) && HI->liveAt(StartIdx)) {
314 assert(MRegisterInfo::isVirtualRegister(Reg));
315 Reg = vrm_->getPhys(Reg);
324 /// processActiveIntervals - expire old intervals and move non-overlapping ones
325 /// to the inactive list.
326 void RALinScan::processActiveIntervals(unsigned CurPoint)
328 DOUT << "\tprocessing active intervals:\n";
330 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
331 LiveInterval *Interval = active_[i].first;
332 LiveInterval::iterator IntervalPos = active_[i].second;
333 unsigned reg = Interval->reg;
335 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
337 if (IntervalPos == Interval->end()) { // Remove expired intervals.
338 DOUT << "\t\tinterval " << *Interval << " expired\n";
339 assert(MRegisterInfo::isVirtualRegister(reg) &&
340 "Can only allocate virtual registers!");
341 reg = vrm_->getPhys(reg);
342 prt_->delRegUse(reg);
344 // Pop off the end of the list.
345 active_[i] = active_.back();
349 } else if (IntervalPos->start > CurPoint) {
350 // Move inactive intervals to inactive list.
351 DOUT << "\t\tinterval " << *Interval << " inactive\n";
352 assert(MRegisterInfo::isVirtualRegister(reg) &&
353 "Can only allocate virtual registers!");
354 reg = vrm_->getPhys(reg);
355 prt_->delRegUse(reg);
357 inactive_.push_back(std::make_pair(Interval, IntervalPos));
359 // Pop off the end of the list.
360 active_[i] = active_.back();
364 // Otherwise, just update the iterator position.
365 active_[i].second = IntervalPos;
370 /// processInactiveIntervals - expire old intervals and move overlapping
371 /// ones to the active list.
372 void RALinScan::processInactiveIntervals(unsigned CurPoint)
374 DOUT << "\tprocessing inactive intervals:\n";
376 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
377 LiveInterval *Interval = inactive_[i].first;
378 LiveInterval::iterator IntervalPos = inactive_[i].second;
379 unsigned reg = Interval->reg;
381 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
383 if (IntervalPos == Interval->end()) { // remove expired intervals.
384 DOUT << "\t\tinterval " << *Interval << " expired\n";
386 // Pop off the end of the list.
387 inactive_[i] = inactive_.back();
388 inactive_.pop_back();
390 } else if (IntervalPos->start <= CurPoint) {
391 // move re-activated intervals in active list
392 DOUT << "\t\tinterval " << *Interval << " active\n";
393 assert(MRegisterInfo::isVirtualRegister(reg) &&
394 "Can only allocate virtual registers!");
395 reg = vrm_->getPhys(reg);
396 prt_->addRegUse(reg);
398 active_.push_back(std::make_pair(Interval, IntervalPos));
400 // Pop off the end of the list.
401 inactive_[i] = inactive_.back();
402 inactive_.pop_back();
405 // Otherwise, just update the iterator position.
406 inactive_[i].second = IntervalPos;
411 /// updateSpillWeights - updates the spill weights of the specifed physical
412 /// register and its weight.
413 static void updateSpillWeights(std::vector<float> &Weights,
414 unsigned reg, float weight,
415 const MRegisterInfo *MRI) {
416 Weights[reg] += weight;
417 for (const unsigned* as = MRI->getAliasSet(reg); *as; ++as)
418 Weights[*as] += weight;
422 RALinScan::IntervalPtrs::iterator
423 FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
424 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
426 if (I->first == LI) return I;
430 static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
431 for (unsigned i = 0, e = V.size(); i != e; ++i) {
432 RALinScan::IntervalPtr &IP = V[i];
433 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
435 if (I != IP.first->begin()) --I;
440 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
442 void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
444 DOUT << "\tallocating current interval: ";
446 PhysRegTracker backupPrt = *prt_;
448 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
449 unsigned StartPosition = cur->beginNumber();
450 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
451 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
453 // for every interval in inactive we overlap with, mark the
454 // register as not free and update spill weights.
455 for (IntervalPtrs::const_iterator i = inactive_.begin(),
456 e = inactive_.end(); i != e; ++i) {
457 unsigned Reg = i->first->reg;
458 assert(MRegisterInfo::isVirtualRegister(Reg) &&
459 "Can only allocate virtual registers!");
460 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(Reg);
461 // If this is not in a related reg class to the register we're allocating,
463 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
464 cur->overlapsFrom(*i->first, i->second-1)) {
465 Reg = vrm_->getPhys(Reg);
466 prt_->addRegUse(Reg);
467 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
471 // Speculatively check to see if we can get a register right now. If not,
472 // we know we won't be able to by adding more constraints. If so, we can
473 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
474 // is very bad (it contains all callee clobbered registers for any functions
475 // with a call), so we want to avoid doing that if possible.
476 unsigned physReg = getFreePhysReg(cur);
478 // We got a register. However, if it's in the fixed_ list, we might
479 // conflict with it. Check to see if we conflict with it or any of its
481 std::set<unsigned> RegAliases;
482 for (const unsigned *AS = mri_->getAliasSet(physReg); *AS; ++AS)
483 RegAliases.insert(*AS);
485 bool ConflictsWithFixed = false;
486 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
487 IntervalPtr &IP = fixed_[i];
488 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
489 // Okay, this reg is on the fixed list. Check to see if we actually
491 LiveInterval *I = IP.first;
492 if (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 ConflictsWithFixed = true;
505 // Okay, the register picked by our speculative getFreePhysReg call turned
506 // out to be in use. Actually add all of the conflicting fixed registers to
507 // prt so we can do an accurate query.
508 if (ConflictsWithFixed) {
509 // For every interval in fixed we overlap with, mark the register as not
510 // free and update spill weights.
511 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
512 IntervalPtr &IP = fixed_[i];
513 LiveInterval *I = IP.first;
515 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
516 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
517 I->endNumber() > StartPosition) {
518 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
520 if (II != I->begin() && II->start > StartPosition)
522 if (cur->overlapsFrom(*I, II)) {
523 unsigned reg = I->reg;
524 prt_->addRegUse(reg);
525 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
530 // Using the newly updated prt_ object, which includes conflicts in the
531 // future, see if there are any registers available.
532 physReg = getFreePhysReg(cur);
536 // Restore the physical register tracker, removing information about the
540 // if we find a free register, we are done: assign this virtual to
541 // the free physical register and add this interval to the active
544 DOUT << mri_->getName(physReg) << '\n';
545 vrm_->assignVirt2Phys(cur->reg, physReg);
546 prt_->addRegUse(physReg);
547 active_.push_back(std::make_pair(cur, cur->begin()));
548 handled_.push_back(cur);
551 DOUT << "no free registers\n";
553 // Compile the spill weights into an array that is better for scanning.
554 std::vector<float> SpillWeights(mri_->getNumRegs(), 0.0);
555 for (std::vector<std::pair<unsigned, float> >::iterator
556 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
557 updateSpillWeights(SpillWeights, I->first, I->second, mri_);
559 // for each interval in active, update spill weights.
560 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
562 unsigned reg = i->first->reg;
563 assert(MRegisterInfo::isVirtualRegister(reg) &&
564 "Can only allocate virtual registers!");
565 reg = vrm_->getPhys(reg);
566 updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
569 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
571 // Find a register to spill.
572 float minWeight = HUGE_VALF;
573 unsigned minReg = cur->preference; // Try the preferred register first.
575 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
576 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
577 e = RC->allocation_order_end(*mf_); i != e; ++i) {
579 if (minWeight > SpillWeights[reg]) {
580 minWeight = SpillWeights[reg];
585 // If we didn't find a register that is spillable, try aliases?
587 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
588 e = RC->allocation_order_end(*mf_); i != e; ++i) {
590 // No need to worry about if the alias register size < regsize of RC.
591 // We are going to spill all registers that alias it anyway.
592 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as) {
593 if (minWeight > SpillWeights[*as]) {
594 minWeight = SpillWeights[*as];
600 // All registers must have inf weight. Just grab one!
602 minReg = *RC->allocation_order_begin(*mf_);
605 DOUT << "\t\tregister with min weight: "
606 << mri_->getName(minReg) << " (" << minWeight << ")\n";
608 // if the current has the minimum weight, we need to spill it and
609 // add any added intervals back to unhandled, and restart
611 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
612 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
613 std::vector<LiveInterval*> added =
614 li_->addIntervalsForSpills(*cur, *vrm_, cur->reg);
616 return; // Early exit if all spills were folded.
618 // Merge added with unhandled. Note that we know that
619 // addIntervalsForSpills returns intervals sorted by their starting
621 for (unsigned i = 0, e = added.size(); i != e; ++i)
622 unhandled_.push(added[i]);
628 // push the current interval back to unhandled since we are going
629 // to re-run at least this iteration. Since we didn't modify it it
630 // should go back right in the front of the list
631 unhandled_.push(cur);
633 // otherwise we spill all intervals aliasing the register with
634 // minimum weight, rollback to the interval with the earliest
635 // start point and let the linear scan algorithm run again
636 std::vector<LiveInterval*> added;
637 assert(MRegisterInfo::isPhysicalRegister(minReg) &&
638 "did not choose a register to spill?");
639 BitVector toSpill(mri_->getNumRegs());
641 // We are going to spill minReg and all its aliases.
642 toSpill[minReg] = true;
643 for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
646 // the earliest start of a spilled interval indicates up to where
647 // in handled we need to roll back
648 unsigned earliestStart = cur->beginNumber();
650 // set of spilled vregs (used later to rollback properly)
651 std::set<unsigned> spilled;
653 // spill live intervals of virtual regs mapped to the physical register we
654 // want to clear (and its aliases). We only spill those that overlap with the
655 // current interval as the rest do not affect its allocation. we also keep
656 // track of the earliest start of all spilled live intervals since this will
657 // mark our rollback point.
658 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
659 unsigned reg = i->first->reg;
660 if (//MRegisterInfo::isVirtualRegister(reg) &&
661 toSpill[vrm_->getPhys(reg)] &&
662 cur->overlapsFrom(*i->first, i->second)) {
663 DOUT << "\t\t\tspilling(a): " << *i->first << '\n';
664 earliestStart = std::min(earliestStart, i->first->beginNumber());
665 std::vector<LiveInterval*> newIs =
666 li_->addIntervalsForSpills(*i->first, *vrm_, reg);
667 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
671 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
672 unsigned reg = i->first->reg;
673 if (//MRegisterInfo::isVirtualRegister(reg) &&
674 toSpill[vrm_->getPhys(reg)] &&
675 cur->overlapsFrom(*i->first, i->second-1)) {
676 DOUT << "\t\t\tspilling(i): " << *i->first << '\n';
677 earliestStart = std::min(earliestStart, i->first->beginNumber());
678 std::vector<LiveInterval*> newIs =
679 li_->addIntervalsForSpills(*i->first, *vrm_, reg);
680 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
685 DOUT << "\t\trolling back to: " << earliestStart << '\n';
687 // Scan handled in reverse order up to the earliest start of a
688 // spilled live interval and undo each one, restoring the state of
690 while (!handled_.empty()) {
691 LiveInterval* i = handled_.back();
692 // If this interval starts before t we are done.
693 if (i->beginNumber() < earliestStart)
695 DOUT << "\t\t\tundo changes for: " << *i << '\n';
698 // When undoing a live interval allocation we must know if it is active or
699 // inactive to properly update the PhysRegTracker and the VirtRegMap.
700 IntervalPtrs::iterator it;
701 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
703 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
704 if (!spilled.count(i->reg))
706 prt_->delRegUse(vrm_->getPhys(i->reg));
707 vrm_->clearVirt(i->reg);
708 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
710 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
711 if (!spilled.count(i->reg))
713 vrm_->clearVirt(i->reg);
715 assert(MRegisterInfo::isVirtualRegister(i->reg) &&
716 "Can only allocate virtual registers!");
717 vrm_->clearVirt(i->reg);
722 // Rewind the iterators in the active, inactive, and fixed lists back to the
723 // point we reverted to.
724 RevertVectorIteratorsTo(active_, earliestStart);
725 RevertVectorIteratorsTo(inactive_, earliestStart);
726 RevertVectorIteratorsTo(fixed_, earliestStart);
728 // scan the rest and undo each interval that expired after t and
729 // insert it in active (the next iteration of the algorithm will
730 // put it in inactive if required)
731 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
732 LiveInterval *HI = handled_[i];
733 if (!HI->expiredAt(earliestStart) &&
734 HI->expiredAt(cur->beginNumber())) {
735 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
736 active_.push_back(std::make_pair(HI, HI->begin()));
737 assert(!MRegisterInfo::isPhysicalRegister(HI->reg));
738 prt_->addRegUse(vrm_->getPhys(HI->reg));
742 // merge added with unhandled
743 for (unsigned i = 0, e = added.size(); i != e; ++i)
744 unhandled_.push(added[i]);
747 /// getFreePhysReg - return a free physical register for this virtual register
748 /// interval if we have one, otherwise return 0.
749 unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
750 std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
751 unsigned MaxInactiveCount = 0;
753 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(cur->reg);
754 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
756 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
758 unsigned reg = i->first->reg;
759 assert(MRegisterInfo::isVirtualRegister(reg) &&
760 "Can only allocate virtual registers!");
762 // If this is not in a related reg class to the register we're allocating,
764 const TargetRegisterClass *RegRC = mf_->getSSARegMap()->getRegClass(reg);
765 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
766 reg = vrm_->getPhys(reg);
767 ++inactiveCounts[reg];
768 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
772 unsigned FreeReg = 0;
773 unsigned FreeRegInactiveCount = 0;
775 // If copy coalescer has assigned a "preferred" register, check if it's
778 if (prt_->isRegAvail(cur->preference)) {
779 DOUT << "\t\tassigned the preferred register: "
780 << mri_->getName(cur->preference) << "\n";
781 return cur->preference;
783 DOUT << "\t\tunable to assign the preferred register: "
784 << mri_->getName(cur->preference) << "\n";
786 // Scan for the first available register.
787 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
788 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
790 if (prt_->isRegAvail(*I)) {
792 FreeRegInactiveCount = inactiveCounts[FreeReg];
796 // If there are no free regs, or if this reg has the max inactive count,
797 // return this register.
798 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
800 // Continue scanning the registers, looking for the one with the highest
801 // inactive count. Alkis found that this reduced register pressure very
802 // slightly on X86 (in rev 1.94 of this file), though this should probably be
804 for (; I != E; ++I) {
806 if (prt_->isRegAvail(Reg) && FreeRegInactiveCount < inactiveCounts[Reg]) {
808 FreeRegInactiveCount = inactiveCounts[Reg];
809 if (FreeRegInactiveCount == MaxInactiveCount)
810 break; // We found the one with the max inactive count.
817 FunctionPass* llvm::createLinearScanRegisterAllocator() {
818 return new RALinScan();