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