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