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");
47 NewHeuristic("new-spilling-heuristic",
48 cl::desc("Use new spilling heuristic"),
49 cl::init(false), cl::Hidden);
51 static RegisterRegAlloc
52 linearscanRegAlloc("linearscan", " linear scan register allocator",
53 createLinearScanRegisterAllocator);
56 struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
58 RALinScan() : MachineFunctionPass(&ID) {}
60 typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
61 typedef SmallVector<IntervalPtr, 32> IntervalPtrs;
63 /// RelatedRegClasses - This structure is built the first time a function is
64 /// compiled, and keeps track of which register classes have registers that
65 /// belong to multiple classes or have aliases that are in other classes.
66 EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
67 DenseMap<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
70 MachineRegisterInfo* mri_;
71 const TargetMachine* tm_;
72 const TargetRegisterInfo* tri_;
73 const TargetInstrInfo* tii_;
74 BitVector allocatableRegs_;
77 const MachineLoopInfo *loopInfo;
79 /// handled_ - Intervals are added to the handled_ set in the order of their
80 /// start value. This is uses for backtracking.
81 std::vector<LiveInterval*> handled_;
83 /// fixed_ - Intervals that correspond to machine registers.
87 /// active_ - Intervals that are currently being processed, and which have a
88 /// live range active for the current point.
91 /// inactive_ - Intervals that are currently being processed, but which have
92 /// a hold at the current point.
93 IntervalPtrs inactive_;
95 typedef std::priority_queue<LiveInterval*,
96 SmallVector<LiveInterval*, 64>,
97 greater_ptr<LiveInterval> > IntervalHeap;
98 IntervalHeap unhandled_;
99 std::auto_ptr<PhysRegTracker> prt_;
100 std::auto_ptr<VirtRegMap> vrm_;
101 std::auto_ptr<Spiller> spiller_;
104 virtual const char* getPassName() const {
105 return "Linear Scan Register Allocator";
108 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
109 AU.addRequired<LiveIntervals>();
110 // Make sure PassManager knows which analyses to make available
111 // to coalescing and which analyses coalescing invalidates.
112 AU.addRequiredTransitive<RegisterCoalescer>();
113 AU.addRequired<LiveStacks>();
114 AU.addPreserved<LiveStacks>();
115 AU.addRequired<MachineLoopInfo>();
116 AU.addPreserved<MachineLoopInfo>();
117 AU.addPreservedID(MachineDominatorsID);
118 MachineFunctionPass::getAnalysisUsage(AU);
121 /// runOnMachineFunction - register allocate the whole function
122 bool runOnMachineFunction(MachineFunction&);
125 /// linearScan - the linear scan algorithm
128 /// initIntervalSets - initialize the interval sets.
130 void initIntervalSets();
132 /// processActiveIntervals - expire old intervals and move non-overlapping
133 /// ones to the inactive list.
134 void processActiveIntervals(unsigned CurPoint);
136 /// processInactiveIntervals - expire old intervals and move overlapping
137 /// ones to the active list.
138 void processInactiveIntervals(unsigned CurPoint);
140 /// assignRegOrStackSlotAtInterval - assign a register if one
141 /// is available, or spill.
142 void assignRegOrStackSlotAtInterval(LiveInterval* cur);
144 /// findIntervalsToSpill - Determine the intervals to spill for the
145 /// specified interval. It's passed the physical registers whose spill
146 /// weight is the lowest among all the registers whose live intervals
147 /// conflict with the interval.
148 void findIntervalsToSpill(LiveInterval *cur,
149 std::vector<std::pair<unsigned,float> > &Candidates,
151 SmallVector<LiveInterval*, 8> &SpillIntervals);
153 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
154 /// try allocate the definition the same register as the source register
155 /// if the register is not defined during live time of the interval. This
156 /// eliminate a copy. This is used to coalesce copies which were not
157 /// coalesced away before allocation either due to dest and src being in
158 /// different register classes or because the coalescer was overly
160 unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
163 /// register handling helpers
166 /// getFreePhysReg - return a free physical register for this virtual
167 /// register interval if we have one, otherwise return 0.
168 unsigned getFreePhysReg(LiveInterval* cur);
170 /// assignVirt2StackSlot - assigns this virtual register to a
171 /// stack slot. returns the stack slot
172 int assignVirt2StackSlot(unsigned virtReg);
174 void ComputeRelatedRegClasses();
176 bool noEarlyClobberConflict(LiveInterval *cur, unsigned RegNo);
177 unsigned findPhysReg(MachineOperand &MO);
179 template <typename ItTy>
180 void printIntervals(const char* const str, ItTy i, ItTy e) const {
181 if (str) DOUT << str << " intervals:\n";
182 for (; i != e; ++i) {
183 DOUT << "\t" << *i->first << " -> ";
184 unsigned reg = i->first->reg;
185 if (TargetRegisterInfo::isVirtualRegister(reg)) {
186 reg = vrm_->getPhys(reg);
188 DOUT << tri_->getName(reg) << '\n';
192 char RALinScan::ID = 0;
195 static RegisterPass<RALinScan>
196 X("linearscan-regalloc", "Linear Scan Register Allocator");
198 void RALinScan::ComputeRelatedRegClasses() {
199 const TargetRegisterInfo &TRI = *tri_;
201 // First pass, add all reg classes to the union, and determine at least one
202 // reg class that each register is in.
203 bool HasAliases = false;
204 for (TargetRegisterInfo::regclass_iterator RCI = TRI.regclass_begin(),
205 E = TRI.regclass_end(); RCI != E; ++RCI) {
206 RelatedRegClasses.insert(*RCI);
207 for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
209 HasAliases = HasAliases || *TRI.getAliasSet(*I) != 0;
211 const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
213 // Already processed this register. Just make sure we know that
214 // multiple register classes share a register.
215 RelatedRegClasses.unionSets(PRC, *RCI);
222 // Second pass, now that we know conservatively what register classes each reg
223 // belongs to, add info about aliases. We don't need to do this for targets
224 // without register aliases.
226 for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
227 I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
229 for (const unsigned *AS = TRI.getAliasSet(I->first); *AS; ++AS)
230 RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
233 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
234 /// try allocate the definition the same register as the source register
235 /// if the register is not defined during live time of the interval. This
236 /// eliminate a copy. This is used to coalesce copies which were not
237 /// coalesced away before allocation either due to dest and src being in
238 /// different register classes or because the coalescer was overly
240 unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
241 if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
244 VNInfo *vni = cur.getValNumInfo(0);
245 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
247 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
248 unsigned SrcReg, DstReg;
249 if (!CopyMI || !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg))
251 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
252 if (!vrm_->isAssignedReg(SrcReg))
255 SrcReg = vrm_->getPhys(SrcReg);
260 const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
261 if (!RC->contains(SrcReg))
265 if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
266 DOUT << "Coalescing: " << cur << " -> " << tri_->getName(SrcReg)
268 vrm_->clearVirt(cur.reg);
269 vrm_->assignVirt2Phys(cur.reg, SrcReg);
277 bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
279 mri_ = &fn.getRegInfo();
280 tm_ = &fn.getTarget();
281 tri_ = tm_->getRegisterInfo();
282 tii_ = tm_->getInstrInfo();
283 allocatableRegs_ = tri_->getAllocatableSet(fn);
284 li_ = &getAnalysis<LiveIntervals>();
285 ls_ = &getAnalysis<LiveStacks>();
286 loopInfo = &getAnalysis<MachineLoopInfo>();
288 // We don't run the coalescer here because we have no reason to
289 // interact with it. If the coalescer requires interaction, it
290 // won't do anything. If it doesn't require interaction, we assume
291 // it was run as a separate pass.
293 // If this is the first function compiled, compute the related reg classes.
294 if (RelatedRegClasses.empty())
295 ComputeRelatedRegClasses();
297 if (!prt_.get()) prt_.reset(new PhysRegTracker(*tri_));
298 vrm_.reset(new VirtRegMap(*mf_));
299 if (!spiller_.get()) spiller_.reset(createSpiller());
305 // Rewrite spill code and update the PhysRegsUsed set.
306 spiller_->runOnMachineFunction(*mf_, *vrm_);
307 vrm_.reset(); // Free the VirtRegMap
309 assert(unhandled_.empty() && "Unhandled live intervals remain!");
318 /// initIntervalSets - initialize the interval sets.
320 void RALinScan::initIntervalSets()
322 assert(unhandled_.empty() && fixed_.empty() &&
323 active_.empty() && inactive_.empty() &&
324 "interval sets should be empty on initialization");
326 handled_.reserve(li_->getNumIntervals());
328 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
329 if (TargetRegisterInfo::isPhysicalRegister(i->second->reg)) {
330 mri_->setPhysRegUsed(i->second->reg);
331 fixed_.push_back(std::make_pair(i->second, i->second->begin()));
333 unhandled_.push(i->second);
337 void RALinScan::linearScan()
339 // linear scan algorithm
340 DOUT << "********** LINEAR SCAN **********\n";
341 DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
343 DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
345 while (!unhandled_.empty()) {
346 // pick the interval with the earliest start point
347 LiveInterval* cur = unhandled_.top();
350 DOUT << "\n*** CURRENT ***: " << *cur << '\n';
353 processActiveIntervals(cur->beginNumber());
354 processInactiveIntervals(cur->beginNumber());
356 assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
357 "Can only allocate virtual registers!");
360 // Allocating a virtual register. try to find a free
361 // physical register or spill an interval (possibly this one) in order to
363 assignRegOrStackSlotAtInterval(cur);
365 DEBUG(printIntervals("active", active_.begin(), active_.end()));
366 DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
369 // expire any remaining active intervals
370 while (!active_.empty()) {
371 IntervalPtr &IP = active_.back();
372 unsigned reg = IP.first->reg;
373 DOUT << "\tinterval " << *IP.first << " expired\n";
374 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
375 "Can only allocate virtual registers!");
376 reg = vrm_->getPhys(reg);
377 prt_->delRegUse(reg);
381 // expire any remaining inactive intervals
382 DEBUG(for (IntervalPtrs::reverse_iterator
383 i = inactive_.rbegin(); i != inactive_.rend(); ++i)
384 DOUT << "\tinterval " << *i->first << " expired\n");
387 // Add live-ins to every BB except for entry. Also perform trivial coalescing.
388 MachineFunction::iterator EntryMBB = mf_->begin();
389 SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
390 for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
391 LiveInterval &cur = *i->second;
393 bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
396 else if (vrm_->isAssignedReg(cur.reg))
397 Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
400 // Ignore splited live intervals.
401 if (!isPhys && vrm_->getPreSplitReg(cur.reg))
403 for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
405 const LiveRange &LR = *I;
406 if (li_->findLiveInMBBs(LR, LiveInMBBs)) {
407 for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
408 if (LiveInMBBs[i] != EntryMBB)
409 LiveInMBBs[i]->addLiveIn(Reg);
418 /// processActiveIntervals - expire old intervals and move non-overlapping ones
419 /// to the inactive list.
420 void RALinScan::processActiveIntervals(unsigned CurPoint)
422 DOUT << "\tprocessing active intervals:\n";
424 for (unsigned i = 0, e = active_.size(); i != e; ++i) {
425 LiveInterval *Interval = active_[i].first;
426 LiveInterval::iterator IntervalPos = active_[i].second;
427 unsigned reg = Interval->reg;
429 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
431 if (IntervalPos == Interval->end()) { // Remove expired intervals.
432 DOUT << "\t\tinterval " << *Interval << " expired\n";
433 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
434 "Can only allocate virtual registers!");
435 reg = vrm_->getPhys(reg);
436 prt_->delRegUse(reg);
438 // Pop off the end of the list.
439 active_[i] = active_.back();
443 } else if (IntervalPos->start > CurPoint) {
444 // Move inactive intervals to inactive list.
445 DOUT << "\t\tinterval " << *Interval << " inactive\n";
446 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
447 "Can only allocate virtual registers!");
448 reg = vrm_->getPhys(reg);
449 prt_->delRegUse(reg);
451 inactive_.push_back(std::make_pair(Interval, IntervalPos));
453 // Pop off the end of the list.
454 active_[i] = active_.back();
458 // Otherwise, just update the iterator position.
459 active_[i].second = IntervalPos;
464 /// processInactiveIntervals - expire old intervals and move overlapping
465 /// ones to the active list.
466 void RALinScan::processInactiveIntervals(unsigned CurPoint)
468 DOUT << "\tprocessing inactive intervals:\n";
470 for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
471 LiveInterval *Interval = inactive_[i].first;
472 LiveInterval::iterator IntervalPos = inactive_[i].second;
473 unsigned reg = Interval->reg;
475 IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
477 if (IntervalPos == Interval->end()) { // remove expired intervals.
478 DOUT << "\t\tinterval " << *Interval << " expired\n";
480 // Pop off the end of the list.
481 inactive_[i] = inactive_.back();
482 inactive_.pop_back();
484 } else if (IntervalPos->start <= CurPoint) {
485 // move re-activated intervals in active list
486 DOUT << "\t\tinterval " << *Interval << " active\n";
487 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
488 "Can only allocate virtual registers!");
489 reg = vrm_->getPhys(reg);
490 prt_->addRegUse(reg);
492 active_.push_back(std::make_pair(Interval, IntervalPos));
494 // Pop off the end of the list.
495 inactive_[i] = inactive_.back();
496 inactive_.pop_back();
499 // Otherwise, just update the iterator position.
500 inactive_[i].second = IntervalPos;
505 /// updateSpillWeights - updates the spill weights of the specifed physical
506 /// register and its weight.
507 static void updateSpillWeights(std::vector<float> &Weights,
508 unsigned reg, float weight,
509 const TargetRegisterInfo *TRI) {
510 Weights[reg] += weight;
511 for (const unsigned* as = TRI->getAliasSet(reg); *as; ++as)
512 Weights[*as] += weight;
516 RALinScan::IntervalPtrs::iterator
517 FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
518 for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
520 if (I->first == LI) return I;
524 static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
525 for (unsigned i = 0, e = V.size(); i != e; ++i) {
526 RALinScan::IntervalPtr &IP = V[i];
527 LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
529 if (I != IP.first->begin()) --I;
534 /// addStackInterval - Create a LiveInterval for stack if the specified live
535 /// interval has been spilled.
536 static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
537 LiveIntervals *li_, float &Weight,
539 int SS = vrm_.getStackSlot(cur->reg);
540 if (SS == VirtRegMap::NO_STACK_SLOT)
542 LiveInterval &SI = ls_->getOrCreateInterval(SS);
546 if (SI.getNumValNums())
547 VNI = SI.getValNumInfo(0);
549 VNI = SI.getNextValue(~0U, 0, ls_->getVNInfoAllocator());
551 LiveInterval &RI = li_->getInterval(cur->reg);
552 // FIXME: This may be overly conservative.
553 SI.MergeRangesInAsValue(RI, VNI);
556 /// getConflictWeight - Return the number of conflicts between cur
557 /// live interval and defs and uses of Reg weighted by loop depthes.
558 static float getConflictWeight(LiveInterval *cur, unsigned Reg,
560 MachineRegisterInfo *mri_,
561 const MachineLoopInfo *loopInfo) {
563 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
564 E = mri_->reg_end(); I != E; ++I) {
565 MachineInstr *MI = &*I;
566 if (cur->liveAt(li_->getInstructionIndex(MI))) {
567 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
568 Conflicts += powf(10.0f, (float)loopDepth);
574 /// findIntervalsToSpill - Determine the intervals to spill for the
575 /// specified interval. It's passed the physical registers whose spill
576 /// weight is the lowest among all the registers whose live intervals
577 /// conflict with the interval.
578 void RALinScan::findIntervalsToSpill(LiveInterval *cur,
579 std::vector<std::pair<unsigned,float> > &Candidates,
581 SmallVector<LiveInterval*, 8> &SpillIntervals) {
582 // We have figured out the *best* register to spill. But there are other
583 // registers that are pretty good as well (spill weight within 3%). Spill
584 // the one that has fewest defs and uses that conflict with cur.
585 float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
586 SmallVector<LiveInterval*, 8> SLIs[3];
588 DOUT << "\tConsidering " << NumCands << " candidates: ";
589 DEBUG(for (unsigned i = 0; i != NumCands; ++i)
590 DOUT << tri_->getName(Candidates[i].first) << " ";
593 // Calculate the number of conflicts of each candidate.
594 for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
595 unsigned Reg = i->first->reg;
596 unsigned PhysReg = vrm_->getPhys(Reg);
597 if (!cur->overlapsFrom(*i->first, i->second))
599 for (unsigned j = 0; j < NumCands; ++j) {
600 unsigned Candidate = Candidates[j].first;
601 if (tri_->regsOverlap(PhysReg, Candidate)) {
603 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
604 SLIs[j].push_back(i->first);
609 for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
610 unsigned Reg = i->first->reg;
611 unsigned PhysReg = vrm_->getPhys(Reg);
612 if (!cur->overlapsFrom(*i->first, i->second-1))
614 for (unsigned j = 0; j < NumCands; ++j) {
615 unsigned Candidate = Candidates[j].first;
616 if (tri_->regsOverlap(PhysReg, Candidate)) {
618 Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
619 SLIs[j].push_back(i->first);
624 // Which is the best candidate?
625 unsigned BestCandidate = 0;
626 float MinConflicts = Conflicts[0];
627 for (unsigned i = 1; i != NumCands; ++i) {
628 if (Conflicts[i] < MinConflicts) {
630 MinConflicts = Conflicts[i];
634 std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
635 std::back_inserter(SpillIntervals));
639 struct WeightCompare {
640 typedef std::pair<unsigned, float> RegWeightPair;
641 bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
642 return LHS.second < RHS.second;
647 static bool weightsAreClose(float w1, float w2) {
651 float diff = w1 - w2;
652 if (diff <= 0.02f) // Within 0.02f
654 return (diff / w2) <= 0.05f; // Within 5%.
657 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
659 void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
661 DOUT << "\tallocating current interval: ";
663 // This is an implicitly defined live interval, just assign any register.
664 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
666 unsigned physReg = cur->preference;
668 physReg = *RC->allocation_order_begin(*mf_);
669 DOUT << tri_->getName(physReg) << '\n';
670 // Note the register is not really in use.
671 vrm_->assignVirt2Phys(cur->reg, physReg);
675 PhysRegTracker backupPrt = *prt_;
677 std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
678 unsigned StartPosition = cur->beginNumber();
679 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
681 // If this live interval is defined by a move instruction and its source is
682 // assigned a physical register that is compatible with the target register
683 // class, then we should try to assign it the same register.
684 // This can happen when the move is from a larger register class to a smaller
685 // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
686 if (!cur->preference && cur->containsOneValue()) {
687 VNInfo *vni = cur->getValNumInfo(0);
688 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
689 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
690 unsigned SrcReg, DstReg;
691 if (CopyMI && tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
693 if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
695 else if (vrm_->isAssignedReg(SrcReg))
696 Reg = vrm_->getPhys(SrcReg);
697 if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
698 cur->preference = Reg;
703 // for every interval in inactive we overlap with, mark the
704 // register as not free and update spill weights.
705 for (IntervalPtrs::const_iterator i = inactive_.begin(),
706 e = inactive_.end(); i != e; ++i) {
707 unsigned Reg = i->first->reg;
708 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
709 "Can only allocate virtual registers!");
710 const TargetRegisterClass *RegRC = mri_->getRegClass(Reg);
711 // If this is not in a related reg class to the register we're allocating,
713 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
714 cur->overlapsFrom(*i->first, i->second-1)) {
715 Reg = vrm_->getPhys(Reg);
716 prt_->addRegUse(Reg);
717 SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
721 // Speculatively check to see if we can get a register right now. If not,
722 // we know we won't be able to by adding more constraints. If so, we can
723 // check to see if it is valid. Doing an exhaustive search of the fixed_ list
724 // is very bad (it contains all callee clobbered registers for any functions
725 // with a call), so we want to avoid doing that if possible.
726 unsigned physReg = getFreePhysReg(cur);
727 unsigned BestPhysReg = physReg;
729 // We got a register. However, if it's in the fixed_ list, we might
730 // conflict with it. Check to see if we conflict with it or any of its
732 SmallSet<unsigned, 8> RegAliases;
733 for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
734 RegAliases.insert(*AS);
736 bool ConflictsWithFixed = false;
737 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
738 IntervalPtr &IP = fixed_[i];
739 if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
740 // Okay, this reg is on the fixed list. Check to see if we actually
742 LiveInterval *I = IP.first;
743 if (I->endNumber() > StartPosition) {
744 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
746 if (II != I->begin() && II->start > StartPosition)
748 if (cur->overlapsFrom(*I, II)) {
749 ConflictsWithFixed = true;
756 // Okay, the register picked by our speculative getFreePhysReg call turned
757 // out to be in use. Actually add all of the conflicting fixed registers to
758 // prt so we can do an accurate query.
759 if (ConflictsWithFixed) {
760 // For every interval in fixed we overlap with, mark the register as not
761 // free and update spill weights.
762 for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
763 IntervalPtr &IP = fixed_[i];
764 LiveInterval *I = IP.first;
766 const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
767 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
768 I->endNumber() > StartPosition) {
769 LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
771 if (II != I->begin() && II->start > StartPosition)
773 if (cur->overlapsFrom(*I, II)) {
774 unsigned reg = I->reg;
775 prt_->addRegUse(reg);
776 SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
781 // Using the newly updated prt_ object, which includes conflicts in the
782 // future, see if there are any registers available.
783 physReg = getFreePhysReg(cur);
787 // Restore the physical register tracker, removing information about the
791 // if we find a free register, we are done: assign this virtual to
792 // the free physical register and add this interval to the active
795 DOUT << tri_->getName(physReg) << '\n';
796 vrm_->assignVirt2Phys(cur->reg, physReg);
797 prt_->addRegUse(physReg);
798 active_.push_back(std::make_pair(cur, cur->begin()));
799 handled_.push_back(cur);
802 DOUT << "no free registers\n";
804 // Compile the spill weights into an array that is better for scanning.
805 std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
806 for (std::vector<std::pair<unsigned, float> >::iterator
807 I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
808 updateSpillWeights(SpillWeights, I->first, I->second, tri_);
810 // for each interval in active, update spill weights.
811 for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
813 unsigned reg = i->first->reg;
814 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
815 "Can only allocate virtual registers!");
816 reg = vrm_->getPhys(reg);
817 updateSpillWeights(SpillWeights, reg, i->first->weight, tri_);
820 DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
822 // Find a register to spill.
823 float minWeight = HUGE_VALF;
824 unsigned minReg = 0; /*cur->preference*/; // Try the preferred register first.
827 std::vector<std::pair<unsigned,float> > RegsWeights;
828 if (!minReg || SpillWeights[minReg] == HUGE_VALF)
829 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
830 e = RC->allocation_order_end(*mf_); i != e; ++i) {
832 float regWeight = SpillWeights[reg];
833 if (minWeight > regWeight)
835 RegsWeights.push_back(std::make_pair(reg, regWeight));
838 // If we didn't find a register that is spillable, try aliases?
840 for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
841 e = RC->allocation_order_end(*mf_); i != e; ++i) {
843 // No need to worry about if the alias register size < regsize of RC.
844 // We are going to spill all registers that alias it anyway.
845 for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
846 RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
850 // Sort all potential spill candidates by weight.
851 std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare());
852 minReg = RegsWeights[0].first;
853 minWeight = RegsWeights[0].second;
854 if (minWeight == HUGE_VALF) {
855 // All registers must have inf weight. Just grab one!
856 minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
857 if (cur->weight == HUGE_VALF ||
858 li_->getApproximateInstructionCount(*cur) == 0) {
859 // Spill a physical register around defs and uses.
860 li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_);
861 assignRegOrStackSlotAtInterval(cur);
866 // Find up to 3 registers to consider as spill candidates.
867 unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
868 while (LastCandidate > 1) {
869 if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
874 DOUT << "\t\tregister(s) with min weight(s): ";
875 DEBUG(for (unsigned i = 0; i != LastCandidate; ++i)
876 DOUT << tri_->getName(RegsWeights[i].first)
877 << " (" << RegsWeights[i].second << ")\n");
879 // if the current has the minimum weight, we need to spill it and
880 // add any added intervals back to unhandled, and restart
882 if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
883 DOUT << "\t\t\tspilling(c): " << *cur << '\n';
885 std::vector<LiveInterval*> added =
886 li_->addIntervalsForSpills(*cur, loopInfo, *vrm_, SSWeight);
887 addStackInterval(cur, ls_, li_, SSWeight, *vrm_);
889 return; // Early exit if all spills were folded.
891 // Merge added with unhandled. Note that we know that
892 // addIntervalsForSpills returns intervals sorted by their starting
894 for (unsigned i = 0, e = added.size(); i != e; ++i)
895 unhandled_.push(added[i]);
901 // push the current interval back to unhandled since we are going
902 // to re-run at least this iteration. Since we didn't modify it it
903 // should go back right in the front of the list
904 unhandled_.push(cur);
906 assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
907 "did not choose a register to spill?");
909 // We spill all intervals aliasing the register with
910 // minimum weight, rollback to the interval with the earliest
911 // start point and let the linear scan algorithm run again
912 SmallVector<LiveInterval*, 8> spillIs;
914 // Determine which intervals have to be spilled.
915 findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
917 // Set of spilled vregs (used later to rollback properly)
918 SmallSet<unsigned, 8> spilled;
920 // The earliest start of a Spilled interval indicates up to where
921 // in handled we need to roll back
922 unsigned earliestStart = cur->beginNumber();
924 // Spill live intervals of virtual regs mapped to the physical register we
925 // want to clear (and its aliases). We only spill those that overlap with the
926 // current interval as the rest do not affect its allocation. we also keep
927 // track of the earliest start of all spilled live intervals since this will
928 // mark our rollback point.
929 std::vector<LiveInterval*> added;
930 while (!spillIs.empty()) {
931 LiveInterval *sli = spillIs.back();
933 DOUT << "\t\t\tspilling(a): " << *sli << '\n';
934 earliestStart = std::min(earliestStart, sli->beginNumber());
936 std::vector<LiveInterval*> newIs =
937 li_->addIntervalsForSpills(*sli, loopInfo, *vrm_, SSWeight);
938 addStackInterval(sli, ls_, li_, SSWeight, *vrm_);
939 std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
940 spilled.insert(sli->reg);
943 DOUT << "\t\trolling back to: " << earliestStart << '\n';
945 // Scan handled in reverse order up to the earliest start of a
946 // spilled live interval and undo each one, restoring the state of
948 while (!handled_.empty()) {
949 LiveInterval* i = handled_.back();
950 // If this interval starts before t we are done.
951 if (i->beginNumber() < earliestStart)
953 DOUT << "\t\t\tundo changes for: " << *i << '\n';
956 // When undoing a live interval allocation we must know if it is active or
957 // inactive to properly update the PhysRegTracker and the VirtRegMap.
958 IntervalPtrs::iterator it;
959 if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
961 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
962 if (!spilled.count(i->reg))
964 prt_->delRegUse(vrm_->getPhys(i->reg));
965 vrm_->clearVirt(i->reg);
966 } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
968 assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
969 if (!spilled.count(i->reg))
971 vrm_->clearVirt(i->reg);
973 assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
974 "Can only allocate virtual registers!");
975 vrm_->clearVirt(i->reg);
979 // It interval has a preference, it must be defined by a copy. Clear the
980 // preference now since the source interval allocation may have been undone
985 // Rewind the iterators in the active, inactive, and fixed lists back to the
986 // point we reverted to.
987 RevertVectorIteratorsTo(active_, earliestStart);
988 RevertVectorIteratorsTo(inactive_, earliestStart);
989 RevertVectorIteratorsTo(fixed_, earliestStart);
991 // scan the rest and undo each interval that expired after t and
992 // insert it in active (the next iteration of the algorithm will
993 // put it in inactive if required)
994 for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
995 LiveInterval *HI = handled_[i];
996 if (!HI->expiredAt(earliestStart) &&
997 HI->expiredAt(cur->beginNumber())) {
998 DOUT << "\t\t\tundo changes for: " << *HI << '\n';
999 active_.push_back(std::make_pair(HI, HI->begin()));
1000 assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
1001 prt_->addRegUse(vrm_->getPhys(HI->reg));
1005 // merge added with unhandled
1006 for (unsigned i = 0, e = added.size(); i != e; ++i)
1007 unhandled_.push(added[i]);
1010 /// findPhysReg - get the physical register, if any, assigned to this operand.
1011 /// This may be an original physical register, or the physical register which
1012 /// has been assigned to a virtual register.
1013 unsigned RALinScan::findPhysReg(MachineOperand &MO) {
1014 unsigned PhysReg = MO.getReg();
1015 if (PhysReg && TargetRegisterInfo::isVirtualRegister(PhysReg)) {
1016 if (!vrm_->hasPhys(PhysReg))
1018 PhysReg = vrm_->getPhys(PhysReg);
1023 /// noEarlyClobberConflict - see whether LiveInternal cur has a conflict with
1024 /// hard reg HReg because of earlyclobbers.
1026 /// Earlyclobber operands may not be assigned the same register as
1027 /// each other, or as earlyclobber-conflict operands (i.e. those that
1028 /// are non-earlyclobbered inputs to an asm that also has earlyclobbers).
1030 /// Thus there are two cases to check for:
1031 /// 1. cur->reg is an earlyclobber-conflict register and HReg is an
1032 /// earlyclobber register in some asm that also has cur->reg as an input.
1033 /// 2. cur->reg is an earlyclobber register and HReg is an
1034 /// earlyclobber-conflict input, or a different earlyclobber register,
1035 /// elsewhere in some asm.
1036 /// In both cases HReg can be assigned by the user, or assigned early in
1037 /// register allocation.
1039 /// Dropping the distinction between earlyclobber and earlyclobber-conflict,
1040 /// keeping only one bit, looks promising, but two earlyclobber-conflict
1041 /// operands may be assigned the same register if they happen to contain the
1042 /// same value, and that implementation would prevent this.
1044 bool RALinScan::noEarlyClobberConflict(LiveInterval *cur, unsigned HReg) {
1045 if (cur->overlapsEarlyClobber) {
1046 for (MachineRegisterInfo::use_iterator I = mri_->use_begin(cur->reg),
1047 E = mri_->use_end(); I!=E; ++I) {
1048 MachineInstr *MI = I.getOperand().getParent();
1049 if (MI->getOpcode()==TargetInstrInfo::INLINEASM) {
1050 for (int i = MI->getNumOperands()-1; i>=0; --i) {
1051 MachineOperand &MO = MI->getOperand(i);
1052 if (MO.isRegister() && MO.isEarlyClobber()) {
1053 unsigned PhysReg = findPhysReg(MO);
1054 if (HReg==PhysReg) {
1055 DOUT << " earlyclobber conflict: " <<
1056 "%reg" << cur->reg << ", " << tri_->getName(HReg) << "\n\t";
1064 if (cur->isEarlyClobber) {
1065 for (MachineRegisterInfo::def_iterator I = mri_->def_begin(cur->reg),
1066 E = mri_->def_end(); I!=E; ++I) {
1067 MachineInstr *MI = I.getOperand().getParent();
1068 if (MI->getOpcode()==TargetInstrInfo::INLINEASM) {
1069 // make sure cur->reg is really clobbered in this instruction.
1070 bool earlyClobberFound = false, overlapFound = false;
1071 for (int i = MI->getNumOperands()-1; i>=0; --i) {
1072 MachineOperand &MO = MI->getOperand(i);
1073 if (MO.isRegister()) {
1074 if ((MO.overlapsEarlyClobber() || MO.isEarlyClobber())) {
1075 unsigned PhysReg = findPhysReg(MO);
1077 overlapFound = true;
1079 if (MO.isEarlyClobber() && cur->reg==MO.getReg())
1080 earlyClobberFound = true;
1083 if (earlyClobberFound && overlapFound) {
1084 DOUT << " earlyclobber conflict: " <<
1085 "%reg" << cur->reg << ", " << tri_->getName(HReg) << "\n\t";
1094 /// getFreePhysReg - return a free physical register for this virtual register
1095 /// interval if we have one, otherwise return 0.
1096 unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
1097 SmallVector<unsigned, 256> inactiveCounts;
1098 unsigned MaxInactiveCount = 0;
1100 const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
1101 const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1103 for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1105 unsigned reg = i->first->reg;
1106 assert(TargetRegisterInfo::isVirtualRegister(reg) &&
1107 "Can only allocate virtual registers!");
1109 // If this is not in a related reg class to the register we're allocating,
1111 const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
1112 if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1113 reg = vrm_->getPhys(reg);
1114 if (inactiveCounts.size() <= reg)
1115 inactiveCounts.resize(reg+1);
1116 ++inactiveCounts[reg];
1117 MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1121 unsigned FreeReg = 0;
1122 unsigned FreeRegInactiveCount = 0;
1124 // If copy coalescer has assigned a "preferred" register, check if it's
1125 // available first. Coalescer can create new earlyclobber interferences,
1126 // so we need to check that.
1127 if (cur->preference) {
1128 if (prt_->isRegAvail(cur->preference) &&
1129 RC->contains(cur->preference) &&
1130 noEarlyClobberConflict(cur, cur->preference)) {
1131 DOUT << "\t\tassigned the preferred register: "
1132 << tri_->getName(cur->preference) << "\n";
1133 return cur->preference;
1135 DOUT << "\t\tunable to assign the preferred register: "
1136 << tri_->getName(cur->preference) << "\n";
1139 // Scan for the first available register.
1140 TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
1141 TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
1142 assert(I != E && "No allocatable register in this register class!");
1144 if (prt_->isRegAvail(*I) &&
1145 noEarlyClobberConflict(cur, *I)) {
1147 if (FreeReg < inactiveCounts.size())
1148 FreeRegInactiveCount = inactiveCounts[FreeReg];
1150 FreeRegInactiveCount = 0;
1154 // If there are no free regs, or if this reg has the max inactive count,
1155 // return this register.
1156 if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
1158 // Continue scanning the registers, looking for the one with the highest
1159 // inactive count. Alkis found that this reduced register pressure very
1160 // slightly on X86 (in rev 1.94 of this file), though this should probably be
1162 for (; I != E; ++I) {
1164 if (prt_->isRegAvail(Reg) && Reg < inactiveCounts.size() &&
1165 FreeRegInactiveCount < inactiveCounts[Reg] &&
1166 noEarlyClobberConflict(cur, *I)) {
1168 FreeRegInactiveCount = inactiveCounts[Reg];
1169 if (FreeRegInactiveCount == MaxInactiveCount)
1170 break; // We found the one with the max inactive count.
1177 FunctionPass* llvm::createLinearScanRegisterAllocator() {
1178 return new RALinScan();