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"
17 #include "llvm/Function.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/CodeGen/LiveStackAnalysis.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/RegAllocRegistry.h"
26 #include "llvm/CodeGen/RegisterCoalescer.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetOptions.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/ADT/EquivalenceClasses.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/Compiler.h"
43 STATISTIC(NumIters , "Number of iterations performed");
44 STATISTIC(NumBacktracks, "Number of times we had to backtrack");
45 STATISTIC(NumCoalesce, "Number of copies coalesced");
48 NewHeuristic("new-spilling-heuristic",
49 cl::desc("Use new spilling heuristic"),
50 cl::init(false), cl::Hidden);
53 PreSplitIntervals("pre-alloc-split",
54 cl::desc("Pre-register allocation live interval splitting"),
55 cl::init(false), cl::Hidden);
57 static RegisterRegAlloc
58 linearscanRegAlloc("linearscan", "linear scan register allocator",
59 createLinearScanRegisterAllocator);
62 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
64 RALinScan() : MachineFunctionPass(&ID) {}
66 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
67 typedef SmallVector<IntervalPtr, 32> IntervalPtrs;
69 /// RelatedRegClasses - This structure is built the first time a function is
70 /// compiled, and keeps track of which register classes have registers that
71 /// belong to multiple classes or have aliases that are in other classes.
72 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
73 DenseMap<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
76 MachineRegisterInfo* mri_;
77 const TargetMachine* tm_;
78 const TargetRegisterInfo* tri_;
79 const TargetInstrInfo* tii_;
80 BitVector allocatableRegs_;
83 const MachineLoopInfo *loopInfo;
85 /// handled_ - Intervals are added to the handled_ set in the order of their
86 /// start value. This is uses for backtracking.
87 std::vector<LiveInterval*> handled_;
89 /// fixed_ - Intervals that correspond to machine registers.
93 /// active_ - Intervals that are currently being processed, and which have a
94 /// live range active for the current point.
97 /// inactive_ - Intervals that are currently being processed, but which have
98 /// a hold at the current point.
99 IntervalPtrs inactive_;
101 typedef std::priority_queue<LiveInterval*,
102 SmallVector<LiveInterval*, 64>,
103 greater_ptr<LiveInterval> > IntervalHeap;
104 IntervalHeap unhandled_;
105 std::auto_ptr<PhysRegTracker> prt_;
106 std::auto_ptr<VirtRegMap> vrm_;
107 std::auto_ptr<Spiller> spiller_;
110 virtual const char* getPassName() const {
111 return "Linear Scan Register Allocator";
114 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
115 AU.addRequired<LiveIntervals>();
117 AU.addRequiredID(StrongPHIEliminationID);
118 // Make sure PassManager knows which analyses to make available
119 // to coalescing and which analyses coalescing invalidates.
120 AU.addRequiredTransitive<RegisterCoalescer>();
121 if (PreSplitIntervals)
122 AU.addRequiredID(PreAllocSplittingID);
123 AU.addRequired<LiveStacks>();
124 AU.addPreserved<LiveStacks>();
125 AU.addRequired<MachineLoopInfo>();
126 AU.addPreserved<MachineLoopInfo>();
127 AU.addPreservedID(MachineDominatorsID);
128 MachineFunctionPass::getAnalysisUsage(AU);
131 /// runOnMachineFunction - register allocate the whole function
132 bool runOnMachineFunction(MachineFunction&);
135 /// linearScan - the linear scan algorithm
138 /// initIntervalSets - initialize the interval sets.
140 void initIntervalSets();
142 /// processActiveIntervals - expire old intervals and move non-overlapping
143 /// ones to the inactive list.
144 void processActiveIntervals(unsigned CurPoint);
146 /// processInactiveIntervals - expire old intervals and move overlapping
147 /// ones to the active list.
148 void processInactiveIntervals(unsigned CurPoint);
150 /// assignRegOrStackSlotAtInterval - assign a register if one
151 /// is available, or spill.
152 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
154 /// findIntervalsToSpill - Determine the intervals to spill for the
155 /// specified interval. It's passed the physical registers whose spill
156 /// weight is the lowest among all the registers whose live intervals
157 /// conflict with the interval.
158 void findIntervalsToSpill(LiveInterval *cur,
159 std::vector<std::pair<unsigned,float> > &Candidates,
161 SmallVector<LiveInterval*, 8> &SpillIntervals);
163 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
164 /// try allocate the definition the same register as the source register
165 /// if the register is not defined during live time of the interval. This
166 /// eliminate a copy. This is used to coalesce copies which were not
167 /// coalesced away before allocation either due to dest and src being in
168 /// different register classes or because the coalescer was overly
170 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
173 /// register handling helpers
176 /// getFreePhysReg - return a free physical register for this virtual
177 /// register interval if we have one, otherwise return 0.
178 unsigned getFreePhysReg(LiveInterval* cur);
180 /// assignVirt2StackSlot - assigns this virtual register to a
181 /// stack slot. returns the stack slot
182 int assignVirt2StackSlot(unsigned virtReg);
184 void ComputeRelatedRegClasses();
186 template <typename ItTy>
187 void printIntervals(const char* const str, ItTy i, ItTy e) const {
188 if (str) DOUT << str << " intervals:\n";
189 for (; i != e; ++i) {
190 DOUT << "\t" << *i->first << " -> ";
191 unsigned reg = i->first->reg;
192 if (TargetRegisterInfo::isVirtualRegister(reg)) {
193 reg = vrm_->getPhys(reg);
195 DOUT << tri_->getName(reg) << '\n';
199 char RALinScan::ID = 0;
202 static RegisterPass<RALinScan>
203 X("linearscan-regalloc", "Linear Scan Register Allocator");
205 void RALinScan::ComputeRelatedRegClasses() {
206 const TargetRegisterInfo &TRI = *tri_;
208 // First pass, add all reg classes to the union, and determine at least one
209 // reg class that each register is in.
210 bool HasAliases = false;
211 for (TargetRegisterInfo::regclass_iterator RCI = TRI.regclass_begin(),
212 E = TRI.regclass_end(); RCI != E; ++RCI) {
213 RelatedRegClasses.insert(*RCI);
214 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
216 HasAliases = HasAliases || *TRI.getAliasSet(*I) != 0;
218 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
220 // Already processed this register. Just make sure we know that
221 // multiple register classes share a register.
222 RelatedRegClasses.unionSets(PRC, *RCI);
229 // Second pass, now that we know conservatively what register classes each reg
230 // belongs to, add info about aliases. We don't need to do this for targets
231 // without register aliases.
233 for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
234 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
236 for (const unsigned *AS = TRI.getAliasSet(I->first); *AS; ++AS)
237 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
240 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
241 /// try allocate the definition the same register as the source register
242 /// if the register is not defined during live time of the interval. This
243 /// eliminate a copy. This is used to coalesce copies which were not
244 /// coalesced away before allocation either due to dest and src being in
245 /// different register classes or because the coalescer was overly
247 unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
248 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
251 VNInfo *vni = cur.getValNumInfo(0);
252 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
254 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
255 unsigned SrcReg, DstReg;
256 if (!CopyMI || !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg))
258 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
259 if (!vrm_->isAssignedReg(SrcReg))
262 SrcReg = vrm_->getPhys(SrcReg);
267 const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
268 if (!RC->contains(SrcReg))
272 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
273 DOUT << "Coalescing: " << cur << " -> " << tri_->getName(SrcReg)
275 vrm_->clearVirt(cur.reg);
276 vrm_->assignVirt2Phys(cur.reg, SrcReg);
284 bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
286 mri_ = &fn.getRegInfo();
287 tm_ = &fn.getTarget();
288 tri_ = tm_->getRegisterInfo();
289 tii_ = tm_->getInstrInfo();
290 allocatableRegs_ = tri_->getAllocatableSet(fn);
291 li_ = &getAnalysis<LiveIntervals>();
292 ls_ = &getAnalysis<LiveStacks>();
293 loopInfo = &getAnalysis<MachineLoopInfo>();
295 // We don't run the coalescer here because we have no reason to
296 // interact with it. If the coalescer requires interaction, it
297 // won't do anything. If it doesn't require interaction, we assume
298 // it was run as a separate pass.
300 // If this is the first function compiled, compute the related reg classes.
301 if (RelatedRegClasses.empty())
302 ComputeRelatedRegClasses();
304 if (!prt_.get()) prt_.reset(new PhysRegTracker(*tri_));
305 vrm_.reset(new VirtRegMap(*mf_));
306 if (!spiller_.get()) spiller_.reset(createSpiller());
312 // Rewrite spill code and update the PhysRegsUsed set.
313 spiller_->runOnMachineFunction(*mf_, *vrm_);
314 vrm_.reset(); // Free the VirtRegMap
316 assert(unhandled_.empty() && "Unhandled live intervals remain!");
325 /// initIntervalSets - initialize the interval sets.
327 void RALinScan::initIntervalSets()
329 assert(unhandled_.empty() && fixed_.empty() &&
330 active_.empty() && inactive_.empty() &&
331 "interval sets should be empty on initialization");
333 handled_.reserve(li_->getNumIntervals());
335 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
336 if (TargetRegisterInfo::isPhysicalRegister(i->second->reg)) {
337 mri_->setPhysRegUsed(i->second->reg);
338 fixed_.push_back(std::make_pair(i->second, i->second->begin()));
340 unhandled_.push(i->second);
344 void RALinScan::linearScan()
346 // linear scan algorithm
347 DOUT << "********** LINEAR SCAN **********\n";
348 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
350 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
352 while (!unhandled_.empty()) {
353 // pick the interval with the earliest start point
354 LiveInterval* cur = unhandled_.top();
357 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
360 processActiveIntervals(cur->beginNumber());
361 processInactiveIntervals(cur->beginNumber());
363 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
364 "Can only allocate virtual registers!");
367 // Allocating a virtual register. try to find a free
368 // physical register or spill an interval (possibly this one) in order to
370 assignRegOrStackSlotAtInterval(cur);
372 DEBUG(printIntervals("active", active_.begin(), active_.end()));
373 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
376 // expire any remaining active intervals
377 while (!active_.empty()) {
378 IntervalPtr &IP = active_.back();
379 unsigned reg = IP.first->reg;
380 DOUT << "\tinterval " << *IP.first << " expired\n";
381 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
382 "Can only allocate virtual registers!");
383 reg = vrm_->getPhys(reg);
384 prt_->delRegUse(reg);
388 // expire any remaining inactive intervals
389 DEBUG(for (IntervalPtrs::reverse_iterator
390 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
391 DOUT << "\tinterval " << *i->first << " expired\n");
394 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
395 MachineFunction::iterator EntryMBB = mf_->begin();
396 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
397 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
398 LiveInterval &cur = *i->second;
400 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
403 else if (vrm_->isAssignedReg(cur.reg))
404 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
407 // Ignore splited live intervals.
408 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
410 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
412 const LiveRange &LR = *I;
413 if (li_->findLiveInMBBs(LR.start, LR.end, LiveInMBBs)) {
414 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
415 if (LiveInMBBs[i] != EntryMBB)
416 LiveInMBBs[i]->addLiveIn(Reg);
425 /// processActiveIntervals - expire old intervals and move non-overlapping ones
426 /// to the inactive list.
427 void RALinScan::processActiveIntervals(unsigned CurPoint)
429 DOUT << "\tprocessing active intervals:\n";
431 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
432 LiveInterval *Interval = active_[i].first;
433 LiveInterval::iterator IntervalPos = active_[i].second;
434 unsigned reg = Interval->reg;
436 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
438 if (IntervalPos == Interval->end()) { // Remove expired intervals.
439 DOUT << "\t\tinterval " << *Interval << " expired\n";
440 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
441 "Can only allocate virtual registers!");
442 reg = vrm_->getPhys(reg);
443 prt_->delRegUse(reg);
445 // Pop off the end of the list.
446 active_[i] = active_.back();
450 } else if (IntervalPos->start > CurPoint) {
451 // Move inactive intervals to inactive list.
452 DOUT << "\t\tinterval " << *Interval << " inactive\n";
453 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
454 "Can only allocate virtual registers!");
455 reg = vrm_->getPhys(reg);
456 prt_->delRegUse(reg);
458 inactive_.push_back(std::make_pair(Interval, IntervalPos));
460 // Pop off the end of the list.
461 active_[i] = active_.back();
465 // Otherwise, just update the iterator position.
466 active_[i].second = IntervalPos;
471 /// processInactiveIntervals - expire old intervals and move overlapping
472 /// ones to the active list.
473 void RALinScan::processInactiveIntervals(unsigned CurPoint)
475 DOUT << "\tprocessing inactive intervals:\n";
477 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
478 LiveInterval *Interval = inactive_[i].first;
479 LiveInterval::iterator IntervalPos = inactive_[i].second;
480 unsigned reg = Interval->reg;
482 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
484 if (IntervalPos == Interval->end()) { // remove expired intervals.
485 DOUT << "\t\tinterval " << *Interval << " expired\n";
487 // Pop off the end of the list.
488 inactive_[i] = inactive_.back();
489 inactive_.pop_back();
491 } else if (IntervalPos->start <= CurPoint) {
492 // move re-activated intervals in active list
493 DOUT << "\t\tinterval " << *Interval << " active\n";
494 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
495 "Can only allocate virtual registers!");
496 reg = vrm_->getPhys(reg);
497 prt_->addRegUse(reg);
499 active_.push_back(std::make_pair(Interval, IntervalPos));
501 // Pop off the end of the list.
502 inactive_[i] = inactive_.back();
503 inactive_.pop_back();
506 // Otherwise, just update the iterator position.
507 inactive_[i].second = IntervalPos;
512 /// updateSpillWeights - updates the spill weights of the specifed physical
513 /// register and its weight.
514 static void updateSpillWeights(std::vector<float> &Weights,
515 unsigned reg, float weight,
516 const TargetRegisterInfo *TRI) {
517 Weights[reg] += weight;
518 for (const unsigned* as = TRI->getAliasSet(reg); *as; ++as)
519 Weights[*as] += weight;
523 RALinScan::IntervalPtrs::iterator
524 FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
525 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
527 if (I->first == LI) return I;
531 static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
532 for (unsigned i = 0, e = V.size(); i != e; ++i) {
533 RALinScan::IntervalPtr &IP = V[i];
534 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
536 if (I != IP.first->begin()) --I;
541 /// addStackInterval - Create a LiveInterval for stack if the specified live
542 /// interval has been spilled.
543 static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
544 LiveIntervals *li_, float &Weight,
546 int SS = vrm_.getStackSlot(cur->reg);
547 if (SS == VirtRegMap::NO_STACK_SLOT)
549 LiveInterval &SI = ls_->getOrCreateInterval(SS);
553 if (SI.getNumValNums())
554 VNI = SI.getValNumInfo(0);
556 VNI = SI.getNextValue(~0U, 0, ls_->getVNInfoAllocator());
558 LiveInterval &RI = li_->getInterval(cur->reg);
559 // FIXME: This may be overly conservative.
560 SI.MergeRangesInAsValue(RI, VNI);
563 /// getConflictWeight - Return the number of conflicts between cur
564 /// live interval and defs and uses of Reg weighted by loop depthes.
565 static float getConflictWeight(LiveInterval *cur, unsigned Reg,
567 MachineRegisterInfo *mri_,
568 const MachineLoopInfo *loopInfo) {
570 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
571 E = mri_->reg_end(); I != E; ++I) {
572 MachineInstr *MI = &*I;
573 if (cur->liveAt(li_->getInstructionIndex(MI))) {
574 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
575 Conflicts += powf(10.0f, (float)loopDepth);
581 /// findIntervalsToSpill - Determine the intervals to spill for the
582 /// specified interval. It's passed the physical registers whose spill
583 /// weight is the lowest among all the registers whose live intervals
584 /// conflict with the interval.
585 void RALinScan::findIntervalsToSpill(LiveInterval *cur,
586 std::vector<std::pair<unsigned,float> > &Candidates,
588 SmallVector<LiveInterval*, 8> &SpillIntervals) {
589 // We have figured out the *best* register to spill. But there are other
590 // registers that are pretty good as well (spill weight within 3%). Spill
591 // the one that has fewest defs and uses that conflict with cur.
592 float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
593 SmallVector<LiveInterval*, 8> SLIs[3];
595 DOUT << "\tConsidering " << NumCands << " candidates: ";
596 DEBUG(for (unsigned i = 0; i != NumCands; ++i)
597 DOUT << tri_->getName(Candidates[i].first) << " ";
600 // Calculate the number of conflicts of each candidate.
601 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
602 unsigned Reg = i->first->reg;
603 unsigned PhysReg = vrm_->getPhys(Reg);
604 if (!cur->overlapsFrom(*i->first, i->second))
606 for (unsigned j = 0; j < NumCands; ++j) {
607 unsigned Candidate = Candidates[j].first;
608 if (tri_->regsOverlap(PhysReg, Candidate)) {
610 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
611 SLIs[j].push_back(i->first);
616 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
617 unsigned Reg = i->first->reg;
618 unsigned PhysReg = vrm_->getPhys(Reg);
619 if (!cur->overlapsFrom(*i->first, i->second-1))
621 for (unsigned j = 0; j < NumCands; ++j) {
622 unsigned Candidate = Candidates[j].first;
623 if (tri_->regsOverlap(PhysReg, Candidate)) {
625 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
626 SLIs[j].push_back(i->first);
631 // Which is the best candidate?
632 unsigned BestCandidate = 0;
633 float MinConflicts = Conflicts[0];
634 for (unsigned i = 1; i != NumCands; ++i) {
635 if (Conflicts[i] < MinConflicts) {
637 MinConflicts = Conflicts[i];
641 std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
642 std::back_inserter(SpillIntervals));
646 struct WeightCompare {
647 typedef std::pair<unsigned, float> RegWeightPair;
648 bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
649 return LHS.second < RHS.second;
654 static bool weightsAreClose(float w1, float w2) {
658 float diff = w1 - w2;
659 if (diff <= 0.02f) // Within 0.02f
661 return (diff / w2) <= 0.05f; // Within 5%.
664 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
666 void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
668 DOUT << "\tallocating current interval: ";
670 // This is an implicitly defined live interval, just assign any register.
671 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
673 unsigned physReg = cur->preference;
675 physReg = *RC->allocation_order_begin(*mf_);
676 DOUT << tri_->getName(physReg) << '\n';
677 // Note the register is not really in use.
678 vrm_->assignVirt2Phys(cur->reg, physReg);
682 PhysRegTracker backupPrt = *prt_;
684 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
685 unsigned StartPosition = cur->beginNumber();
686 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
688 // If this live interval is defined by a move instruction and its source is
689 // assigned a physical register that is compatible with the target register
690 // class, then we should try to assign it the same register.
691 // This can happen when the move is from a larger register class to a smaller
692 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
693 if (!cur->preference && cur->containsOneValue()) {
694 VNInfo *vni = cur->getValNumInfo(0);
695 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
696 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
697 unsigned SrcReg, DstReg;
698 if (CopyMI && tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
700 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
702 else if (vrm_->isAssignedReg(SrcReg))
703 Reg = vrm_->getPhys(SrcReg);
704 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
705 cur->preference = Reg;
710 // for every interval in inactive we overlap with, mark the
711 // register as not free and update spill weights.
712 for (IntervalPtrs::const_iterator i = inactive_.begin(),
713 e = inactive_.end(); i != e; ++i) {
714 unsigned Reg = i->first->reg;
715 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
716 "Can only allocate virtual registers!");
717 const TargetRegisterClass *RegRC = mri_->getRegClass(Reg);
718 // If this is not in a related reg class to the register we're allocating,
720 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
721 cur->overlapsFrom(*i->first, i->second-1)) {
722 Reg = vrm_->getPhys(Reg);
723 prt_->addRegUse(Reg);
724 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
728 // Speculatively check to see if we can get a register right now. If not,
729 // we know we won't be able to by adding more constraints. If so, we can
730 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
731 // is very bad (it contains all callee clobbered registers for any functions
732 // with a call), so we want to avoid doing that if possible.
733 unsigned physReg = getFreePhysReg(cur);
734 unsigned BestPhysReg = physReg;
736 // We got a register. However, if it's in the fixed_ list, we might
737 // conflict with it. Check to see if we conflict with it or any of its
739 SmallSet<unsigned, 8> RegAliases;
740 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
741 RegAliases.insert(*AS);
743 bool ConflictsWithFixed = false;
744 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
745 IntervalPtr &IP = fixed_[i];
746 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
747 // Okay, this reg is on the fixed list. Check to see if we actually
749 LiveInterval *I = IP.first;
750 if (I->endNumber() > StartPosition) {
751 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
753 if (II != I->begin() && II->start > StartPosition)
755 if (cur->overlapsFrom(*I, II)) {
756 ConflictsWithFixed = true;
763 // Okay, the register picked by our speculative getFreePhysReg call turned
764 // out to be in use. Actually add all of the conflicting fixed registers to
765 // prt so we can do an accurate query.
766 if (ConflictsWithFixed) {
767 // For every interval in fixed we overlap with, mark the register as not
768 // free and update spill weights.
769 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
770 IntervalPtr &IP = fixed_[i];
771 LiveInterval *I = IP.first;
773 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
774 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
775 I->endNumber() > StartPosition) {
776 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
778 if (II != I->begin() && II->start > StartPosition)
780 if (cur->overlapsFrom(*I, II)) {
781 unsigned reg = I->reg;
782 prt_->addRegUse(reg);
783 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
788 // Using the newly updated prt_ object, which includes conflicts in the
789 // future, see if there are any registers available.
790 physReg = getFreePhysReg(cur);
794 // Restore the physical register tracker, removing information about the
798 // if we find a free register, we are done: assign this virtual to
799 // the free physical register and add this interval to the active
802 DOUT << tri_->getName(physReg) << '\n';
803 vrm_->assignVirt2Phys(cur->reg, physReg);
804 prt_->addRegUse(physReg);
805 active_.push_back(std::make_pair(cur, cur->begin()));
806 handled_.push_back(cur);
809 DOUT << "no free registers\n";
811 // Compile the spill weights into an array that is better for scanning.
812 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
813 for (std::vector<std::pair<unsigned, float> >::iterator
814 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
815 updateSpillWeights(SpillWeights, I->first, I->second, tri_);
817 // for each interval in active, update spill weights.
818 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
820 unsigned reg = i->first->reg;
821 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
822 "Can only allocate virtual registers!");
823 reg = vrm_->getPhys(reg);
824 updateSpillWeights(SpillWeights, reg, i->first->weight, tri_);
827 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
829 // Find a register to spill.
830 float minWeight = HUGE_VALF;
831 unsigned minReg = 0; /*cur->preference*/; // Try the preferred register first.
834 std::vector<std::pair<unsigned,float> > RegsWeights;
835 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
836 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
837 e = RC->allocation_order_end(*mf_); i != e; ++i) {
839 float regWeight = SpillWeights[reg];
840 if (minWeight > regWeight)
842 RegsWeights.push_back(std::make_pair(reg, regWeight));
845 // If we didn't find a register that is spillable, try aliases?
847 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
848 e = RC->allocation_order_end(*mf_); i != e; ++i) {
850 // No need to worry about if the alias register size < regsize of RC.
851 // We are going to spill all registers that alias it anyway.
852 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
853 RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
857 // Sort all potential spill candidates by weight.
858 std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare());
859 minReg = RegsWeights[0].first;
860 minWeight = RegsWeights[0].second;
861 if (minWeight == HUGE_VALF) {
862 // All registers must have inf weight. Just grab one!
863 minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
864 if (cur->weight == HUGE_VALF ||
865 li_->getApproximateInstructionCount(*cur) == 0) {
866 // Spill a physical register around defs and uses.
867 li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_);
868 assignRegOrStackSlotAtInterval(cur);
873 // Find up to 3 registers to consider as spill candidates.
874 unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
875 while (LastCandidate > 1) {
876 if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
881 DOUT << "\t\tregister(s) with min weight(s): ";
882 DEBUG(for (unsigned i = 0; i != LastCandidate; ++i)
883 DOUT << tri_->getName(RegsWeights[i].first)
884 << " (" << RegsWeights[i].second << ")\n");
886 // if the current has the minimum weight, we need to spill it and
887 // add any added intervals back to unhandled, and restart
889 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
890 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
892 SmallVector<LiveInterval*, 8> spillIs;
893 std::vector<LiveInterval*> added =
894 li_->addIntervalsForSpills(*cur, spillIs, loopInfo, *vrm_, SSWeight);
895 addStackInterval(cur, ls_, li_, SSWeight, *vrm_);
897 return; // Early exit if all spills were folded.
899 // Merge added with unhandled. Note that we know that
900 // addIntervalsForSpills returns intervals sorted by their starting
902 for (unsigned i = 0, e = added.size(); i != e; ++i)
903 unhandled_.push(added[i]);
909 // push the current interval back to unhandled since we are going
910 // to re-run at least this iteration. Since we didn't modify it it
911 // should go back right in the front of the list
912 unhandled_.push(cur);
914 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
915 "did not choose a register to spill?");
917 // We spill all intervals aliasing the register with
918 // minimum weight, rollback to the interval with the earliest
919 // start point and let the linear scan algorithm run again
920 SmallVector<LiveInterval*, 8> spillIs;
922 // Determine which intervals have to be spilled.
923 findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
925 // Set of spilled vregs (used later to rollback properly)
926 SmallSet<unsigned, 8> spilled;
928 // The earliest start of a Spilled interval indicates up to where
929 // in handled we need to roll back
930 unsigned earliestStart = cur->beginNumber();
932 // Spill live intervals of virtual regs mapped to the physical register we
933 // want to clear (and its aliases). We only spill those that overlap with the
934 // current interval as the rest do not affect its allocation. we also keep
935 // track of the earliest start of all spilled live intervals since this will
936 // mark our rollback point.
937 std::vector<LiveInterval*> added;
938 while (!spillIs.empty()) {
939 LiveInterval *sli = spillIs.back();
941 DOUT << "\t\t\tspilling(a): " << *sli << '\n';
942 earliestStart = std::min(earliestStart, sli->beginNumber());
944 std::vector<LiveInterval*> newIs =
945 li_->addIntervalsForSpills(*sli, spillIs, loopInfo, *vrm_, SSWeight);
946 addStackInterval(sli, ls_, li_, SSWeight, *vrm_);
947 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
948 spilled.insert(sli->reg);
951 DOUT << "\t\trolling back to: " << earliestStart << '\n';
953 // Scan handled in reverse order up to the earliest start of a
954 // spilled live interval and undo each one, restoring the state of
956 while (!handled_.empty()) {
957 LiveInterval* i = handled_.back();
958 // If this interval starts before t we are done.
959 if (i->beginNumber() < earliestStart)
961 DOUT << "\t\t\tundo changes for: " << *i << '\n';
964 // When undoing a live interval allocation we must know if it is active or
965 // inactive to properly update the PhysRegTracker and the VirtRegMap.
966 IntervalPtrs::iterator it;
967 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
969 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
970 if (!spilled.count(i->reg))
972 prt_->delRegUse(vrm_->getPhys(i->reg));
973 vrm_->clearVirt(i->reg);
974 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
976 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
977 if (!spilled.count(i->reg))
979 vrm_->clearVirt(i->reg);
981 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
982 "Can only allocate virtual registers!");
983 vrm_->clearVirt(i->reg);
987 // It interval has a preference, it must be defined by a copy. Clear the
988 // preference now since the source interval allocation may have been undone
993 // Rewind the iterators in the active, inactive, and fixed lists back to the
994 // point we reverted to.
995 RevertVectorIteratorsTo(active_, earliestStart);
996 RevertVectorIteratorsTo(inactive_, earliestStart);
997 RevertVectorIteratorsTo(fixed_, earliestStart);
999 // scan the rest and undo each interval that expired after t and
1000 // insert it in active (the next iteration of the algorithm will
1001 // put it in inactive if required)
1002 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
1003 LiveInterval *HI = handled_[i];
1004 if (!HI->expiredAt(earliestStart) &&
1005 HI->expiredAt(cur->beginNumber())) {
1006 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
1007 active_.push_back(std::make_pair(HI, HI->begin()));
1008 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
1009 prt_->addRegUse(vrm_->getPhys(HI->reg));
1013 // merge added with unhandled
1014 for (unsigned i = 0, e = added.size(); i != e; ++i)
1015 unhandled_.push(added[i]);
1018 /// getFreePhysReg - return a free physical register for this virtual register
1019 /// interval if we have one, otherwise return 0.
1020 unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
1021 SmallVector<unsigned, 256> inactiveCounts;
1022 unsigned MaxInactiveCount = 0;
1024 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
1025 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1027 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1029 unsigned reg = i->first->reg;
1030 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
1031 "Can only allocate virtual registers!");
1033 // If this is not in a related reg class to the register we're allocating,
1035 const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
1036 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1037 reg = vrm_->getPhys(reg);
1038 if (inactiveCounts.size() <= reg)
1039 inactiveCounts.resize(reg+1);
1040 ++inactiveCounts[reg];
1041 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1045 unsigned FreeReg = 0;
1046 unsigned FreeRegInactiveCount = 0;
1048 // If copy coalescer has assigned a "preferred" register, check if it's
1050 if (cur->preference) {
1051 if (prt_->isRegAvail(cur->preference) &&
1052 RC->contains(cur->preference)) {
1053 DOUT << "\t\tassigned the preferred register: "
1054 << tri_->getName(cur->preference) << "\n";
1055 return cur->preference;
1057 DOUT << "\t\tunable to assign the preferred register: "
1058 << tri_->getName(cur->preference) << "\n";
1061 // Scan for the first available register.
1062 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
1063 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
1064 assert(I != E && "No allocatable register in this register class!");
1066 if (prt_->isRegAvail(*I)) {
1068 if (FreeReg < inactiveCounts.size())
1069 FreeRegInactiveCount = inactiveCounts[FreeReg];
1071 FreeRegInactiveCount = 0;
1075 // If there are no free regs, or if this reg has the max inactive count,
1076 // return this register.
1077 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
1079 // Continue scanning the registers, looking for the one with the highest
1080 // inactive count. Alkis found that this reduced register pressure very
1081 // slightly on X86 (in rev 1.94 of this file), though this should probably be
1083 for (; I != E; ++I) {
1085 if (prt_->isRegAvail(Reg) && Reg < inactiveCounts.size() &&
1086 FreeRegInactiveCount < inactiveCounts[Reg]) {
1088 FreeRegInactiveCount = inactiveCounts[Reg];
1089 if (FreeRegInactiveCount == MaxInactiveCount)
1090 break; // We found the one with the max inactive count.
1097 FunctionPass* llvm::createLinearScanRegisterAllocator() {
1098 return new RALinScan();