Code clean up. Bye bye PhysRegTracker.
[llvm/msp430.git] / lib / CodeGen / RegAllocLinearScan.cpp
blob83c1cbb385fbe1cea27b95833c5b791cd2f8602f
1 //===-- RegAllocLinearScan.cpp - Linear Scan register allocator -----------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a linear scan register allocator.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "regalloc"
15 #include "VirtRegMap.h"
16 #include "Spiller.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/SmallSet.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/Compiler.h"
37 #include <algorithm>
38 #include <set>
39 #include <queue>
40 #include <memory>
41 #include <cmath>
42 using namespace llvm;
44 STATISTIC(NumIters , "Number of iterations performed");
45 STATISTIC(NumBacktracks, "Number of times we had to backtrack");
46 STATISTIC(NumCoalesce, "Number of copies coalesced");
47 STATISTIC(NumDowngrade, "Number of registers downgraded");
49 static cl::opt<bool>
50 NewHeuristic("new-spilling-heuristic",
51 cl::desc("Use new spilling heuristic"),
52 cl::init(false), cl::Hidden);
54 static cl::opt<bool>
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);
63 namespace {
64 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
65 static char ID;
66 RALinScan() : MachineFunctionPass(&ID) {}
68 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
69 typedef SmallVector<IntervalPtr, 32> IntervalPtrs;
70 private:
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;
77 // NextReloadMap - For each register in the map, it maps to the another
78 // register which is defined by a reload from the same stack slot and
79 // both reloads are in the same basic block.
80 DenseMap<unsigned, unsigned> NextReloadMap;
82 // DowngradedRegs - A set of registers which are being "downgraded", i.e.
83 // un-favored for allocation.
84 SmallSet<unsigned, 8> DowngradedRegs;
86 // DowngradeMap - A map from virtual registers to physical registers being
87 // downgraded for the virtual registers.
88 DenseMap<unsigned, unsigned> DowngradeMap;
90 MachineFunction* mf_;
91 MachineRegisterInfo* mri_;
92 const TargetMachine* tm_;
93 const TargetRegisterInfo* tri_;
94 const TargetInstrInfo* tii_;
95 BitVector allocatableRegs_;
96 LiveIntervals* li_;
97 LiveStacks* ls_;
98 const MachineLoopInfo *loopInfo;
100 /// handled_ - Intervals are added to the handled_ set in the order of their
101 /// start value. This is uses for backtracking.
102 std::vector<LiveInterval*> handled_;
104 /// fixed_ - Intervals that correspond to machine registers.
106 IntervalPtrs fixed_;
108 /// active_ - Intervals that are currently being processed, and which have a
109 /// live range active for the current point.
110 IntervalPtrs active_;
112 /// inactive_ - Intervals that are currently being processed, but which have
113 /// a hold at the current point.
114 IntervalPtrs inactive_;
116 typedef std::priority_queue<LiveInterval*,
117 SmallVector<LiveInterval*, 64>,
118 greater_ptr<LiveInterval> > IntervalHeap;
119 IntervalHeap unhandled_;
121 /// regUse_ - Tracks register usage.
122 SmallVector<unsigned, 32> regUse_;
123 SmallVector<unsigned, 32> regUseBackUp_;
125 /// vrm_ - Tracks register assignments.
126 VirtRegMap* vrm_;
128 std::auto_ptr<Spiller> spiller_;
130 public:
131 virtual const char* getPassName() const {
132 return "Linear Scan Register Allocator";
135 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
136 AU.addRequired<LiveIntervals>();
137 if (StrongPHIElim)
138 AU.addRequiredID(StrongPHIEliminationID);
139 // Make sure PassManager knows which analyses to make available
140 // to coalescing and which analyses coalescing invalidates.
141 AU.addRequiredTransitive<RegisterCoalescer>();
142 if (PreSplitIntervals)
143 AU.addRequiredID(PreAllocSplittingID);
144 AU.addRequired<LiveStacks>();
145 AU.addPreserved<LiveStacks>();
146 AU.addRequired<MachineLoopInfo>();
147 AU.addPreserved<MachineLoopInfo>();
148 AU.addRequired<VirtRegMap>();
149 AU.addPreserved<VirtRegMap>();
150 AU.addPreservedID(MachineDominatorsID);
151 MachineFunctionPass::getAnalysisUsage(AU);
154 /// runOnMachineFunction - register allocate the whole function
155 bool runOnMachineFunction(MachineFunction&);
157 private:
158 /// linearScan - the linear scan algorithm
159 void linearScan();
161 /// initIntervalSets - initialize the interval sets.
163 void initIntervalSets();
165 /// processActiveIntervals - expire old intervals and move non-overlapping
166 /// ones to the inactive list.
167 void processActiveIntervals(unsigned CurPoint);
169 /// processInactiveIntervals - expire old intervals and move overlapping
170 /// ones to the active list.
171 void processInactiveIntervals(unsigned CurPoint);
173 /// hasNextReloadInterval - Return the next liveinterval that's being
174 /// defined by a reload from the same SS as the specified one.
175 LiveInterval *hasNextReloadInterval(LiveInterval *cur);
177 /// DowngradeRegister - Downgrade a register for allocation.
178 void DowngradeRegister(LiveInterval *li, unsigned Reg);
180 /// UpgradeRegister - Upgrade a register for allocation.
181 void UpgradeRegister(unsigned Reg);
183 /// assignRegOrStackSlotAtInterval - assign a register if one
184 /// is available, or spill.
185 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
187 void updateSpillWeights(std::vector<float> &Weights,
188 unsigned reg, float weight,
189 const TargetRegisterClass *RC);
191 /// findIntervalsToSpill - Determine the intervals to spill for the
192 /// specified interval. It's passed the physical registers whose spill
193 /// weight is the lowest among all the registers whose live intervals
194 /// conflict with the interval.
195 void findIntervalsToSpill(LiveInterval *cur,
196 std::vector<std::pair<unsigned,float> > &Candidates,
197 unsigned NumCands,
198 SmallVector<LiveInterval*, 8> &SpillIntervals);
200 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
201 /// try allocate the definition the same register as the source register
202 /// if the register is not defined during live time of the interval. This
203 /// eliminate a copy. This is used to coalesce copies which were not
204 /// coalesced away before allocation either due to dest and src being in
205 /// different register classes or because the coalescer was overly
206 /// conservative.
207 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
210 /// Register usage / availability tracking helpers.
213 void initRegUses() {
214 regUse_.resize(tri_->getNumRegs(), 0);
215 regUseBackUp_.resize(tri_->getNumRegs(), 0);
218 void finalizeRegUses() {
219 regUse_.clear();
220 regUseBackUp_.clear();
223 void addRegUse(unsigned physReg) {
224 assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
225 "should be physical register!");
226 ++regUse_[physReg];
227 for (const unsigned* as = tri_->getAliasSet(physReg); *as; ++as)
228 ++regUse_[*as];
231 void delRegUse(unsigned physReg) {
232 assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
233 "should be physical register!");
234 assert(regUse_[physReg] != 0);
235 --regUse_[physReg];
236 for (const unsigned* as = tri_->getAliasSet(physReg); *as; ++as) {
237 assert(regUse_[*as] != 0);
238 --regUse_[*as];
242 bool isRegAvail(unsigned physReg) const {
243 assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
244 "should be physical register!");
245 return regUse_[physReg] == 0;
248 void backUpRegUses() {
249 regUseBackUp_ = regUse_;
252 void restoreRegUses() {
253 regUse_ = regUseBackUp_;
257 /// Register handling helpers.
260 /// getFreePhysReg - return a free physical register for this virtual
261 /// register interval if we have one, otherwise return 0.
262 unsigned getFreePhysReg(LiveInterval* cur);
263 unsigned getFreePhysReg(const TargetRegisterClass *RC,
264 unsigned MaxInactiveCount,
265 SmallVector<unsigned, 256> &inactiveCounts,
266 bool SkipDGRegs);
268 /// assignVirt2StackSlot - assigns this virtual register to a
269 /// stack slot. returns the stack slot
270 int assignVirt2StackSlot(unsigned virtReg);
272 void ComputeRelatedRegClasses();
274 template <typename ItTy>
275 void printIntervals(const char* const str, ItTy i, ItTy e) const {
276 if (str) DOUT << str << " intervals:\n";
277 for (; i != e; ++i) {
278 DOUT << "\t" << *i->first << " -> ";
279 unsigned reg = i->first->reg;
280 if (TargetRegisterInfo::isVirtualRegister(reg)) {
281 reg = vrm_->getPhys(reg);
283 DOUT << tri_->getName(reg) << '\n';
287 char RALinScan::ID = 0;
290 static RegisterPass<RALinScan>
291 X("linearscan-regalloc", "Linear Scan Register Allocator");
293 void RALinScan::ComputeRelatedRegClasses() {
294 // First pass, add all reg classes to the union, and determine at least one
295 // reg class that each register is in.
296 bool HasAliases = false;
297 for (TargetRegisterInfo::regclass_iterator RCI = tri_->regclass_begin(),
298 E = tri_->regclass_end(); RCI != E; ++RCI) {
299 RelatedRegClasses.insert(*RCI);
300 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
301 I != E; ++I) {
302 HasAliases = HasAliases || *tri_->getAliasSet(*I) != 0;
304 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
305 if (PRC) {
306 // Already processed this register. Just make sure we know that
307 // multiple register classes share a register.
308 RelatedRegClasses.unionSets(PRC, *RCI);
309 } else {
310 PRC = *RCI;
315 // Second pass, now that we know conservatively what register classes each reg
316 // belongs to, add info about aliases. We don't need to do this for targets
317 // without register aliases.
318 if (HasAliases)
319 for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
320 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
321 I != E; ++I)
322 for (const unsigned *AS = tri_->getAliasSet(I->first); *AS; ++AS)
323 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
326 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
327 /// try allocate the definition the same register as the source register
328 /// if the register is not defined during live time of the interval. This
329 /// eliminate a copy. This is used to coalesce copies which were not
330 /// coalesced away before allocation either due to dest and src being in
331 /// different register classes or because the coalescer was overly
332 /// conservative.
333 unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
334 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
335 return Reg;
337 VNInfo *vni = cur.begin()->valno;
338 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
339 return Reg;
340 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
341 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
342 if (!CopyMI ||
343 !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg))
344 return Reg;
345 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
346 if (!vrm_->isAssignedReg(SrcReg))
347 return Reg;
348 else
349 SrcReg = vrm_->getPhys(SrcReg);
351 if (Reg == SrcReg)
352 return Reg;
354 const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
355 if (!RC->contains(SrcReg))
356 return Reg;
358 // Try to coalesce.
359 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
360 DOUT << "Coalescing: " << cur << " -> " << tri_->getName(SrcReg)
361 << '\n';
362 vrm_->clearVirt(cur.reg);
363 vrm_->assignVirt2Phys(cur.reg, SrcReg);
364 ++NumCoalesce;
365 return SrcReg;
368 return Reg;
371 bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
372 mf_ = &fn;
373 mri_ = &fn.getRegInfo();
374 tm_ = &fn.getTarget();
375 tri_ = tm_->getRegisterInfo();
376 tii_ = tm_->getInstrInfo();
377 allocatableRegs_ = tri_->getAllocatableSet(fn);
378 li_ = &getAnalysis<LiveIntervals>();
379 ls_ = &getAnalysis<LiveStacks>();
380 loopInfo = &getAnalysis<MachineLoopInfo>();
382 // We don't run the coalescer here because we have no reason to
383 // interact with it. If the coalescer requires interaction, it
384 // won't do anything. If it doesn't require interaction, we assume
385 // it was run as a separate pass.
387 // If this is the first function compiled, compute the related reg classes.
388 if (RelatedRegClasses.empty())
389 ComputeRelatedRegClasses();
391 // Also resize register usage trackers.
392 initRegUses();
394 vrm_ = &getAnalysis<VirtRegMap>();
395 if (!spiller_.get()) spiller_.reset(createSpiller());
397 initIntervalSets();
399 linearScan();
401 // Rewrite spill code and update the PhysRegsUsed set.
402 spiller_->runOnMachineFunction(*mf_, *vrm_, li_);
404 assert(unhandled_.empty() && "Unhandled live intervals remain!");
406 finalizeRegUses();
408 fixed_.clear();
409 active_.clear();
410 inactive_.clear();
411 handled_.clear();
412 NextReloadMap.clear();
413 DowngradedRegs.clear();
414 DowngradeMap.clear();
416 return true;
419 /// initIntervalSets - initialize the interval sets.
421 void RALinScan::initIntervalSets()
423 assert(unhandled_.empty() && fixed_.empty() &&
424 active_.empty() && inactive_.empty() &&
425 "interval sets should be empty on initialization");
427 handled_.reserve(li_->getNumIntervals());
429 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
430 if (TargetRegisterInfo::isPhysicalRegister(i->second->reg)) {
431 mri_->setPhysRegUsed(i->second->reg);
432 fixed_.push_back(std::make_pair(i->second, i->second->begin()));
433 } else
434 unhandled_.push(i->second);
438 void RALinScan::linearScan()
440 // linear scan algorithm
441 DOUT << "********** LINEAR SCAN **********\n";
442 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
444 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
446 while (!unhandled_.empty()) {
447 // pick the interval with the earliest start point
448 LiveInterval* cur = unhandled_.top();
449 unhandled_.pop();
450 ++NumIters;
451 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
453 if (!cur->empty()) {
454 processActiveIntervals(cur->beginNumber());
455 processInactiveIntervals(cur->beginNumber());
457 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
458 "Can only allocate virtual registers!");
461 // Allocating a virtual register. try to find a free
462 // physical register or spill an interval (possibly this one) in order to
463 // assign it one.
464 assignRegOrStackSlotAtInterval(cur);
466 DEBUG(printIntervals("active", active_.begin(), active_.end()));
467 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
470 // Expire any remaining active intervals
471 while (!active_.empty()) {
472 IntervalPtr &IP = active_.back();
473 unsigned reg = IP.first->reg;
474 DOUT << "\tinterval " << *IP.first << " expired\n";
475 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
476 "Can only allocate virtual registers!");
477 reg = vrm_->getPhys(reg);
478 delRegUse(reg);
479 active_.pop_back();
482 // Expire any remaining inactive intervals
483 DEBUG(for (IntervalPtrs::reverse_iterator
484 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
485 DOUT << "\tinterval " << *i->first << " expired\n");
486 inactive_.clear();
488 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
489 MachineFunction::iterator EntryMBB = mf_->begin();
490 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
491 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
492 LiveInterval &cur = *i->second;
493 unsigned Reg = 0;
494 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
495 if (isPhys)
496 Reg = cur.reg;
497 else if (vrm_->isAssignedReg(cur.reg))
498 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
499 if (!Reg)
500 continue;
501 // Ignore splited live intervals.
502 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
503 continue;
504 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
505 I != E; ++I) {
506 const LiveRange &LR = *I;
507 if (li_->findLiveInMBBs(LR.start, LR.end, LiveInMBBs)) {
508 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
509 if (LiveInMBBs[i] != EntryMBB)
510 LiveInMBBs[i]->addLiveIn(Reg);
511 LiveInMBBs.clear();
516 DOUT << *vrm_;
519 /// processActiveIntervals - expire old intervals and move non-overlapping ones
520 /// to the inactive list.
521 void RALinScan::processActiveIntervals(unsigned CurPoint)
523 DOUT << "\tprocessing active intervals:\n";
525 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
526 LiveInterval *Interval = active_[i].first;
527 LiveInterval::iterator IntervalPos = active_[i].second;
528 unsigned reg = Interval->reg;
530 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
532 if (IntervalPos == Interval->end()) { // Remove expired intervals.
533 DOUT << "\t\tinterval " << *Interval << " expired\n";
534 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
535 "Can only allocate virtual registers!");
536 reg = vrm_->getPhys(reg);
537 delRegUse(reg);
539 // Pop off the end of the list.
540 active_[i] = active_.back();
541 active_.pop_back();
542 --i; --e;
544 } else if (IntervalPos->start > CurPoint) {
545 // Move inactive intervals to inactive list.
546 DOUT << "\t\tinterval " << *Interval << " inactive\n";
547 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
548 "Can only allocate virtual registers!");
549 reg = vrm_->getPhys(reg);
550 delRegUse(reg);
551 // add to inactive.
552 inactive_.push_back(std::make_pair(Interval, IntervalPos));
554 // Pop off the end of the list.
555 active_[i] = active_.back();
556 active_.pop_back();
557 --i; --e;
558 } else {
559 // Otherwise, just update the iterator position.
560 active_[i].second = IntervalPos;
565 /// processInactiveIntervals - expire old intervals and move overlapping
566 /// ones to the active list.
567 void RALinScan::processInactiveIntervals(unsigned CurPoint)
569 DOUT << "\tprocessing inactive intervals:\n";
571 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
572 LiveInterval *Interval = inactive_[i].first;
573 LiveInterval::iterator IntervalPos = inactive_[i].second;
574 unsigned reg = Interval->reg;
576 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
578 if (IntervalPos == Interval->end()) { // remove expired intervals.
579 DOUT << "\t\tinterval " << *Interval << " expired\n";
581 // Pop off the end of the list.
582 inactive_[i] = inactive_.back();
583 inactive_.pop_back();
584 --i; --e;
585 } else if (IntervalPos->start <= CurPoint) {
586 // move re-activated intervals in active list
587 DOUT << "\t\tinterval " << *Interval << " active\n";
588 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
589 "Can only allocate virtual registers!");
590 reg = vrm_->getPhys(reg);
591 addRegUse(reg);
592 // add to active
593 active_.push_back(std::make_pair(Interval, IntervalPos));
595 // Pop off the end of the list.
596 inactive_[i] = inactive_.back();
597 inactive_.pop_back();
598 --i; --e;
599 } else {
600 // Otherwise, just update the iterator position.
601 inactive_[i].second = IntervalPos;
606 /// updateSpillWeights - updates the spill weights of the specifed physical
607 /// register and its weight.
608 void RALinScan::updateSpillWeights(std::vector<float> &Weights,
609 unsigned reg, float weight,
610 const TargetRegisterClass *RC) {
611 SmallSet<unsigned, 4> Processed;
612 SmallSet<unsigned, 4> SuperAdded;
613 SmallVector<unsigned, 4> Supers;
614 Weights[reg] += weight;
615 Processed.insert(reg);
616 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as) {
617 Weights[*as] += weight;
618 Processed.insert(*as);
619 if (tri_->isSubRegister(*as, reg) &&
620 SuperAdded.insert(*as) &&
621 RC->contains(*as)) {
622 Supers.push_back(*as);
626 // If the alias is a super-register, and the super-register is in the
627 // register class we are trying to allocate. Then add the weight to all
628 // sub-registers of the super-register even if they are not aliases.
629 // e.g. allocating for GR32, bh is not used, updating bl spill weight.
630 // bl should get the same spill weight otherwise it will be choosen
631 // as a spill candidate since spilling bh doesn't make ebx available.
632 for (unsigned i = 0, e = Supers.size(); i != e; ++i) {
633 for (const unsigned *sr = tri_->getSubRegisters(Supers[i]); *sr; ++sr)
634 if (!Processed.count(*sr))
635 Weights[*sr] += weight;
639 static
640 RALinScan::IntervalPtrs::iterator
641 FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
642 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
643 I != E; ++I)
644 if (I->first == LI) return I;
645 return IP.end();
648 static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
649 for (unsigned i = 0, e = V.size(); i != e; ++i) {
650 RALinScan::IntervalPtr &IP = V[i];
651 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
652 IP.second, Point);
653 if (I != IP.first->begin()) --I;
654 IP.second = I;
658 /// addStackInterval - Create a LiveInterval for stack if the specified live
659 /// interval has been spilled.
660 static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
661 LiveIntervals *li_, float &Weight,
662 VirtRegMap &vrm_) {
663 int SS = vrm_.getStackSlot(cur->reg);
664 if (SS == VirtRegMap::NO_STACK_SLOT)
665 return;
666 LiveInterval &SI = ls_->getOrCreateInterval(SS);
667 SI.weight += Weight;
669 VNInfo *VNI;
670 if (SI.hasAtLeastOneValue())
671 VNI = SI.getValNumInfo(0);
672 else
673 VNI = SI.getNextValue(~0U, 0, ls_->getVNInfoAllocator());
675 LiveInterval &RI = li_->getInterval(cur->reg);
676 // FIXME: This may be overly conservative.
677 SI.MergeRangesInAsValue(RI, VNI);
680 /// getConflictWeight - Return the number of conflicts between cur
681 /// live interval and defs and uses of Reg weighted by loop depthes.
682 static float getConflictWeight(LiveInterval *cur, unsigned Reg,
683 LiveIntervals *li_,
684 MachineRegisterInfo *mri_,
685 const MachineLoopInfo *loopInfo) {
686 float Conflicts = 0;
687 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
688 E = mri_->reg_end(); I != E; ++I) {
689 MachineInstr *MI = &*I;
690 if (cur->liveAt(li_->getInstructionIndex(MI))) {
691 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
692 Conflicts += powf(10.0f, (float)loopDepth);
695 return Conflicts;
698 /// findIntervalsToSpill - Determine the intervals to spill for the
699 /// specified interval. It's passed the physical registers whose spill
700 /// weight is the lowest among all the registers whose live intervals
701 /// conflict with the interval.
702 void RALinScan::findIntervalsToSpill(LiveInterval *cur,
703 std::vector<std::pair<unsigned,float> > &Candidates,
704 unsigned NumCands,
705 SmallVector<LiveInterval*, 8> &SpillIntervals) {
706 // We have figured out the *best* register to spill. But there are other
707 // registers that are pretty good as well (spill weight within 3%). Spill
708 // the one that has fewest defs and uses that conflict with cur.
709 float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
710 SmallVector<LiveInterval*, 8> SLIs[3];
712 DOUT << "\tConsidering " << NumCands << " candidates: ";
713 DEBUG(for (unsigned i = 0; i != NumCands; ++i)
714 DOUT << tri_->getName(Candidates[i].first) << " ";
715 DOUT << "\n";);
717 // Calculate the number of conflicts of each candidate.
718 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
719 unsigned Reg = i->first->reg;
720 unsigned PhysReg = vrm_->getPhys(Reg);
721 if (!cur->overlapsFrom(*i->first, i->second))
722 continue;
723 for (unsigned j = 0; j < NumCands; ++j) {
724 unsigned Candidate = Candidates[j].first;
725 if (tri_->regsOverlap(PhysReg, Candidate)) {
726 if (NumCands > 1)
727 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
728 SLIs[j].push_back(i->first);
733 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
734 unsigned Reg = i->first->reg;
735 unsigned PhysReg = vrm_->getPhys(Reg);
736 if (!cur->overlapsFrom(*i->first, i->second-1))
737 continue;
738 for (unsigned j = 0; j < NumCands; ++j) {
739 unsigned Candidate = Candidates[j].first;
740 if (tri_->regsOverlap(PhysReg, Candidate)) {
741 if (NumCands > 1)
742 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
743 SLIs[j].push_back(i->first);
748 // Which is the best candidate?
749 unsigned BestCandidate = 0;
750 float MinConflicts = Conflicts[0];
751 for (unsigned i = 1; i != NumCands; ++i) {
752 if (Conflicts[i] < MinConflicts) {
753 BestCandidate = i;
754 MinConflicts = Conflicts[i];
758 std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
759 std::back_inserter(SpillIntervals));
762 namespace {
763 struct WeightCompare {
764 typedef std::pair<unsigned, float> RegWeightPair;
765 bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
766 return LHS.second < RHS.second;
771 static bool weightsAreClose(float w1, float w2) {
772 if (!NewHeuristic)
773 return false;
775 float diff = w1 - w2;
776 if (diff <= 0.02f) // Within 0.02f
777 return true;
778 return (diff / w2) <= 0.05f; // Within 5%.
781 LiveInterval *RALinScan::hasNextReloadInterval(LiveInterval *cur) {
782 DenseMap<unsigned, unsigned>::iterator I = NextReloadMap.find(cur->reg);
783 if (I == NextReloadMap.end())
784 return 0;
785 return &li_->getInterval(I->second);
788 void RALinScan::DowngradeRegister(LiveInterval *li, unsigned Reg) {
789 bool isNew = DowngradedRegs.insert(Reg);
790 isNew = isNew; // Silence compiler warning.
791 assert(isNew && "Multiple reloads holding the same register?");
792 DowngradeMap.insert(std::make_pair(li->reg, Reg));
793 for (const unsigned *AS = tri_->getAliasSet(Reg); *AS; ++AS) {
794 isNew = DowngradedRegs.insert(*AS);
795 isNew = isNew; // Silence compiler warning.
796 assert(isNew && "Multiple reloads holding the same register?");
797 DowngradeMap.insert(std::make_pair(li->reg, *AS));
799 ++NumDowngrade;
802 void RALinScan::UpgradeRegister(unsigned Reg) {
803 if (Reg) {
804 DowngradedRegs.erase(Reg);
805 for (const unsigned *AS = tri_->getAliasSet(Reg); *AS; ++AS)
806 DowngradedRegs.erase(*AS);
810 namespace {
811 struct LISorter {
812 bool operator()(LiveInterval* A, LiveInterval* B) {
813 return A->beginNumber() < B->beginNumber();
818 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
819 /// spill.
820 void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
822 DOUT << "\tallocating current interval: ";
824 // This is an implicitly defined live interval, just assign any register.
825 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
826 if (cur->empty()) {
827 unsigned physReg = cur->preference;
828 if (!physReg)
829 physReg = *RC->allocation_order_begin(*mf_);
830 DOUT << tri_->getName(physReg) << '\n';
831 // Note the register is not really in use.
832 vrm_->assignVirt2Phys(cur->reg, physReg);
833 return;
836 backUpRegUses();
838 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
839 unsigned StartPosition = cur->beginNumber();
840 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
842 // If start of this live interval is defined by a move instruction and its
843 // source is assigned a physical register that is compatible with the target
844 // register class, then we should try to assign it the same register.
845 // This can happen when the move is from a larger register class to a smaller
846 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
847 if (!cur->preference && cur->hasAtLeastOneValue()) {
848 VNInfo *vni = cur->begin()->valno;
849 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
850 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
851 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
852 if (CopyMI &&
853 tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg)) {
854 unsigned Reg = 0;
855 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
856 Reg = SrcReg;
857 else if (vrm_->isAssignedReg(SrcReg))
858 Reg = vrm_->getPhys(SrcReg);
859 if (Reg) {
860 if (SrcSubReg)
861 Reg = tri_->getSubReg(Reg, SrcSubReg);
862 if (DstSubReg)
863 Reg = tri_->getMatchingSuperReg(Reg, DstSubReg, RC);
864 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
865 cur->preference = Reg;
871 // For every interval in inactive we overlap with, mark the
872 // register as not free and update spill weights.
873 for (IntervalPtrs::const_iterator i = inactive_.begin(),
874 e = inactive_.end(); i != e; ++i) {
875 unsigned Reg = i->first->reg;
876 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
877 "Can only allocate virtual registers!");
878 const TargetRegisterClass *RegRC = mri_->getRegClass(Reg);
879 // If this is not in a related reg class to the register we're allocating,
880 // don't check it.
881 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
882 cur->overlapsFrom(*i->first, i->second-1)) {
883 Reg = vrm_->getPhys(Reg);
884 addRegUse(Reg);
885 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
889 // Speculatively check to see if we can get a register right now. If not,
890 // we know we won't be able to by adding more constraints. If so, we can
891 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
892 // is very bad (it contains all callee clobbered registers for any functions
893 // with a call), so we want to avoid doing that if possible.
894 unsigned physReg = getFreePhysReg(cur);
895 unsigned BestPhysReg = physReg;
896 if (physReg) {
897 // We got a register. However, if it's in the fixed_ list, we might
898 // conflict with it. Check to see if we conflict with it or any of its
899 // aliases.
900 SmallSet<unsigned, 8> RegAliases;
901 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
902 RegAliases.insert(*AS);
904 bool ConflictsWithFixed = false;
905 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
906 IntervalPtr &IP = fixed_[i];
907 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
908 // Okay, this reg is on the fixed list. Check to see if we actually
909 // conflict.
910 LiveInterval *I = IP.first;
911 if (I->endNumber() > StartPosition) {
912 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
913 IP.second = II;
914 if (II != I->begin() && II->start > StartPosition)
915 --II;
916 if (cur->overlapsFrom(*I, II)) {
917 ConflictsWithFixed = true;
918 break;
924 // Okay, the register picked by our speculative getFreePhysReg call turned
925 // out to be in use. Actually add all of the conflicting fixed registers to
926 // regUse_ so we can do an accurate query.
927 if (ConflictsWithFixed) {
928 // For every interval in fixed we overlap with, mark the register as not
929 // free and update spill weights.
930 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
931 IntervalPtr &IP = fixed_[i];
932 LiveInterval *I = IP.first;
934 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
935 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
936 I->endNumber() > StartPosition) {
937 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
938 IP.second = II;
939 if (II != I->begin() && II->start > StartPosition)
940 --II;
941 if (cur->overlapsFrom(*I, II)) {
942 unsigned reg = I->reg;
943 addRegUse(reg);
944 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
949 // Using the newly updated regUse_ object, which includes conflicts in the
950 // future, see if there are any registers available.
951 physReg = getFreePhysReg(cur);
955 // Restore the physical register tracker, removing information about the
956 // future.
957 restoreRegUses();
959 // If we find a free register, we are done: assign this virtual to
960 // the free physical register and add this interval to the active
961 // list.
962 if (physReg) {
963 DOUT << tri_->getName(physReg) << '\n';
964 vrm_->assignVirt2Phys(cur->reg, physReg);
965 addRegUse(physReg);
966 active_.push_back(std::make_pair(cur, cur->begin()));
967 handled_.push_back(cur);
969 // "Upgrade" the physical register since it has been allocated.
970 UpgradeRegister(physReg);
971 if (LiveInterval *NextReloadLI = hasNextReloadInterval(cur)) {
972 // "Downgrade" physReg to try to keep physReg from being allocated until
973 // the next reload from the same SS is allocated.
974 NextReloadLI->preference = physReg;
975 DowngradeRegister(cur, physReg);
977 return;
979 DOUT << "no free registers\n";
981 // Compile the spill weights into an array that is better for scanning.
982 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
983 for (std::vector<std::pair<unsigned, float> >::iterator
984 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
985 updateSpillWeights(SpillWeights, I->first, I->second, RC);
987 // for each interval in active, update spill weights.
988 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
989 i != e; ++i) {
990 unsigned reg = i->first->reg;
991 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
992 "Can only allocate virtual registers!");
993 reg = vrm_->getPhys(reg);
994 updateSpillWeights(SpillWeights, reg, i->first->weight, RC);
997 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
999 // Find a register to spill.
1000 float minWeight = HUGE_VALF;
1001 unsigned minReg = 0; /*cur->preference*/; // Try the pref register first.
1003 bool Found = false;
1004 std::vector<std::pair<unsigned,float> > RegsWeights;
1005 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
1006 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
1007 e = RC->allocation_order_end(*mf_); i != e; ++i) {
1008 unsigned reg = *i;
1009 float regWeight = SpillWeights[reg];
1010 if (minWeight > regWeight)
1011 Found = true;
1012 RegsWeights.push_back(std::make_pair(reg, regWeight));
1015 // If we didn't find a register that is spillable, try aliases?
1016 if (!Found) {
1017 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
1018 e = RC->allocation_order_end(*mf_); i != e; ++i) {
1019 unsigned reg = *i;
1020 // No need to worry about if the alias register size < regsize of RC.
1021 // We are going to spill all registers that alias it anyway.
1022 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
1023 RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
1027 // Sort all potential spill candidates by weight.
1028 std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare());
1029 minReg = RegsWeights[0].first;
1030 minWeight = RegsWeights[0].second;
1031 if (minWeight == HUGE_VALF) {
1032 // All registers must have inf weight. Just grab one!
1033 minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
1034 if (cur->weight == HUGE_VALF ||
1035 li_->getApproximateInstructionCount(*cur) == 0) {
1036 // Spill a physical register around defs and uses.
1037 if (li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_)) {
1038 // spillPhysRegAroundRegDefsUses may have invalidated iterator stored
1039 // in fixed_. Reset them.
1040 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1041 IntervalPtr &IP = fixed_[i];
1042 LiveInterval *I = IP.first;
1043 if (I->reg == minReg || tri_->isSubRegister(minReg, I->reg))
1044 IP.second = I->advanceTo(I->begin(), StartPosition);
1047 DowngradedRegs.clear();
1048 assignRegOrStackSlotAtInterval(cur);
1049 } else {
1050 cerr << "Ran out of registers during register allocation!\n";
1051 exit(1);
1053 return;
1057 // Find up to 3 registers to consider as spill candidates.
1058 unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
1059 while (LastCandidate > 1) {
1060 if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
1061 break;
1062 --LastCandidate;
1065 DOUT << "\t\tregister(s) with min weight(s): ";
1066 DEBUG(for (unsigned i = 0; i != LastCandidate; ++i)
1067 DOUT << tri_->getName(RegsWeights[i].first)
1068 << " (" << RegsWeights[i].second << ")\n");
1070 // If the current has the minimum weight, we need to spill it and
1071 // add any added intervals back to unhandled, and restart
1072 // linearscan.
1073 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
1074 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
1075 float SSWeight;
1076 SmallVector<LiveInterval*, 8> spillIs;
1077 std::vector<LiveInterval*> added =
1078 li_->addIntervalsForSpills(*cur, spillIs, loopInfo, *vrm_, SSWeight);
1079 std::sort(added.begin(), added.end(), LISorter());
1080 addStackInterval(cur, ls_, li_, SSWeight, *vrm_);
1081 if (added.empty())
1082 return; // Early exit if all spills were folded.
1084 // Merge added with unhandled. Note that we have already sorted
1085 // intervals returned by addIntervalsForSpills by their starting
1086 // point.
1087 // This also update the NextReloadMap. That is, it adds mapping from a
1088 // register defined by a reload from SS to the next reload from SS in the
1089 // same basic block.
1090 MachineBasicBlock *LastReloadMBB = 0;
1091 LiveInterval *LastReload = 0;
1092 int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1093 for (unsigned i = 0, e = added.size(); i != e; ++i) {
1094 LiveInterval *ReloadLi = added[i];
1095 if (ReloadLi->weight == HUGE_VALF &&
1096 li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1097 unsigned ReloadIdx = ReloadLi->beginNumber();
1098 MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1099 int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1100 if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1101 // Last reload of same SS is in the same MBB. We want to try to
1102 // allocate both reloads the same register and make sure the reg
1103 // isn't clobbered in between if at all possible.
1104 assert(LastReload->beginNumber() < ReloadIdx);
1105 NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1107 LastReloadMBB = ReloadMBB;
1108 LastReload = ReloadLi;
1109 LastReloadSS = ReloadSS;
1111 unhandled_.push(ReloadLi);
1113 return;
1116 ++NumBacktracks;
1118 // Push the current interval back to unhandled since we are going
1119 // to re-run at least this iteration. Since we didn't modify it it
1120 // should go back right in the front of the list
1121 unhandled_.push(cur);
1123 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
1124 "did not choose a register to spill?");
1126 // We spill all intervals aliasing the register with
1127 // minimum weight, rollback to the interval with the earliest
1128 // start point and let the linear scan algorithm run again
1129 SmallVector<LiveInterval*, 8> spillIs;
1131 // Determine which intervals have to be spilled.
1132 findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
1134 // Set of spilled vregs (used later to rollback properly)
1135 SmallSet<unsigned, 8> spilled;
1137 // The earliest start of a Spilled interval indicates up to where
1138 // in handled we need to roll back
1139 unsigned earliestStart = cur->beginNumber();
1141 // Spill live intervals of virtual regs mapped to the physical register we
1142 // want to clear (and its aliases). We only spill those that overlap with the
1143 // current interval as the rest do not affect its allocation. we also keep
1144 // track of the earliest start of all spilled live intervals since this will
1145 // mark our rollback point.
1146 std::vector<LiveInterval*> added;
1147 while (!spillIs.empty()) {
1148 LiveInterval *sli = spillIs.back();
1149 spillIs.pop_back();
1150 DOUT << "\t\t\tspilling(a): " << *sli << '\n';
1151 earliestStart = std::min(earliestStart, sli->beginNumber());
1152 float SSWeight;
1153 std::vector<LiveInterval*> newIs =
1154 li_->addIntervalsForSpills(*sli, spillIs, loopInfo, *vrm_, SSWeight);
1155 addStackInterval(sli, ls_, li_, SSWeight, *vrm_);
1156 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
1157 spilled.insert(sli->reg);
1160 DOUT << "\t\trolling back to: " << earliestStart << '\n';
1162 // Scan handled in reverse order up to the earliest start of a
1163 // spilled live interval and undo each one, restoring the state of
1164 // unhandled.
1165 while (!handled_.empty()) {
1166 LiveInterval* i = handled_.back();
1167 // If this interval starts before t we are done.
1168 if (i->beginNumber() < earliestStart)
1169 break;
1170 DOUT << "\t\t\tundo changes for: " << *i << '\n';
1171 handled_.pop_back();
1173 // When undoing a live interval allocation we must know if it is active or
1174 // inactive to properly update regUse_ and the VirtRegMap.
1175 IntervalPtrs::iterator it;
1176 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
1177 active_.erase(it);
1178 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
1179 if (!spilled.count(i->reg))
1180 unhandled_.push(i);
1181 delRegUse(vrm_->getPhys(i->reg));
1182 vrm_->clearVirt(i->reg);
1183 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
1184 inactive_.erase(it);
1185 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
1186 if (!spilled.count(i->reg))
1187 unhandled_.push(i);
1188 vrm_->clearVirt(i->reg);
1189 } else {
1190 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
1191 "Can only allocate virtual registers!");
1192 vrm_->clearVirt(i->reg);
1193 unhandled_.push(i);
1196 DenseMap<unsigned, unsigned>::iterator ii = DowngradeMap.find(i->reg);
1197 if (ii == DowngradeMap.end())
1198 // It interval has a preference, it must be defined by a copy. Clear the
1199 // preference now since the source interval allocation may have been
1200 // undone as well.
1201 i->preference = 0;
1202 else {
1203 UpgradeRegister(ii->second);
1207 // Rewind the iterators in the active, inactive, and fixed lists back to the
1208 // point we reverted to.
1209 RevertVectorIteratorsTo(active_, earliestStart);
1210 RevertVectorIteratorsTo(inactive_, earliestStart);
1211 RevertVectorIteratorsTo(fixed_, earliestStart);
1213 // Scan the rest and undo each interval that expired after t and
1214 // insert it in active (the next iteration of the algorithm will
1215 // put it in inactive if required)
1216 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
1217 LiveInterval *HI = handled_[i];
1218 if (!HI->expiredAt(earliestStart) &&
1219 HI->expiredAt(cur->beginNumber())) {
1220 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
1221 active_.push_back(std::make_pair(HI, HI->begin()));
1222 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
1223 addRegUse(vrm_->getPhys(HI->reg));
1227 // Merge added with unhandled.
1228 // This also update the NextReloadMap. That is, it adds mapping from a
1229 // register defined by a reload from SS to the next reload from SS in the
1230 // same basic block.
1231 MachineBasicBlock *LastReloadMBB = 0;
1232 LiveInterval *LastReload = 0;
1233 int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1234 std::sort(added.begin(), added.end(), LISorter());
1235 for (unsigned i = 0, e = added.size(); i != e; ++i) {
1236 LiveInterval *ReloadLi = added[i];
1237 if (ReloadLi->weight == HUGE_VALF &&
1238 li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1239 unsigned ReloadIdx = ReloadLi->beginNumber();
1240 MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1241 int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1242 if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1243 // Last reload of same SS is in the same MBB. We want to try to
1244 // allocate both reloads the same register and make sure the reg
1245 // isn't clobbered in between if at all possible.
1246 assert(LastReload->beginNumber() < ReloadIdx);
1247 NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1249 LastReloadMBB = ReloadMBB;
1250 LastReload = ReloadLi;
1251 LastReloadSS = ReloadSS;
1253 unhandled_.push(ReloadLi);
1257 unsigned RALinScan::getFreePhysReg(const TargetRegisterClass *RC,
1258 unsigned MaxInactiveCount,
1259 SmallVector<unsigned, 256> &inactiveCounts,
1260 bool SkipDGRegs) {
1261 unsigned FreeReg = 0;
1262 unsigned FreeRegInactiveCount = 0;
1264 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
1265 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
1266 assert(I != E && "No allocatable register in this register class!");
1268 // Scan for the first available register.
1269 for (; I != E; ++I) {
1270 unsigned Reg = *I;
1271 // Ignore "downgraded" registers.
1272 if (SkipDGRegs && DowngradedRegs.count(Reg))
1273 continue;
1274 if (isRegAvail(Reg)) {
1275 FreeReg = Reg;
1276 if (FreeReg < inactiveCounts.size())
1277 FreeRegInactiveCount = inactiveCounts[FreeReg];
1278 else
1279 FreeRegInactiveCount = 0;
1280 break;
1284 // If there are no free regs, or if this reg has the max inactive count,
1285 // return this register.
1286 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount)
1287 return FreeReg;
1289 // Continue scanning the registers, looking for the one with the highest
1290 // inactive count. Alkis found that this reduced register pressure very
1291 // slightly on X86 (in rev 1.94 of this file), though this should probably be
1292 // reevaluated now.
1293 for (; I != E; ++I) {
1294 unsigned Reg = *I;
1295 // Ignore "downgraded" registers.
1296 if (SkipDGRegs && DowngradedRegs.count(Reg))
1297 continue;
1298 if (isRegAvail(Reg) && Reg < inactiveCounts.size() &&
1299 FreeRegInactiveCount < inactiveCounts[Reg]) {
1300 FreeReg = Reg;
1301 FreeRegInactiveCount = inactiveCounts[Reg];
1302 if (FreeRegInactiveCount == MaxInactiveCount)
1303 break; // We found the one with the max inactive count.
1307 return FreeReg;
1310 /// getFreePhysReg - return a free physical register for this virtual register
1311 /// interval if we have one, otherwise return 0.
1312 unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
1313 SmallVector<unsigned, 256> inactiveCounts;
1314 unsigned MaxInactiveCount = 0;
1316 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
1317 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1319 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1320 i != e; ++i) {
1321 unsigned reg = i->first->reg;
1322 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
1323 "Can only allocate virtual registers!");
1325 // If this is not in a related reg class to the register we're allocating,
1326 // don't check it.
1327 const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
1328 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1329 reg = vrm_->getPhys(reg);
1330 if (inactiveCounts.size() <= reg)
1331 inactiveCounts.resize(reg+1);
1332 ++inactiveCounts[reg];
1333 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1337 // If copy coalescer has assigned a "preferred" register, check if it's
1338 // available first.
1339 if (cur->preference) {
1340 DOUT << "(preferred: " << tri_->getName(cur->preference) << ") ";
1341 if (isRegAvail(cur->preference) &&
1342 RC->contains(cur->preference))
1343 return cur->preference;
1346 if (!DowngradedRegs.empty()) {
1347 unsigned FreeReg = getFreePhysReg(RC, MaxInactiveCount, inactiveCounts,
1348 true);
1349 if (FreeReg)
1350 return FreeReg;
1352 return getFreePhysReg(RC, MaxInactiveCount, inactiveCounts, false);
1355 FunctionPass* llvm::createLinearScanRegisterAllocator() {
1356 return new RALinScan();