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