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/TargetInstrInfo.h"
30 #include "llvm/ADT/EquivalenceClasses.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/Compiler.h"
42 STATISTIC(NumIters , "Number of iterations performed");
43 STATISTIC(NumBacktracks, "Number of times we had to backtrack");
44 STATISTIC(NumCoalesce, "Number of copies coalesced");
46 static RegisterRegAlloc
47 linearscanRegAlloc("linearscan", " linear scan register allocator",
48 createLinearScanRegisterAllocator);
51 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
53 RALinScan() : MachineFunctionPass((intptr_t)&ID) {}
55 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
56 typedef std::vector<IntervalPtr> IntervalPtrs;
58 /// RelatedRegClasses - This structure is built the first time a function is
59 /// compiled, and keeps track of which register classes have registers that
60 /// belong to multiple classes or have aliases that are in other classes.
61 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
62 std::map<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
65 const TargetMachine* tm_;
66 const TargetRegisterInfo* tri_;
67 const TargetInstrInfo* tii_;
68 MachineRegisterInfo *reginfo_;
69 BitVector allocatableRegs_;
72 const MachineLoopInfo *loopInfo;
74 /// handled_ - Intervals are added to the handled_ set in the order of their
75 /// start value. This is uses for backtracking.
76 std::vector<LiveInterval*> handled_;
78 /// fixed_ - Intervals that correspond to machine registers.
82 /// active_ - Intervals that are currently being processed, and which have a
83 /// live range active for the current point.
86 /// inactive_ - Intervals that are currently being processed, but which have
87 /// a hold at the current point.
88 IntervalPtrs inactive_;
90 typedef std::priority_queue<LiveInterval*,
91 std::vector<LiveInterval*>,
92 greater_ptr<LiveInterval> > IntervalHeap;
93 IntervalHeap unhandled_;
94 std::auto_ptr<PhysRegTracker> prt_;
95 std::auto_ptr<VirtRegMap> vrm_;
96 std::auto_ptr<Spiller> spiller_;
99 virtual const char* getPassName() const {
100 return "Linear Scan Register Allocator";
103 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
104 AU.addRequired<LiveIntervals>();
105 // Make sure PassManager knows which analyses to make available
106 // to coalescing and which analyses coalescing invalidates.
107 AU.addRequiredTransitive<RegisterCoalescer>();
108 AU.addRequired<LiveStacks>();
109 AU.addPreserved<LiveStacks>();
110 AU.addRequired<MachineLoopInfo>();
111 AU.addPreserved<MachineLoopInfo>();
112 AU.addPreservedID(MachineDominatorsID);
113 MachineFunctionPass::getAnalysisUsage(AU);
116 /// runOnMachineFunction - register allocate the whole function
117 bool runOnMachineFunction(MachineFunction&);
120 /// linearScan - the linear scan algorithm
123 /// initIntervalSets - initialize the interval sets.
125 void initIntervalSets();
127 /// processActiveIntervals - expire old intervals and move non-overlapping
128 /// ones to the inactive list.
129 void processActiveIntervals(unsigned CurPoint);
131 /// processInactiveIntervals - expire old intervals and move overlapping
132 /// ones to the active list.
133 void processInactiveIntervals(unsigned CurPoint);
135 /// assignRegOrStackSlotAtInterval - assign a register if one
136 /// is available, or spill.
137 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
139 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
140 /// try allocate the definition the same register as the source register
141 /// if the register is not defined during live time of the interval. This
142 /// eliminate a copy. This is used to coalesce copies which were not
143 /// coalesced away before allocation either due to dest and src being in
144 /// different register classes or because the coalescer was overly
146 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
149 /// register handling helpers
152 /// getFreePhysReg - return a free physical register for this virtual
153 /// register interval if we have one, otherwise return 0.
154 unsigned getFreePhysReg(LiveInterval* cur);
156 /// assignVirt2StackSlot - assigns this virtual register to a
157 /// stack slot. returns the stack slot
158 int assignVirt2StackSlot(unsigned virtReg);
160 void ComputeRelatedRegClasses();
162 template <typename ItTy>
163 void printIntervals(const char* const str, ItTy i, ItTy e) const {
164 if (str) DOUT << str << " intervals:\n";
165 for (; i != e; ++i) {
166 DOUT << "\t" << *i->first << " -> ";
167 unsigned reg = i->first->reg;
168 if (TargetRegisterInfo::isVirtualRegister(reg)) {
169 reg = vrm_->getPhys(reg);
171 DOUT << tri_->getName(reg) << '\n';
175 char RALinScan::ID = 0;
178 static RegisterPass<RALinScan>
179 X("linearscan-regalloc", "Linear Scan Register Allocator");
181 void RALinScan::ComputeRelatedRegClasses() {
182 const TargetRegisterInfo &TRI = *tri_;
184 // First pass, add all reg classes to the union, and determine at least one
185 // reg class that each register is in.
186 bool HasAliases = false;
187 for (TargetRegisterInfo::regclass_iterator RCI = TRI.regclass_begin(),
188 E = TRI.regclass_end(); RCI != E; ++RCI) {
189 RelatedRegClasses.insert(*RCI);
190 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
192 HasAliases = HasAliases || *TRI.getAliasSet(*I) != 0;
194 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
196 // Already processed this register. Just make sure we know that
197 // multiple register classes share a register.
198 RelatedRegClasses.unionSets(PRC, *RCI);
205 // Second pass, now that we know conservatively what register classes each reg
206 // belongs to, add info about aliases. We don't need to do this for targets
207 // without register aliases.
209 for (std::map<unsigned, const TargetRegisterClass*>::iterator
210 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
212 for (const unsigned *AS = TRI.getAliasSet(I->first); *AS; ++AS)
213 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
216 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
217 /// try allocate the definition the same register as the source register
218 /// if the register is not defined during live time of the interval. This
219 /// eliminate a copy. This is used to coalesce copies which were not
220 /// coalesced away before allocation either due to dest and src being in
221 /// different register classes or because the coalescer was overly
223 unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
224 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
227 VNInfo *vni = cur.getValNumInfo(0);
228 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
230 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
231 unsigned SrcReg, DstReg;
232 if (!CopyMI || !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg))
234 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
235 if (!vrm_->isAssignedReg(SrcReg))
238 SrcReg = vrm_->getPhys(SrcReg);
243 const TargetRegisterClass *RC = reginfo_->getRegClass(cur.reg);
244 if (!RC->contains(SrcReg))
248 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
249 DOUT << "Coalescing: " << cur << " -> " << tri_->getName(SrcReg)
251 vrm_->clearVirt(cur.reg);
252 vrm_->assignVirt2Phys(cur.reg, SrcReg);
260 bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
262 tm_ = &fn.getTarget();
263 tri_ = tm_->getRegisterInfo();
264 tii_ = tm_->getInstrInfo();
265 reginfo_ = &mf_->getRegInfo();
266 allocatableRegs_ = tri_->getAllocatableSet(fn);
267 li_ = &getAnalysis<LiveIntervals>();
268 ls_ = &getAnalysis<LiveStacks>();
269 loopInfo = &getAnalysis<MachineLoopInfo>();
271 // We don't run the coalescer here because we have no reason to
272 // interact with it. If the coalescer requires interaction, it
273 // won't do anything. If it doesn't require interaction, we assume
274 // it was run as a separate pass.
276 // If this is the first function compiled, compute the related reg classes.
277 if (RelatedRegClasses.empty())
278 ComputeRelatedRegClasses();
280 if (!prt_.get()) prt_.reset(new PhysRegTracker(*tri_));
281 vrm_.reset(new VirtRegMap(*mf_));
282 if (!spiller_.get()) spiller_.reset(createSpiller());
288 // Rewrite spill code and update the PhysRegsUsed set.
289 spiller_->runOnMachineFunction(*mf_, *vrm_);
290 vrm_.reset(); // Free the VirtRegMap
292 while (!unhandled_.empty()) unhandled_.pop();
301 /// initIntervalSets - initialize the interval sets.
303 void RALinScan::initIntervalSets()
305 assert(unhandled_.empty() && fixed_.empty() &&
306 active_.empty() && inactive_.empty() &&
307 "interval sets should be empty on initialization");
309 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
310 if (TargetRegisterInfo::isPhysicalRegister(i->second.reg)) {
311 reginfo_->setPhysRegUsed(i->second.reg);
312 fixed_.push_back(std::make_pair(&i->second, i->second.begin()));
314 unhandled_.push(&i->second);
318 void RALinScan::linearScan()
320 // linear scan algorithm
321 DOUT << "********** LINEAR SCAN **********\n";
322 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
324 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
326 while (!unhandled_.empty()) {
327 // pick the interval with the earliest start point
328 LiveInterval* cur = unhandled_.top();
331 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
334 processActiveIntervals(cur->beginNumber());
335 processInactiveIntervals(cur->beginNumber());
337 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
338 "Can only allocate virtual registers!");
341 // Allocating a virtual register. try to find a free
342 // physical register or spill an interval (possibly this one) in order to
344 assignRegOrStackSlotAtInterval(cur);
346 DEBUG(printIntervals("active", active_.begin(), active_.end()));
347 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
350 // expire any remaining active intervals
351 while (!active_.empty()) {
352 IntervalPtr &IP = active_.back();
353 unsigned reg = IP.first->reg;
354 DOUT << "\tinterval " << *IP.first << " expired\n";
355 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
356 "Can only allocate virtual registers!");
357 reg = vrm_->getPhys(reg);
358 prt_->delRegUse(reg);
362 // expire any remaining inactive intervals
363 DEBUG(for (IntervalPtrs::reverse_iterator
364 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
365 DOUT << "\tinterval " << *i->first << " expired\n");
368 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
369 MachineFunction::iterator EntryMBB = mf_->begin();
370 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
371 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
372 LiveInterval &cur = i->second;
374 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
377 else if (vrm_->isAssignedReg(cur.reg))
378 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
381 // Ignore splited live intervals.
382 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
384 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
386 const LiveRange &LR = *I;
387 if (li_->findLiveInMBBs(LR, LiveInMBBs)) {
388 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
389 if (LiveInMBBs[i] != EntryMBB)
390 LiveInMBBs[i]->addLiveIn(Reg);
399 /// processActiveIntervals - expire old intervals and move non-overlapping ones
400 /// to the inactive list.
401 void RALinScan::processActiveIntervals(unsigned CurPoint)
403 DOUT << "\tprocessing active intervals:\n";
405 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
406 LiveInterval *Interval = active_[i].first;
407 LiveInterval::iterator IntervalPos = active_[i].second;
408 unsigned reg = Interval->reg;
410 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
412 if (IntervalPos == Interval->end()) { // Remove expired intervals.
413 DOUT << "\t\tinterval " << *Interval << " expired\n";
414 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
415 "Can only allocate virtual registers!");
416 reg = vrm_->getPhys(reg);
417 prt_->delRegUse(reg);
419 // Pop off the end of the list.
420 active_[i] = active_.back();
424 } else if (IntervalPos->start > CurPoint) {
425 // Move inactive intervals to inactive list.
426 DOUT << "\t\tinterval " << *Interval << " inactive\n";
427 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
428 "Can only allocate virtual registers!");
429 reg = vrm_->getPhys(reg);
430 prt_->delRegUse(reg);
432 inactive_.push_back(std::make_pair(Interval, IntervalPos));
434 // Pop off the end of the list.
435 active_[i] = active_.back();
439 // Otherwise, just update the iterator position.
440 active_[i].second = IntervalPos;
445 /// processInactiveIntervals - expire old intervals and move overlapping
446 /// ones to the active list.
447 void RALinScan::processInactiveIntervals(unsigned CurPoint)
449 DOUT << "\tprocessing inactive intervals:\n";
451 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
452 LiveInterval *Interval = inactive_[i].first;
453 LiveInterval::iterator IntervalPos = inactive_[i].second;
454 unsigned reg = Interval->reg;
456 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
458 if (IntervalPos == Interval->end()) { // remove expired intervals.
459 DOUT << "\t\tinterval " << *Interval << " expired\n";
461 // Pop off the end of the list.
462 inactive_[i] = inactive_.back();
463 inactive_.pop_back();
465 } else if (IntervalPos->start <= CurPoint) {
466 // move re-activated intervals in active list
467 DOUT << "\t\tinterval " << *Interval << " active\n";
468 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
469 "Can only allocate virtual registers!");
470 reg = vrm_->getPhys(reg);
471 prt_->addRegUse(reg);
473 active_.push_back(std::make_pair(Interval, IntervalPos));
475 // Pop off the end of the list.
476 inactive_[i] = inactive_.back();
477 inactive_.pop_back();
480 // Otherwise, just update the iterator position.
481 inactive_[i].second = IntervalPos;
486 /// updateSpillWeights - updates the spill weights of the specifed physical
487 /// register and its weight.
488 static void updateSpillWeights(std::vector<float> &Weights,
489 unsigned reg, float weight,
490 const TargetRegisterInfo *TRI) {
491 Weights[reg] += weight;
492 for (const unsigned* as = TRI->getAliasSet(reg); *as; ++as)
493 Weights[*as] += weight;
497 RALinScan::IntervalPtrs::iterator
498 FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
499 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
501 if (I->first == LI) return I;
505 static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
506 for (unsigned i = 0, e = V.size(); i != e; ++i) {
507 RALinScan::IntervalPtr &IP = V[i];
508 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
510 if (I != IP.first->begin()) --I;
515 /// addStackInterval - Create a LiveInterval for stack if the specified live
516 /// interval has been spilled.
517 static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
518 LiveIntervals *li_, VirtRegMap &vrm_) {
519 int SS = vrm_.getStackSlot(cur->reg);
520 if (SS == VirtRegMap::NO_STACK_SLOT)
522 LiveInterval &SI = ls_->getOrCreateInterval(SS);
524 if (SI.getNumValNums())
525 VNI = SI.getValNumInfo(0);
527 VNI = SI.getNextValue(~0U, 0, ls_->getVNInfoAllocator());
529 LiveInterval &RI = li_->getInterval(cur->reg);
530 // FIXME: This may be overly conservative.
531 SI.MergeRangesInAsValue(RI, VNI);
532 SI.weight += RI.weight;
535 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
537 void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
539 DOUT << "\tallocating current interval: ";
541 // This is an implicitly defined live interval, just assign any register.
542 const TargetRegisterClass *RC = reginfo_->getRegClass(cur->reg);
544 unsigned physReg = cur->preference;
546 physReg = *RC->allocation_order_begin(*mf_);
547 DOUT << tri_->getName(physReg) << '\n';
548 // Note the register is not really in use.
549 vrm_->assignVirt2Phys(cur->reg, physReg);
553 PhysRegTracker backupPrt = *prt_;
555 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
556 unsigned StartPosition = cur->beginNumber();
557 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
559 // If this live interval is defined by a move instruction and its source is
560 // assigned a physical register that is compatible with the target register
561 // class, then we should try to assign it the same register.
562 // This can happen when the move is from a larger register class to a smaller
563 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
564 if (!cur->preference && cur->containsOneValue()) {
565 VNInfo *vni = cur->getValNumInfo(0);
566 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
567 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
568 unsigned SrcReg, DstReg;
569 if (CopyMI && tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
571 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
573 else if (vrm_->isAssignedReg(SrcReg))
574 Reg = vrm_->getPhys(SrcReg);
575 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
576 cur->preference = Reg;
581 // for every interval in inactive we overlap with, mark the
582 // register as not free and update spill weights.
583 for (IntervalPtrs::const_iterator i = inactive_.begin(),
584 e = inactive_.end(); i != e; ++i) {
585 unsigned Reg = i->first->reg;
586 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
587 "Can only allocate virtual registers!");
588 const TargetRegisterClass *RegRC = reginfo_->getRegClass(Reg);
589 // If this is not in a related reg class to the register we're allocating,
591 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
592 cur->overlapsFrom(*i->first, i->second-1)) {
593 Reg = vrm_->getPhys(Reg);
594 prt_->addRegUse(Reg);
595 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
599 // Speculatively check to see if we can get a register right now. If not,
600 // we know we won't be able to by adding more constraints. If so, we can
601 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
602 // is very bad (it contains all callee clobbered registers for any functions
603 // with a call), so we want to avoid doing that if possible.
604 unsigned physReg = getFreePhysReg(cur);
605 unsigned BestPhysReg = physReg;
607 // We got a register. However, if it's in the fixed_ list, we might
608 // conflict with it. Check to see if we conflict with it or any of its
610 SmallSet<unsigned, 8> RegAliases;
611 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
612 RegAliases.insert(*AS);
614 bool ConflictsWithFixed = false;
615 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
616 IntervalPtr &IP = fixed_[i];
617 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
618 // Okay, this reg is on the fixed list. Check to see if we actually
620 LiveInterval *I = IP.first;
621 if (I->endNumber() > StartPosition) {
622 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
624 if (II != I->begin() && II->start > StartPosition)
626 if (cur->overlapsFrom(*I, II)) {
627 ConflictsWithFixed = true;
634 // Okay, the register picked by our speculative getFreePhysReg call turned
635 // out to be in use. Actually add all of the conflicting fixed registers to
636 // prt so we can do an accurate query.
637 if (ConflictsWithFixed) {
638 // For every interval in fixed we overlap with, mark the register as not
639 // free and update spill weights.
640 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
641 IntervalPtr &IP = fixed_[i];
642 LiveInterval *I = IP.first;
644 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
645 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
646 I->endNumber() > StartPosition) {
647 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
649 if (II != I->begin() && II->start > StartPosition)
651 if (cur->overlapsFrom(*I, II)) {
652 unsigned reg = I->reg;
653 prt_->addRegUse(reg);
654 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
659 // Using the newly updated prt_ object, which includes conflicts in the
660 // future, see if there are any registers available.
661 physReg = getFreePhysReg(cur);
665 // Restore the physical register tracker, removing information about the
669 // if we find a free register, we are done: assign this virtual to
670 // the free physical register and add this interval to the active
673 DOUT << tri_->getName(physReg) << '\n';
674 vrm_->assignVirt2Phys(cur->reg, physReg);
675 prt_->addRegUse(physReg);
676 active_.push_back(std::make_pair(cur, cur->begin()));
677 handled_.push_back(cur);
680 DOUT << "no free registers\n";
682 // Compile the spill weights into an array that is better for scanning.
683 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0);
684 for (std::vector<std::pair<unsigned, float> >::iterator
685 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
686 updateSpillWeights(SpillWeights, I->first, I->second, tri_);
688 // for each interval in active, update spill weights.
689 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
691 unsigned reg = i->first->reg;
692 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
693 "Can only allocate virtual registers!");
694 reg = vrm_->getPhys(reg);
695 updateSpillWeights(SpillWeights, reg, i->first->weight, tri_);
698 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
700 // Find a register to spill.
701 float minWeight = HUGE_VALF;
702 unsigned minReg = cur->preference; // Try the preferred register first.
704 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
705 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
706 e = RC->allocation_order_end(*mf_); i != e; ++i) {
708 if (minWeight > SpillWeights[reg]) {
709 minWeight = SpillWeights[reg];
714 // If we didn't find a register that is spillable, try aliases?
716 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
717 e = RC->allocation_order_end(*mf_); i != e; ++i) {
719 // No need to worry about if the alias register size < regsize of RC.
720 // We are going to spill all registers that alias it anyway.
721 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as) {
722 if (minWeight > SpillWeights[*as]) {
723 minWeight = SpillWeights[*as];
729 // All registers must have inf weight. Just grab one!
731 minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
732 if (cur->weight == HUGE_VALF || cur->getSize() == 1)
733 // Spill a physical register around defs and uses.
734 li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_);
738 DOUT << "\t\tregister with min weight: "
739 << tri_->getName(minReg) << " (" << minWeight << ")\n";
741 // if the current has the minimum weight, we need to spill it and
742 // add any added intervals back to unhandled, and restart
744 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
745 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
746 std::vector<LiveInterval*> added =
747 li_->addIntervalsForSpills(*cur, loopInfo, *vrm_);
748 addStackInterval(cur, ls_, li_, *vrm_);
750 return; // Early exit if all spills were folded.
752 // Merge added with unhandled. Note that we know that
753 // addIntervalsForSpills returns intervals sorted by their starting
755 for (unsigned i = 0, e = added.size(); i != e; ++i)
756 unhandled_.push(added[i]);
762 // push the current interval back to unhandled since we are going
763 // to re-run at least this iteration. Since we didn't modify it it
764 // should go back right in the front of the list
765 unhandled_.push(cur);
767 // otherwise we spill all intervals aliasing the register with
768 // minimum weight, rollback to the interval with the earliest
769 // start point and let the linear scan algorithm run again
770 std::vector<LiveInterval*> added;
771 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
772 "did not choose a register to spill?");
773 BitVector toSpill(tri_->getNumRegs());
775 // We are going to spill minReg and all its aliases.
776 toSpill[minReg] = true;
777 for (const unsigned* as = tri_->getAliasSet(minReg); *as; ++as)
780 // the earliest start of a spilled interval indicates up to where
781 // in handled we need to roll back
782 unsigned earliestStart = cur->beginNumber();
784 // set of spilled vregs (used later to rollback properly)
785 SmallSet<unsigned, 32> spilled;
787 // spill live intervals of virtual regs mapped to the physical register we
788 // want to clear (and its aliases). We only spill those that overlap with the
789 // current interval as the rest do not affect its allocation. we also keep
790 // track of the earliest start of all spilled live intervals since this will
791 // mark our rollback point.
792 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
793 unsigned reg = i->first->reg;
794 if (//TargetRegisterInfo::isVirtualRegister(reg) &&
795 toSpill[vrm_->getPhys(reg)] &&
796 cur->overlapsFrom(*i->first, i->second)) {
797 DOUT << "\t\t\tspilling(a): " << *i->first << '\n';
798 earliestStart = std::min(earliestStart, i->first->beginNumber());
799 std::vector<LiveInterval*> newIs =
800 li_->addIntervalsForSpills(*i->first, loopInfo, *vrm_);
801 addStackInterval(i->first, ls_, li_, *vrm_);
802 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
806 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
807 unsigned reg = i->first->reg;
808 if (//TargetRegisterInfo::isVirtualRegister(reg) &&
809 toSpill[vrm_->getPhys(reg)] &&
810 cur->overlapsFrom(*i->first, i->second-1)) {
811 DOUT << "\t\t\tspilling(i): " << *i->first << '\n';
812 earliestStart = std::min(earliestStart, i->first->beginNumber());
813 std::vector<LiveInterval*> newIs =
814 li_->addIntervalsForSpills(*i->first, loopInfo, *vrm_);
815 addStackInterval(i->first, ls_, li_, *vrm_);
816 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
821 DOUT << "\t\trolling back to: " << earliestStart << '\n';
823 // Scan handled in reverse order up to the earliest start of a
824 // spilled live interval and undo each one, restoring the state of
826 while (!handled_.empty()) {
827 LiveInterval* i = handled_.back();
828 // If this interval starts before t we are done.
829 if (i->beginNumber() < earliestStart)
831 DOUT << "\t\t\tundo changes for: " << *i << '\n';
834 // When undoing a live interval allocation we must know if it is active or
835 // inactive to properly update the PhysRegTracker and the VirtRegMap.
836 IntervalPtrs::iterator it;
837 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
839 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
840 if (!spilled.count(i->reg))
842 prt_->delRegUse(vrm_->getPhys(i->reg));
843 vrm_->clearVirt(i->reg);
844 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
846 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
847 if (!spilled.count(i->reg))
849 vrm_->clearVirt(i->reg);
851 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
852 "Can only allocate virtual registers!");
853 vrm_->clearVirt(i->reg);
857 // It interval has a preference, it must be defined by a copy. Clear the
858 // preference now since the source interval allocation may have been undone
863 // Rewind the iterators in the active, inactive, and fixed lists back to the
864 // point we reverted to.
865 RevertVectorIteratorsTo(active_, earliestStart);
866 RevertVectorIteratorsTo(inactive_, earliestStart);
867 RevertVectorIteratorsTo(fixed_, earliestStart);
869 // scan the rest and undo each interval that expired after t and
870 // insert it in active (the next iteration of the algorithm will
871 // put it in inactive if required)
872 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
873 LiveInterval *HI = handled_[i];
874 if (!HI->expiredAt(earliestStart) &&
875 HI->expiredAt(cur->beginNumber())) {
876 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
877 active_.push_back(std::make_pair(HI, HI->begin()));
878 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
879 prt_->addRegUse(vrm_->getPhys(HI->reg));
883 // merge added with unhandled
884 for (unsigned i = 0, e = added.size(); i != e; ++i)
885 unhandled_.push(added[i]);
888 /// getFreePhysReg - return a free physical register for this virtual register
889 /// interval if we have one, otherwise return 0.
890 unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
891 SmallVector<unsigned, 256> inactiveCounts;
892 unsigned MaxInactiveCount = 0;
894 const TargetRegisterClass *RC = reginfo_->getRegClass(cur->reg);
895 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
897 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
899 unsigned reg = i->first->reg;
900 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
901 "Can only allocate virtual registers!");
903 // If this is not in a related reg class to the register we're allocating,
905 const TargetRegisterClass *RegRC = reginfo_->getRegClass(reg);
906 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
907 reg = vrm_->getPhys(reg);
908 if (inactiveCounts.size() <= reg)
909 inactiveCounts.resize(reg+1);
910 ++inactiveCounts[reg];
911 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
915 unsigned FreeReg = 0;
916 unsigned FreeRegInactiveCount = 0;
918 // If copy coalescer has assigned a "preferred" register, check if it's
920 if (cur->preference) {
921 if (prt_->isRegAvail(cur->preference)) {
922 DOUT << "\t\tassigned the preferred register: "
923 << tri_->getName(cur->preference) << "\n";
924 return cur->preference;
926 DOUT << "\t\tunable to assign the preferred register: "
927 << tri_->getName(cur->preference) << "\n";
930 // Scan for the first available register.
931 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
932 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
933 assert(I != E && "No allocatable register in this register class!");
935 if (prt_->isRegAvail(*I)) {
937 if (FreeReg < inactiveCounts.size())
938 FreeRegInactiveCount = inactiveCounts[FreeReg];
940 FreeRegInactiveCount = 0;
944 // If there are no free regs, or if this reg has the max inactive count,
945 // return this register.
946 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
948 // Continue scanning the registers, looking for the one with the highest
949 // inactive count. Alkis found that this reduced register pressure very
950 // slightly on X86 (in rev 1.94 of this file), though this should probably be
952 for (; I != E; ++I) {
954 if (prt_->isRegAvail(Reg) && Reg < inactiveCounts.size() &&
955 FreeRegInactiveCount < inactiveCounts[Reg]) {
957 FreeRegInactiveCount = inactiveCounts[Reg];
958 if (FreeRegInactiveCount == MaxInactiveCount)
959 break; // We found the one with the max inactive count.
966 FunctionPass* llvm::createLinearScanRegisterAllocator() {
967 return new RALinScan();