Fix batch of converting RegisterPass<> to INTIALIZE_PASS().
[oota-llvm.git] / lib / CodeGen / RegAllocLinearScan.cpp
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.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "regalloc"
15 #include "VirtRegMap.h"
16 #include "VirtRegRewriter.h"
17 #include "Spiller.h"
18 #include "llvm/Function.h"
19 #include "llvm/CodeGen/CalcSpillWeights.h"
20 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
21 #include "llvm/CodeGen/LiveStackAnalysis.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/MachineLoopInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/CodeGen/RegAllocRegistry.h"
28 #include "llvm/CodeGen/RegisterCoalescer.h"
29 #include "llvm/Target/TargetRegisterInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/ADT/EquivalenceClasses.h"
34 #include "llvm/ADT/SmallSet.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include <algorithm>
41 #include <set>
42 #include <queue>
43 #include <memory>
44 #include <cmath>
45
46 using namespace llvm;
47
48 STATISTIC(NumIters     , "Number of iterations performed");
49 STATISTIC(NumBacktracks, "Number of times we had to backtrack");
50 STATISTIC(NumCoalesce,   "Number of copies coalesced");
51 STATISTIC(NumDowngrade,  "Number of registers downgraded");
52
53 static cl::opt<bool>
54 NewHeuristic("new-spilling-heuristic",
55              cl::desc("Use new spilling heuristic"),
56              cl::init(false), cl::Hidden);
57
58 static cl::opt<bool>
59 PreSplitIntervals("pre-alloc-split",
60                   cl::desc("Pre-register allocation live interval splitting"),
61                   cl::init(false), cl::Hidden);
62
63 static cl::opt<bool>
64 TrivCoalesceEnds("trivial-coalesce-ends",
65                   cl::desc("Attempt trivial coalescing of interval ends"),
66                   cl::init(false), cl::Hidden);
67
68 static RegisterRegAlloc
69 linearscanRegAlloc("linearscan", "linear scan register allocator",
70                    createLinearScanRegisterAllocator);
71
72 namespace {
73   // When we allocate a register, add it to a fixed-size queue of
74   // registers to skip in subsequent allocations. This trades a small
75   // amount of register pressure and increased spills for flexibility in
76   // the post-pass scheduler.
77   //
78   // Note that in a the number of registers used for reloading spills
79   // will be one greater than the value of this option.
80   //
81   // One big limitation of this is that it doesn't differentiate between
82   // different register classes. So on x86-64, if there is xmm register
83   // pressure, it can caused fewer GPRs to be held in the queue.
84   static cl::opt<unsigned>
85   NumRecentlyUsedRegs("linearscan-skip-count",
86                       cl::desc("Number of registers for linearscan to remember"
87                                "to skip."),
88                       cl::init(0),
89                       cl::Hidden);
90  
91   struct RALinScan : public MachineFunctionPass {
92     static char ID;
93     RALinScan() : MachineFunctionPass(&ID) {
94       // Initialize the queue to record recently-used registers.
95       if (NumRecentlyUsedRegs > 0)
96         RecentRegs.resize(NumRecentlyUsedRegs, 0);
97       RecentNext = RecentRegs.begin();
98     }
99
100     typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
101     typedef SmallVector<IntervalPtr, 32> IntervalPtrs;
102   private:
103     /// RelatedRegClasses - This structure is built the first time a function is
104     /// compiled, and keeps track of which register classes have registers that
105     /// belong to multiple classes or have aliases that are in other classes.
106     EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
107     DenseMap<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
108
109     // NextReloadMap - For each register in the map, it maps to the another
110     // register which is defined by a reload from the same stack slot and
111     // both reloads are in the same basic block.
112     DenseMap<unsigned, unsigned> NextReloadMap;
113
114     // DowngradedRegs - A set of registers which are being "downgraded", i.e.
115     // un-favored for allocation.
116     SmallSet<unsigned, 8> DowngradedRegs;
117
118     // DowngradeMap - A map from virtual registers to physical registers being
119     // downgraded for the virtual registers.
120     DenseMap<unsigned, unsigned> DowngradeMap;
121
122     MachineFunction* mf_;
123     MachineRegisterInfo* mri_;
124     const TargetMachine* tm_;
125     const TargetRegisterInfo* tri_;
126     const TargetInstrInfo* tii_;
127     BitVector allocatableRegs_;
128     LiveIntervals* li_;
129     LiveStacks* ls_;
130     MachineLoopInfo *loopInfo;
131
132     /// handled_ - Intervals are added to the handled_ set in the order of their
133     /// start value.  This is uses for backtracking.
134     std::vector<LiveInterval*> handled_;
135
136     /// fixed_ - Intervals that correspond to machine registers.
137     ///
138     IntervalPtrs fixed_;
139
140     /// active_ - Intervals that are currently being processed, and which have a
141     /// live range active for the current point.
142     IntervalPtrs active_;
143
144     /// inactive_ - Intervals that are currently being processed, but which have
145     /// a hold at the current point.
146     IntervalPtrs inactive_;
147
148     typedef std::priority_queue<LiveInterval*,
149                                 SmallVector<LiveInterval*, 64>,
150                                 greater_ptr<LiveInterval> > IntervalHeap;
151     IntervalHeap unhandled_;
152
153     /// regUse_ - Tracks register usage.
154     SmallVector<unsigned, 32> regUse_;
155     SmallVector<unsigned, 32> regUseBackUp_;
156
157     /// vrm_ - Tracks register assignments.
158     VirtRegMap* vrm_;
159
160     std::auto_ptr<VirtRegRewriter> rewriter_;
161
162     std::auto_ptr<Spiller> spiller_;
163
164     // The queue of recently-used registers.
165     SmallVector<unsigned, 4> RecentRegs;
166     SmallVector<unsigned, 4>::iterator RecentNext;
167
168     // Record that we just picked this register.
169     void recordRecentlyUsed(unsigned reg) {
170       assert(reg != 0 && "Recently used register is NOREG!");
171       if (!RecentRegs.empty()) {
172         *RecentNext++ = reg;
173         if (RecentNext == RecentRegs.end())
174           RecentNext = RecentRegs.begin();
175       }
176     }
177
178   public:
179     virtual const char* getPassName() const {
180       return "Linear Scan Register Allocator";
181     }
182
183     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
184       AU.setPreservesCFG();
185       AU.addRequired<LiveIntervals>();
186       AU.addPreserved<SlotIndexes>();
187       if (StrongPHIElim)
188         AU.addRequiredID(StrongPHIEliminationID);
189       // Make sure PassManager knows which analyses to make available
190       // to coalescing and which analyses coalescing invalidates.
191       AU.addRequiredTransitive<RegisterCoalescer>();
192       AU.addRequired<CalculateSpillWeights>();
193       if (PreSplitIntervals)
194         AU.addRequiredID(PreAllocSplittingID);
195       AU.addRequired<LiveStacks>();
196       AU.addPreserved<LiveStacks>();
197       AU.addRequired<MachineLoopInfo>();
198       AU.addPreserved<MachineLoopInfo>();
199       AU.addRequired<VirtRegMap>();
200       AU.addPreserved<VirtRegMap>();
201       AU.addPreservedID(MachineDominatorsID);
202       MachineFunctionPass::getAnalysisUsage(AU);
203     }
204
205     /// runOnMachineFunction - register allocate the whole function
206     bool runOnMachineFunction(MachineFunction&);
207
208     // Determine if we skip this register due to its being recently used.
209     bool isRecentlyUsed(unsigned reg) const {
210       return std::find(RecentRegs.begin(), RecentRegs.end(), reg) !=
211              RecentRegs.end();
212     }
213
214   private:
215     /// linearScan - the linear scan algorithm
216     void linearScan();
217
218     /// initIntervalSets - initialize the interval sets.
219     ///
220     void initIntervalSets();
221
222     /// processActiveIntervals - expire old intervals and move non-overlapping
223     /// ones to the inactive list.
224     void processActiveIntervals(SlotIndex CurPoint);
225
226     /// processInactiveIntervals - expire old intervals and move overlapping
227     /// ones to the active list.
228     void processInactiveIntervals(SlotIndex CurPoint);
229
230     /// hasNextReloadInterval - Return the next liveinterval that's being
231     /// defined by a reload from the same SS as the specified one.
232     LiveInterval *hasNextReloadInterval(LiveInterval *cur);
233
234     /// DowngradeRegister - Downgrade a register for allocation.
235     void DowngradeRegister(LiveInterval *li, unsigned Reg);
236
237     /// UpgradeRegister - Upgrade a register for allocation.
238     void UpgradeRegister(unsigned Reg);
239
240     /// assignRegOrStackSlotAtInterval - assign a register if one
241     /// is available, or spill.
242     void assignRegOrStackSlotAtInterval(LiveInterval* cur);
243
244     void updateSpillWeights(std::vector<float> &Weights,
245                             unsigned reg, float weight,
246                             const TargetRegisterClass *RC);
247
248     /// findIntervalsToSpill - Determine the intervals to spill for the
249     /// specified interval. It's passed the physical registers whose spill
250     /// weight is the lowest among all the registers whose live intervals
251     /// conflict with the interval.
252     void findIntervalsToSpill(LiveInterval *cur,
253                             std::vector<std::pair<unsigned,float> > &Candidates,
254                             unsigned NumCands,
255                             SmallVector<LiveInterval*, 8> &SpillIntervals);
256
257     /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
258     /// try allocate the definition the same register as the source register
259     /// if the register is not defined during live time of the interval. This
260     /// eliminate a copy. This is used to coalesce copies which were not
261     /// coalesced away before allocation either due to dest and src being in
262     /// different register classes or because the coalescer was overly
263     /// conservative.
264     unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
265
266     ///
267     /// Register usage / availability tracking helpers.
268     ///
269
270     void initRegUses() {
271       regUse_.resize(tri_->getNumRegs(), 0);
272       regUseBackUp_.resize(tri_->getNumRegs(), 0);
273     }
274
275     void finalizeRegUses() {
276 #ifndef NDEBUG
277       // Verify all the registers are "freed".
278       bool Error = false;
279       for (unsigned i = 0, e = tri_->getNumRegs(); i != e; ++i) {
280         if (regUse_[i] != 0) {
281           dbgs() << tri_->getName(i) << " is still in use!\n";
282           Error = true;
283         }
284       }
285       if (Error)
286         llvm_unreachable(0);
287 #endif
288       regUse_.clear();
289       regUseBackUp_.clear();
290     }
291
292     void addRegUse(unsigned physReg) {
293       assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
294              "should be physical register!");
295       ++regUse_[physReg];
296       for (const unsigned* as = tri_->getAliasSet(physReg); *as; ++as)
297         ++regUse_[*as];
298     }
299
300     void delRegUse(unsigned physReg) {
301       assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
302              "should be physical register!");
303       assert(regUse_[physReg] != 0);
304       --regUse_[physReg];
305       for (const unsigned* as = tri_->getAliasSet(physReg); *as; ++as) {
306         assert(regUse_[*as] != 0);
307         --regUse_[*as];
308       }
309     }
310
311     bool isRegAvail(unsigned physReg) const {
312       assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
313              "should be physical register!");
314       return regUse_[physReg] == 0;
315     }
316
317     void backUpRegUses() {
318       regUseBackUp_ = regUse_;
319     }
320
321     void restoreRegUses() {
322       regUse_ = regUseBackUp_;
323     }
324
325     ///
326     /// Register handling helpers.
327     ///
328
329     /// getFreePhysReg - return a free physical register for this virtual
330     /// register interval if we have one, otherwise return 0.
331     unsigned getFreePhysReg(LiveInterval* cur);
332     unsigned getFreePhysReg(LiveInterval* cur,
333                             const TargetRegisterClass *RC,
334                             unsigned MaxInactiveCount,
335                             SmallVector<unsigned, 256> &inactiveCounts,
336                             bool SkipDGRegs);
337
338     void ComputeRelatedRegClasses();
339
340     template <typename ItTy>
341     void printIntervals(const char* const str, ItTy i, ItTy e) const {
342       DEBUG({
343           if (str)
344             dbgs() << str << " intervals:\n";
345
346           for (; i != e; ++i) {
347             dbgs() << "\t" << *i->first << " -> ";
348
349             unsigned reg = i->first->reg;
350             if (TargetRegisterInfo::isVirtualRegister(reg))
351               reg = vrm_->getPhys(reg);
352
353             dbgs() << tri_->getName(reg) << '\n';
354           }
355         });
356     }
357   };
358   char RALinScan::ID = 0;
359 }
360
361 INITIALIZE_PASS(RALinScan, "linearscan-regalloc",
362                 "Linear Scan Register Allocator", false, false);
363
364 void RALinScan::ComputeRelatedRegClasses() {
365   // First pass, add all reg classes to the union, and determine at least one
366   // reg class that each register is in.
367   bool HasAliases = false;
368   for (TargetRegisterInfo::regclass_iterator RCI = tri_->regclass_begin(),
369        E = tri_->regclass_end(); RCI != E; ++RCI) {
370     RelatedRegClasses.insert(*RCI);
371     for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
372          I != E; ++I) {
373       HasAliases = HasAliases || *tri_->getAliasSet(*I) != 0;
374       
375       const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
376       if (PRC) {
377         // Already processed this register.  Just make sure we know that
378         // multiple register classes share a register.
379         RelatedRegClasses.unionSets(PRC, *RCI);
380       } else {
381         PRC = *RCI;
382       }
383     }
384   }
385   
386   // Second pass, now that we know conservatively what register classes each reg
387   // belongs to, add info about aliases.  We don't need to do this for targets
388   // without register aliases.
389   if (HasAliases)
390     for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
391          I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
392          I != E; ++I)
393       for (const unsigned *AS = tri_->getAliasSet(I->first); *AS; ++AS)
394         RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
395 }
396
397 /// attemptTrivialCoalescing - If a simple interval is defined by a copy, try
398 /// allocate the definition the same register as the source register if the
399 /// register is not defined during live time of the interval. If the interval is
400 /// killed by a copy, try to use the destination register. This eliminates a
401 /// copy. This is used to coalesce copies which were not coalesced away before
402 /// allocation either due to dest and src being in different register classes or
403 /// because the coalescer was overly conservative.
404 unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
405   unsigned Preference = vrm_->getRegAllocPref(cur.reg);
406   if ((Preference && Preference == Reg) || !cur.containsOneValue())
407     return Reg;
408
409   // We cannot handle complicated live ranges. Simple linear stuff only.
410   if (cur.ranges.size() != 1)
411     return Reg;
412
413   const LiveRange &range = cur.ranges.front();
414
415   VNInfo *vni = range.valno;
416   if (vni->isUnused())
417     return Reg;
418
419   unsigned CandReg;
420   {
421     MachineInstr *CopyMI;
422     if (vni->def != SlotIndex() && vni->isDefAccurate() &&
423         (CopyMI = li_->getInstructionFromIndex(vni->def)) && CopyMI->isCopy())
424       // Defined by a copy, try to extend SrcReg forward
425       CandReg = CopyMI->getOperand(1).getReg();
426     else if (TrivCoalesceEnds &&
427             (CopyMI = li_->getInstructionFromIndex(range.end.getBaseIndex())) &&
428              CopyMI->isCopy() && cur.reg == CopyMI->getOperand(1).getReg())
429       // Only used by a copy, try to extend DstReg backwards
430       CandReg = CopyMI->getOperand(0).getReg();
431     else
432       return Reg;
433   }
434
435   if (TargetRegisterInfo::isVirtualRegister(CandReg)) {
436     if (!vrm_->isAssignedReg(CandReg))
437       return Reg;
438     CandReg = vrm_->getPhys(CandReg);
439   }
440   if (Reg == CandReg)
441     return Reg;
442
443   const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
444   if (!RC->contains(CandReg))
445     return Reg;
446
447   if (li_->conflictsWithPhysReg(cur, *vrm_, CandReg))
448     return Reg;
449
450   // Try to coalesce.
451   DEBUG(dbgs() << "Coalescing: " << cur << " -> " << tri_->getName(CandReg)
452         << '\n');
453   vrm_->clearVirt(cur.reg);
454   vrm_->assignVirt2Phys(cur.reg, CandReg);
455
456   ++NumCoalesce;
457   return CandReg;
458 }
459
460 bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
461   mf_ = &fn;
462   mri_ = &fn.getRegInfo();
463   tm_ = &fn.getTarget();
464   tri_ = tm_->getRegisterInfo();
465   tii_ = tm_->getInstrInfo();
466   allocatableRegs_ = tri_->getAllocatableSet(fn);
467   li_ = &getAnalysis<LiveIntervals>();
468   ls_ = &getAnalysis<LiveStacks>();
469   loopInfo = &getAnalysis<MachineLoopInfo>();
470
471   // We don't run the coalescer here because we have no reason to
472   // interact with it.  If the coalescer requires interaction, it
473   // won't do anything.  If it doesn't require interaction, we assume
474   // it was run as a separate pass.
475
476   // If this is the first function compiled, compute the related reg classes.
477   if (RelatedRegClasses.empty())
478     ComputeRelatedRegClasses();
479
480   // Also resize register usage trackers.
481   initRegUses();
482
483   vrm_ = &getAnalysis<VirtRegMap>();
484   if (!rewriter_.get()) rewriter_.reset(createVirtRegRewriter());
485   
486   spiller_.reset(createSpiller(*this, *mf_, *vrm_));
487   
488   initIntervalSets();
489
490   linearScan();
491
492   // Rewrite spill code and update the PhysRegsUsed set.
493   rewriter_->runOnMachineFunction(*mf_, *vrm_, li_);
494
495   assert(unhandled_.empty() && "Unhandled live intervals remain!");
496
497   finalizeRegUses();
498
499   fixed_.clear();
500   active_.clear();
501   inactive_.clear();
502   handled_.clear();
503   NextReloadMap.clear();
504   DowngradedRegs.clear();
505   DowngradeMap.clear();
506   spiller_.reset(0);
507
508   return true;
509 }
510
511 /// initIntervalSets - initialize the interval sets.
512 ///
513 void RALinScan::initIntervalSets()
514 {
515   assert(unhandled_.empty() && fixed_.empty() &&
516          active_.empty() && inactive_.empty() &&
517          "interval sets should be empty on initialization");
518
519   handled_.reserve(li_->getNumIntervals());
520
521   for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
522     if (TargetRegisterInfo::isPhysicalRegister(i->second->reg)) {
523       if (!i->second->empty()) {
524         mri_->setPhysRegUsed(i->second->reg);
525         fixed_.push_back(std::make_pair(i->second, i->second->begin()));
526       }
527     } else {
528       if (i->second->empty()) {
529         assignRegOrStackSlotAtInterval(i->second);
530       }
531       else
532         unhandled_.push(i->second);
533     }
534   }
535 }
536
537 void RALinScan::linearScan() {
538   // linear scan algorithm
539   DEBUG({
540       dbgs() << "********** LINEAR SCAN **********\n"
541              << "********** Function: " 
542              << mf_->getFunction()->getName() << '\n';
543       printIntervals("fixed", fixed_.begin(), fixed_.end());
544     });
545
546   while (!unhandled_.empty()) {
547     // pick the interval with the earliest start point
548     LiveInterval* cur = unhandled_.top();
549     unhandled_.pop();
550     ++NumIters;
551     DEBUG(dbgs() << "\n*** CURRENT ***: " << *cur << '\n');
552
553     assert(!cur->empty() && "Empty interval in unhandled set.");
554
555     processActiveIntervals(cur->beginIndex());
556     processInactiveIntervals(cur->beginIndex());
557
558     assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
559            "Can only allocate virtual registers!");
560
561     // Allocating a virtual register. try to find a free
562     // physical register or spill an interval (possibly this one) in order to
563     // assign it one.
564     assignRegOrStackSlotAtInterval(cur);
565
566     DEBUG({
567         printIntervals("active", active_.begin(), active_.end());
568         printIntervals("inactive", inactive_.begin(), inactive_.end());
569       });
570   }
571
572   // Expire any remaining active intervals
573   while (!active_.empty()) {
574     IntervalPtr &IP = active_.back();
575     unsigned reg = IP.first->reg;
576     DEBUG(dbgs() << "\tinterval " << *IP.first << " expired\n");
577     assert(TargetRegisterInfo::isVirtualRegister(reg) &&
578            "Can only allocate virtual registers!");
579     reg = vrm_->getPhys(reg);
580     delRegUse(reg);
581     active_.pop_back();
582   }
583
584   // Expire any remaining inactive intervals
585   DEBUG({
586       for (IntervalPtrs::reverse_iterator
587              i = inactive_.rbegin(); i != inactive_.rend(); ++i)
588         dbgs() << "\tinterval " << *i->first << " expired\n";
589     });
590   inactive_.clear();
591
592   // Add live-ins to every BB except for entry. Also perform trivial coalescing.
593   MachineFunction::iterator EntryMBB = mf_->begin();
594   SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
595   for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
596     LiveInterval &cur = *i->second;
597     unsigned Reg = 0;
598     bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
599     if (isPhys)
600       Reg = cur.reg;
601     else if (vrm_->isAssignedReg(cur.reg))
602       Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
603     if (!Reg)
604       continue;
605     // Ignore splited live intervals.
606     if (!isPhys && vrm_->getPreSplitReg(cur.reg))
607       continue;
608
609     for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
610          I != E; ++I) {
611       const LiveRange &LR = *I;
612       if (li_->findLiveInMBBs(LR.start, LR.end, LiveInMBBs)) {
613         for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
614           if (LiveInMBBs[i] != EntryMBB) {
615             assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
616                    "Adding a virtual register to livein set?");
617             LiveInMBBs[i]->addLiveIn(Reg);
618           }
619         LiveInMBBs.clear();
620       }
621     }
622   }
623
624   DEBUG(dbgs() << *vrm_);
625
626   // Look for physical registers that end up not being allocated even though
627   // register allocator had to spill other registers in its register class.
628   if (ls_->getNumIntervals() == 0)
629     return;
630   if (!vrm_->FindUnusedRegisters(li_))
631     return;
632 }
633
634 /// processActiveIntervals - expire old intervals and move non-overlapping ones
635 /// to the inactive list.
636 void RALinScan::processActiveIntervals(SlotIndex CurPoint)
637 {
638   DEBUG(dbgs() << "\tprocessing active intervals:\n");
639
640   for (unsigned i = 0, e = active_.size(); i != e; ++i) {
641     LiveInterval *Interval = active_[i].first;
642     LiveInterval::iterator IntervalPos = active_[i].second;
643     unsigned reg = Interval->reg;
644
645     IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
646
647     if (IntervalPos == Interval->end()) {     // Remove expired intervals.
648       DEBUG(dbgs() << "\t\tinterval " << *Interval << " expired\n");
649       assert(TargetRegisterInfo::isVirtualRegister(reg) &&
650              "Can only allocate virtual registers!");
651       reg = vrm_->getPhys(reg);
652       delRegUse(reg);
653
654       // Pop off the end of the list.
655       active_[i] = active_.back();
656       active_.pop_back();
657       --i; --e;
658
659     } else if (IntervalPos->start > CurPoint) {
660       // Move inactive intervals to inactive list.
661       DEBUG(dbgs() << "\t\tinterval " << *Interval << " inactive\n");
662       assert(TargetRegisterInfo::isVirtualRegister(reg) &&
663              "Can only allocate virtual registers!");
664       reg = vrm_->getPhys(reg);
665       delRegUse(reg);
666       // add to inactive.
667       inactive_.push_back(std::make_pair(Interval, IntervalPos));
668
669       // Pop off the end of the list.
670       active_[i] = active_.back();
671       active_.pop_back();
672       --i; --e;
673     } else {
674       // Otherwise, just update the iterator position.
675       active_[i].second = IntervalPos;
676     }
677   }
678 }
679
680 /// processInactiveIntervals - expire old intervals and move overlapping
681 /// ones to the active list.
682 void RALinScan::processInactiveIntervals(SlotIndex CurPoint)
683 {
684   DEBUG(dbgs() << "\tprocessing inactive intervals:\n");
685
686   for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
687     LiveInterval *Interval = inactive_[i].first;
688     LiveInterval::iterator IntervalPos = inactive_[i].second;
689     unsigned reg = Interval->reg;
690
691     IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
692
693     if (IntervalPos == Interval->end()) {       // remove expired intervals.
694       DEBUG(dbgs() << "\t\tinterval " << *Interval << " expired\n");
695
696       // Pop off the end of the list.
697       inactive_[i] = inactive_.back();
698       inactive_.pop_back();
699       --i; --e;
700     } else if (IntervalPos->start <= CurPoint) {
701       // move re-activated intervals in active list
702       DEBUG(dbgs() << "\t\tinterval " << *Interval << " active\n");
703       assert(TargetRegisterInfo::isVirtualRegister(reg) &&
704              "Can only allocate virtual registers!");
705       reg = vrm_->getPhys(reg);
706       addRegUse(reg);
707       // add to active
708       active_.push_back(std::make_pair(Interval, IntervalPos));
709
710       // Pop off the end of the list.
711       inactive_[i] = inactive_.back();
712       inactive_.pop_back();
713       --i; --e;
714     } else {
715       // Otherwise, just update the iterator position.
716       inactive_[i].second = IntervalPos;
717     }
718   }
719 }
720
721 /// updateSpillWeights - updates the spill weights of the specifed physical
722 /// register and its weight.
723 void RALinScan::updateSpillWeights(std::vector<float> &Weights,
724                                    unsigned reg, float weight,
725                                    const TargetRegisterClass *RC) {
726   SmallSet<unsigned, 4> Processed;
727   SmallSet<unsigned, 4> SuperAdded;
728   SmallVector<unsigned, 4> Supers;
729   Weights[reg] += weight;
730   Processed.insert(reg);
731   for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as) {
732     Weights[*as] += weight;
733     Processed.insert(*as);
734     if (tri_->isSubRegister(*as, reg) &&
735         SuperAdded.insert(*as) &&
736         RC->contains(*as)) {
737       Supers.push_back(*as);
738     }
739   }
740
741   // If the alias is a super-register, and the super-register is in the
742   // register class we are trying to allocate. Then add the weight to all
743   // sub-registers of the super-register even if they are not aliases.
744   // e.g. allocating for GR32, bh is not used, updating bl spill weight.
745   //      bl should get the same spill weight otherwise it will be choosen
746   //      as a spill candidate since spilling bh doesn't make ebx available.
747   for (unsigned i = 0, e = Supers.size(); i != e; ++i) {
748     for (const unsigned *sr = tri_->getSubRegisters(Supers[i]); *sr; ++sr)
749       if (!Processed.count(*sr))
750         Weights[*sr] += weight;
751   }
752 }
753
754 static
755 RALinScan::IntervalPtrs::iterator
756 FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
757   for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
758        I != E; ++I)
759     if (I->first == LI) return I;
760   return IP.end();
761 }
762
763 static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, SlotIndex Point){
764   for (unsigned i = 0, e = V.size(); i != e; ++i) {
765     RALinScan::IntervalPtr &IP = V[i];
766     LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
767                                                 IP.second, Point);
768     if (I != IP.first->begin()) --I;
769     IP.second = I;
770   }
771 }
772
773 /// addStackInterval - Create a LiveInterval for stack if the specified live
774 /// interval has been spilled.
775 static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
776                              LiveIntervals *li_,
777                              MachineRegisterInfo* mri_, VirtRegMap &vrm_) {
778   int SS = vrm_.getStackSlot(cur->reg);
779   if (SS == VirtRegMap::NO_STACK_SLOT)
780     return;
781
782   const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
783   LiveInterval &SI = ls_->getOrCreateInterval(SS, RC);
784
785   VNInfo *VNI;
786   if (SI.hasAtLeastOneValue())
787     VNI = SI.getValNumInfo(0);
788   else
789     VNI = SI.getNextValue(SlotIndex(), 0, false,
790                           ls_->getVNInfoAllocator());
791
792   LiveInterval &RI = li_->getInterval(cur->reg);
793   // FIXME: This may be overly conservative.
794   SI.MergeRangesInAsValue(RI, VNI);
795 }
796
797 /// getConflictWeight - Return the number of conflicts between cur
798 /// live interval and defs and uses of Reg weighted by loop depthes.
799 static
800 float getConflictWeight(LiveInterval *cur, unsigned Reg, LiveIntervals *li_,
801                         MachineRegisterInfo *mri_,
802                         MachineLoopInfo *loopInfo) {
803   float Conflicts = 0;
804   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
805          E = mri_->reg_end(); I != E; ++I) {
806     MachineInstr *MI = &*I;
807     if (cur->liveAt(li_->getInstructionIndex(MI))) {
808       unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
809       Conflicts += std::pow(10.0f, (float)loopDepth);
810     }
811   }
812   return Conflicts;
813 }
814
815 /// findIntervalsToSpill - Determine the intervals to spill for the
816 /// specified interval. It's passed the physical registers whose spill
817 /// weight is the lowest among all the registers whose live intervals
818 /// conflict with the interval.
819 void RALinScan::findIntervalsToSpill(LiveInterval *cur,
820                             std::vector<std::pair<unsigned,float> > &Candidates,
821                             unsigned NumCands,
822                             SmallVector<LiveInterval*, 8> &SpillIntervals) {
823   // We have figured out the *best* register to spill. But there are other
824   // registers that are pretty good as well (spill weight within 3%). Spill
825   // the one that has fewest defs and uses that conflict with cur.
826   float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
827   SmallVector<LiveInterval*, 8> SLIs[3];
828
829   DEBUG({
830       dbgs() << "\tConsidering " << NumCands << " candidates: ";
831       for (unsigned i = 0; i != NumCands; ++i)
832         dbgs() << tri_->getName(Candidates[i].first) << " ";
833       dbgs() << "\n";
834     });
835   
836   // Calculate the number of conflicts of each candidate.
837   for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
838     unsigned Reg = i->first->reg;
839     unsigned PhysReg = vrm_->getPhys(Reg);
840     if (!cur->overlapsFrom(*i->first, i->second))
841       continue;
842     for (unsigned j = 0; j < NumCands; ++j) {
843       unsigned Candidate = Candidates[j].first;
844       if (tri_->regsOverlap(PhysReg, Candidate)) {
845         if (NumCands > 1)
846           Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
847         SLIs[j].push_back(i->first);
848       }
849     }
850   }
851
852   for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
853     unsigned Reg = i->first->reg;
854     unsigned PhysReg = vrm_->getPhys(Reg);
855     if (!cur->overlapsFrom(*i->first, i->second-1))
856       continue;
857     for (unsigned j = 0; j < NumCands; ++j) {
858       unsigned Candidate = Candidates[j].first;
859       if (tri_->regsOverlap(PhysReg, Candidate)) {
860         if (NumCands > 1)
861           Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
862         SLIs[j].push_back(i->first);
863       }
864     }
865   }
866
867   // Which is the best candidate?
868   unsigned BestCandidate = 0;
869   float MinConflicts = Conflicts[0];
870   for (unsigned i = 1; i != NumCands; ++i) {
871     if (Conflicts[i] < MinConflicts) {
872       BestCandidate = i;
873       MinConflicts = Conflicts[i];
874     }
875   }
876
877   std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
878             std::back_inserter(SpillIntervals));
879 }
880
881 namespace {
882   struct WeightCompare {
883   private:
884     const RALinScan &Allocator;
885
886   public:
887     WeightCompare(const RALinScan &Alloc) : Allocator(Alloc) {}
888
889     typedef std::pair<unsigned, float> RegWeightPair;
890     bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
891       return LHS.second < RHS.second && !Allocator.isRecentlyUsed(LHS.first);
892     }
893   };
894 }
895
896 static bool weightsAreClose(float w1, float w2) {
897   if (!NewHeuristic)
898     return false;
899
900   float diff = w1 - w2;
901   if (diff <= 0.02f)  // Within 0.02f
902     return true;
903   return (diff / w2) <= 0.05f;  // Within 5%.
904 }
905
906 LiveInterval *RALinScan::hasNextReloadInterval(LiveInterval *cur) {
907   DenseMap<unsigned, unsigned>::iterator I = NextReloadMap.find(cur->reg);
908   if (I == NextReloadMap.end())
909     return 0;
910   return &li_->getInterval(I->second);
911 }
912
913 void RALinScan::DowngradeRegister(LiveInterval *li, unsigned Reg) {
914   bool isNew = DowngradedRegs.insert(Reg);
915   isNew = isNew; // Silence compiler warning.
916   assert(isNew && "Multiple reloads holding the same register?");
917   DowngradeMap.insert(std::make_pair(li->reg, Reg));
918   for (const unsigned *AS = tri_->getAliasSet(Reg); *AS; ++AS) {
919     isNew = DowngradedRegs.insert(*AS);
920     isNew = isNew; // Silence compiler warning.
921     assert(isNew && "Multiple reloads holding the same register?");
922     DowngradeMap.insert(std::make_pair(li->reg, *AS));
923   }
924   ++NumDowngrade;
925 }
926
927 void RALinScan::UpgradeRegister(unsigned Reg) {
928   if (Reg) {
929     DowngradedRegs.erase(Reg);
930     for (const unsigned *AS = tri_->getAliasSet(Reg); *AS; ++AS)
931       DowngradedRegs.erase(*AS);
932   }
933 }
934
935 namespace {
936   struct LISorter {
937     bool operator()(LiveInterval* A, LiveInterval* B) {
938       return A->beginIndex() < B->beginIndex();
939     }
940   };
941 }
942
943 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
944 /// spill.
945 void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur) {
946   DEBUG(dbgs() << "\tallocating current interval: ");
947
948   // This is an implicitly defined live interval, just assign any register.
949   const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
950   if (cur->empty()) {
951     unsigned physReg = vrm_->getRegAllocPref(cur->reg);
952     if (!physReg)
953       physReg = *RC->allocation_order_begin(*mf_);
954     DEBUG(dbgs() <<  tri_->getName(physReg) << '\n');
955     // Note the register is not really in use.
956     vrm_->assignVirt2Phys(cur->reg, physReg);
957     return;
958   }
959
960   backUpRegUses();
961
962   std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
963   SlotIndex StartPosition = cur->beginIndex();
964   const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
965
966   // If start of this live interval is defined by a move instruction and its
967   // source is assigned a physical register that is compatible with the target
968   // register class, then we should try to assign it the same register.
969   // This can happen when the move is from a larger register class to a smaller
970   // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
971   if (!vrm_->getRegAllocPref(cur->reg) && cur->hasAtLeastOneValue()) {
972     VNInfo *vni = cur->begin()->valno;
973     if ((vni->def != SlotIndex()) && !vni->isUnused() &&
974          vni->isDefAccurate()) {
975       MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
976       if (CopyMI && CopyMI->isCopy()) {
977         unsigned DstSubReg = CopyMI->getOperand(0).getSubReg();
978         unsigned SrcReg = CopyMI->getOperand(1).getReg();
979         unsigned SrcSubReg = CopyMI->getOperand(1).getSubReg();
980         unsigned Reg = 0;
981         if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
982           Reg = SrcReg;
983         else if (vrm_->isAssignedReg(SrcReg))
984           Reg = vrm_->getPhys(SrcReg);
985         if (Reg) {
986           if (SrcSubReg)
987             Reg = tri_->getSubReg(Reg, SrcSubReg);
988           if (DstSubReg)
989             Reg = tri_->getMatchingSuperReg(Reg, DstSubReg, RC);
990           if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
991             mri_->setRegAllocationHint(cur->reg, 0, Reg);
992         }
993       }
994     }
995   }
996
997   // For every interval in inactive we overlap with, mark the
998   // register as not free and update spill weights.
999   for (IntervalPtrs::const_iterator i = inactive_.begin(),
1000          e = inactive_.end(); i != e; ++i) {
1001     unsigned Reg = i->first->reg;
1002     assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
1003            "Can only allocate virtual registers!");
1004     const TargetRegisterClass *RegRC = mri_->getRegClass(Reg);
1005     // If this is not in a related reg class to the register we're allocating, 
1006     // don't check it.
1007     if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
1008         cur->overlapsFrom(*i->first, i->second-1)) {
1009       Reg = vrm_->getPhys(Reg);
1010       addRegUse(Reg);
1011       SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
1012     }
1013   }
1014   
1015   // Speculatively check to see if we can get a register right now.  If not,
1016   // we know we won't be able to by adding more constraints.  If so, we can
1017   // check to see if it is valid.  Doing an exhaustive search of the fixed_ list
1018   // is very bad (it contains all callee clobbered registers for any functions
1019   // with a call), so we want to avoid doing that if possible.
1020   unsigned physReg = getFreePhysReg(cur);
1021   unsigned BestPhysReg = physReg;
1022   if (physReg) {
1023     // We got a register.  However, if it's in the fixed_ list, we might
1024     // conflict with it.  Check to see if we conflict with it or any of its
1025     // aliases.
1026     SmallSet<unsigned, 8> RegAliases;
1027     for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
1028       RegAliases.insert(*AS);
1029     
1030     bool ConflictsWithFixed = false;
1031     for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1032       IntervalPtr &IP = fixed_[i];
1033       if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
1034         // Okay, this reg is on the fixed list.  Check to see if we actually
1035         // conflict.
1036         LiveInterval *I = IP.first;
1037         if (I->endIndex() > StartPosition) {
1038           LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
1039           IP.second = II;
1040           if (II != I->begin() && II->start > StartPosition)
1041             --II;
1042           if (cur->overlapsFrom(*I, II)) {
1043             ConflictsWithFixed = true;
1044             break;
1045           }
1046         }
1047       }
1048     }
1049     
1050     // Okay, the register picked by our speculative getFreePhysReg call turned
1051     // out to be in use.  Actually add all of the conflicting fixed registers to
1052     // regUse_ so we can do an accurate query.
1053     if (ConflictsWithFixed) {
1054       // For every interval in fixed we overlap with, mark the register as not
1055       // free and update spill weights.
1056       for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1057         IntervalPtr &IP = fixed_[i];
1058         LiveInterval *I = IP.first;
1059
1060         const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
1061         if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&       
1062             I->endIndex() > StartPosition) {
1063           LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
1064           IP.second = II;
1065           if (II != I->begin() && II->start > StartPosition)
1066             --II;
1067           if (cur->overlapsFrom(*I, II)) {
1068             unsigned reg = I->reg;
1069             addRegUse(reg);
1070             SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
1071           }
1072         }
1073       }
1074
1075       // Using the newly updated regUse_ object, which includes conflicts in the
1076       // future, see if there are any registers available.
1077       physReg = getFreePhysReg(cur);
1078     }
1079   }
1080     
1081   // Restore the physical register tracker, removing information about the
1082   // future.
1083   restoreRegUses();
1084   
1085   // If we find a free register, we are done: assign this virtual to
1086   // the free physical register and add this interval to the active
1087   // list.
1088   if (physReg) {
1089     DEBUG(dbgs() <<  tri_->getName(physReg) << '\n');
1090     vrm_->assignVirt2Phys(cur->reg, physReg);
1091     addRegUse(physReg);
1092     active_.push_back(std::make_pair(cur, cur->begin()));
1093     handled_.push_back(cur);
1094
1095     // "Upgrade" the physical register since it has been allocated.
1096     UpgradeRegister(physReg);
1097     if (LiveInterval *NextReloadLI = hasNextReloadInterval(cur)) {
1098       // "Downgrade" physReg to try to keep physReg from being allocated until
1099       // the next reload from the same SS is allocated. 
1100       mri_->setRegAllocationHint(NextReloadLI->reg, 0, physReg);
1101       DowngradeRegister(cur, physReg);
1102     }
1103     return;
1104   }
1105   DEBUG(dbgs() << "no free registers\n");
1106
1107   // Compile the spill weights into an array that is better for scanning.
1108   std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
1109   for (std::vector<std::pair<unsigned, float> >::iterator
1110        I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
1111     updateSpillWeights(SpillWeights, I->first, I->second, RC);
1112   
1113   // for each interval in active, update spill weights.
1114   for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
1115        i != e; ++i) {
1116     unsigned reg = i->first->reg;
1117     assert(TargetRegisterInfo::isVirtualRegister(reg) &&
1118            "Can only allocate virtual registers!");
1119     reg = vrm_->getPhys(reg);
1120     updateSpillWeights(SpillWeights, reg, i->first->weight, RC);
1121   }
1122  
1123   DEBUG(dbgs() << "\tassigning stack slot at interval "<< *cur << ":\n");
1124
1125   // Find a register to spill.
1126   float minWeight = HUGE_VALF;
1127   unsigned minReg = 0;
1128
1129   bool Found = false;
1130   std::vector<std::pair<unsigned,float> > RegsWeights;
1131   if (!minReg || SpillWeights[minReg] == HUGE_VALF)
1132     for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
1133            e = RC->allocation_order_end(*mf_); i != e; ++i) {
1134       unsigned reg = *i;
1135       float regWeight = SpillWeights[reg];
1136       // Skip recently allocated registers.
1137       if (minWeight > regWeight && !isRecentlyUsed(reg))
1138         Found = true;
1139       RegsWeights.push_back(std::make_pair(reg, regWeight));
1140     }
1141   
1142   // If we didn't find a register that is spillable, try aliases?
1143   if (!Found) {
1144     for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
1145            e = RC->allocation_order_end(*mf_); i != e; ++i) {
1146       unsigned reg = *i;
1147       // No need to worry about if the alias register size < regsize of RC.
1148       // We are going to spill all registers that alias it anyway.
1149       for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
1150         RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
1151     }
1152   }
1153
1154   // Sort all potential spill candidates by weight.
1155   std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare(*this));
1156   minReg = RegsWeights[0].first;
1157   minWeight = RegsWeights[0].second;
1158   if (minWeight == HUGE_VALF) {
1159     // All registers must have inf weight. Just grab one!
1160     minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
1161     if (cur->weight == HUGE_VALF ||
1162         li_->getApproximateInstructionCount(*cur) == 0) {
1163       // Spill a physical register around defs and uses.
1164       if (li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_)) {
1165         // spillPhysRegAroundRegDefsUses may have invalidated iterator stored
1166         // in fixed_. Reset them.
1167         for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1168           IntervalPtr &IP = fixed_[i];
1169           LiveInterval *I = IP.first;
1170           if (I->reg == minReg || tri_->isSubRegister(minReg, I->reg))
1171             IP.second = I->advanceTo(I->begin(), StartPosition);
1172         }
1173
1174         DowngradedRegs.clear();
1175         assignRegOrStackSlotAtInterval(cur);
1176       } else {
1177         assert(false && "Ran out of registers during register allocation!");
1178         report_fatal_error("Ran out of registers during register allocation!");
1179       }
1180       return;
1181     }
1182   }
1183
1184   // Find up to 3 registers to consider as spill candidates.
1185   unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
1186   while (LastCandidate > 1) {
1187     if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
1188       break;
1189     --LastCandidate;
1190   }
1191
1192   DEBUG({
1193       dbgs() << "\t\tregister(s) with min weight(s): ";
1194
1195       for (unsigned i = 0; i != LastCandidate; ++i)
1196         dbgs() << tri_->getName(RegsWeights[i].first)
1197                << " (" << RegsWeights[i].second << ")\n";
1198     });
1199
1200   // If the current has the minimum weight, we need to spill it and
1201   // add any added intervals back to unhandled, and restart
1202   // linearscan.
1203   if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
1204     DEBUG(dbgs() << "\t\t\tspilling(c): " << *cur << '\n');
1205     SmallVector<LiveInterval*, 8> spillIs;
1206     std::vector<LiveInterval*> added;
1207     spiller_->spill(cur, added, spillIs);
1208
1209     std::sort(added.begin(), added.end(), LISorter());
1210     addStackInterval(cur, ls_, li_, mri_, *vrm_);
1211     if (added.empty())
1212       return;  // Early exit if all spills were folded.
1213
1214     // Merge added with unhandled.  Note that we have already sorted
1215     // intervals returned by addIntervalsForSpills by their starting
1216     // point.
1217     // This also update the NextReloadMap. That is, it adds mapping from a
1218     // register defined by a reload from SS to the next reload from SS in the
1219     // same basic block.
1220     MachineBasicBlock *LastReloadMBB = 0;
1221     LiveInterval *LastReload = 0;
1222     int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1223     for (unsigned i = 0, e = added.size(); i != e; ++i) {
1224       LiveInterval *ReloadLi = added[i];
1225       if (ReloadLi->weight == HUGE_VALF &&
1226           li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1227         SlotIndex ReloadIdx = ReloadLi->beginIndex();
1228         MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1229         int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1230         if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1231           // Last reload of same SS is in the same MBB. We want to try to
1232           // allocate both reloads the same register and make sure the reg
1233           // isn't clobbered in between if at all possible.
1234           assert(LastReload->beginIndex() < ReloadIdx);
1235           NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1236         }
1237         LastReloadMBB = ReloadMBB;
1238         LastReload = ReloadLi;
1239         LastReloadSS = ReloadSS;
1240       }
1241       unhandled_.push(ReloadLi);
1242     }
1243     return;
1244   }
1245
1246   ++NumBacktracks;
1247
1248   // Push the current interval back to unhandled since we are going
1249   // to re-run at least this iteration. Since we didn't modify it it
1250   // should go back right in the front of the list
1251   unhandled_.push(cur);
1252
1253   assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
1254          "did not choose a register to spill?");
1255
1256   // We spill all intervals aliasing the register with
1257   // minimum weight, rollback to the interval with the earliest
1258   // start point and let the linear scan algorithm run again
1259   SmallVector<LiveInterval*, 8> spillIs;
1260
1261   // Determine which intervals have to be spilled.
1262   findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
1263
1264   // Set of spilled vregs (used later to rollback properly)
1265   SmallSet<unsigned, 8> spilled;
1266
1267   // The earliest start of a Spilled interval indicates up to where
1268   // in handled we need to roll back
1269   assert(!spillIs.empty() && "No spill intervals?"); 
1270   SlotIndex earliestStart = spillIs[0]->beginIndex();
1271   
1272   // Spill live intervals of virtual regs mapped to the physical register we
1273   // want to clear (and its aliases).  We only spill those that overlap with the
1274   // current interval as the rest do not affect its allocation. we also keep
1275   // track of the earliest start of all spilled live intervals since this will
1276   // mark our rollback point.
1277   std::vector<LiveInterval*> added;
1278   while (!spillIs.empty()) {
1279     LiveInterval *sli = spillIs.back();
1280     spillIs.pop_back();
1281     DEBUG(dbgs() << "\t\t\tspilling(a): " << *sli << '\n');
1282     if (sli->beginIndex() < earliestStart)
1283       earliestStart = sli->beginIndex();
1284        
1285     spiller_->spill(sli, added, spillIs, &earliestStart);
1286     addStackInterval(sli, ls_, li_, mri_, *vrm_);
1287     spilled.insert(sli->reg);
1288   }
1289
1290   DEBUG(dbgs() << "\t\trolling back to: " << earliestStart << '\n');
1291
1292   // Scan handled in reverse order up to the earliest start of a
1293   // spilled live interval and undo each one, restoring the state of
1294   // unhandled.
1295   while (!handled_.empty()) {
1296     LiveInterval* i = handled_.back();
1297     // If this interval starts before t we are done.
1298     if (!i->empty() && i->beginIndex() < earliestStart)
1299       break;
1300     DEBUG(dbgs() << "\t\t\tundo changes for: " << *i << '\n');
1301     handled_.pop_back();
1302
1303     // When undoing a live interval allocation we must know if it is active or
1304     // inactive to properly update regUse_ and the VirtRegMap.
1305     IntervalPtrs::iterator it;
1306     if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
1307       active_.erase(it);
1308       assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
1309       if (!spilled.count(i->reg))
1310         unhandled_.push(i);
1311       delRegUse(vrm_->getPhys(i->reg));
1312       vrm_->clearVirt(i->reg);
1313     } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
1314       inactive_.erase(it);
1315       assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
1316       if (!spilled.count(i->reg))
1317         unhandled_.push(i);
1318       vrm_->clearVirt(i->reg);
1319     } else {
1320       assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
1321              "Can only allocate virtual registers!");
1322       vrm_->clearVirt(i->reg);
1323       unhandled_.push(i);
1324     }
1325
1326     DenseMap<unsigned, unsigned>::iterator ii = DowngradeMap.find(i->reg);
1327     if (ii == DowngradeMap.end())
1328       // It interval has a preference, it must be defined by a copy. Clear the
1329       // preference now since the source interval allocation may have been
1330       // undone as well.
1331       mri_->setRegAllocationHint(i->reg, 0, 0);
1332     else {
1333       UpgradeRegister(ii->second);
1334     }
1335   }
1336
1337   // Rewind the iterators in the active, inactive, and fixed lists back to the
1338   // point we reverted to.
1339   RevertVectorIteratorsTo(active_, earliestStart);
1340   RevertVectorIteratorsTo(inactive_, earliestStart);
1341   RevertVectorIteratorsTo(fixed_, earliestStart);
1342
1343   // Scan the rest and undo each interval that expired after t and
1344   // insert it in active (the next iteration of the algorithm will
1345   // put it in inactive if required)
1346   for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
1347     LiveInterval *HI = handled_[i];
1348     if (!HI->expiredAt(earliestStart) &&
1349         HI->expiredAt(cur->beginIndex())) {
1350       DEBUG(dbgs() << "\t\t\tundo changes for: " << *HI << '\n');
1351       active_.push_back(std::make_pair(HI, HI->begin()));
1352       assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
1353       addRegUse(vrm_->getPhys(HI->reg));
1354     }
1355   }
1356
1357   // Merge added with unhandled.
1358   // This also update the NextReloadMap. That is, it adds mapping from a
1359   // register defined by a reload from SS to the next reload from SS in the
1360   // same basic block.
1361   MachineBasicBlock *LastReloadMBB = 0;
1362   LiveInterval *LastReload = 0;
1363   int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1364   std::sort(added.begin(), added.end(), LISorter());
1365   for (unsigned i = 0, e = added.size(); i != e; ++i) {
1366     LiveInterval *ReloadLi = added[i];
1367     if (ReloadLi->weight == HUGE_VALF &&
1368         li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1369       SlotIndex ReloadIdx = ReloadLi->beginIndex();
1370       MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1371       int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1372       if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1373         // Last reload of same SS is in the same MBB. We want to try to
1374         // allocate both reloads the same register and make sure the reg
1375         // isn't clobbered in between if at all possible.
1376         assert(LastReload->beginIndex() < ReloadIdx);
1377         NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1378       }
1379       LastReloadMBB = ReloadMBB;
1380       LastReload = ReloadLi;
1381       LastReloadSS = ReloadSS;
1382     }
1383     unhandled_.push(ReloadLi);
1384   }
1385 }
1386
1387 unsigned RALinScan::getFreePhysReg(LiveInterval* cur,
1388                                    const TargetRegisterClass *RC,
1389                                    unsigned MaxInactiveCount,
1390                                    SmallVector<unsigned, 256> &inactiveCounts,
1391                                    bool SkipDGRegs) {
1392   unsigned FreeReg = 0;
1393   unsigned FreeRegInactiveCount = 0;
1394
1395   std::pair<unsigned, unsigned> Hint = mri_->getRegAllocationHint(cur->reg);
1396   // Resolve second part of the hint (if possible) given the current allocation.
1397   unsigned physReg = Hint.second;
1398   if (physReg &&
1399       TargetRegisterInfo::isVirtualRegister(physReg) && vrm_->hasPhys(physReg))
1400     physReg = vrm_->getPhys(physReg);
1401
1402   TargetRegisterClass::iterator I, E;
1403   tie(I, E) = tri_->getAllocationOrder(RC, Hint.first, physReg, *mf_);
1404   assert(I != E && "No allocatable register in this register class!");
1405
1406   // Scan for the first available register.
1407   for (; I != E; ++I) {
1408     unsigned Reg = *I;
1409     // Ignore "downgraded" registers.
1410     if (SkipDGRegs && DowngradedRegs.count(Reg))
1411       continue;
1412     // Skip recently allocated registers.
1413     if (isRegAvail(Reg) && !isRecentlyUsed(Reg)) {
1414       FreeReg = Reg;
1415       if (FreeReg < inactiveCounts.size())
1416         FreeRegInactiveCount = inactiveCounts[FreeReg];
1417       else
1418         FreeRegInactiveCount = 0;
1419       break;
1420     }
1421   }
1422
1423   // If there are no free regs, or if this reg has the max inactive count,
1424   // return this register.
1425   if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) {
1426     // Remember what register we picked so we can skip it next time.
1427     if (FreeReg != 0) recordRecentlyUsed(FreeReg);
1428     return FreeReg;
1429   }
1430
1431   // Continue scanning the registers, looking for the one with the highest
1432   // inactive count.  Alkis found that this reduced register pressure very
1433   // slightly on X86 (in rev 1.94 of this file), though this should probably be
1434   // reevaluated now.
1435   for (; I != E; ++I) {
1436     unsigned Reg = *I;
1437     // Ignore "downgraded" registers.
1438     if (SkipDGRegs && DowngradedRegs.count(Reg))
1439       continue;
1440     if (isRegAvail(Reg) && Reg < inactiveCounts.size() &&
1441         FreeRegInactiveCount < inactiveCounts[Reg] && !isRecentlyUsed(Reg)) {
1442       FreeReg = Reg;
1443       FreeRegInactiveCount = inactiveCounts[Reg];
1444       if (FreeRegInactiveCount == MaxInactiveCount)
1445         break;    // We found the one with the max inactive count.
1446     }
1447   }
1448
1449   // Remember what register we picked so we can skip it next time.
1450   recordRecentlyUsed(FreeReg);
1451
1452   return FreeReg;
1453 }
1454
1455 /// getFreePhysReg - return a free physical register for this virtual register
1456 /// interval if we have one, otherwise return 0.
1457 unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
1458   SmallVector<unsigned, 256> inactiveCounts;
1459   unsigned MaxInactiveCount = 0;
1460   
1461   const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
1462   const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1463  
1464   for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1465        i != e; ++i) {
1466     unsigned reg = i->first->reg;
1467     assert(TargetRegisterInfo::isVirtualRegister(reg) &&
1468            "Can only allocate virtual registers!");
1469
1470     // If this is not in a related reg class to the register we're allocating, 
1471     // don't check it.
1472     const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
1473     if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1474       reg = vrm_->getPhys(reg);
1475       if (inactiveCounts.size() <= reg)
1476         inactiveCounts.resize(reg+1);
1477       ++inactiveCounts[reg];
1478       MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1479     }
1480   }
1481
1482   // If copy coalescer has assigned a "preferred" register, check if it's
1483   // available first.
1484   unsigned Preference = vrm_->getRegAllocPref(cur->reg);
1485   if (Preference) {
1486     DEBUG(dbgs() << "(preferred: " << tri_->getName(Preference) << ") ");
1487     if (isRegAvail(Preference) && 
1488         RC->contains(Preference))
1489       return Preference;
1490   }
1491
1492   if (!DowngradedRegs.empty()) {
1493     unsigned FreeReg = getFreePhysReg(cur, RC, MaxInactiveCount, inactiveCounts,
1494                                       true);
1495     if (FreeReg)
1496       return FreeReg;
1497   }
1498   return getFreePhysReg(cur, RC, MaxInactiveCount, inactiveCounts, false);
1499 }
1500
1501 FunctionPass* llvm::createLinearScanRegisterAllocator() {
1502   return new RALinScan();
1503 }