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/Analysis/LoopInfo.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/CodeGen/RegAllocRegistry.h"
24 #include "llvm/CodeGen/RegisterCoalescer.h"
25 #include "llvm/CodeGen/SSARegMap.h"
26 #include "llvm/Target/MRegisterInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/ADT/EquivalenceClasses.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/Compiler.h"
41 STATISTIC(NumIters , "Number of iterations performed");
42 STATISTIC(NumBacktracks, "Number of times we had to backtrack");
43 STATISTIC(NumCoalesce, "Number of copies coalesced");
45 static RegisterRegAlloc
46 linearscanRegAlloc("linearscan", " linear scan register allocator",
47 createLinearScanRegisterAllocator);
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_;
66 const TargetInstrInfo* tii_;
68 BitVector allocatableRegs_;
70 const LoopInfo *loopInfo;
72 /// handled_ - Intervals are added to the handled_ set in the order of their
73 /// start value. This is uses for backtracking.
74 std::vector<LiveInterval*> handled_;
76 /// fixed_ - Intervals that correspond to machine registers.
80 /// active_ - Intervals that are currently being processed, and which have a
81 /// live range active for the current point.
84 /// inactive_ - Intervals that are currently being processed, but which have
85 /// a hold at the current point.
86 IntervalPtrs inactive_;
88 typedef std::priority_queue<LiveInterval*,
89 std::vector<LiveInterval*>,
90 greater_ptr<LiveInterval> > IntervalHeap;
91 IntervalHeap unhandled_;
92 std::auto_ptr<PhysRegTracker> prt_;
93 std::auto_ptr<VirtRegMap> vrm_;
94 std::auto_ptr<Spiller> spiller_;
97 virtual const char* getPassName() const {
98 return "Linear Scan Register Allocator";
101 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
102 AU.addRequired<LiveIntervals>();
103 // Make sure PassManager knows which analyses to make available
104 // to coalescing and which analyses coalescing invalidates.
105 AU.addRequiredTransitive<RegisterCoalescer>();
106 AU.addRequired<LoopInfo>();
107 MachineFunctionPass::getAnalysisUsage(AU);
110 /// runOnMachineFunction - register allocate the whole function
111 bool runOnMachineFunction(MachineFunction&);
114 /// linearScan - the linear scan algorithm
117 /// initIntervalSets - initialize the interval sets.
119 void initIntervalSets();
121 /// processActiveIntervals - expire old intervals and move non-overlapping
122 /// ones to the inactive list.
123 void processActiveIntervals(unsigned CurPoint);
125 /// processInactiveIntervals - expire old intervals and move overlapping
126 /// ones to the active list.
127 void processInactiveIntervals(unsigned CurPoint);
129 /// assignRegOrStackSlotAtInterval - assign a register if one
130 /// is available, or spill.
131 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
133 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
134 /// try allocate the definition the same register as the source register
135 /// if the register is not defined during live time of the interval. This
136 /// eliminate a copy. This is used to coalesce copies which were not
137 /// coalesced away before allocation either due to dest and src being in
138 /// different register classes or because the coalescer was overly
140 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
143 /// register handling helpers
146 /// getFreePhysReg - return a free physical register for this virtual
147 /// register interval if we have one, otherwise return 0.
148 unsigned getFreePhysReg(LiveInterval* cur);
150 /// assignVirt2StackSlot - assigns this virtual register to a
151 /// stack slot. returns the stack slot
152 int assignVirt2StackSlot(unsigned virtReg);
154 void ComputeRelatedRegClasses();
156 template <typename ItTy>
157 void printIntervals(const char* const str, ItTy i, ItTy e) const {
158 if (str) DOUT << str << " intervals:\n";
159 for (; i != e; ++i) {
160 DOUT << "\t" << *i->first << " -> ";
161 unsigned reg = i->first->reg;
162 if (MRegisterInfo::isVirtualRegister(reg)) {
163 reg = vrm_->getPhys(reg);
165 DOUT << mri_->getName(reg) << '\n';
169 char RALinScan::ID = 0;
172 void RALinScan::ComputeRelatedRegClasses() {
173 const MRegisterInfo &MRI = *mri_;
175 // First pass, add all reg classes to the union, and determine at least one
176 // reg class that each register is in.
177 bool HasAliases = false;
178 for (MRegisterInfo::regclass_iterator RCI = MRI.regclass_begin(),
179 E = MRI.regclass_end(); RCI != E; ++RCI) {
180 RelatedRegClasses.insert(*RCI);
181 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
183 HasAliases = HasAliases || *MRI.getAliasSet(*I) != 0;
185 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
187 // Already processed this register. Just make sure we know that
188 // multiple register classes share a register.
189 RelatedRegClasses.unionSets(PRC, *RCI);
196 // Second pass, now that we know conservatively what register classes each reg
197 // belongs to, add info about aliases. We don't need to do this for targets
198 // without register aliases.
200 for (std::map<unsigned, const TargetRegisterClass*>::iterator
201 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
203 for (const unsigned *AS = MRI.getAliasSet(I->first); *AS; ++AS)
204 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
207 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
208 /// try allocate the definition the same register as the source register
209 /// if the register is not defined during live time of the interval. This
210 /// eliminate a copy. This is used to coalesce copies which were not
211 /// coalesced away before allocation either due to dest and src being in
212 /// different register classes or because the coalescer was overly
214 unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
215 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
218 VNInfo *vni = cur.getValNumInfo(0);
219 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
221 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
222 unsigned SrcReg, DstReg;
223 if (!CopyMI || !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg))
225 if (MRegisterInfo::isVirtualRegister(SrcReg))
226 if (!vrm_->isAssignedReg(SrcReg))
229 SrcReg = vrm_->getPhys(SrcReg);
233 const TargetRegisterClass *RC = regmap_->getRegClass(cur.reg);
234 if (!RC->contains(SrcReg))
238 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
239 DOUT << "Coalescing: " << cur << " -> " << mri_->getName(SrcReg) << '\n';
240 vrm_->clearVirt(cur.reg);
241 vrm_->assignVirt2Phys(cur.reg, SrcReg);
249 bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
251 tm_ = &fn.getTarget();
252 mri_ = tm_->getRegisterInfo();
253 tii_ = tm_->getInstrInfo();
254 regmap_ = mf_->getSSARegMap();
255 allocatableRegs_ = mri_->getAllocatableSet(fn);
256 li_ = &getAnalysis<LiveIntervals>();
257 loopInfo = &getAnalysis<LoopInfo>();
259 // We don't run the coalescer here because we have no reason to
260 // interact with it. If the coalescer requires interaction, it
261 // won't do anything. If it doesn't require interaction, we assume
262 // it was run as a separate pass.
264 // If this is the first function compiled, compute the related reg classes.
265 if (RelatedRegClasses.empty())
266 ComputeRelatedRegClasses();
268 if (!prt_.get()) prt_.reset(new PhysRegTracker(*mri_));
269 vrm_.reset(new VirtRegMap(*mf_));
270 if (!spiller_.get()) spiller_.reset(createSpiller());
276 // Rewrite spill code and update the PhysRegsUsed set.
277 spiller_->runOnMachineFunction(*mf_, *vrm_);
278 vrm_.reset(); // Free the VirtRegMap
280 while (!unhandled_.empty()) unhandled_.pop();
289 /// initIntervalSets - initialize the interval sets.
291 void RALinScan::initIntervalSets()
293 assert(unhandled_.empty() && fixed_.empty() &&
294 active_.empty() && inactive_.empty() &&
295 "interval sets should be empty on initialization");
297 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
298 if (MRegisterInfo::isPhysicalRegister(i->second.reg)) {
299 mf_->setPhysRegUsed(i->second.reg);
300 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
302 unhandled_.push(&i->second);
306 void RALinScan::linearScan()
308 // linear scan algorithm
309 DOUT << "********** LINEAR SCAN **********\n";
310 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
312 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
314 while (!unhandled_.empty()) {
315 // pick the interval with the earliest start point
316 LiveInterval* cur = unhandled_.top();
319 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
321 processActiveIntervals(cur->beginNumber());
322 processInactiveIntervals(cur->beginNumber());
324 assert(MRegisterInfo::isVirtualRegister(cur->reg) &&
325 "Can only allocate virtual registers!");
327 // Allocating a virtual register. try to find a free
328 // physical register or spill an interval (possibly this one) in order to
330 assignRegOrStackSlotAtInterval(cur);
332 DEBUG(printIntervals("active", active_.begin(), active_.end()));
333 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
336 // expire any remaining active intervals
337 while (!active_.empty()) {
338 IntervalPtr &IP = active_.back();
339 unsigned reg = IP.first->reg;
340 DOUT << "\tinterval " << *IP.first << " expired\n";
341 assert(MRegisterInfo::isVirtualRegister(reg) &&
342 "Can only allocate virtual registers!");
343 reg = vrm_->getPhys(reg);
344 prt_->delRegUse(reg);
348 // expire any remaining inactive intervals
349 DEBUG(for (IntervalPtrs::reverse_iterator
350 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
351 DOUT << "\tinterval " << *i->first << " expired\n");
354 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
355 MachineFunction::iterator EntryMBB = mf_->begin();
356 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
357 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
358 LiveInterval &cur = i->second;
360 bool isPhys = MRegisterInfo::isPhysicalRegister(cur.reg);
363 else if (vrm_->isAssignedReg(cur.reg))
364 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
367 // Ignore splited live intervals.
368 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
370 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
372 const LiveRange &LR = *I;
373 if (li_->findLiveInMBBs(LR, LiveInMBBs)) {
374 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
375 if (LiveInMBBs[i] != EntryMBB)
376 LiveInMBBs[i]->addLiveIn(Reg);
385 /// processActiveIntervals - expire old intervals and move non-overlapping ones
386 /// to the inactive list.
387 void RALinScan::processActiveIntervals(unsigned CurPoint)
389 DOUT << "\tprocessing active intervals:\n";
391 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
392 LiveInterval *Interval = active_[i].first;
393 LiveInterval::iterator IntervalPos = active_[i].second;
394 unsigned reg = Interval->reg;
396 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
398 if (IntervalPos == Interval->end()) { // Remove expired intervals.
399 DOUT << "\t\tinterval " << *Interval << " expired\n";
400 assert(MRegisterInfo::isVirtualRegister(reg) &&
401 "Can only allocate virtual registers!");
402 reg = vrm_->getPhys(reg);
403 prt_->delRegUse(reg);
405 // Pop off the end of the list.
406 active_[i] = active_.back();
410 } else if (IntervalPos->start > CurPoint) {
411 // Move inactive intervals to inactive list.
412 DOUT << "\t\tinterval " << *Interval << " inactive\n";
413 assert(MRegisterInfo::isVirtualRegister(reg) &&
414 "Can only allocate virtual registers!");
415 reg = vrm_->getPhys(reg);
416 prt_->delRegUse(reg);
418 inactive_.push_back(std::make_pair(Interval, IntervalPos));
420 // Pop off the end of the list.
421 active_[i] = active_.back();
425 // Otherwise, just update the iterator position.
426 active_[i].second = IntervalPos;
431 /// processInactiveIntervals - expire old intervals and move overlapping
432 /// ones to the active list.
433 void RALinScan::processInactiveIntervals(unsigned CurPoint)
435 DOUT << "\tprocessing inactive intervals:\n";
437 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
438 LiveInterval *Interval = inactive_[i].first;
439 LiveInterval::iterator IntervalPos = inactive_[i].second;
440 unsigned reg = Interval->reg;
442 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
444 if (IntervalPos == Interval->end()) { // remove expired intervals.
445 DOUT << "\t\tinterval " << *Interval << " expired\n";
447 // Pop off the end of the list.
448 inactive_[i] = inactive_.back();
449 inactive_.pop_back();
451 } else if (IntervalPos->start <= CurPoint) {
452 // move re-activated intervals in active list
453 DOUT << "\t\tinterval " << *Interval << " active\n";
454 assert(MRegisterInfo::isVirtualRegister(reg) &&
455 "Can only allocate virtual registers!");
456 reg = vrm_->getPhys(reg);
457 prt_->addRegUse(reg);
459 active_.push_back(std::make_pair(Interval, IntervalPos));
461 // Pop off the end of the list.
462 inactive_[i] = inactive_.back();
463 inactive_.pop_back();
466 // Otherwise, just update the iterator position.
467 inactive_[i].second = IntervalPos;
472 /// updateSpillWeights - updates the spill weights of the specifed physical
473 /// register and its weight.
474 static void updateSpillWeights(std::vector<float> &Weights,
475 unsigned reg, float weight,
476 const MRegisterInfo *MRI) {
477 Weights[reg] += weight;
478 for (const unsigned* as = MRI->getAliasSet(reg); *as; ++as)
479 Weights[*as] += weight;
483 RALinScan::IntervalPtrs::iterator
484 FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
485 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
487 if (I->first == LI) return I;
491 static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
492 for (unsigned i = 0, e = V.size(); i != e; ++i) {
493 RALinScan::IntervalPtr &IP = V[i];
494 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
496 if (I != IP.first->begin()) --I;
501 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
503 void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
505 DOUT << "\tallocating current interval: ";
507 PhysRegTracker backupPrt = *prt_;
509 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
510 unsigned StartPosition = cur->beginNumber();
511 const TargetRegisterClass *RC = regmap_->getRegClass(cur->reg);
512 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
514 // If this live interval is defined by a move instruction and its source is
515 // assigned a physical register that is compatible with the target register
516 // class, then we should try to assign it the same register.
517 // This can happen when the move is from a larger register class to a smaller
518 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
519 if (!cur->preference && cur->containsOneValue()) {
520 VNInfo *vni = cur->getValNumInfo(0);
521 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
522 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
523 unsigned SrcReg, DstReg;
524 if (tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
526 if (MRegisterInfo::isPhysicalRegister(SrcReg))
528 else if (vrm_->isAssignedReg(SrcReg))
529 Reg = vrm_->getPhys(SrcReg);
530 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
531 cur->preference = Reg;
536 // for every interval in inactive we overlap with, mark the
537 // register as not free and update spill weights.
538 for (IntervalPtrs::const_iterator i = inactive_.begin(),
539 e = inactive_.end(); i != e; ++i) {
540 unsigned Reg = i->first->reg;
541 assert(MRegisterInfo::isVirtualRegister(Reg) &&
542 "Can only allocate virtual registers!");
543 const TargetRegisterClass *RegRC = regmap_->getRegClass(Reg);
544 // If this is not in a related reg class to the register we're allocating,
546 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
547 cur->overlapsFrom(*i->first, i->second-1)) {
548 Reg = vrm_->getPhys(Reg);
549 prt_->addRegUse(Reg);
550 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
554 // Speculatively check to see if we can get a register right now. If not,
555 // we know we won't be able to by adding more constraints. If so, we can
556 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
557 // is very bad (it contains all callee clobbered registers for any functions
558 // with a call), so we want to avoid doing that if possible.
559 unsigned physReg = getFreePhysReg(cur);
561 // We got a register. However, if it's in the fixed_ list, we might
562 // conflict with it. Check to see if we conflict with it or any of its
564 SmallSet<unsigned, 8> RegAliases;
565 for (const unsigned *AS = mri_->getAliasSet(physReg); *AS; ++AS)
566 RegAliases.insert(*AS);
568 bool ConflictsWithFixed = false;
569 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
570 IntervalPtr &IP = fixed_[i];
571 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
572 // Okay, this reg is on the fixed list. Check to see if we actually
574 LiveInterval *I = IP.first;
575 if (I->endNumber() > StartPosition) {
576 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
578 if (II != I->begin() && II->start > StartPosition)
580 if (cur->overlapsFrom(*I, II)) {
581 ConflictsWithFixed = true;
588 // Okay, the register picked by our speculative getFreePhysReg call turned
589 // out to be in use. Actually add all of the conflicting fixed registers to
590 // prt so we can do an accurate query.
591 if (ConflictsWithFixed) {
592 // For every interval in fixed we overlap with, mark the register as not
593 // free and update spill weights.
594 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
595 IntervalPtr &IP = fixed_[i];
596 LiveInterval *I = IP.first;
598 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
599 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
600 I->endNumber() > StartPosition) {
601 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
603 if (II != I->begin() && II->start > StartPosition)
605 if (cur->overlapsFrom(*I, II)) {
606 unsigned reg = I->reg;
607 prt_->addRegUse(reg);
608 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
613 // Using the newly updated prt_ object, which includes conflicts in the
614 // future, see if there are any registers available.
615 physReg = getFreePhysReg(cur);
619 // Restore the physical register tracker, removing information about the
623 // if we find a free register, we are done: assign this virtual to
624 // the free physical register and add this interval to the active
627 DOUT << mri_->getName(physReg) << '\n';
628 vrm_->assignVirt2Phys(cur->reg, physReg);
629 prt_->addRegUse(physReg);
630 active_.push_back(std::make_pair(cur, cur->begin()));
631 handled_.push_back(cur);
634 DOUT << "no free registers\n";
636 // Compile the spill weights into an array that is better for scanning.
637 std::vector<float> SpillWeights(mri_->getNumRegs(), 0.0);
638 for (std::vector<std::pair<unsigned, float> >::iterator
639 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
640 updateSpillWeights(SpillWeights, I->first, I->second, mri_);
642 // for each interval in active, update spill weights.
643 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
645 unsigned reg = i->first->reg;
646 assert(MRegisterInfo::isVirtualRegister(reg) &&
647 "Can only allocate virtual registers!");
648 reg = vrm_->getPhys(reg);
649 updateSpillWeights(SpillWeights, reg, i->first->weight, mri_);
652 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
654 // Find a register to spill.
655 float minWeight = HUGE_VALF;
656 unsigned minReg = cur->preference; // Try the preferred register first.
658 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
659 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
660 e = RC->allocation_order_end(*mf_); i != e; ++i) {
662 if (minWeight > SpillWeights[reg]) {
663 minWeight = SpillWeights[reg];
668 // If we didn't find a register that is spillable, try aliases?
670 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
671 e = RC->allocation_order_end(*mf_); i != e; ++i) {
673 // No need to worry about if the alias register size < regsize of RC.
674 // We are going to spill all registers that alias it anyway.
675 for (const unsigned* as = mri_->getAliasSet(reg); *as; ++as) {
676 if (minWeight > SpillWeights[*as]) {
677 minWeight = SpillWeights[*as];
683 // All registers must have inf weight. Just grab one!
685 minReg = *RC->allocation_order_begin(*mf_);
688 DOUT << "\t\tregister with min weight: "
689 << mri_->getName(minReg) << " (" << minWeight << ")\n";
691 // if the current has the minimum weight, we need to spill it and
692 // add any added intervals back to unhandled, and restart
694 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
695 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
696 std::vector<LiveInterval*> added =
697 li_->addIntervalsForSpills(*cur, loopInfo, *vrm_);
699 return; // Early exit if all spills were folded.
701 // Merge added with unhandled. Note that we know that
702 // addIntervalsForSpills returns intervals sorted by their starting
704 for (unsigned i = 0, e = added.size(); i != e; ++i)
705 unhandled_.push(added[i]);
711 // push the current interval back to unhandled since we are going
712 // to re-run at least this iteration. Since we didn't modify it it
713 // should go back right in the front of the list
714 unhandled_.push(cur);
716 // otherwise we spill all intervals aliasing the register with
717 // minimum weight, rollback to the interval with the earliest
718 // start point and let the linear scan algorithm run again
719 std::vector<LiveInterval*> added;
720 assert(MRegisterInfo::isPhysicalRegister(minReg) &&
721 "did not choose a register to spill?");
722 BitVector toSpill(mri_->getNumRegs());
724 // We are going to spill minReg and all its aliases.
725 toSpill[minReg] = true;
726 for (const unsigned* as = mri_->getAliasSet(minReg); *as; ++as)
729 // the earliest start of a spilled interval indicates up to where
730 // in handled we need to roll back
731 unsigned earliestStart = cur->beginNumber();
733 // set of spilled vregs (used later to rollback properly)
734 SmallSet<unsigned, 32> spilled;
736 // spill live intervals of virtual regs mapped to the physical register we
737 // want to clear (and its aliases). We only spill those that overlap with the
738 // current interval as the rest do not affect its allocation. we also keep
739 // track of the earliest start of all spilled live intervals since this will
740 // mark our rollback point.
741 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
742 unsigned reg = i->first->reg;
743 if (//MRegisterInfo::isVirtualRegister(reg) &&
744 toSpill[vrm_->getPhys(reg)] &&
745 cur->overlapsFrom(*i->first, i->second)) {
746 DOUT << "\t\t\tspilling(a): " << *i->first << '\n';
747 earliestStart = std::min(earliestStart, i->first->beginNumber());
748 std::vector<LiveInterval*> newIs =
749 li_->addIntervalsForSpills(*i->first, loopInfo, *vrm_);
750 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
754 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
755 unsigned reg = i->first->reg;
756 if (//MRegisterInfo::isVirtualRegister(reg) &&
757 toSpill[vrm_->getPhys(reg)] &&
758 cur->overlapsFrom(*i->first, i->second-1)) {
759 DOUT << "\t\t\tspilling(i): " << *i->first << '\n';
760 earliestStart = std::min(earliestStart, i->first->beginNumber());
761 std::vector<LiveInterval*> newIs =
762 li_->addIntervalsForSpills(*i->first, loopInfo, *vrm_);
763 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
768 DOUT << "\t\trolling back to: " << earliestStart << '\n';
770 // Scan handled in reverse order up to the earliest start of a
771 // spilled live interval and undo each one, restoring the state of
773 while (!handled_.empty()) {
774 LiveInterval* i = handled_.back();
775 // If this interval starts before t we are done.
776 if (i->beginNumber() < earliestStart)
778 DOUT << "\t\t\tundo changes for: " << *i << '\n';
781 // When undoing a live interval allocation we must know if it is active or
782 // inactive to properly update the PhysRegTracker and the VirtRegMap.
783 IntervalPtrs::iterator it;
784 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
786 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
787 if (!spilled.count(i->reg))
789 prt_->delRegUse(vrm_->getPhys(i->reg));
790 vrm_->clearVirt(i->reg);
791 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
793 assert(!MRegisterInfo::isPhysicalRegister(i->reg));
794 if (!spilled.count(i->reg))
796 vrm_->clearVirt(i->reg);
798 assert(MRegisterInfo::isVirtualRegister(i->reg) &&
799 "Can only allocate virtual registers!");
800 vrm_->clearVirt(i->reg);
804 // It interval has a preference, it must be defined by a copy. Clear the
805 // preference now since the source interval allocation may have been undone
810 // Rewind the iterators in the active, inactive, and fixed lists back to the
811 // point we reverted to.
812 RevertVectorIteratorsTo(active_, earliestStart);
813 RevertVectorIteratorsTo(inactive_, earliestStart);
814 RevertVectorIteratorsTo(fixed_, earliestStart);
816 // scan the rest and undo each interval that expired after t and
817 // insert it in active (the next iteration of the algorithm will
818 // put it in inactive if required)
819 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
820 LiveInterval *HI = handled_[i];
821 if (!HI->expiredAt(earliestStart) &&
822 HI->expiredAt(cur->beginNumber())) {
823 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
824 active_.push_back(std::make_pair(HI, HI->begin()));
825 assert(!MRegisterInfo::isPhysicalRegister(HI->reg));
826 prt_->addRegUse(vrm_->getPhys(HI->reg));
830 // merge added with unhandled
831 for (unsigned i = 0, e = added.size(); i != e; ++i)
832 unhandled_.push(added[i]);
835 /// getFreePhysReg - return a free physical register for this virtual register
836 /// interval if we have one, otherwise return 0.
837 unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
838 std::vector<unsigned> inactiveCounts(mri_->getNumRegs(), 0);
839 unsigned MaxInactiveCount = 0;
841 const TargetRegisterClass *RC = regmap_->getRegClass(cur->reg);
842 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
844 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
846 unsigned reg = i->first->reg;
847 assert(MRegisterInfo::isVirtualRegister(reg) &&
848 "Can only allocate virtual registers!");
850 // If this is not in a related reg class to the register we're allocating,
852 const TargetRegisterClass *RegRC = regmap_->getRegClass(reg);
853 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
854 reg = vrm_->getPhys(reg);
855 ++inactiveCounts[reg];
856 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
860 unsigned FreeReg = 0;
861 unsigned FreeRegInactiveCount = 0;
863 // If copy coalescer has assigned a "preferred" register, check if it's
866 if (prt_->isRegAvail(cur->preference)) {
867 DOUT << "\t\tassigned the preferred register: "
868 << mri_->getName(cur->preference) << "\n";
869 return cur->preference;
871 DOUT << "\t\tunable to assign the preferred register: "
872 << mri_->getName(cur->preference) << "\n";
874 // Scan for the first available register.
875 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
876 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
878 if (prt_->isRegAvail(*I)) {
880 FreeRegInactiveCount = inactiveCounts[FreeReg];
884 // If there are no free regs, or if this reg has the max inactive count,
885 // return this register.
886 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
888 // Continue scanning the registers, looking for the one with the highest
889 // inactive count. Alkis found that this reduced register pressure very
890 // slightly on X86 (in rev 1.94 of this file), though this should probably be
892 for (; I != E; ++I) {
894 if (prt_->isRegAvail(Reg) && FreeRegInactiveCount < inactiveCounts[Reg]) {
896 FreeRegInactiveCount = inactiveCounts[Reg];
897 if (FreeRegInactiveCount == MaxInactiveCount)
898 break; // We found the one with the max inactive count.
905 FunctionPass* llvm::createLinearScanRegisterAllocator() {
906 return new RALinScan();