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 "PhysRegTracker.h"
16 #include "VirtRegMap.h"
18 #include "llvm/Function.h"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/CodeGen/LiveStackAnalysis.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/RegAllocRegistry.h"
27 #include "llvm/CodeGen/RegisterCoalescer.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/ADT/EquivalenceClasses.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/Compiler.h"
45 STATISTIC(NumIters , "Number of iterations performed");
46 STATISTIC(NumBacktracks, "Number of times we had to backtrack");
47 STATISTIC(NumCoalesce, "Number of copies coalesced");
50 NewHeuristic("new-spilling-heuristic",
51 cl::desc("Use new spilling heuristic"),
52 cl::init(false), cl::Hidden);
55 PreSplitIntervals("pre-alloc-split",
56 cl::desc("Pre-register allocation live interval splitting"),
57 cl::init(false), cl::Hidden);
59 static RegisterRegAlloc
60 linearscanRegAlloc("linearscan", "linear scan register allocator",
61 createLinearScanRegisterAllocator);
64 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
66 RALinScan() : MachineFunctionPass(&ID) {}
68 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
69 typedef SmallVector<IntervalPtr, 32> IntervalPtrs;
71 /// RelatedRegClasses - This structure is built the first time a function is
72 /// compiled, and keeps track of which register classes have registers that
73 /// belong to multiple classes or have aliases that are in other classes.
74 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
75 DenseMap<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
78 MachineRegisterInfo* mri_;
79 const TargetMachine* tm_;
80 const TargetRegisterInfo* tri_;
81 const TargetInstrInfo* tii_;
82 BitVector allocatableRegs_;
85 const MachineLoopInfo *loopInfo;
87 /// handled_ - Intervals are added to the handled_ set in the order of their
88 /// start value. This is uses for backtracking.
89 std::vector<LiveInterval*> handled_;
91 /// fixed_ - Intervals that correspond to machine registers.
95 /// active_ - Intervals that are currently being processed, and which have a
96 /// live range active for the current point.
99 /// inactive_ - Intervals that are currently being processed, but which have
100 /// a hold at the current point.
101 IntervalPtrs inactive_;
103 typedef std::priority_queue<LiveInterval*,
104 SmallVector<LiveInterval*, 64>,
105 greater_ptr<LiveInterval> > IntervalHeap;
106 IntervalHeap unhandled_;
107 std::auto_ptr<PhysRegTracker> prt_;
109 std::auto_ptr<Spiller> spiller_;
112 virtual const char* getPassName() const {
113 return "Linear Scan Register Allocator";
116 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
117 AU.addRequired<LiveIntervals>();
119 AU.addRequiredID(StrongPHIEliminationID);
120 // Make sure PassManager knows which analyses to make available
121 // to coalescing and which analyses coalescing invalidates.
122 AU.addRequiredTransitive<RegisterCoalescer>();
123 if (PreSplitIntervals)
124 AU.addRequiredID(PreAllocSplittingID);
125 AU.addRequired<LiveStacks>();
126 AU.addPreserved<LiveStacks>();
127 AU.addRequired<MachineLoopInfo>();
128 AU.addPreserved<MachineLoopInfo>();
129 AU.addRequired<VirtRegMap>();
130 AU.addPreserved<VirtRegMap>();
131 AU.addPreservedID(MachineDominatorsID);
132 MachineFunctionPass::getAnalysisUsage(AU);
135 /// runOnMachineFunction - register allocate the whole function
136 bool runOnMachineFunction(MachineFunction&);
139 /// linearScan - the linear scan algorithm
142 /// initIntervalSets - initialize the interval sets.
144 void initIntervalSets();
146 /// processActiveIntervals - expire old intervals and move non-overlapping
147 /// ones to the inactive list.
148 void processActiveIntervals(unsigned CurPoint);
150 /// processInactiveIntervals - expire old intervals and move overlapping
151 /// ones to the active list.
152 void processInactiveIntervals(unsigned CurPoint);
154 /// assignRegOrStackSlotAtInterval - assign a register if one
155 /// is available, or spill.
156 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
158 /// findIntervalsToSpill - Determine the intervals to spill for the
159 /// specified interval. It's passed the physical registers whose spill
160 /// weight is the lowest among all the registers whose live intervals
161 /// conflict with the interval.
162 void findIntervalsToSpill(LiveInterval *cur,
163 std::vector<std::pair<unsigned,float> > &Candidates,
165 SmallVector<LiveInterval*, 8> &SpillIntervals);
167 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
168 /// try allocate the definition the same register as the source register
169 /// if the register is not defined during live time of the interval. This
170 /// eliminate a copy. This is used to coalesce copies which were not
171 /// coalesced away before allocation either due to dest and src being in
172 /// different register classes or because the coalescer was overly
174 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
177 /// register handling helpers
180 /// getFreePhysReg - return a free physical register for this virtual
181 /// register interval if we have one, otherwise return 0.
182 unsigned getFreePhysReg(LiveInterval* cur);
184 /// assignVirt2StackSlot - assigns this virtual register to a
185 /// stack slot. returns the stack slot
186 int assignVirt2StackSlot(unsigned virtReg);
188 void ComputeRelatedRegClasses();
190 template <typename ItTy>
191 void printIntervals(const char* const str, ItTy i, ItTy e) const {
192 if (str) DOUT << str << " intervals:\n";
193 for (; i != e; ++i) {
194 DOUT << "\t" << *i->first << " -> ";
195 unsigned reg = i->first->reg;
196 if (TargetRegisterInfo::isVirtualRegister(reg)) {
197 reg = vrm_->getPhys(reg);
199 DOUT << tri_->getName(reg) << '\n';
203 char RALinScan::ID = 0;
206 static RegisterPass<RALinScan>
207 X("linearscan-regalloc", "Linear Scan Register Allocator");
209 void RALinScan::ComputeRelatedRegClasses() {
210 const TargetRegisterInfo &TRI = *tri_;
212 // First pass, add all reg classes to the union, and determine at least one
213 // reg class that each register is in.
214 bool HasAliases = false;
215 for (TargetRegisterInfo::regclass_iterator RCI = TRI.regclass_begin(),
216 E = TRI.regclass_end(); RCI != E; ++RCI) {
217 RelatedRegClasses.insert(*RCI);
218 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
220 HasAliases = HasAliases || *TRI.getAliasSet(*I) != 0;
222 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
224 // Already processed this register. Just make sure we know that
225 // multiple register classes share a register.
226 RelatedRegClasses.unionSets(PRC, *RCI);
233 // Second pass, now that we know conservatively what register classes each reg
234 // belongs to, add info about aliases. We don't need to do this for targets
235 // without register aliases.
237 for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
238 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
240 for (const unsigned *AS = TRI.getAliasSet(I->first); *AS; ++AS)
241 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
244 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
245 /// try allocate the definition the same register as the source register
246 /// if the register is not defined during live time of the interval. This
247 /// eliminate a copy. This is used to coalesce copies which were not
248 /// coalesced away before allocation either due to dest and src being in
249 /// different register classes or because the coalescer was overly
251 unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
252 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
255 VNInfo *vni = cur.begin()->valno;
256 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
258 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
259 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
261 !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg))
263 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
264 if (!vrm_->isAssignedReg(SrcReg))
267 SrcReg = vrm_->getPhys(SrcReg);
272 const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
273 if (!RC->contains(SrcReg))
277 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
278 DOUT << "Coalescing: " << cur << " -> " << tri_->getName(SrcReg)
280 vrm_->clearVirt(cur.reg);
281 vrm_->assignVirt2Phys(cur.reg, SrcReg);
289 bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
291 mri_ = &fn.getRegInfo();
292 tm_ = &fn.getTarget();
293 tri_ = tm_->getRegisterInfo();
294 tii_ = tm_->getInstrInfo();
295 allocatableRegs_ = tri_->getAllocatableSet(fn);
296 li_ = &getAnalysis<LiveIntervals>();
297 ls_ = &getAnalysis<LiveStacks>();
298 loopInfo = &getAnalysis<MachineLoopInfo>();
300 // We don't run the coalescer here because we have no reason to
301 // interact with it. If the coalescer requires interaction, it
302 // won't do anything. If it doesn't require interaction, we assume
303 // it was run as a separate pass.
305 // If this is the first function compiled, compute the related reg classes.
306 if (RelatedRegClasses.empty())
307 ComputeRelatedRegClasses();
309 if (!prt_.get()) prt_.reset(new PhysRegTracker(*tri_));
310 vrm_ = &getAnalysis<VirtRegMap>();
311 if (!spiller_.get()) spiller_.reset(createSpiller());
317 // Rewrite spill code and update the PhysRegsUsed set.
318 spiller_->runOnMachineFunction(*mf_, *vrm_);
320 assert(unhandled_.empty() && "Unhandled live intervals remain!");
329 /// initIntervalSets - initialize the interval sets.
331 void RALinScan::initIntervalSets()
333 assert(unhandled_.empty() && fixed_.empty() &&
334 active_.empty() && inactive_.empty() &&
335 "interval sets should be empty on initialization");
337 handled_.reserve(li_->getNumIntervals());
339 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
340 if (TargetRegisterInfo::isPhysicalRegister(i->second->reg)) {
341 mri_->setPhysRegUsed(i->second->reg);
342 fixed_.push_back(std::make_pair(i->second, i->second->begin()));
344 unhandled_.push(i->second);
348 void RALinScan::linearScan()
350 // linear scan algorithm
351 DOUT << "********** LINEAR SCAN **********\n";
352 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
354 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
356 while (!unhandled_.empty()) {
357 // pick the interval with the earliest start point
358 LiveInterval* cur = unhandled_.top();
361 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
364 processActiveIntervals(cur->beginNumber());
365 processInactiveIntervals(cur->beginNumber());
367 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
368 "Can only allocate virtual registers!");
371 // Allocating a virtual register. try to find a free
372 // physical register or spill an interval (possibly this one) in order to
374 assignRegOrStackSlotAtInterval(cur);
376 DEBUG(printIntervals("active", active_.begin(), active_.end()));
377 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
380 // expire any remaining active intervals
381 while (!active_.empty()) {
382 IntervalPtr &IP = active_.back();
383 unsigned reg = IP.first->reg;
384 DOUT << "\tinterval " << *IP.first << " expired\n";
385 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
386 "Can only allocate virtual registers!");
387 reg = vrm_->getPhys(reg);
388 prt_->delRegUse(reg);
392 // expire any remaining inactive intervals
393 DEBUG(for (IntervalPtrs::reverse_iterator
394 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
395 DOUT << "\tinterval " << *i->first << " expired\n");
398 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
399 MachineFunction::iterator EntryMBB = mf_->begin();
400 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
401 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
402 LiveInterval &cur = *i->second;
404 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
407 else if (vrm_->isAssignedReg(cur.reg))
408 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
411 // Ignore splited live intervals.
412 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
414 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
416 const LiveRange &LR = *I;
417 if (li_->findLiveInMBBs(LR.start, LR.end, LiveInMBBs)) {
418 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
419 if (LiveInMBBs[i] != EntryMBB)
420 LiveInMBBs[i]->addLiveIn(Reg);
429 /// processActiveIntervals - expire old intervals and move non-overlapping ones
430 /// to the inactive list.
431 void RALinScan::processActiveIntervals(unsigned CurPoint)
433 DOUT << "\tprocessing active intervals:\n";
435 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
436 LiveInterval *Interval = active_[i].first;
437 LiveInterval::iterator IntervalPos = active_[i].second;
438 unsigned reg = Interval->reg;
440 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
442 if (IntervalPos == Interval->end()) { // Remove expired intervals.
443 DOUT << "\t\tinterval " << *Interval << " expired\n";
444 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
445 "Can only allocate virtual registers!");
446 reg = vrm_->getPhys(reg);
447 prt_->delRegUse(reg);
449 // Pop off the end of the list.
450 active_[i] = active_.back();
454 } else if (IntervalPos->start > CurPoint) {
455 // Move inactive intervals to inactive list.
456 DOUT << "\t\tinterval " << *Interval << " inactive\n";
457 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
458 "Can only allocate virtual registers!");
459 reg = vrm_->getPhys(reg);
460 prt_->delRegUse(reg);
462 inactive_.push_back(std::make_pair(Interval, IntervalPos));
464 // Pop off the end of the list.
465 active_[i] = active_.back();
469 // Otherwise, just update the iterator position.
470 active_[i].second = IntervalPos;
475 /// processInactiveIntervals - expire old intervals and move overlapping
476 /// ones to the active list.
477 void RALinScan::processInactiveIntervals(unsigned CurPoint)
479 DOUT << "\tprocessing inactive intervals:\n";
481 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
482 LiveInterval *Interval = inactive_[i].first;
483 LiveInterval::iterator IntervalPos = inactive_[i].second;
484 unsigned reg = Interval->reg;
486 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
488 if (IntervalPos == Interval->end()) { // remove expired intervals.
489 DOUT << "\t\tinterval " << *Interval << " expired\n";
491 // Pop off the end of the list.
492 inactive_[i] = inactive_.back();
493 inactive_.pop_back();
495 } else if (IntervalPos->start <= CurPoint) {
496 // move re-activated intervals in active list
497 DOUT << "\t\tinterval " << *Interval << " active\n";
498 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
499 "Can only allocate virtual registers!");
500 reg = vrm_->getPhys(reg);
501 prt_->addRegUse(reg);
503 active_.push_back(std::make_pair(Interval, IntervalPos));
505 // Pop off the end of the list.
506 inactive_[i] = inactive_.back();
507 inactive_.pop_back();
510 // Otherwise, just update the iterator position.
511 inactive_[i].second = IntervalPos;
516 /// updateSpillWeights - updates the spill weights of the specifed physical
517 /// register and its weight.
518 static void updateSpillWeights(std::vector<float> &Weights,
519 unsigned reg, float weight,
520 const TargetRegisterInfo *TRI) {
521 Weights[reg] += weight;
522 for (const unsigned* as = TRI->getAliasSet(reg); *as; ++as)
523 Weights[*as] += weight;
527 RALinScan::IntervalPtrs::iterator
528 FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
529 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
531 if (I->first == LI) return I;
535 static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
536 for (unsigned i = 0, e = V.size(); i != e; ++i) {
537 RALinScan::IntervalPtr &IP = V[i];
538 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
540 if (I != IP.first->begin()) --I;
545 /// addStackInterval - Create a LiveInterval for stack if the specified live
546 /// interval has been spilled.
547 static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
548 LiveIntervals *li_, float &Weight,
550 int SS = vrm_.getStackSlot(cur->reg);
551 if (SS == VirtRegMap::NO_STACK_SLOT)
553 LiveInterval &SI = ls_->getOrCreateInterval(SS);
557 if (SI.hasAtLeastOneValue())
558 VNI = SI.getValNumInfo(0);
560 VNI = SI.getNextValue(~0U, 0, ls_->getVNInfoAllocator());
562 LiveInterval &RI = li_->getInterval(cur->reg);
563 // FIXME: This may be overly conservative.
564 SI.MergeRangesInAsValue(RI, VNI);
567 /// getConflictWeight - Return the number of conflicts between cur
568 /// live interval and defs and uses of Reg weighted by loop depthes.
569 static float getConflictWeight(LiveInterval *cur, unsigned Reg,
571 MachineRegisterInfo *mri_,
572 const MachineLoopInfo *loopInfo) {
574 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
575 E = mri_->reg_end(); I != E; ++I) {
576 MachineInstr *MI = &*I;
577 if (cur->liveAt(li_->getInstructionIndex(MI))) {
578 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
579 Conflicts += powf(10.0f, (float)loopDepth);
585 /// findIntervalsToSpill - Determine the intervals to spill for the
586 /// specified interval. It's passed the physical registers whose spill
587 /// weight is the lowest among all the registers whose live intervals
588 /// conflict with the interval.
589 void RALinScan::findIntervalsToSpill(LiveInterval *cur,
590 std::vector<std::pair<unsigned,float> > &Candidates,
592 SmallVector<LiveInterval*, 8> &SpillIntervals) {
593 // We have figured out the *best* register to spill. But there are other
594 // registers that are pretty good as well (spill weight within 3%). Spill
595 // the one that has fewest defs and uses that conflict with cur.
596 float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
597 SmallVector<LiveInterval*, 8> SLIs[3];
599 DOUT << "\tConsidering " << NumCands << " candidates: ";
600 DEBUG(for (unsigned i = 0; i != NumCands; ++i)
601 DOUT << tri_->getName(Candidates[i].first) << " ";
604 // Calculate the number of conflicts of each candidate.
605 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
606 unsigned Reg = i->first->reg;
607 unsigned PhysReg = vrm_->getPhys(Reg);
608 if (!cur->overlapsFrom(*i->first, i->second))
610 for (unsigned j = 0; j < NumCands; ++j) {
611 unsigned Candidate = Candidates[j].first;
612 if (tri_->regsOverlap(PhysReg, Candidate)) {
614 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
615 SLIs[j].push_back(i->first);
620 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
621 unsigned Reg = i->first->reg;
622 unsigned PhysReg = vrm_->getPhys(Reg);
623 if (!cur->overlapsFrom(*i->first, i->second-1))
625 for (unsigned j = 0; j < NumCands; ++j) {
626 unsigned Candidate = Candidates[j].first;
627 if (tri_->regsOverlap(PhysReg, Candidate)) {
629 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
630 SLIs[j].push_back(i->first);
635 // Which is the best candidate?
636 unsigned BestCandidate = 0;
637 float MinConflicts = Conflicts[0];
638 for (unsigned i = 1; i != NumCands; ++i) {
639 if (Conflicts[i] < MinConflicts) {
641 MinConflicts = Conflicts[i];
645 std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
646 std::back_inserter(SpillIntervals));
650 struct WeightCompare {
651 typedef std::pair<unsigned, float> RegWeightPair;
652 bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
653 return LHS.second < RHS.second;
658 static bool weightsAreClose(float w1, float w2) {
662 float diff = w1 - w2;
663 if (diff <= 0.02f) // Within 0.02f
665 return (diff / w2) <= 0.05f; // Within 5%.
668 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
670 void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
672 DOUT << "\tallocating current interval: ";
674 // This is an implicitly defined live interval, just assign any register.
675 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
677 unsigned physReg = cur->preference;
679 physReg = *RC->allocation_order_begin(*mf_);
680 DOUT << tri_->getName(physReg) << '\n';
681 // Note the register is not really in use.
682 vrm_->assignVirt2Phys(cur->reg, physReg);
686 PhysRegTracker backupPrt = *prt_;
688 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
689 unsigned StartPosition = cur->beginNumber();
690 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
692 // If start of this live interval is defined by a move instruction and its
693 // source is assigned a physical register that is compatible with the target
694 // register class, then we should try to assign it the same register.
695 // This can happen when the move is from a larger register class to a smaller
696 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
697 if (!cur->preference && cur->hasAtLeastOneValue()) {
698 VNInfo *vni = cur->begin()->valno;
699 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
700 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
701 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
703 tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg)) {
705 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
707 else if (vrm_->isAssignedReg(SrcReg))
708 Reg = vrm_->getPhys(SrcReg);
709 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
710 cur->preference = Reg;
715 // for every interval in inactive we overlap with, mark the
716 // register as not free and update spill weights.
717 for (IntervalPtrs::const_iterator i = inactive_.begin(),
718 e = inactive_.end(); i != e; ++i) {
719 unsigned Reg = i->first->reg;
720 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
721 "Can only allocate virtual registers!");
722 const TargetRegisterClass *RegRC = mri_->getRegClass(Reg);
723 // If this is not in a related reg class to the register we're allocating,
725 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
726 cur->overlapsFrom(*i->first, i->second-1)) {
727 Reg = vrm_->getPhys(Reg);
728 prt_->addRegUse(Reg);
729 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
733 // Speculatively check to see if we can get a register right now. If not,
734 // we know we won't be able to by adding more constraints. If so, we can
735 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
736 // is very bad (it contains all callee clobbered registers for any functions
737 // with a call), so we want to avoid doing that if possible.
738 unsigned physReg = getFreePhysReg(cur);
739 unsigned BestPhysReg = physReg;
741 // We got a register. However, if it's in the fixed_ list, we might
742 // conflict with it. Check to see if we conflict with it or any of its
744 SmallSet<unsigned, 8> RegAliases;
745 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
746 RegAliases.insert(*AS);
748 bool ConflictsWithFixed = false;
749 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
750 IntervalPtr &IP = fixed_[i];
751 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
752 // Okay, this reg is on the fixed list. Check to see if we actually
754 LiveInterval *I = IP.first;
755 if (I->endNumber() > StartPosition) {
756 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
758 if (II != I->begin() && II->start > StartPosition)
760 if (cur->overlapsFrom(*I, II)) {
761 ConflictsWithFixed = true;
768 // Okay, the register picked by our speculative getFreePhysReg call turned
769 // out to be in use. Actually add all of the conflicting fixed registers to
770 // prt so we can do an accurate query.
771 if (ConflictsWithFixed) {
772 // For every interval in fixed we overlap with, mark the register as not
773 // free and update spill weights.
774 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
775 IntervalPtr &IP = fixed_[i];
776 LiveInterval *I = IP.first;
778 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
779 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
780 I->endNumber() > StartPosition) {
781 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
783 if (II != I->begin() && II->start > StartPosition)
785 if (cur->overlapsFrom(*I, II)) {
786 unsigned reg = I->reg;
787 prt_->addRegUse(reg);
788 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
793 // Using the newly updated prt_ object, which includes conflicts in the
794 // future, see if there are any registers available.
795 physReg = getFreePhysReg(cur);
799 // Restore the physical register tracker, removing information about the
803 // if we find a free register, we are done: assign this virtual to
804 // the free physical register and add this interval to the active
807 DOUT << tri_->getName(physReg) << '\n';
808 vrm_->assignVirt2Phys(cur->reg, physReg);
809 prt_->addRegUse(physReg);
810 active_.push_back(std::make_pair(cur, cur->begin()));
811 handled_.push_back(cur);
814 DOUT << "no free registers\n";
816 // Compile the spill weights into an array that is better for scanning.
817 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
818 for (std::vector<std::pair<unsigned, float> >::iterator
819 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
820 updateSpillWeights(SpillWeights, I->first, I->second, tri_);
822 // for each interval in active, update spill weights.
823 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
825 unsigned reg = i->first->reg;
826 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
827 "Can only allocate virtual registers!");
828 reg = vrm_->getPhys(reg);
829 updateSpillWeights(SpillWeights, reg, i->first->weight, tri_);
832 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
834 // Find a register to spill.
835 float minWeight = HUGE_VALF;
836 unsigned minReg = 0; /*cur->preference*/; // Try the preferred register first.
839 std::vector<std::pair<unsigned,float> > RegsWeights;
840 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
841 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
842 e = RC->allocation_order_end(*mf_); i != e; ++i) {
844 float regWeight = SpillWeights[reg];
845 if (minWeight > regWeight)
847 RegsWeights.push_back(std::make_pair(reg, regWeight));
850 // If we didn't find a register that is spillable, try aliases?
852 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
853 e = RC->allocation_order_end(*mf_); i != e; ++i) {
855 // No need to worry about if the alias register size < regsize of RC.
856 // We are going to spill all registers that alias it anyway.
857 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
858 RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
862 // Sort all potential spill candidates by weight.
863 std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare());
864 minReg = RegsWeights[0].first;
865 minWeight = RegsWeights[0].second;
866 if (minWeight == HUGE_VALF) {
867 // All registers must have inf weight. Just grab one!
868 minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
869 if (cur->weight == HUGE_VALF ||
870 li_->getApproximateInstructionCount(*cur) == 0) {
871 // Spill a physical register around defs and uses.
872 li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_);
873 assignRegOrStackSlotAtInterval(cur);
878 // Find up to 3 registers to consider as spill candidates.
879 unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
880 while (LastCandidate > 1) {
881 if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
886 DOUT << "\t\tregister(s) with min weight(s): ";
887 DEBUG(for (unsigned i = 0; i != LastCandidate; ++i)
888 DOUT << tri_->getName(RegsWeights[i].first)
889 << " (" << RegsWeights[i].second << ")\n");
891 // if the current has the minimum weight, we need to spill it and
892 // add any added intervals back to unhandled, and restart
894 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
895 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
897 SmallVector<LiveInterval*, 8> spillIs;
898 std::vector<LiveInterval*> added =
899 li_->addIntervalsForSpills(*cur, spillIs, loopInfo, *vrm_, SSWeight);
900 addStackInterval(cur, ls_, li_, SSWeight, *vrm_);
902 return; // Early exit if all spills were folded.
904 // Merge added with unhandled. Note that we know that
905 // addIntervalsForSpills returns intervals sorted by their starting
907 for (unsigned i = 0, e = added.size(); i != e; ++i)
908 unhandled_.push(added[i]);
914 // push the current interval back to unhandled since we are going
915 // to re-run at least this iteration. Since we didn't modify it it
916 // should go back right in the front of the list
917 unhandled_.push(cur);
919 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
920 "did not choose a register to spill?");
922 // We spill all intervals aliasing the register with
923 // minimum weight, rollback to the interval with the earliest
924 // start point and let the linear scan algorithm run again
925 SmallVector<LiveInterval*, 8> spillIs;
927 // Determine which intervals have to be spilled.
928 findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
930 // Set of spilled vregs (used later to rollback properly)
931 SmallSet<unsigned, 8> spilled;
933 // The earliest start of a Spilled interval indicates up to where
934 // in handled we need to roll back
935 unsigned earliestStart = cur->beginNumber();
937 // Spill live intervals of virtual regs mapped to the physical register we
938 // want to clear (and its aliases). We only spill those that overlap with the
939 // current interval as the rest do not affect its allocation. we also keep
940 // track of the earliest start of all spilled live intervals since this will
941 // mark our rollback point.
942 std::vector<LiveInterval*> added;
943 while (!spillIs.empty()) {
944 LiveInterval *sli = spillIs.back();
946 DOUT << "\t\t\tspilling(a): " << *sli << '\n';
947 earliestStart = std::min(earliestStart, sli->beginNumber());
949 std::vector<LiveInterval*> newIs =
950 li_->addIntervalsForSpills(*sli, spillIs, loopInfo, *vrm_, SSWeight);
951 addStackInterval(sli, ls_, li_, SSWeight, *vrm_);
952 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
953 spilled.insert(sli->reg);
956 DOUT << "\t\trolling back to: " << earliestStart << '\n';
958 // Scan handled in reverse order up to the earliest start of a
959 // spilled live interval and undo each one, restoring the state of
961 while (!handled_.empty()) {
962 LiveInterval* i = handled_.back();
963 // If this interval starts before t we are done.
964 if (i->beginNumber() < earliestStart)
966 DOUT << "\t\t\tundo changes for: " << *i << '\n';
969 // When undoing a live interval allocation we must know if it is active or
970 // inactive to properly update the PhysRegTracker and the VirtRegMap.
971 IntervalPtrs::iterator it;
972 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
974 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
975 if (!spilled.count(i->reg))
977 prt_->delRegUse(vrm_->getPhys(i->reg));
978 vrm_->clearVirt(i->reg);
979 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
981 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
982 if (!spilled.count(i->reg))
984 vrm_->clearVirt(i->reg);
986 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
987 "Can only allocate virtual registers!");
988 vrm_->clearVirt(i->reg);
992 // It interval has a preference, it must be defined by a copy. Clear the
993 // preference now since the source interval allocation may have been undone
998 // Rewind the iterators in the active, inactive, and fixed lists back to the
999 // point we reverted to.
1000 RevertVectorIteratorsTo(active_, earliestStart);
1001 RevertVectorIteratorsTo(inactive_, earliestStart);
1002 RevertVectorIteratorsTo(fixed_, earliestStart);
1004 // scan the rest and undo each interval that expired after t and
1005 // insert it in active (the next iteration of the algorithm will
1006 // put it in inactive if required)
1007 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
1008 LiveInterval *HI = handled_[i];
1009 if (!HI->expiredAt(earliestStart) &&
1010 HI->expiredAt(cur->beginNumber())) {
1011 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
1012 active_.push_back(std::make_pair(HI, HI->begin()));
1013 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
1014 prt_->addRegUse(vrm_->getPhys(HI->reg));
1018 // merge added with unhandled
1019 for (unsigned i = 0, e = added.size(); i != e; ++i)
1020 unhandled_.push(added[i]);
1023 /// getFreePhysReg - return a free physical register for this virtual register
1024 /// interval if we have one, otherwise return 0.
1025 unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
1026 SmallVector<unsigned, 256> inactiveCounts;
1027 unsigned MaxInactiveCount = 0;
1029 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
1030 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1032 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1034 unsigned reg = i->first->reg;
1035 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
1036 "Can only allocate virtual registers!");
1038 // If this is not in a related reg class to the register we're allocating,
1040 const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
1041 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1042 reg = vrm_->getPhys(reg);
1043 if (inactiveCounts.size() <= reg)
1044 inactiveCounts.resize(reg+1);
1045 ++inactiveCounts[reg];
1046 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1050 unsigned FreeReg = 0;
1051 unsigned FreeRegInactiveCount = 0;
1053 // If copy coalescer has assigned a "preferred" register, check if it's
1055 if (cur->preference) {
1056 if (prt_->isRegAvail(cur->preference) &&
1057 RC->contains(cur->preference)) {
1058 DOUT << "\t\tassigned the preferred register: "
1059 << tri_->getName(cur->preference) << "\n";
1060 return cur->preference;
1062 DOUT << "\t\tunable to assign the preferred register: "
1063 << tri_->getName(cur->preference) << "\n";
1066 // Scan for the first available register.
1067 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
1068 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
1069 assert(I != E && "No allocatable register in this register class!");
1071 if (prt_->isRegAvail(*I)) {
1073 if (FreeReg < inactiveCounts.size())
1074 FreeRegInactiveCount = inactiveCounts[FreeReg];
1076 FreeRegInactiveCount = 0;
1080 // If there are no free regs, or if this reg has the max inactive count,
1081 // return this register.
1082 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
1084 // Continue scanning the registers, looking for the one with the highest
1085 // inactive count. Alkis found that this reduced register pressure very
1086 // slightly on X86 (in rev 1.94 of this file), though this should probably be
1088 for (; I != E; ++I) {
1090 if (prt_->isRegAvail(Reg) && Reg < inactiveCounts.size() &&
1091 FreeRegInactiveCount < inactiveCounts[Reg]) {
1093 FreeRegInactiveCount = inactiveCounts[Reg];
1094 if (FreeRegInactiveCount == MaxInactiveCount)
1095 break; // We found the one with the max inactive count.
1102 FunctionPass* llvm::createLinearScanRegisterAllocator() {
1103 return new RALinScan();