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/Target/TargetInstrInfo.h"
28 #include "llvm/ADT/EquivalenceClasses.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/Compiler.h"
40 STATISTIC(NumIters , "Number of iterations performed");
41 STATISTIC(NumBacktracks, "Number of times we had to backtrack");
42 STATISTIC(NumCoalesce, "Number of copies coalesced");
44 static RegisterRegAlloc
45 linearscanRegAlloc("linearscan", " linear scan register allocator",
46 createLinearScanRegisterAllocator);
49 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
51 RALinScan() : MachineFunctionPass((intptr_t)&ID) {}
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_;
65 const TargetInstrInfo* tii_;
67 BitVector allocatableRegs_;
70 /// handled_ - Intervals are added to the handled_ set in the order of their
71 /// start value. This is uses for backtracking.
72 std::vector<LiveInterval*> handled_;
74 /// fixed_ - Intervals that correspond to machine registers.
78 /// active_ - Intervals that are currently being processed, and which have a
79 /// live range active for the current point.
82 /// inactive_ - Intervals that are currently being processed, but which have
83 /// a hold at the current point.
84 IntervalPtrs inactive_;
86 typedef std::priority_queue<LiveInterval*,
87 std::vector<LiveInterval*>,
88 greater_ptr<LiveInterval> > IntervalHeap;
89 IntervalHeap unhandled_;
90 std::auto_ptr<PhysRegTracker> prt_;
91 std::auto_ptr<VirtRegMap> vrm_;
92 std::auto_ptr<Spiller> spiller_;
95 virtual const char* getPassName() const {
96 return "Linear Scan Register Allocator";
99 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
100 AU.addRequired<LiveIntervals>();
101 // Make sure PassManager knows which analyses to make available
102 // to coalescing and which analyses coalescing invalidates.
103 AU.addRequiredTransitive<RegisterCoalescer>();
104 MachineFunctionPass::getAnalysisUsage(AU);
107 /// runOnMachineFunction - register allocate the whole function
108 bool runOnMachineFunction(MachineFunction&);
111 /// linearScan - the linear scan algorithm
114 /// initIntervalSets - initialize the interval sets.
116 void initIntervalSets();
118 /// processActiveIntervals - expire old intervals and move non-overlapping
119 /// ones to the inactive list.
120 void processActiveIntervals(unsigned CurPoint);
122 /// processInactiveIntervals - expire old intervals and move overlapping
123 /// ones to the active list.
124 void processInactiveIntervals(unsigned CurPoint);
126 /// assignRegOrStackSlotAtInterval - assign a register if one
127 /// is available, or spill.
128 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
130 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
131 /// try allocate the definition the same register as the source register
132 /// if the register is not defined during live time of the interval. This
133 /// eliminate a copy. This is used to coalesce copies which were not
134 /// coalesced away before allocation either due to dest and src being in
135 /// different register classes or because the coalescer was overly
137 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
140 /// register handling helpers
143 /// getFreePhysReg - return a free physical register for this virtual
144 /// register interval if we have one, otherwise return 0.
145 unsigned getFreePhysReg(LiveInterval* cur);
147 /// assignVirt2StackSlot - assigns this virtual register to a
148 /// stack slot. returns the stack slot
149 int assignVirt2StackSlot(unsigned virtReg);
151 void ComputeRelatedRegClasses();
153 template <typename ItTy>
154 void printIntervals(const char* const str, ItTy i, ItTy e) const {
155 if (str) DOUT << str << " intervals:\n";
156 for (; i != e; ++i) {
157 DOUT << "\t" << *i->first << " -> ";
158 unsigned reg = i->first->reg;
159 if (MRegisterInfo::isVirtualRegister(reg)) {
160 reg = vrm_->getPhys(reg);
162 DOUT << mri_->getName(reg) << '\n';
166 char RALinScan::ID = 0;
169 void RALinScan::ComputeRelatedRegClasses() {
170 const MRegisterInfo &MRI = *mri_;
172 // First pass, add all reg classes to the union, and determine at least one
173 // reg class that each register is in.
174 bool HasAliases = false;
175 for (MRegisterInfo::regclass_iterator RCI = MRI.regclass_begin(),
176 E = MRI.regclass_end(); RCI != E; ++RCI) {
177 RelatedRegClasses.insert(*RCI);
178 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
180 HasAliases = HasAliases || *MRI.getAliasSet(*I) != 0;
182 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
184 // Already processed this register. Just make sure we know that
185 // multiple register classes share a register.
186 RelatedRegClasses.unionSets(PRC, *RCI);
193 // Second pass, now that we know conservatively what register classes each reg
194 // belongs to, add info about aliases. We don't need to do this for targets
195 // without register aliases.
197 for (std::map<unsigned, const TargetRegisterClass*>::iterator
198 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
200 for (const unsigned *AS = MRI.getAliasSet(I->first); *AS; ++AS)
201 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
204 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
205 /// try allocate the definition the same register as the source register
206 /// if the register is not defined during live time of the interval. This
207 /// eliminate a copy. This is used to coalesce copies which were not
208 /// coalesced away before allocation either due to dest and src being in
209 /// different register classes or because the coalescer was overly
211 unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
212 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
215 VNInfo *vni = cur.getValNumInfo(0);
216 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
218 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
219 unsigned SrcReg, DstReg;
220 if (!CopyMI || !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg))
222 if (MRegisterInfo::isVirtualRegister(SrcReg))
223 if (!vrm_->isAssignedReg(SrcReg))
226 SrcReg = vrm_->getPhys(SrcReg);
230 const TargetRegisterClass *RC = regmap_->getRegClass(cur.reg);
231 if (!RC->contains(SrcReg))
235 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
236 vrm_->clearVirt(cur.reg);
237 vrm_->assignVirt2Phys(cur.reg, SrcReg);
245 bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
247 tm_ = &fn.getTarget();
248 mri_ = tm_->getRegisterInfo();
249 tii_ = tm_->getInstrInfo();
250 regmap_ = mf_->getSSARegMap();
251 allocatableRegs_ = mri_->getAllocatableSet(fn);
252 li_ = &getAnalysis<LiveIntervals>();
254 // We don't run the coalescer here because we have no reason to
255 // interact with it. If the coalescer requires interaction, it
256 // won't do anything. If it doesn't require interaction, we assume
257 // it was run as a separate pass.
259 // If this is the first function compiled, compute the related reg classes.
260 if (RelatedRegClasses.empty())
261 ComputeRelatedRegClasses();
263 if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
264 vrm_.reset(new VirtRegMap(*mf_));
265 if (!spiller_.get()) spiller_.reset(createSpiller());
271 // Rewrite spill code and update the PhysRegsUsed set.
272 spiller_->runOnMachineFunction(*mf_, *vrm_);
273 vrm_.reset(); // Free the VirtRegMap
275 while (!unhandled_.empty()) unhandled_.pop();
284 /// initIntervalSets - initialize the interval sets.
286 void RALinScan::initIntervalSets()
288 assert(unhandled_.empty() && fixed_.empty() &&
289 active_.empty() && inactive_.empty() &&
290 "interval sets should be empty on initialization");
292 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
293 if (MRegisterInfo::isPhysicalRegister(i->second.reg)) {
294 mf_->setPhysRegUsed(i->second.reg);
295 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
297 unhandled_.push(&i->second);
301 void RALinScan::linearScan()
303 // linear scan algorithm
304 DOUT << "********** LINEAR SCAN **********\n";
305 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
307 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
309 while (!unhandled_.empty()) {
310 // pick the interval with the earliest start point
311 LiveInterval* cur = unhandled_.top();
314 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
316 processActiveIntervals(cur->beginNumber());
317 processInactiveIntervals(cur->beginNumber());
319 assert(MRegisterInfo::isVirtualRegister(cur->reg) &&
320 "Can only allocate virtual registers!");
322 // Allocating a virtual register. try to find a free
323 // physical register or spill an interval (possibly this one) in order to
325 assignRegOrStackSlotAtInterval(cur);
327 DEBUG(printIntervals("active", active_.begin(), active_.end()));
328 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
331 // expire any remaining active intervals
332 while (!active_.empty()) {
333 IntervalPtr &IP = active_.back();
334 unsigned reg = IP.first->reg;
335 DOUT << "\tinterval " << *IP.first << " expired\n";
336 assert(MRegisterInfo::isVirtualRegister(reg) &&
337 "Can only allocate virtual registers!");
338 reg = vrm_->getPhys(reg);
339 prt_->delRegUse(reg);
343 // expire any remaining inactive intervals
344 DEBUG(for (IntervalPtrs::reverse_iterator
345 i = inactive_.rbegin(); i != inactive_.rend(); )
346 DOUT << "\tinterval " << *i->first << " expired\n");
349 // Add live-ins to every BB except for entry.
350 MachineFunction::iterator EntryMBB = mf_->begin();
351 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
352 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
353 LiveInterval &cur = i->second;
355 if (MRegisterInfo::isPhysicalRegister(cur.reg))
357 else if (vrm_->isAssignedReg(cur.reg))
358 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
361 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
363 const LiveRange &LR = *I;
364 if (li_->findLiveInMBBs(LR, LiveInMBBs)) {
365 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
366 if (LiveInMBBs[i] != EntryMBB)
367 LiveInMBBs[i]->addLiveIn(Reg);
376 /// processActiveIntervals - expire old intervals and move non-overlapping ones
377 /// to the inactive list.
378 void RALinScan::processActiveIntervals(unsigned CurPoint)
380 DOUT << "\tprocessing active intervals:\n";
382 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
383 LiveInterval *Interval = active_[i].first;
384 LiveInterval::iterator IntervalPos = active_[i].second;
385 unsigned reg = Interval->reg;
387 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
389 if (IntervalPos == Interval->end()) { // Remove expired intervals.
390 DOUT << "\t\tinterval " << *Interval << " expired\n";
391 assert(MRegisterInfo::isVirtualRegister(reg) &&
392 "Can only allocate virtual registers!");
393 reg = vrm_->getPhys(reg);
394 prt_->delRegUse(reg);
396 // Pop off the end of the list.
397 active_[i] = active_.back();
401 } else if (IntervalPos->start > CurPoint) {
402 // Move inactive intervals to inactive list.
403 DOUT << "\t\tinterval " << *Interval << " inactive\n";
404 assert(MRegisterInfo::isVirtualRegister(reg) &&
405 "Can only allocate virtual registers!");
406 reg = vrm_->getPhys(reg);
407 prt_->delRegUse(reg);
409 inactive_.push_back(std::make_pair(Interval, IntervalPos));
411 // Pop off the end of the list.
412 active_[i] = active_.back();
416 // Otherwise, just update the iterator position.
417 active_[i].second = IntervalPos;
422 /// processInactiveIntervals - expire old intervals and move overlapping
423 /// ones to the active list.
424 void RALinScan::processInactiveIntervals(unsigned CurPoint)
426 DOUT << "\tprocessing inactive intervals:\n";
428 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
429 LiveInterval *Interval = inactive_[i].first;
430 LiveInterval::iterator IntervalPos = inactive_[i].second;
431 unsigned reg = Interval->reg;
433 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
435 if (IntervalPos == Interval->end()) { // remove expired intervals.
436 DOUT << "\t\tinterval " << *Interval << " expired\n";
438 // Pop off the end of the list.
439 inactive_[i] = inactive_.back();
440 inactive_.pop_back();
442 } else if (IntervalPos->start <= CurPoint) {
443 // move re-activated intervals in active list
444 DOUT << "\t\tinterval " << *Interval << " active\n";
445 assert(MRegisterInfo::isVirtualRegister(reg) &&
446 "Can only allocate virtual registers!");
447 reg = vrm_->getPhys(reg);
448 prt_->addRegUse(reg);
450 active_.push_back(std::make_pair(Interval, IntervalPos));
452 // Pop off the end of the list.
453 inactive_[i] = inactive_.back();
454 inactive_.pop_back();
457 // Otherwise, just update the iterator position.
458 inactive_[i].second = IntervalPos;
463 /// updateSpillWeights - updates the spill weights of the specifed physical
464 /// register and its weight.
465 static void updateSpillWeights(std::vector<float> &Weights,
466 unsigned reg, float weight,
467 const MRegisterInfo *MRI) {
468 Weights[reg] += weight;
469 for (const unsigned* as = MRI->getAliasSet(reg); *as; ++as)
470 Weights[*as] += weight;
474 RALinScan::IntervalPtrs::iterator
475 FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
476 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
478 if (I->first == LI) return I;
482 static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
483 for (unsigned i = 0, e = V.size(); i != e; ++i) {
484 RALinScan::IntervalPtr &IP = V[i];
485 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
487 if (I != IP.first->begin()) --I;
492 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
494 void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
496 DOUT << "\tallocating current interval: ";
498 PhysRegTracker backupPrt = *prt_;
500 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
501 unsigned StartPosition = cur->beginNumber();
502 const TargetRegisterClass *RC = regmap_->getRegClass(cur->reg);
503 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
505 // If this live interval is defined by a move instruction and its source is
506 // assigned a physical register that is compatible with the target register
507 // class, then we should try to assign it the same register.
508 // This can happen when the move is from a larger register class to a smaller
509 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
510 if (!cur->preference && cur->containsOneValue()) {
511 VNInfo *vni = cur->getValNumInfo(0);
512 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
513 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
514 unsigned SrcReg, DstReg;
515 if (tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
517 if (MRegisterInfo::isPhysicalRegister(SrcReg))
519 else if (vrm_->isAssignedReg(SrcReg))
520 Reg = vrm_->getPhys(SrcReg);
521 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
522 cur->preference = Reg;
527 // for every interval in inactive we overlap with, mark the
528 // register as not free and update spill weights.
529 for (IntervalPtrs::const_iterator i = inactive_.begin(),
530 e = inactive_.end(); i != e; ++i) {
531 unsigned Reg = i->first->reg;
532 assert(MRegisterInfo::isVirtualRegister(Reg) &&
533 "Can only allocate virtual registers!");
534 const TargetRegisterClass *RegRC = regmap_->getRegClass(Reg);
535 // If this is not in a related reg class to the register we're allocating,
537 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
538 cur->overlapsFrom(*i->first, i->second-1)) {
539 Reg = vrm_->getPhys(Reg);
540 prt_->addRegUse(Reg);
541 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
545 // Speculatively check to see if we can get a register right now. If not,
546 // we know we won't be able to by adding more constraints. If so, we can
547 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
548 // is very bad (it contains all callee clobbered registers for any functions
549 // with a call), so we want to avoid doing that if possible.
550 unsigned physReg = getFreePhysReg(cur);
552 // We got a register. However, if it's in the fixed_ list, we might
553 // conflict with it. Check to see if we conflict with it or any of its
555 SmallSet<unsigned, 8> RegAliases;
556 for (const unsigned *AS = mri_->getAliasSet(physReg); *AS; ++AS)
557 RegAliases.insert(*AS);
559 bool ConflictsWithFixed = false;
560 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
561 IntervalPtr &IP = fixed_[i];
562 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
563 // Okay, this reg is on the fixed list. Check to see if we actually
565 LiveInterval *I = IP.first;
566 if (I->endNumber() > StartPosition) {
567 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
569 if (II != I->begin() && II->start > StartPosition)
571 if (cur->overlapsFrom(*I, II)) {
572 ConflictsWithFixed = true;
579 // Okay, the register picked by our speculative getFreePhysReg call turned
580 // out to be in use. Actually add all of the conflicting fixed registers to
581 // prt so we can do an accurate query.
582 if (ConflictsWithFixed) {
583 // For every interval in fixed we overlap with, mark the register as not
584 // free and update spill weights.
585 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
586 IntervalPtr &IP = fixed_[i];
587 LiveInterval *I = IP.first;
589 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
590 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
591 I->endNumber() > StartPosition) {
592 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
594 if (II != I->begin() && II->start > StartPosition)
596 if (cur->overlapsFrom(*I, II)) {
597 unsigned reg = I->reg;
598 prt_->addRegUse(reg);
599 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
604 // Using the newly updated prt_ object, which includes conflicts in the
605 // future, see if there are any registers available.
606 physReg = getFreePhysReg(cur);
610 // Restore the physical register tracker, removing information about the
614 // if we find a free register, we are done: assign this virtual to
615 // the free physical register and add this interval to the active
618 DOUT << mri_->getName(physReg) << '\n';
619 vrm_->assignVirt2Phys(cur->reg, physReg);
620 prt_->addRegUse(physReg);
621 active_.push_back(std::make_pair(cur, cur->begin()));
622 handled_.push_back(cur);
625 DOUT << "no free registers\n";
627 // Compile the spill weights into an array that is better for scanning.
628 std::vector<float> SpillWeights(mri_->getNumRegs(), 0.0);
629 for (std::vector<std::pair<unsigned, float> >::iterator
630 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
631 updateSpillWeights(SpillWeights, I->first, I->second, mri_);
633 // for each interval in active, update spill weights.
634 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
636 unsigned reg = i->first->reg;
637 assert(MRegisterInfo::isVirtualRegister(reg) &&
638 "Can only allocate virtual registers!");
639 reg = vrm_->getPhys(reg);
640 updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
643 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
645 // Find a register to spill.
646 float minWeight = HUGE_VALF;
647 unsigned minReg = cur->preference; // Try the preferred register first.
649 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
650 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
651 e = RC->allocation_order_end(*mf_); i != e; ++i) {
653 if (minWeight > SpillWeights[reg]) {
654 minWeight = SpillWeights[reg];
659 // If we didn't find a register that is spillable, try aliases?
661 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
662 e = RC->allocation_order_end(*mf_); i != e; ++i) {
664 // No need to worry about if the alias register size < regsize of RC.
665 // We are going to spill all registers that alias it anyway.
666 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as) {
667 if (minWeight > SpillWeights[*as]) {
668 minWeight = SpillWeights[*as];
674 // All registers must have inf weight. Just grab one!
676 minReg = *RC->allocation_order_begin(*mf_);
679 DOUT << "\t\tregister with min weight: "
680 << mri_->getName(minReg) << " (" << minWeight << ")\n";
682 // if the current has the minimum weight, we need to spill it and
683 // add any added intervals back to unhandled, and restart
685 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
686 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
687 std::vector<LiveInterval*> added =
688 li_->addIntervalsForSpills(*cur, *vrm_, cur->reg);
690 return; // Early exit if all spills were folded.
692 // Merge added with unhandled. Note that we know that
693 // addIntervalsForSpills returns intervals sorted by their starting
695 for (unsigned i = 0, e = added.size(); i != e; ++i)
696 unhandled_.push(added[i]);
702 // push the current interval back to unhandled since we are going
703 // to re-run at least this iteration. Since we didn't modify it it
704 // should go back right in the front of the list
705 unhandled_.push(cur);
707 // otherwise we spill all intervals aliasing the register with
708 // minimum weight, rollback to the interval with the earliest
709 // start point and let the linear scan algorithm run again
710 std::vector<LiveInterval*> added;
711 assert(MRegisterInfo::isPhysicalRegister(minReg) &&
712 "did not choose a register to spill?");
713 BitVector toSpill(mri_->getNumRegs());
715 // We are going to spill minReg and all its aliases.
716 toSpill[minReg] = true;
717 for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
720 // the earliest start of a spilled interval indicates up to where
721 // in handled we need to roll back
722 unsigned earliestStart = cur->beginNumber();
724 // set of spilled vregs (used later to rollback properly)
725 SmallSet<unsigned, 32> spilled;
727 // spill live intervals of virtual regs mapped to the physical register we
728 // want to clear (and its aliases). We only spill those that overlap with the
729 // current interval as the rest do not affect its allocation. we also keep
730 // track of the earliest start of all spilled live intervals since this will
731 // mark our rollback point.
732 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
733 unsigned reg = i->first->reg;
734 if (//MRegisterInfo::isVirtualRegister(reg) &&
735 toSpill[vrm_->getPhys(reg)] &&
736 cur->overlapsFrom(*i->first, i->second)) {
737 DOUT << "\t\t\tspilling(a): " << *i->first << '\n';
738 earliestStart = std::min(earliestStart, i->first->beginNumber());
739 std::vector<LiveInterval*> newIs =
740 li_->addIntervalsForSpills(*i->first, *vrm_, reg);
741 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
745 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
746 unsigned reg = i->first->reg;
747 if (//MRegisterInfo::isVirtualRegister(reg) &&
748 toSpill[vrm_->getPhys(reg)] &&
749 cur->overlapsFrom(*i->first, i->second-1)) {
750 DOUT << "\t\t\tspilling(i): " << *i->first << '\n';
751 earliestStart = std::min(earliestStart, i->first->beginNumber());
752 std::vector<LiveInterval*> newIs =
753 li_->addIntervalsForSpills(*i->first, *vrm_, reg);
754 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
759 DOUT << "\t\trolling back to: " << earliestStart << '\n';
761 // Scan handled in reverse order up to the earliest start of a
762 // spilled live interval and undo each one, restoring the state of
764 while (!handled_.empty()) {
765 LiveInterval* i = handled_.back();
766 // If this interval starts before t we are done.
767 if (i->beginNumber() < earliestStart)
769 DOUT << "\t\t\tundo changes for: " << *i << '\n';
772 // When undoing a live interval allocation we must know if it is active or
773 // inactive to properly update the PhysRegTracker and the VirtRegMap.
774 IntervalPtrs::iterator it;
775 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
777 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
778 if (!spilled.count(i->reg))
780 prt_->delRegUse(vrm_->getPhys(i->reg));
781 vrm_->clearVirt(i->reg);
782 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
784 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
785 if (!spilled.count(i->reg))
787 vrm_->clearVirt(i->reg);
789 assert(MRegisterInfo::isVirtualRegister(i->reg) &&
790 "Can only allocate virtual registers!");
791 vrm_->clearVirt(i->reg);
795 // It interval has a preference, it must be defined by a copy. Clear the
796 // preference now since the source interval allocation may have been undone
801 // Rewind the iterators in the active, inactive, and fixed lists back to the
802 // point we reverted to.
803 RevertVectorIteratorsTo(active_, earliestStart);
804 RevertVectorIteratorsTo(inactive_, earliestStart);
805 RevertVectorIteratorsTo(fixed_, earliestStart);
807 // scan the rest and undo each interval that expired after t and
808 // insert it in active (the next iteration of the algorithm will
809 // put it in inactive if required)
810 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
811 LiveInterval *HI = handled_[i];
812 if (!HI->expiredAt(earliestStart) &&
813 HI->expiredAt(cur->beginNumber())) {
814 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
815 active_.push_back(std::make_pair(HI, HI->begin()));
816 assert(!MRegisterInfo::isPhysicalRegister(HI->reg));
817 prt_->addRegUse(vrm_->getPhys(HI->reg));
821 // merge added with unhandled
822 for (unsigned i = 0, e = added.size(); i != e; ++i)
823 unhandled_.push(added[i]);
826 /// getFreePhysReg - return a free physical register for this virtual register
827 /// interval if we have one, otherwise return 0.
828 unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
829 std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
830 unsigned MaxInactiveCount = 0;
832 const TargetRegisterClass *RC = regmap_->getRegClass(cur->reg);
833 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
835 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
837 unsigned reg = i->first->reg;
838 assert(MRegisterInfo::isVirtualRegister(reg) &&
839 "Can only allocate virtual registers!");
841 // If this is not in a related reg class to the register we're allocating,
843 const TargetRegisterClass *RegRC = regmap_->getRegClass(reg);
844 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
845 reg = vrm_->getPhys(reg);
846 ++inactiveCounts[reg];
847 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
851 unsigned FreeReg = 0;
852 unsigned FreeRegInactiveCount = 0;
854 // If copy coalescer has assigned a "preferred" register, check if it's
857 if (prt_->isRegAvail(cur->preference)) {
858 DOUT << "\t\tassigned the preferred register: "
859 << mri_->getName(cur->preference) << "\n";
860 return cur->preference;
862 DOUT << "\t\tunable to assign the preferred register: "
863 << mri_->getName(cur->preference) << "\n";
865 // Scan for the first available register.
866 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
867 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
869 if (prt_->isRegAvail(*I)) {
871 FreeRegInactiveCount = inactiveCounts[FreeReg];
875 // If there are no free regs, or if this reg has the max inactive count,
876 // return this register.
877 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
879 // Continue scanning the registers, looking for the one with the highest
880 // inactive count. Alkis found that this reduced register pressure very
881 // slightly on X86 (in rev 1.94 of this file), though this should probably be
883 for (; I != E; ++I) {
885 if (prt_->isRegAvail(Reg) && FreeRegInactiveCount < inactiveCounts[Reg]) {
887 FreeRegInactiveCount = inactiveCounts[Reg];
888 if (FreeRegInactiveCount == MaxInactiveCount)
889 break; // We found the one with the max inactive count.
896 FunctionPass* llvm::createLinearScanRegisterAllocator() {
897 return new RALinScan();