1 //===-- RegAllocLinearScan.cpp - Linear Scan register allocator -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a linear scan register allocator.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "regalloc"
15 #include "LiveDebugVariables.h"
16 #include "VirtRegMap.h"
17 #include "VirtRegRewriter.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Function.h"
21 #include "llvm/CodeGen/CalcSpillWeights.h"
22 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineInstr.h"
25 #include "llvm/CodeGen/MachineLoopInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/Passes.h"
28 #include "llvm/CodeGen/RegAllocRegistry.h"
29 #include "llvm/CodeGen/RegisterCoalescer.h"
30 #include "llvm/Target/TargetRegisterInfo.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/ADT/EquivalenceClasses.h"
35 #include "llvm/ADT/SmallSet.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/raw_ostream.h"
49 STATISTIC(NumIters , "Number of iterations performed");
50 STATISTIC(NumBacktracks, "Number of times we had to backtrack");
51 STATISTIC(NumCoalesce, "Number of copies coalesced");
52 STATISTIC(NumDowngrade, "Number of registers downgraded");
55 NewHeuristic("new-spilling-heuristic",
56 cl::desc("Use new spilling heuristic"),
57 cl::init(false), cl::Hidden);
60 PreSplitIntervals("pre-alloc-split",
61 cl::desc("Pre-register allocation live interval splitting"),
62 cl::init(false), cl::Hidden);
65 TrivCoalesceEnds("trivial-coalesce-ends",
66 cl::desc("Attempt trivial coalescing of interval ends"),
67 cl::init(false), cl::Hidden);
69 static RegisterRegAlloc
70 linearscanRegAlloc("linearscan", "linear scan register allocator",
71 createLinearScanRegisterAllocator);
74 // When we allocate a register, add it to a fixed-size queue of
75 // registers to skip in subsequent allocations. This trades a small
76 // amount of register pressure and increased spills for flexibility in
77 // the post-pass scheduler.
79 // Note that in a the number of registers used for reloading spills
80 // will be one greater than the value of this option.
82 // One big limitation of this is that it doesn't differentiate between
83 // different register classes. So on x86-64, if there is xmm register
84 // pressure, it can caused fewer GPRs to be held in the queue.
85 static cl::opt<unsigned>
86 NumRecentlyUsedRegs("linearscan-skip-count",
87 cl::desc("Number of registers for linearscan to remember"
92 struct RALinScan : public MachineFunctionPass {
94 RALinScan() : MachineFunctionPass(ID) {
95 initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
96 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
97 initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
98 initializeRegisterCoalescerAnalysisGroup(
99 *PassRegistry::getPassRegistry());
100 initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
101 initializePreAllocSplittingPass(*PassRegistry::getPassRegistry());
102 initializeLiveStacksPass(*PassRegistry::getPassRegistry());
103 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
104 initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
105 initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
106 initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
108 // Initialize the queue to record recently-used registers.
109 if (NumRecentlyUsedRegs > 0)
110 RecentRegs.resize(NumRecentlyUsedRegs, 0);
111 RecentNext = RecentRegs.begin();
114 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
115 typedef SmallVector<IntervalPtr, 32> IntervalPtrs;
117 /// RelatedRegClasses - This structure is built the first time a function is
118 /// compiled, and keeps track of which register classes have registers that
119 /// belong to multiple classes or have aliases that are in other classes.
120 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
121 DenseMap<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
123 // NextReloadMap - For each register in the map, it maps to the another
124 // register which is defined by a reload from the same stack slot and
125 // both reloads are in the same basic block.
126 DenseMap<unsigned, unsigned> NextReloadMap;
128 // DowngradedRegs - A set of registers which are being "downgraded", i.e.
129 // un-favored for allocation.
130 SmallSet<unsigned, 8> DowngradedRegs;
132 // DowngradeMap - A map from virtual registers to physical registers being
133 // downgraded for the virtual registers.
134 DenseMap<unsigned, unsigned> DowngradeMap;
136 MachineFunction* mf_;
137 MachineRegisterInfo* mri_;
138 const TargetMachine* tm_;
139 const TargetRegisterInfo* tri_;
140 const TargetInstrInfo* tii_;
141 BitVector allocatableRegs_;
142 BitVector reservedRegs_;
144 MachineLoopInfo *loopInfo;
146 /// handled_ - Intervals are added to the handled_ set in the order of their
147 /// start value. This is uses for backtracking.
148 std::vector<LiveInterval*> handled_;
150 /// fixed_ - Intervals that correspond to machine registers.
154 /// active_ - Intervals that are currently being processed, and which have a
155 /// live range active for the current point.
156 IntervalPtrs active_;
158 /// inactive_ - Intervals that are currently being processed, but which have
159 /// a hold at the current point.
160 IntervalPtrs inactive_;
162 typedef std::priority_queue<LiveInterval*,
163 SmallVector<LiveInterval*, 64>,
164 greater_ptr<LiveInterval> > IntervalHeap;
165 IntervalHeap unhandled_;
167 /// regUse_ - Tracks register usage.
168 SmallVector<unsigned, 32> regUse_;
169 SmallVector<unsigned, 32> regUseBackUp_;
171 /// vrm_ - Tracks register assignments.
174 std::auto_ptr<VirtRegRewriter> rewriter_;
176 std::auto_ptr<Spiller> spiller_;
178 // The queue of recently-used registers.
179 SmallVector<unsigned, 4> RecentRegs;
180 SmallVector<unsigned, 4>::iterator RecentNext;
182 // Record that we just picked this register.
183 void recordRecentlyUsed(unsigned reg) {
184 assert(reg != 0 && "Recently used register is NOREG!");
185 if (!RecentRegs.empty()) {
187 if (RecentNext == RecentRegs.end())
188 RecentNext = RecentRegs.begin();
193 virtual const char* getPassName() const {
194 return "Linear Scan Register Allocator";
197 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
198 AU.setPreservesCFG();
199 AU.addRequired<AliasAnalysis>();
200 AU.addPreserved<AliasAnalysis>();
201 AU.addRequired<LiveIntervals>();
202 AU.addPreserved<SlotIndexes>();
204 AU.addRequiredID(StrongPHIEliminationID);
205 // Make sure PassManager knows which analyses to make available
206 // to coalescing and which analyses coalescing invalidates.
207 AU.addRequiredTransitive<RegisterCoalescer>();
208 AU.addRequired<CalculateSpillWeights>();
209 if (PreSplitIntervals)
210 AU.addRequiredID(PreAllocSplittingID);
211 AU.addRequiredID(LiveStacksID);
212 AU.addPreservedID(LiveStacksID);
213 AU.addRequired<MachineLoopInfo>();
214 AU.addPreserved<MachineLoopInfo>();
215 AU.addRequired<VirtRegMap>();
216 AU.addPreserved<VirtRegMap>();
217 AU.addRequired<LiveDebugVariables>();
218 AU.addPreserved<LiveDebugVariables>();
219 AU.addRequiredID(MachineDominatorsID);
220 AU.addPreservedID(MachineDominatorsID);
221 MachineFunctionPass::getAnalysisUsage(AU);
224 /// runOnMachineFunction - register allocate the whole function
225 bool runOnMachineFunction(MachineFunction&);
227 // Determine if we skip this register due to its being recently used.
228 bool isRecentlyUsed(unsigned reg) const {
229 return std::find(RecentRegs.begin(), RecentRegs.end(), reg) !=
234 /// linearScan - the linear scan algorithm
237 /// initIntervalSets - initialize the interval sets.
239 void initIntervalSets();
241 /// processActiveIntervals - expire old intervals and move non-overlapping
242 /// ones to the inactive list.
243 void processActiveIntervals(SlotIndex CurPoint);
245 /// processInactiveIntervals - expire old intervals and move overlapping
246 /// ones to the active list.
247 void processInactiveIntervals(SlotIndex CurPoint);
249 /// hasNextReloadInterval - Return the next liveinterval that's being
250 /// defined by a reload from the same SS as the specified one.
251 LiveInterval *hasNextReloadInterval(LiveInterval *cur);
253 /// DowngradeRegister - Downgrade a register for allocation.
254 void DowngradeRegister(LiveInterval *li, unsigned Reg);
256 /// UpgradeRegister - Upgrade a register for allocation.
257 void UpgradeRegister(unsigned Reg);
259 /// assignRegOrStackSlotAtInterval - assign a register if one
260 /// is available, or spill.
261 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
263 void updateSpillWeights(std::vector<float> &Weights,
264 unsigned reg, float weight,
265 const TargetRegisterClass *RC);
267 /// findIntervalsToSpill - Determine the intervals to spill for the
268 /// specified interval. It's passed the physical registers whose spill
269 /// weight is the lowest among all the registers whose live intervals
270 /// conflict with the interval.
271 void findIntervalsToSpill(LiveInterval *cur,
272 std::vector<std::pair<unsigned,float> > &Candidates,
274 SmallVector<LiveInterval*, 8> &SpillIntervals);
276 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
277 /// try to allocate the definition to the same register as the source,
278 /// if the register is not defined during the life time of the interval.
279 /// This eliminates a copy, and is used to coalesce copies which were not
280 /// coalesced away before allocation either due to dest and src being in
281 /// different register classes or because the coalescer was overly
283 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
286 /// Register usage / availability tracking helpers.
290 regUse_.resize(tri_->getNumRegs(), 0);
291 regUseBackUp_.resize(tri_->getNumRegs(), 0);
294 void finalizeRegUses() {
296 // Verify all the registers are "freed".
298 for (unsigned i = 0, e = tri_->getNumRegs(); i != e; ++i) {
299 if (regUse_[i] != 0) {
300 dbgs() << tri_->getName(i) << " is still in use!\n";
308 regUseBackUp_.clear();
311 void addRegUse(unsigned physReg) {
312 assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
313 "should be physical register!");
315 for (const unsigned* as = tri_->getAliasSet(physReg); *as; ++as)
319 void delRegUse(unsigned physReg) {
320 assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
321 "should be physical register!");
322 assert(regUse_[physReg] != 0);
324 for (const unsigned* as = tri_->getAliasSet(physReg); *as; ++as) {
325 assert(regUse_[*as] != 0);
330 bool isRegAvail(unsigned physReg) const {
331 assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
332 "should be physical register!");
333 return regUse_[physReg] == 0;
336 void backUpRegUses() {
337 regUseBackUp_ = regUse_;
340 void restoreRegUses() {
341 regUse_ = regUseBackUp_;
345 /// Register handling helpers.
348 /// getFreePhysReg - return a free physical register for this virtual
349 /// register interval if we have one, otherwise return 0.
350 unsigned getFreePhysReg(LiveInterval* cur);
351 unsigned getFreePhysReg(LiveInterval* cur,
352 const TargetRegisterClass *RC,
353 unsigned MaxInactiveCount,
354 SmallVector<unsigned, 256> &inactiveCounts,
357 /// getFirstNonReservedPhysReg - return the first non-reserved physical
358 /// register in the register class.
359 unsigned getFirstNonReservedPhysReg(const TargetRegisterClass *RC) {
360 TargetRegisterClass::iterator aoe = RC->allocation_order_end(*mf_);
361 TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_);
362 while (i != aoe && reservedRegs_.test(*i))
364 assert(i != aoe && "All registers reserved?!");
368 void ComputeRelatedRegClasses();
370 template <typename ItTy>
371 void printIntervals(const char* const str, ItTy i, ItTy e) const {
374 dbgs() << str << " intervals:\n";
376 for (; i != e; ++i) {
377 dbgs() << "\t" << *i->first << " -> ";
379 unsigned reg = i->first->reg;
380 if (TargetRegisterInfo::isVirtualRegister(reg))
381 reg = vrm_->getPhys(reg);
383 dbgs() << tri_->getName(reg) << '\n';
388 char RALinScan::ID = 0;
391 INITIALIZE_PASS_BEGIN(RALinScan, "linearscan-regalloc",
392 "Linear Scan Register Allocator", false, false)
393 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
394 INITIALIZE_PASS_DEPENDENCY(StrongPHIElimination)
395 INITIALIZE_PASS_DEPENDENCY(CalculateSpillWeights)
396 INITIALIZE_PASS_DEPENDENCY(PreAllocSplitting)
397 INITIALIZE_PASS_DEPENDENCY(LiveStacks)
398 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
399 INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
400 INITIALIZE_AG_DEPENDENCY(RegisterCoalescer)
401 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
402 INITIALIZE_PASS_END(RALinScan, "linearscan-regalloc",
403 "Linear Scan Register Allocator", false, false)
405 void RALinScan::ComputeRelatedRegClasses() {
406 // First pass, add all reg classes to the union, and determine at least one
407 // reg class that each register is in.
408 bool HasAliases = false;
409 for (TargetRegisterInfo::regclass_iterator RCI = tri_->regclass_begin(),
410 E = tri_->regclass_end(); RCI != E; ++RCI) {
411 RelatedRegClasses.insert(*RCI);
412 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
414 HasAliases = HasAliases || *tri_->getAliasSet(*I) != 0;
416 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
418 // Already processed this register. Just make sure we know that
419 // multiple register classes share a register.
420 RelatedRegClasses.unionSets(PRC, *RCI);
427 // Second pass, now that we know conservatively what register classes each reg
428 // belongs to, add info about aliases. We don't need to do this for targets
429 // without register aliases.
431 for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
432 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
434 for (const unsigned *AS = tri_->getAliasSet(I->first); *AS; ++AS)
435 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
438 /// attemptTrivialCoalescing - If a simple interval is defined by a copy, try
439 /// allocate the definition the same register as the source register if the
440 /// register is not defined during live time of the interval. If the interval is
441 /// killed by a copy, try to use the destination register. This eliminates a
442 /// copy. This is used to coalesce copies which were not coalesced away before
443 /// allocation either due to dest and src being in different register classes or
444 /// because the coalescer was overly conservative.
445 unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
446 unsigned Preference = vrm_->getRegAllocPref(cur.reg);
447 if ((Preference && Preference == Reg) || !cur.containsOneValue())
450 // We cannot handle complicated live ranges. Simple linear stuff only.
451 if (cur.ranges.size() != 1)
454 const LiveRange &range = cur.ranges.front();
456 VNInfo *vni = range.valno;
462 MachineInstr *CopyMI;
463 if ((CopyMI = li_->getInstructionFromIndex(vni->def)) && CopyMI->isCopy())
464 // Defined by a copy, try to extend SrcReg forward
465 CandReg = CopyMI->getOperand(1).getReg();
466 else if (TrivCoalesceEnds &&
467 (CopyMI = li_->getInstructionFromIndex(range.end.getBaseIndex())) &&
468 CopyMI->isCopy() && cur.reg == CopyMI->getOperand(1).getReg())
469 // Only used by a copy, try to extend DstReg backwards
470 CandReg = CopyMI->getOperand(0).getReg();
474 // If the target of the copy is a sub-register then don't coalesce.
475 if(CopyMI->getOperand(0).getSubReg())
479 if (TargetRegisterInfo::isVirtualRegister(CandReg)) {
480 if (!vrm_->isAssignedReg(CandReg))
482 CandReg = vrm_->getPhys(CandReg);
487 const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
488 if (!RC->contains(CandReg))
491 if (li_->conflictsWithPhysReg(cur, *vrm_, CandReg))
495 DEBUG(dbgs() << "Coalescing: " << cur << " -> " << tri_->getName(CandReg)
497 vrm_->clearVirt(cur.reg);
498 vrm_->assignVirt2Phys(cur.reg, CandReg);
504 bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
506 mri_ = &fn.getRegInfo();
507 tm_ = &fn.getTarget();
508 tri_ = tm_->getRegisterInfo();
509 tii_ = tm_->getInstrInfo();
510 allocatableRegs_ = tri_->getAllocatableSet(fn);
511 reservedRegs_ = tri_->getReservedRegs(fn);
512 li_ = &getAnalysis<LiveIntervals>();
513 loopInfo = &getAnalysis<MachineLoopInfo>();
515 // We don't run the coalescer here because we have no reason to
516 // interact with it. If the coalescer requires interaction, it
517 // won't do anything. If it doesn't require interaction, we assume
518 // it was run as a separate pass.
520 // If this is the first function compiled, compute the related reg classes.
521 if (RelatedRegClasses.empty())
522 ComputeRelatedRegClasses();
524 // Also resize register usage trackers.
527 vrm_ = &getAnalysis<VirtRegMap>();
528 if (!rewriter_.get()) rewriter_.reset(createVirtRegRewriter());
530 spiller_.reset(createSpiller(*this, *mf_, *vrm_));
536 // Rewrite spill code and update the PhysRegsUsed set.
537 rewriter_->runOnMachineFunction(*mf_, *vrm_, li_);
539 // Write out new DBG_VALUE instructions.
540 getAnalysis<LiveDebugVariables>().emitDebugValues(vrm_);
542 assert(unhandled_.empty() && "Unhandled live intervals remain!");
550 NextReloadMap.clear();
551 DowngradedRegs.clear();
552 DowngradeMap.clear();
558 /// initIntervalSets - initialize the interval sets.
560 void RALinScan::initIntervalSets()
562 assert(unhandled_.empty() && fixed_.empty() &&
563 active_.empty() && inactive_.empty() &&
564 "interval sets should be empty on initialization");
566 handled_.reserve(li_->getNumIntervals());
568 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
569 if (TargetRegisterInfo::isPhysicalRegister(i->second->reg)) {
570 if (!i->second->empty()) {
571 mri_->setPhysRegUsed(i->second->reg);
572 fixed_.push_back(std::make_pair(i->second, i->second->begin()));
575 if (i->second->empty()) {
576 assignRegOrStackSlotAtInterval(i->second);
579 unhandled_.push(i->second);
584 void RALinScan::linearScan() {
585 // linear scan algorithm
587 dbgs() << "********** LINEAR SCAN **********\n"
588 << "********** Function: "
589 << mf_->getFunction()->getName() << '\n';
590 printIntervals("fixed", fixed_.begin(), fixed_.end());
593 while (!unhandled_.empty()) {
594 // pick the interval with the earliest start point
595 LiveInterval* cur = unhandled_.top();
598 DEBUG(dbgs() << "\n*** CURRENT ***: " << *cur << '\n');
600 assert(!cur->empty() && "Empty interval in unhandled set.");
602 processActiveIntervals(cur->beginIndex());
603 processInactiveIntervals(cur->beginIndex());
605 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
606 "Can only allocate virtual registers!");
608 // Allocating a virtual register. try to find a free
609 // physical register or spill an interval (possibly this one) in order to
611 assignRegOrStackSlotAtInterval(cur);
614 printIntervals("active", active_.begin(), active_.end());
615 printIntervals("inactive", inactive_.begin(), inactive_.end());
619 // Expire any remaining active intervals
620 while (!active_.empty()) {
621 IntervalPtr &IP = active_.back();
622 unsigned reg = IP.first->reg;
623 DEBUG(dbgs() << "\tinterval " << *IP.first << " expired\n");
624 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
625 "Can only allocate virtual registers!");
626 reg = vrm_->getPhys(reg);
631 // Expire any remaining inactive intervals
633 for (IntervalPtrs::reverse_iterator
634 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
635 dbgs() << "\tinterval " << *i->first << " expired\n";
639 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
640 MachineFunction::iterator EntryMBB = mf_->begin();
641 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
642 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
643 LiveInterval &cur = *i->second;
645 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
648 else if (vrm_->isAssignedReg(cur.reg))
649 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
652 // Ignore splited live intervals.
653 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
656 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
658 const LiveRange &LR = *I;
659 if (li_->findLiveInMBBs(LR.start, LR.end, LiveInMBBs)) {
660 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
661 if (LiveInMBBs[i] != EntryMBB) {
662 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
663 "Adding a virtual register to livein set?");
664 LiveInMBBs[i]->addLiveIn(Reg);
671 DEBUG(dbgs() << *vrm_);
673 // Look for physical registers that end up not being allocated even though
674 // register allocator had to spill other registers in its register class.
675 if (!vrm_->FindUnusedRegisters(li_))
679 /// processActiveIntervals - expire old intervals and move non-overlapping ones
680 /// to the inactive list.
681 void RALinScan::processActiveIntervals(SlotIndex CurPoint)
683 DEBUG(dbgs() << "\tprocessing active intervals:\n");
685 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
686 LiveInterval *Interval = active_[i].first;
687 LiveInterval::iterator IntervalPos = active_[i].second;
688 unsigned reg = Interval->reg;
690 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
692 if (IntervalPos == Interval->end()) { // Remove expired intervals.
693 DEBUG(dbgs() << "\t\tinterval " << *Interval << " expired\n");
694 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
695 "Can only allocate virtual registers!");
696 reg = vrm_->getPhys(reg);
699 // Pop off the end of the list.
700 active_[i] = active_.back();
704 } else if (IntervalPos->start > CurPoint) {
705 // Move inactive intervals to inactive list.
706 DEBUG(dbgs() << "\t\tinterval " << *Interval << " inactive\n");
707 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
708 "Can only allocate virtual registers!");
709 reg = vrm_->getPhys(reg);
712 inactive_.push_back(std::make_pair(Interval, IntervalPos));
714 // Pop off the end of the list.
715 active_[i] = active_.back();
719 // Otherwise, just update the iterator position.
720 active_[i].second = IntervalPos;
725 /// processInactiveIntervals - expire old intervals and move overlapping
726 /// ones to the active list.
727 void RALinScan::processInactiveIntervals(SlotIndex CurPoint)
729 DEBUG(dbgs() << "\tprocessing inactive intervals:\n");
731 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
732 LiveInterval *Interval = inactive_[i].first;
733 LiveInterval::iterator IntervalPos = inactive_[i].second;
734 unsigned reg = Interval->reg;
736 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
738 if (IntervalPos == Interval->end()) { // remove expired intervals.
739 DEBUG(dbgs() << "\t\tinterval " << *Interval << " expired\n");
741 // Pop off the end of the list.
742 inactive_[i] = inactive_.back();
743 inactive_.pop_back();
745 } else if (IntervalPos->start <= CurPoint) {
746 // move re-activated intervals in active list
747 DEBUG(dbgs() << "\t\tinterval " << *Interval << " active\n");
748 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
749 "Can only allocate virtual registers!");
750 reg = vrm_->getPhys(reg);
753 active_.push_back(std::make_pair(Interval, IntervalPos));
755 // Pop off the end of the list.
756 inactive_[i] = inactive_.back();
757 inactive_.pop_back();
760 // Otherwise, just update the iterator position.
761 inactive_[i].second = IntervalPos;
766 /// updateSpillWeights - updates the spill weights of the specifed physical
767 /// register and its weight.
768 void RALinScan::updateSpillWeights(std::vector<float> &Weights,
769 unsigned reg, float weight,
770 const TargetRegisterClass *RC) {
771 SmallSet<unsigned, 4> Processed;
772 SmallSet<unsigned, 4> SuperAdded;
773 SmallVector<unsigned, 4> Supers;
774 Weights[reg] += weight;
775 Processed.insert(reg);
776 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as) {
777 Weights[*as] += weight;
778 Processed.insert(*as);
779 if (tri_->isSubRegister(*as, reg) &&
780 SuperAdded.insert(*as) &&
782 Supers.push_back(*as);
786 // If the alias is a super-register, and the super-register is in the
787 // register class we are trying to allocate. Then add the weight to all
788 // sub-registers of the super-register even if they are not aliases.
789 // e.g. allocating for GR32, bh is not used, updating bl spill weight.
790 // bl should get the same spill weight otherwise it will be choosen
791 // as a spill candidate since spilling bh doesn't make ebx available.
792 for (unsigned i = 0, e = Supers.size(); i != e; ++i) {
793 for (const unsigned *sr = tri_->getSubRegisters(Supers[i]); *sr; ++sr)
794 if (!Processed.count(*sr))
795 Weights[*sr] += weight;
800 RALinScan::IntervalPtrs::iterator
801 FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
802 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
804 if (I->first == LI) return I;
808 static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V,
810 for (unsigned i = 0, e = V.size(); i != e; ++i) {
811 RALinScan::IntervalPtr &IP = V[i];
812 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
814 if (I != IP.first->begin()) --I;
819 /// getConflictWeight - Return the number of conflicts between cur
820 /// live interval and defs and uses of Reg weighted by loop depthes.
822 float getConflictWeight(LiveInterval *cur, unsigned Reg, LiveIntervals *li_,
823 MachineRegisterInfo *mri_,
824 MachineLoopInfo *loopInfo) {
826 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
827 E = mri_->reg_end(); I != E; ++I) {
828 MachineInstr *MI = &*I;
829 if (cur->liveAt(li_->getInstructionIndex(MI))) {
830 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
831 Conflicts += std::pow(10.0f, (float)loopDepth);
837 /// findIntervalsToSpill - Determine the intervals to spill for the
838 /// specified interval. It's passed the physical registers whose spill
839 /// weight is the lowest among all the registers whose live intervals
840 /// conflict with the interval.
841 void RALinScan::findIntervalsToSpill(LiveInterval *cur,
842 std::vector<std::pair<unsigned,float> > &Candidates,
844 SmallVector<LiveInterval*, 8> &SpillIntervals) {
845 // We have figured out the *best* register to spill. But there are other
846 // registers that are pretty good as well (spill weight within 3%). Spill
847 // the one that has fewest defs and uses that conflict with cur.
848 float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
849 SmallVector<LiveInterval*, 8> SLIs[3];
852 dbgs() << "\tConsidering " << NumCands << " candidates: ";
853 for (unsigned i = 0; i != NumCands; ++i)
854 dbgs() << tri_->getName(Candidates[i].first) << " ";
858 // Calculate the number of conflicts of each candidate.
859 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
860 unsigned Reg = i->first->reg;
861 unsigned PhysReg = vrm_->getPhys(Reg);
862 if (!cur->overlapsFrom(*i->first, i->second))
864 for (unsigned j = 0; j < NumCands; ++j) {
865 unsigned Candidate = Candidates[j].first;
866 if (tri_->regsOverlap(PhysReg, Candidate)) {
868 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
869 SLIs[j].push_back(i->first);
874 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
875 unsigned Reg = i->first->reg;
876 unsigned PhysReg = vrm_->getPhys(Reg);
877 if (!cur->overlapsFrom(*i->first, i->second-1))
879 for (unsigned j = 0; j < NumCands; ++j) {
880 unsigned Candidate = Candidates[j].first;
881 if (tri_->regsOverlap(PhysReg, Candidate)) {
883 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
884 SLIs[j].push_back(i->first);
889 // Which is the best candidate?
890 unsigned BestCandidate = 0;
891 float MinConflicts = Conflicts[0];
892 for (unsigned i = 1; i != NumCands; ++i) {
893 if (Conflicts[i] < MinConflicts) {
895 MinConflicts = Conflicts[i];
899 std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
900 std::back_inserter(SpillIntervals));
904 struct WeightCompare {
906 const RALinScan &Allocator;
909 WeightCompare(const RALinScan &Alloc) : Allocator(Alloc) {}
911 typedef std::pair<unsigned, float> RegWeightPair;
912 bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
913 return LHS.second < RHS.second && !Allocator.isRecentlyUsed(LHS.first);
918 static bool weightsAreClose(float w1, float w2) {
922 float diff = w1 - w2;
923 if (diff <= 0.02f) // Within 0.02f
925 return (diff / w2) <= 0.05f; // Within 5%.
928 LiveInterval *RALinScan::hasNextReloadInterval(LiveInterval *cur) {
929 DenseMap<unsigned, unsigned>::iterator I = NextReloadMap.find(cur->reg);
930 if (I == NextReloadMap.end())
932 return &li_->getInterval(I->second);
935 void RALinScan::DowngradeRegister(LiveInterval *li, unsigned Reg) {
936 bool isNew = DowngradedRegs.insert(Reg);
937 isNew = isNew; // Silence compiler warning.
938 assert(isNew && "Multiple reloads holding the same register?");
939 DowngradeMap.insert(std::make_pair(li->reg, Reg));
940 for (const unsigned *AS = tri_->getAliasSet(Reg); *AS; ++AS) {
941 isNew = DowngradedRegs.insert(*AS);
942 isNew = isNew; // Silence compiler warning.
943 assert(isNew && "Multiple reloads holding the same register?");
944 DowngradeMap.insert(std::make_pair(li->reg, *AS));
949 void RALinScan::UpgradeRegister(unsigned Reg) {
951 DowngradedRegs.erase(Reg);
952 for (const unsigned *AS = tri_->getAliasSet(Reg); *AS; ++AS)
953 DowngradedRegs.erase(*AS);
959 bool operator()(LiveInterval* A, LiveInterval* B) {
960 return A->beginIndex() < B->beginIndex();
965 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
967 void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur) {
968 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
969 DEBUG(dbgs() << "\tallocating current interval from "
970 << RC->getName() << ": ");
972 // This is an implicitly defined live interval, just assign any register.
974 unsigned physReg = vrm_->getRegAllocPref(cur->reg);
976 physReg = getFirstNonReservedPhysReg(RC);
977 DEBUG(dbgs() << tri_->getName(physReg) << '\n');
978 // Note the register is not really in use.
979 vrm_->assignVirt2Phys(cur->reg, physReg);
985 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
986 SlotIndex StartPosition = cur->beginIndex();
987 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
989 // If start of this live interval is defined by a move instruction and its
990 // source is assigned a physical register that is compatible with the target
991 // register class, then we should try to assign it the same register.
992 // This can happen when the move is from a larger register class to a smaller
993 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
994 if (!vrm_->getRegAllocPref(cur->reg) && cur->hasAtLeastOneValue()) {
995 VNInfo *vni = cur->begin()->valno;
996 if (!vni->isUnused()) {
997 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
998 if (CopyMI && CopyMI->isCopy()) {
999 unsigned DstSubReg = CopyMI->getOperand(0).getSubReg();
1000 unsigned SrcReg = CopyMI->getOperand(1).getReg();
1001 unsigned SrcSubReg = CopyMI->getOperand(1).getSubReg();
1003 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
1005 else if (vrm_->isAssignedReg(SrcReg))
1006 Reg = vrm_->getPhys(SrcReg);
1009 Reg = tri_->getSubReg(Reg, SrcSubReg);
1011 Reg = tri_->getMatchingSuperReg(Reg, DstSubReg, RC);
1012 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
1013 mri_->setRegAllocationHint(cur->reg, 0, Reg);
1019 // For every interval in inactive we overlap with, mark the
1020 // register as not free and update spill weights.
1021 for (IntervalPtrs::const_iterator i = inactive_.begin(),
1022 e = inactive_.end(); i != e; ++i) {
1023 unsigned Reg = i->first->reg;
1024 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
1025 "Can only allocate virtual registers!");
1026 const TargetRegisterClass *RegRC = mri_->getRegClass(Reg);
1027 // If this is not in a related reg class to the register we're allocating,
1029 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
1030 cur->overlapsFrom(*i->first, i->second-1)) {
1031 Reg = vrm_->getPhys(Reg);
1033 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
1037 // Speculatively check to see if we can get a register right now. If not,
1038 // we know we won't be able to by adding more constraints. If so, we can
1039 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
1040 // is very bad (it contains all callee clobbered registers for any functions
1041 // with a call), so we want to avoid doing that if possible.
1042 unsigned physReg = getFreePhysReg(cur);
1043 unsigned BestPhysReg = physReg;
1045 // We got a register. However, if it's in the fixed_ list, we might
1046 // conflict with it. Check to see if we conflict with it or any of its
1048 SmallSet<unsigned, 8> RegAliases;
1049 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
1050 RegAliases.insert(*AS);
1052 bool ConflictsWithFixed = false;
1053 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1054 IntervalPtr &IP = fixed_[i];
1055 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
1056 // Okay, this reg is on the fixed list. Check to see if we actually
1058 LiveInterval *I = IP.first;
1059 if (I->endIndex() > StartPosition) {
1060 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
1062 if (II != I->begin() && II->start > StartPosition)
1064 if (cur->overlapsFrom(*I, II)) {
1065 ConflictsWithFixed = true;
1072 // Okay, the register picked by our speculative getFreePhysReg call turned
1073 // out to be in use. Actually add all of the conflicting fixed registers to
1074 // regUse_ so we can do an accurate query.
1075 if (ConflictsWithFixed) {
1076 // For every interval in fixed we overlap with, mark the register as not
1077 // free and update spill weights.
1078 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1079 IntervalPtr &IP = fixed_[i];
1080 LiveInterval *I = IP.first;
1082 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
1083 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
1084 I->endIndex() > StartPosition) {
1085 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
1087 if (II != I->begin() && II->start > StartPosition)
1089 if (cur->overlapsFrom(*I, II)) {
1090 unsigned reg = I->reg;
1092 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
1097 // Using the newly updated regUse_ object, which includes conflicts in the
1098 // future, see if there are any registers available.
1099 physReg = getFreePhysReg(cur);
1103 // Restore the physical register tracker, removing information about the
1107 // If we find a free register, we are done: assign this virtual to
1108 // the free physical register and add this interval to the active
1111 DEBUG(dbgs() << tri_->getName(physReg) << '\n');
1112 vrm_->assignVirt2Phys(cur->reg, physReg);
1114 active_.push_back(std::make_pair(cur, cur->begin()));
1115 handled_.push_back(cur);
1117 // "Upgrade" the physical register since it has been allocated.
1118 UpgradeRegister(physReg);
1119 if (LiveInterval *NextReloadLI = hasNextReloadInterval(cur)) {
1120 // "Downgrade" physReg to try to keep physReg from being allocated until
1121 // the next reload from the same SS is allocated.
1122 mri_->setRegAllocationHint(NextReloadLI->reg, 0, physReg);
1123 DowngradeRegister(cur, physReg);
1127 DEBUG(dbgs() << "no free registers\n");
1129 // Compile the spill weights into an array that is better for scanning.
1130 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
1131 for (std::vector<std::pair<unsigned, float> >::iterator
1132 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
1133 updateSpillWeights(SpillWeights, I->first, I->second, RC);
1135 // for each interval in active, update spill weights.
1136 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
1138 unsigned reg = i->first->reg;
1139 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
1140 "Can only allocate virtual registers!");
1141 reg = vrm_->getPhys(reg);
1142 updateSpillWeights(SpillWeights, reg, i->first->weight, RC);
1145 DEBUG(dbgs() << "\tassigning stack slot at interval "<< *cur << ":\n");
1147 // Find a register to spill.
1148 float minWeight = HUGE_VALF;
1149 unsigned minReg = 0;
1152 std::vector<std::pair<unsigned,float> > RegsWeights;
1153 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
1154 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
1155 e = RC->allocation_order_end(*mf_); i != e; ++i) {
1157 float regWeight = SpillWeights[reg];
1158 // Don't even consider reserved regs.
1159 if (reservedRegs_.test(reg))
1161 // Skip recently allocated registers and reserved registers.
1162 if (minWeight > regWeight && !isRecentlyUsed(reg))
1164 RegsWeights.push_back(std::make_pair(reg, regWeight));
1167 // If we didn't find a register that is spillable, try aliases?
1169 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
1170 e = RC->allocation_order_end(*mf_); i != e; ++i) {
1172 if (reservedRegs_.test(reg))
1174 // No need to worry about if the alias register size < regsize of RC.
1175 // We are going to spill all registers that alias it anyway.
1176 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
1177 RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
1181 // Sort all potential spill candidates by weight.
1182 std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare(*this));
1183 minReg = RegsWeights[0].first;
1184 minWeight = RegsWeights[0].second;
1185 if (minWeight == HUGE_VALF) {
1186 // All registers must have inf weight. Just grab one!
1187 minReg = BestPhysReg ? BestPhysReg : getFirstNonReservedPhysReg(RC);
1188 if (cur->weight == HUGE_VALF ||
1189 li_->getApproximateInstructionCount(*cur) == 0) {
1190 // Spill a physical register around defs and uses.
1191 if (li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_)) {
1192 // spillPhysRegAroundRegDefsUses may have invalidated iterator stored
1193 // in fixed_. Reset them.
1194 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1195 IntervalPtr &IP = fixed_[i];
1196 LiveInterval *I = IP.first;
1197 if (I->reg == minReg || tri_->isSubRegister(minReg, I->reg))
1198 IP.second = I->advanceTo(I->begin(), StartPosition);
1201 DowngradedRegs.clear();
1202 assignRegOrStackSlotAtInterval(cur);
1204 assert(false && "Ran out of registers during register allocation!");
1205 report_fatal_error("Ran out of registers during register allocation!");
1211 // Find up to 3 registers to consider as spill candidates.
1212 unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
1213 while (LastCandidate > 1) {
1214 if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
1220 dbgs() << "\t\tregister(s) with min weight(s): ";
1222 for (unsigned i = 0; i != LastCandidate; ++i)
1223 dbgs() << tri_->getName(RegsWeights[i].first)
1224 << " (" << RegsWeights[i].second << ")\n";
1227 // If the current has the minimum weight, we need to spill it and
1228 // add any added intervals back to unhandled, and restart
1230 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
1231 DEBUG(dbgs() << "\t\t\tspilling(c): " << *cur << '\n');
1232 SmallVector<LiveInterval*, 8> spillIs, added;
1233 spiller_->spill(cur, added, spillIs);
1235 std::sort(added.begin(), added.end(), LISorter());
1237 return; // Early exit if all spills were folded.
1239 // Merge added with unhandled. Note that we have already sorted
1240 // intervals returned by addIntervalsForSpills by their starting
1242 // This also update the NextReloadMap. That is, it adds mapping from a
1243 // register defined by a reload from SS to the next reload from SS in the
1244 // same basic block.
1245 MachineBasicBlock *LastReloadMBB = 0;
1246 LiveInterval *LastReload = 0;
1247 int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1248 for (unsigned i = 0, e = added.size(); i != e; ++i) {
1249 LiveInterval *ReloadLi = added[i];
1250 if (ReloadLi->weight == HUGE_VALF &&
1251 li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1252 SlotIndex ReloadIdx = ReloadLi->beginIndex();
1253 MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1254 int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1255 if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1256 // Last reload of same SS is in the same MBB. We want to try to
1257 // allocate both reloads the same register and make sure the reg
1258 // isn't clobbered in between if at all possible.
1259 assert(LastReload->beginIndex() < ReloadIdx);
1260 NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1262 LastReloadMBB = ReloadMBB;
1263 LastReload = ReloadLi;
1264 LastReloadSS = ReloadSS;
1266 unhandled_.push(ReloadLi);
1273 // Push the current interval back to unhandled since we are going
1274 // to re-run at least this iteration. Since we didn't modify it it
1275 // should go back right in the front of the list
1276 unhandled_.push(cur);
1278 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
1279 "did not choose a register to spill?");
1281 // We spill all intervals aliasing the register with
1282 // minimum weight, rollback to the interval with the earliest
1283 // start point and let the linear scan algorithm run again
1284 SmallVector<LiveInterval*, 8> spillIs;
1286 // Determine which intervals have to be spilled.
1287 findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
1289 // Set of spilled vregs (used later to rollback properly)
1290 SmallSet<unsigned, 8> spilled;
1292 // The earliest start of a Spilled interval indicates up to where
1293 // in handled we need to roll back
1294 assert(!spillIs.empty() && "No spill intervals?");
1295 SlotIndex earliestStart = spillIs[0]->beginIndex();
1297 // Spill live intervals of virtual regs mapped to the physical register we
1298 // want to clear (and its aliases). We only spill those that overlap with the
1299 // current interval as the rest do not affect its allocation. we also keep
1300 // track of the earliest start of all spilled live intervals since this will
1301 // mark our rollback point.
1302 SmallVector<LiveInterval*, 8> added;
1303 while (!spillIs.empty()) {
1304 LiveInterval *sli = spillIs.back();
1306 DEBUG(dbgs() << "\t\t\tspilling(a): " << *sli << '\n');
1307 if (sli->beginIndex() < earliestStart)
1308 earliestStart = sli->beginIndex();
1309 spiller_->spill(sli, added, spillIs);
1310 spilled.insert(sli->reg);
1313 // Include any added intervals in earliestStart.
1314 for (unsigned i = 0, e = added.size(); i != e; ++i) {
1315 SlotIndex SI = added[i]->beginIndex();
1316 if (SI < earliestStart)
1320 DEBUG(dbgs() << "\t\trolling back to: " << earliestStart << '\n');
1322 // Scan handled in reverse order up to the earliest start of a
1323 // spilled live interval and undo each one, restoring the state of
1325 while (!handled_.empty()) {
1326 LiveInterval* i = handled_.back();
1327 // If this interval starts before t we are done.
1328 if (!i->empty() && i->beginIndex() < earliestStart)
1330 DEBUG(dbgs() << "\t\t\tundo changes for: " << *i << '\n');
1331 handled_.pop_back();
1333 // When undoing a live interval allocation we must know if it is active or
1334 // inactive to properly update regUse_ and the VirtRegMap.
1335 IntervalPtrs::iterator it;
1336 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
1338 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
1339 if (!spilled.count(i->reg))
1341 delRegUse(vrm_->getPhys(i->reg));
1342 vrm_->clearVirt(i->reg);
1343 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
1344 inactive_.erase(it);
1345 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
1346 if (!spilled.count(i->reg))
1348 vrm_->clearVirt(i->reg);
1350 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
1351 "Can only allocate virtual registers!");
1352 vrm_->clearVirt(i->reg);
1356 DenseMap<unsigned, unsigned>::iterator ii = DowngradeMap.find(i->reg);
1357 if (ii == DowngradeMap.end())
1358 // It interval has a preference, it must be defined by a copy. Clear the
1359 // preference now since the source interval allocation may have been
1361 mri_->setRegAllocationHint(i->reg, 0, 0);
1363 UpgradeRegister(ii->second);
1367 // Rewind the iterators in the active, inactive, and fixed lists back to the
1368 // point we reverted to.
1369 RevertVectorIteratorsTo(active_, earliestStart);
1370 RevertVectorIteratorsTo(inactive_, earliestStart);
1371 RevertVectorIteratorsTo(fixed_, earliestStart);
1373 // Scan the rest and undo each interval that expired after t and
1374 // insert it in active (the next iteration of the algorithm will
1375 // put it in inactive if required)
1376 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
1377 LiveInterval *HI = handled_[i];
1378 if (!HI->expiredAt(earliestStart) &&
1379 HI->expiredAt(cur->beginIndex())) {
1380 DEBUG(dbgs() << "\t\t\tundo changes for: " << *HI << '\n');
1381 active_.push_back(std::make_pair(HI, HI->begin()));
1382 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
1383 addRegUse(vrm_->getPhys(HI->reg));
1387 // Merge added with unhandled.
1388 // This also update the NextReloadMap. That is, it adds mapping from a
1389 // register defined by a reload from SS to the next reload from SS in the
1390 // same basic block.
1391 MachineBasicBlock *LastReloadMBB = 0;
1392 LiveInterval *LastReload = 0;
1393 int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1394 std::sort(added.begin(), added.end(), LISorter());
1395 for (unsigned i = 0, e = added.size(); i != e; ++i) {
1396 LiveInterval *ReloadLi = added[i];
1397 if (ReloadLi->weight == HUGE_VALF &&
1398 li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1399 SlotIndex ReloadIdx = ReloadLi->beginIndex();
1400 MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1401 int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1402 if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1403 // Last reload of same SS is in the same MBB. We want to try to
1404 // allocate both reloads the same register and make sure the reg
1405 // isn't clobbered in between if at all possible.
1406 assert(LastReload->beginIndex() < ReloadIdx);
1407 NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1409 LastReloadMBB = ReloadMBB;
1410 LastReload = ReloadLi;
1411 LastReloadSS = ReloadSS;
1413 unhandled_.push(ReloadLi);
1417 unsigned RALinScan::getFreePhysReg(LiveInterval* cur,
1418 const TargetRegisterClass *RC,
1419 unsigned MaxInactiveCount,
1420 SmallVector<unsigned, 256> &inactiveCounts,
1422 unsigned FreeReg = 0;
1423 unsigned FreeRegInactiveCount = 0;
1425 std::pair<unsigned, unsigned> Hint = mri_->getRegAllocationHint(cur->reg);
1426 // Resolve second part of the hint (if possible) given the current allocation.
1427 unsigned physReg = Hint.second;
1429 TargetRegisterInfo::isVirtualRegister(physReg) && vrm_->hasPhys(physReg))
1430 physReg = vrm_->getPhys(physReg);
1432 TargetRegisterClass::iterator I, E;
1433 tie(I, E) = tri_->getAllocationOrder(RC, Hint.first, physReg, *mf_);
1434 assert(I != E && "No allocatable register in this register class!");
1436 // Scan for the first available register.
1437 for (; I != E; ++I) {
1439 // Ignore "downgraded" registers.
1440 if (SkipDGRegs && DowngradedRegs.count(Reg))
1442 // Skip reserved registers.
1443 if (reservedRegs_.test(Reg))
1445 // Skip recently allocated registers.
1446 if (isRegAvail(Reg) && !isRecentlyUsed(Reg)) {
1448 if (FreeReg < inactiveCounts.size())
1449 FreeRegInactiveCount = inactiveCounts[FreeReg];
1451 FreeRegInactiveCount = 0;
1456 // If there are no free regs, or if this reg has the max inactive count,
1457 // return this register.
1458 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) {
1459 // Remember what register we picked so we can skip it next time.
1460 if (FreeReg != 0) recordRecentlyUsed(FreeReg);
1464 // Continue scanning the registers, looking for the one with the highest
1465 // inactive count. Alkis found that this reduced register pressure very
1466 // slightly on X86 (in rev 1.94 of this file), though this should probably be
1468 for (; I != E; ++I) {
1470 // Ignore "downgraded" registers.
1471 if (SkipDGRegs && DowngradedRegs.count(Reg))
1473 // Skip reserved registers.
1474 if (reservedRegs_.test(Reg))
1476 if (isRegAvail(Reg) && Reg < inactiveCounts.size() &&
1477 FreeRegInactiveCount < inactiveCounts[Reg] && !isRecentlyUsed(Reg)) {
1479 FreeRegInactiveCount = inactiveCounts[Reg];
1480 if (FreeRegInactiveCount == MaxInactiveCount)
1481 break; // We found the one with the max inactive count.
1485 // Remember what register we picked so we can skip it next time.
1486 recordRecentlyUsed(FreeReg);
1491 /// getFreePhysReg - return a free physical register for this virtual register
1492 /// interval if we have one, otherwise return 0.
1493 unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
1494 SmallVector<unsigned, 256> inactiveCounts;
1495 unsigned MaxInactiveCount = 0;
1497 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
1498 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1500 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1502 unsigned reg = i->first->reg;
1503 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
1504 "Can only allocate virtual registers!");
1506 // If this is not in a related reg class to the register we're allocating,
1508 const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
1509 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1510 reg = vrm_->getPhys(reg);
1511 if (inactiveCounts.size() <= reg)
1512 inactiveCounts.resize(reg+1);
1513 ++inactiveCounts[reg];
1514 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1518 // If copy coalescer has assigned a "preferred" register, check if it's
1520 unsigned Preference = vrm_->getRegAllocPref(cur->reg);
1522 DEBUG(dbgs() << "(preferred: " << tri_->getName(Preference) << ") ");
1523 if (isRegAvail(Preference) &&
1524 RC->contains(Preference))
1528 if (!DowngradedRegs.empty()) {
1529 unsigned FreeReg = getFreePhysReg(cur, RC, MaxInactiveCount, inactiveCounts,
1534 return getFreePhysReg(cur, RC, MaxInactiveCount, inactiveCounts, false);
1537 FunctionPass* llvm::createLinearScanRegisterAllocator() {
1538 return new RALinScan();