Implement Jakob's suggestion on how to detect fall thought without calling
[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 <queue>
44 #include <memory>
45 #include <cmath>
46
47 using namespace llvm;
48
49 STATISTIC(NumIters     , "Number of iterations performed");
50 STATISTIC(NumBacktracks, "Number of times we had to backtrack");
51 STATISTIC(NumCoalesce,   "Number of copies coalesced");
52 STATISTIC(NumDowngrade,  "Number of registers downgraded");
53
54 static cl::opt<bool>
55 NewHeuristic("new-spilling-heuristic",
56              cl::desc("Use new spilling heuristic"),
57              cl::init(false), cl::Hidden);
58
59 static cl::opt<bool>
60 PreSplitIntervals("pre-alloc-split",
61                   cl::desc("Pre-register allocation live interval splitting"),
62                   cl::init(false), cl::Hidden);
63
64 static cl::opt<bool>
65 TrivCoalesceEnds("trivial-coalesce-ends",
66                   cl::desc("Attempt trivial coalescing of interval ends"),
67                   cl::init(false), cl::Hidden);
68
69 static cl::opt<bool>
70 AvoidWAWHazard("avoid-waw-hazard",
71                cl::desc("Avoid write-write hazards for some register classes"),
72                cl::init(false), cl::Hidden);
73
74 static RegisterRegAlloc
75 linearscanRegAlloc("linearscan", "linear scan register allocator",
76                    createLinearScanRegisterAllocator);
77
78 namespace {
79   // When we allocate a register, add it to a fixed-size queue of
80   // registers to skip in subsequent allocations. This trades a small
81   // amount of register pressure and increased spills for flexibility in
82   // the post-pass scheduler.
83   //
84   // Note that in a the number of registers used for reloading spills
85   // will be one greater than the value of this option.
86   //
87   // One big limitation of this is that it doesn't differentiate between
88   // different register classes. So on x86-64, if there is xmm register
89   // pressure, it can caused fewer GPRs to be held in the queue.
90   static cl::opt<unsigned>
91   NumRecentlyUsedRegs("linearscan-skip-count",
92                       cl::desc("Number of registers for linearscan to remember"
93                                "to skip."),
94                       cl::init(0),
95                       cl::Hidden);
96
97   struct RALinScan : public MachineFunctionPass {
98     static char ID;
99     RALinScan() : MachineFunctionPass(ID) {
100       initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
101       initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
102       initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
103       initializeRegisterCoalescerAnalysisGroup(
104         *PassRegistry::getPassRegistry());
105       initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
106       initializePreAllocSplittingPass(*PassRegistry::getPassRegistry());
107       initializeLiveStacksPass(*PassRegistry::getPassRegistry());
108       initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
109       initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
110       initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
111       initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
112       
113       // Initialize the queue to record recently-used registers.
114       if (NumRecentlyUsedRegs > 0)
115         RecentRegs.resize(NumRecentlyUsedRegs, 0);
116       RecentNext = RecentRegs.begin();
117       avoidWAW_ = 0;
118     }
119
120     typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
121     typedef SmallVector<IntervalPtr, 32> IntervalPtrs;
122   private:
123     /// RelatedRegClasses - This structure is built the first time a function is
124     /// compiled, and keeps track of which register classes have registers that
125     /// belong to multiple classes or have aliases that are in other classes.
126     EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
127     DenseMap<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
128
129     // NextReloadMap - For each register in the map, it maps to the another
130     // register which is defined by a reload from the same stack slot and
131     // both reloads are in the same basic block.
132     DenseMap<unsigned, unsigned> NextReloadMap;
133
134     // DowngradedRegs - A set of registers which are being "downgraded", i.e.
135     // un-favored for allocation.
136     SmallSet<unsigned, 8> DowngradedRegs;
137
138     // DowngradeMap - A map from virtual registers to physical registers being
139     // downgraded for the virtual registers.
140     DenseMap<unsigned, unsigned> DowngradeMap;
141
142     MachineFunction* mf_;
143     MachineRegisterInfo* mri_;
144     const TargetMachine* tm_;
145     const TargetRegisterInfo* tri_;
146     const TargetInstrInfo* tii_;
147     BitVector allocatableRegs_;
148     BitVector reservedRegs_;
149     LiveIntervals* li_;
150     MachineLoopInfo *loopInfo;
151
152     /// handled_ - Intervals are added to the handled_ set in the order of their
153     /// start value.  This is uses for backtracking.
154     std::vector<LiveInterval*> handled_;
155
156     /// fixed_ - Intervals that correspond to machine registers.
157     ///
158     IntervalPtrs fixed_;
159
160     /// active_ - Intervals that are currently being processed, and which have a
161     /// live range active for the current point.
162     IntervalPtrs active_;
163
164     /// inactive_ - Intervals that are currently being processed, but which have
165     /// a hold at the current point.
166     IntervalPtrs inactive_;
167
168     typedef std::priority_queue<LiveInterval*,
169                                 SmallVector<LiveInterval*, 64>,
170                                 greater_ptr<LiveInterval> > IntervalHeap;
171     IntervalHeap unhandled_;
172
173     /// regUse_ - Tracks register usage.
174     SmallVector<unsigned, 32> regUse_;
175     SmallVector<unsigned, 32> regUseBackUp_;
176
177     /// vrm_ - Tracks register assignments.
178     VirtRegMap* vrm_;
179
180     std::auto_ptr<VirtRegRewriter> rewriter_;
181
182     std::auto_ptr<Spiller> spiller_;
183
184     // The queue of recently-used registers.
185     SmallVector<unsigned, 4> RecentRegs;
186     SmallVector<unsigned, 4>::iterator RecentNext;
187
188     // Last write-after-write register written.
189     unsigned avoidWAW_;
190
191     // Record that we just picked this register.
192     void recordRecentlyUsed(unsigned reg) {
193       assert(reg != 0 && "Recently used register is NOREG!");
194       if (!RecentRegs.empty()) {
195         *RecentNext++ = reg;
196         if (RecentNext == RecentRegs.end())
197           RecentNext = RecentRegs.begin();
198       }
199     }
200
201   public:
202     virtual const char* getPassName() const {
203       return "Linear Scan Register Allocator";
204     }
205
206     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
207       AU.setPreservesCFG();
208       AU.addRequired<AliasAnalysis>();
209       AU.addPreserved<AliasAnalysis>();
210       AU.addRequired<LiveIntervals>();
211       AU.addPreserved<SlotIndexes>();
212       if (StrongPHIElim)
213         AU.addRequiredID(StrongPHIEliminationID);
214       // Make sure PassManager knows which analyses to make available
215       // to coalescing and which analyses coalescing invalidates.
216       AU.addRequiredTransitive<RegisterCoalescer>();
217       AU.addRequired<CalculateSpillWeights>();
218       if (PreSplitIntervals)
219         AU.addRequiredID(PreAllocSplittingID);
220       AU.addRequiredID(LiveStacksID);
221       AU.addPreservedID(LiveStacksID);
222       AU.addRequired<MachineLoopInfo>();
223       AU.addPreserved<MachineLoopInfo>();
224       AU.addRequired<VirtRegMap>();
225       AU.addPreserved<VirtRegMap>();
226       AU.addRequired<LiveDebugVariables>();
227       AU.addPreserved<LiveDebugVariables>();
228       AU.addRequiredID(MachineDominatorsID);
229       AU.addPreservedID(MachineDominatorsID);
230       MachineFunctionPass::getAnalysisUsage(AU);
231     }
232
233     /// runOnMachineFunction - register allocate the whole function
234     bool runOnMachineFunction(MachineFunction&);
235
236     // Determine if we skip this register due to its being recently used.
237     bool isRecentlyUsed(unsigned reg) const {
238       return reg == avoidWAW_ ||
239        std::find(RecentRegs.begin(), RecentRegs.end(), reg) != RecentRegs.end();
240     }
241
242   private:
243     /// linearScan - the linear scan algorithm
244     void linearScan();
245
246     /// initIntervalSets - initialize the interval sets.
247     ///
248     void initIntervalSets();
249
250     /// processActiveIntervals - expire old intervals and move non-overlapping
251     /// ones to the inactive list.
252     void processActiveIntervals(SlotIndex CurPoint);
253
254     /// processInactiveIntervals - expire old intervals and move overlapping
255     /// ones to the active list.
256     void processInactiveIntervals(SlotIndex CurPoint);
257
258     /// hasNextReloadInterval - Return the next liveinterval that's being
259     /// defined by a reload from the same SS as the specified one.
260     LiveInterval *hasNextReloadInterval(LiveInterval *cur);
261
262     /// DowngradeRegister - Downgrade a register for allocation.
263     void DowngradeRegister(LiveInterval *li, unsigned Reg);
264
265     /// UpgradeRegister - Upgrade a register for allocation.
266     void UpgradeRegister(unsigned Reg);
267
268     /// assignRegOrStackSlotAtInterval - assign a register if one
269     /// is available, or spill.
270     void assignRegOrStackSlotAtInterval(LiveInterval* cur);
271
272     void updateSpillWeights(std::vector<float> &Weights,
273                             unsigned reg, float weight,
274                             const TargetRegisterClass *RC);
275
276     /// findIntervalsToSpill - Determine the intervals to spill for the
277     /// specified interval. It's passed the physical registers whose spill
278     /// weight is the lowest among all the registers whose live intervals
279     /// conflict with the interval.
280     void findIntervalsToSpill(LiveInterval *cur,
281                             std::vector<std::pair<unsigned,float> > &Candidates,
282                             unsigned NumCands,
283                             SmallVector<LiveInterval*, 8> &SpillIntervals);
284
285     /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
286     /// try to allocate the definition to the same register as the source,
287     /// if the register is not defined during the life time of the interval.
288     /// This eliminates a copy, and is used to coalesce copies which were not
289     /// coalesced away before allocation either due to dest and src being in
290     /// different register classes or because the coalescer was overly
291     /// conservative.
292     unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
293
294     ///
295     /// Register usage / availability tracking helpers.
296     ///
297
298     void initRegUses() {
299       regUse_.resize(tri_->getNumRegs(), 0);
300       regUseBackUp_.resize(tri_->getNumRegs(), 0);
301     }
302
303     void finalizeRegUses() {
304 #ifndef NDEBUG
305       // Verify all the registers are "freed".
306       bool Error = false;
307       for (unsigned i = 0, e = tri_->getNumRegs(); i != e; ++i) {
308         if (regUse_[i] != 0) {
309           dbgs() << tri_->getName(i) << " is still in use!\n";
310           Error = true;
311         }
312       }
313       if (Error)
314         llvm_unreachable(0);
315 #endif
316       regUse_.clear();
317       regUseBackUp_.clear();
318     }
319
320     void addRegUse(unsigned physReg) {
321       assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
322              "should be physical register!");
323       ++regUse_[physReg];
324       for (const unsigned* as = tri_->getAliasSet(physReg); *as; ++as)
325         ++regUse_[*as];
326     }
327
328     void delRegUse(unsigned physReg) {
329       assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
330              "should be physical register!");
331       assert(regUse_[physReg] != 0);
332       --regUse_[physReg];
333       for (const unsigned* as = tri_->getAliasSet(physReg); *as; ++as) {
334         assert(regUse_[*as] != 0);
335         --regUse_[*as];
336       }
337     }
338
339     bool isRegAvail(unsigned physReg) const {
340       assert(TargetRegisterInfo::isPhysicalRegister(physReg) &&
341              "should be physical register!");
342       return regUse_[physReg] == 0;
343     }
344
345     void backUpRegUses() {
346       regUseBackUp_ = regUse_;
347     }
348
349     void restoreRegUses() {
350       regUse_ = regUseBackUp_;
351     }
352
353     ///
354     /// Register handling helpers.
355     ///
356
357     /// getFreePhysReg - return a free physical register for this virtual
358     /// register interval if we have one, otherwise return 0.
359     unsigned getFreePhysReg(LiveInterval* cur);
360     unsigned getFreePhysReg(LiveInterval* cur,
361                             const TargetRegisterClass *RC,
362                             unsigned MaxInactiveCount,
363                             SmallVector<unsigned, 256> &inactiveCounts,
364                             bool SkipDGRegs);
365
366     /// getFirstNonReservedPhysReg - return the first non-reserved physical
367     /// register in the register class.
368     unsigned getFirstNonReservedPhysReg(const TargetRegisterClass *RC) {
369         TargetRegisterClass::iterator aoe = RC->allocation_order_end(*mf_);
370         TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_);
371         while (i != aoe && reservedRegs_.test(*i))
372           ++i;
373         assert(i != aoe && "All registers reserved?!");
374         return *i;
375       }
376
377     void ComputeRelatedRegClasses();
378
379     template <typename ItTy>
380     void printIntervals(const char* const str, ItTy i, ItTy e) const {
381       DEBUG({
382           if (str)
383             dbgs() << str << " intervals:\n";
384
385           for (; i != e; ++i) {
386             dbgs() << '\t' << *i->first << " -> ";
387
388             unsigned reg = i->first->reg;
389             if (TargetRegisterInfo::isVirtualRegister(reg))
390               reg = vrm_->getPhys(reg);
391
392             dbgs() << tri_->getName(reg) << '\n';
393           }
394         });
395     }
396   };
397   char RALinScan::ID = 0;
398 }
399
400 INITIALIZE_PASS_BEGIN(RALinScan, "linearscan-regalloc",
401                       "Linear Scan Register Allocator", false, false)
402 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
403 INITIALIZE_PASS_DEPENDENCY(StrongPHIElimination)
404 INITIALIZE_PASS_DEPENDENCY(CalculateSpillWeights)
405 INITIALIZE_PASS_DEPENDENCY(PreAllocSplitting)
406 INITIALIZE_PASS_DEPENDENCY(LiveStacks)
407 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
408 INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
409 INITIALIZE_AG_DEPENDENCY(RegisterCoalescer)
410 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
411 INITIALIZE_PASS_END(RALinScan, "linearscan-regalloc",
412                     "Linear Scan Register Allocator", false, false)
413
414 void RALinScan::ComputeRelatedRegClasses() {
415   // First pass, add all reg classes to the union, and determine at least one
416   // reg class that each register is in.
417   bool HasAliases = false;
418   for (TargetRegisterInfo::regclass_iterator RCI = tri_->regclass_begin(),
419        E = tri_->regclass_end(); RCI != E; ++RCI) {
420     RelatedRegClasses.insert(*RCI);
421     for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
422          I != E; ++I) {
423       HasAliases = HasAliases || *tri_->getAliasSet(*I) != 0;
424
425       const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
426       if (PRC) {
427         // Already processed this register.  Just make sure we know that
428         // multiple register classes share a register.
429         RelatedRegClasses.unionSets(PRC, *RCI);
430       } else {
431         PRC = *RCI;
432       }
433     }
434   }
435
436   // Second pass, now that we know conservatively what register classes each reg
437   // belongs to, add info about aliases.  We don't need to do this for targets
438   // without register aliases.
439   if (HasAliases)
440     for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
441          I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
442          I != E; ++I)
443       for (const unsigned *AS = tri_->getAliasSet(I->first); *AS; ++AS) {
444         const TargetRegisterClass *AliasClass = 
445           OneClassForEachPhysReg.lookup(*AS);
446         if (AliasClass)
447           RelatedRegClasses.unionSets(I->second, AliasClass);
448       }
449 }
450
451 /// attemptTrivialCoalescing - If a simple interval is defined by a copy, try
452 /// allocate the definition the same register as the source register if the
453 /// register is not defined during live time of the interval. If the interval is
454 /// killed by a copy, try to use the destination register. This eliminates a
455 /// copy. This is used to coalesce copies which were not coalesced away before
456 /// allocation either due to dest and src being in different register classes or
457 /// because the coalescer was overly conservative.
458 unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
459   unsigned Preference = vrm_->getRegAllocPref(cur.reg);
460   if ((Preference && Preference == Reg) || !cur.containsOneValue())
461     return Reg;
462
463   // We cannot handle complicated live ranges. Simple linear stuff only.
464   if (cur.ranges.size() != 1)
465     return Reg;
466
467   const LiveRange &range = cur.ranges.front();
468
469   VNInfo *vni = range.valno;
470   if (vni->isUnused() || !vni->def.isValid())
471     return Reg;
472
473   unsigned CandReg;
474   {
475     MachineInstr *CopyMI;
476     if ((CopyMI = li_->getInstructionFromIndex(vni->def)) && CopyMI->isCopy())
477       // Defined by a copy, try to extend SrcReg forward
478       CandReg = CopyMI->getOperand(1).getReg();
479     else if (TrivCoalesceEnds &&
480             (CopyMI = li_->getInstructionFromIndex(range.end.getBaseIndex())) &&
481              CopyMI->isCopy() && cur.reg == CopyMI->getOperand(1).getReg())
482       // Only used by a copy, try to extend DstReg backwards
483       CandReg = CopyMI->getOperand(0).getReg();
484     else
485       return Reg;
486
487     // If the target of the copy is a sub-register then don't coalesce.
488     if(CopyMI->getOperand(0).getSubReg())
489       return Reg;
490   }
491
492   if (TargetRegisterInfo::isVirtualRegister(CandReg)) {
493     if (!vrm_->isAssignedReg(CandReg))
494       return Reg;
495     CandReg = vrm_->getPhys(CandReg);
496   }
497   if (Reg == CandReg)
498     return Reg;
499
500   const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
501   if (!RC->contains(CandReg))
502     return Reg;
503
504   if (li_->conflictsWithPhysReg(cur, *vrm_, CandReg))
505     return Reg;
506
507   // Try to coalesce.
508   DEBUG(dbgs() << "Coalescing: " << cur << " -> " << tri_->getName(CandReg)
509         << '\n');
510   vrm_->clearVirt(cur.reg);
511   vrm_->assignVirt2Phys(cur.reg, CandReg);
512
513   ++NumCoalesce;
514   return CandReg;
515 }
516
517 bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
518   mf_ = &fn;
519   mri_ = &fn.getRegInfo();
520   tm_ = &fn.getTarget();
521   tri_ = tm_->getRegisterInfo();
522   tii_ = tm_->getInstrInfo();
523   allocatableRegs_ = tri_->getAllocatableSet(fn);
524   reservedRegs_ = tri_->getReservedRegs(fn);
525   li_ = &getAnalysis<LiveIntervals>();
526   loopInfo = &getAnalysis<MachineLoopInfo>();
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   if (!minReg || SpillWeights[minReg] == HUGE_VALF)
1170     for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
1171            e = RC->allocation_order_end(*mf_); i != e; ++i) {
1172       unsigned reg = *i;
1173       float regWeight = SpillWeights[reg];
1174       // Don't even consider reserved regs.
1175       if (reservedRegs_.test(reg))
1176         continue;
1177       // Skip recently allocated registers and reserved registers.
1178       if (minWeight > regWeight && !isRecentlyUsed(reg))
1179         Found = true;
1180       RegsWeights.push_back(std::make_pair(reg, regWeight));
1181     }
1182
1183   // If we didn't find a register that is spillable, try aliases?
1184   if (!Found) {
1185     for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
1186            e = RC->allocation_order_end(*mf_); i != e; ++i) {
1187       unsigned reg = *i;
1188       if (reservedRegs_.test(reg))
1189         continue;
1190       // No need to worry about if the alias register size < regsize of RC.
1191       // We are going to spill all registers that alias it anyway.
1192       for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
1193         RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
1194     }
1195   }
1196
1197   // Sort all potential spill candidates by weight.
1198   std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare(*this));
1199   minReg = RegsWeights[0].first;
1200   minWeight = RegsWeights[0].second;
1201   if (minWeight == HUGE_VALF) {
1202     // All registers must have inf weight. Just grab one!
1203     minReg = BestPhysReg ? BestPhysReg : getFirstNonReservedPhysReg(RC);
1204     if (cur->weight == HUGE_VALF ||
1205         li_->getApproximateInstructionCount(*cur) == 0) {
1206       // Spill a physical register around defs and uses.
1207       if (li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_)) {
1208         // spillPhysRegAroundRegDefsUses may have invalidated iterator stored
1209         // in fixed_. Reset them.
1210         for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1211           IntervalPtr &IP = fixed_[i];
1212           LiveInterval *I = IP.first;
1213           if (I->reg == minReg || tri_->isSubRegister(minReg, I->reg))
1214             IP.second = I->advanceTo(I->begin(), StartPosition);
1215         }
1216
1217         DowngradedRegs.clear();
1218         assignRegOrStackSlotAtInterval(cur);
1219       } else {
1220         assert(false && "Ran out of registers during register allocation!");
1221         report_fatal_error("Ran out of registers during register allocation!");
1222       }
1223       return;
1224     }
1225   }
1226
1227   // Find up to 3 registers to consider as spill candidates.
1228   unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
1229   while (LastCandidate > 1) {
1230     if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
1231       break;
1232     --LastCandidate;
1233   }
1234
1235   DEBUG({
1236       dbgs() << "\t\tregister(s) with min weight(s): ";
1237
1238       for (unsigned i = 0; i != LastCandidate; ++i)
1239         dbgs() << tri_->getName(RegsWeights[i].first)
1240                << " (" << RegsWeights[i].second << ")\n";
1241     });
1242
1243   // If the current has the minimum weight, we need to spill it and
1244   // add any added intervals back to unhandled, and restart
1245   // linearscan.
1246   if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
1247     DEBUG(dbgs() << "\t\t\tspilling(c): " << *cur << '\n');
1248     SmallVector<LiveInterval*, 8> added;
1249     LiveRangeEdit LRE(*cur, added);
1250     spiller_->spill(LRE);
1251
1252     std::sort(added.begin(), added.end(), LISorter());
1253     if (added.empty())
1254       return;  // Early exit if all spills were folded.
1255
1256     // Merge added with unhandled.  Note that we have already sorted
1257     // intervals returned by addIntervalsForSpills by their starting
1258     // point.
1259     // This also update the NextReloadMap. That is, it adds mapping from a
1260     // register defined by a reload from SS to the next reload from SS in the
1261     // same basic block.
1262     MachineBasicBlock *LastReloadMBB = 0;
1263     LiveInterval *LastReload = 0;
1264     int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1265     for (unsigned i = 0, e = added.size(); i != e; ++i) {
1266       LiveInterval *ReloadLi = added[i];
1267       if (ReloadLi->weight == HUGE_VALF &&
1268           li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1269         SlotIndex ReloadIdx = ReloadLi->beginIndex();
1270         MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1271         int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1272         if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1273           // Last reload of same SS is in the same MBB. We want to try to
1274           // allocate both reloads the same register and make sure the reg
1275           // isn't clobbered in between if at all possible.
1276           assert(LastReload->beginIndex() < ReloadIdx);
1277           NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1278         }
1279         LastReloadMBB = ReloadMBB;
1280         LastReload = ReloadLi;
1281         LastReloadSS = ReloadSS;
1282       }
1283       unhandled_.push(ReloadLi);
1284     }
1285     return;
1286   }
1287
1288   ++NumBacktracks;
1289
1290   // Push the current interval back to unhandled since we are going
1291   // to re-run at least this iteration. Since we didn't modify it it
1292   // should go back right in the front of the list
1293   unhandled_.push(cur);
1294
1295   assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
1296          "did not choose a register to spill?");
1297
1298   // We spill all intervals aliasing the register with
1299   // minimum weight, rollback to the interval with the earliest
1300   // start point and let the linear scan algorithm run again
1301   SmallVector<LiveInterval*, 8> spillIs;
1302
1303   // Determine which intervals have to be spilled.
1304   findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
1305
1306   // Set of spilled vregs (used later to rollback properly)
1307   SmallSet<unsigned, 8> spilled;
1308
1309   // The earliest start of a Spilled interval indicates up to where
1310   // in handled we need to roll back
1311   assert(!spillIs.empty() && "No spill intervals?");
1312   SlotIndex earliestStart = spillIs[0]->beginIndex();
1313
1314   // Spill live intervals of virtual regs mapped to the physical register we
1315   // want to clear (and its aliases).  We only spill those that overlap with the
1316   // current interval as the rest do not affect its allocation. we also keep
1317   // track of the earliest start of all spilled live intervals since this will
1318   // mark our rollback point.
1319   SmallVector<LiveInterval*, 8> added;
1320   while (!spillIs.empty()) {
1321     LiveInterval *sli = spillIs.back();
1322     spillIs.pop_back();
1323     DEBUG(dbgs() << "\t\t\tspilling(a): " << *sli << '\n');
1324     if (sli->beginIndex() < earliestStart)
1325       earliestStart = sli->beginIndex();
1326     LiveRangeEdit LRE(*sli, added, 0, &spillIs);
1327     spiller_->spill(LRE);
1328     spilled.insert(sli->reg);
1329   }
1330
1331   // Include any added intervals in earliestStart.
1332   for (unsigned i = 0, e = added.size(); i != e; ++i) {
1333     SlotIndex SI = added[i]->beginIndex();
1334     if (SI < earliestStart)
1335       earliestStart = SI;
1336   }
1337
1338   DEBUG(dbgs() << "\t\trolling back to: " << earliestStart << '\n');
1339
1340   // Scan handled in reverse order up to the earliest start of a
1341   // spilled live interval and undo each one, restoring the state of
1342   // unhandled.
1343   while (!handled_.empty()) {
1344     LiveInterval* i = handled_.back();
1345     // If this interval starts before t we are done.
1346     if (!i->empty() && i->beginIndex() < earliestStart)
1347       break;
1348     DEBUG(dbgs() << "\t\t\tundo changes for: " << *i << '\n');
1349     handled_.pop_back();
1350
1351     // When undoing a live interval allocation we must know if it is active or
1352     // inactive to properly update regUse_ and the VirtRegMap.
1353     IntervalPtrs::iterator it;
1354     if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
1355       active_.erase(it);
1356       assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
1357       if (!spilled.count(i->reg))
1358         unhandled_.push(i);
1359       delRegUse(vrm_->getPhys(i->reg));
1360       vrm_->clearVirt(i->reg);
1361     } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
1362       inactive_.erase(it);
1363       assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
1364       if (!spilled.count(i->reg))
1365         unhandled_.push(i);
1366       vrm_->clearVirt(i->reg);
1367     } else {
1368       assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
1369              "Can only allocate virtual registers!");
1370       vrm_->clearVirt(i->reg);
1371       unhandled_.push(i);
1372     }
1373
1374     DenseMap<unsigned, unsigned>::iterator ii = DowngradeMap.find(i->reg);
1375     if (ii == DowngradeMap.end())
1376       // It interval has a preference, it must be defined by a copy. Clear the
1377       // preference now since the source interval allocation may have been
1378       // undone as well.
1379       mri_->setRegAllocationHint(i->reg, 0, 0);
1380     else {
1381       UpgradeRegister(ii->second);
1382     }
1383   }
1384
1385   // Rewind the iterators in the active, inactive, and fixed lists back to the
1386   // point we reverted to.
1387   RevertVectorIteratorsTo(active_, earliestStart);
1388   RevertVectorIteratorsTo(inactive_, earliestStart);
1389   RevertVectorIteratorsTo(fixed_, earliestStart);
1390
1391   // Scan the rest and undo each interval that expired after t and
1392   // insert it in active (the next iteration of the algorithm will
1393   // put it in inactive if required)
1394   for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
1395     LiveInterval *HI = handled_[i];
1396     if (!HI->expiredAt(earliestStart) &&
1397         HI->expiredAt(cur->beginIndex())) {
1398       DEBUG(dbgs() << "\t\t\tundo changes for: " << *HI << '\n');
1399       active_.push_back(std::make_pair(HI, HI->begin()));
1400       assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
1401       addRegUse(vrm_->getPhys(HI->reg));
1402     }
1403   }
1404
1405   // Merge added with unhandled.
1406   // This also update the NextReloadMap. That is, it adds mapping from a
1407   // register defined by a reload from SS to the next reload from SS in the
1408   // same basic block.
1409   MachineBasicBlock *LastReloadMBB = 0;
1410   LiveInterval *LastReload = 0;
1411   int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1412   std::sort(added.begin(), added.end(), LISorter());
1413   for (unsigned i = 0, e = added.size(); i != e; ++i) {
1414     LiveInterval *ReloadLi = added[i];
1415     if (ReloadLi->weight == HUGE_VALF &&
1416         li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1417       SlotIndex ReloadIdx = ReloadLi->beginIndex();
1418       MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1419       int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1420       if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1421         // Last reload of same SS is in the same MBB. We want to try to
1422         // allocate both reloads the same register and make sure the reg
1423         // isn't clobbered in between if at all possible.
1424         assert(LastReload->beginIndex() < ReloadIdx);
1425         NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1426       }
1427       LastReloadMBB = ReloadMBB;
1428       LastReload = ReloadLi;
1429       LastReloadSS = ReloadSS;
1430     }
1431     unhandled_.push(ReloadLi);
1432   }
1433 }
1434
1435 unsigned RALinScan::getFreePhysReg(LiveInterval* cur,
1436                                    const TargetRegisterClass *RC,
1437                                    unsigned MaxInactiveCount,
1438                                    SmallVector<unsigned, 256> &inactiveCounts,
1439                                    bool SkipDGRegs) {
1440   unsigned FreeReg = 0;
1441   unsigned FreeRegInactiveCount = 0;
1442
1443   std::pair<unsigned, unsigned> Hint = mri_->getRegAllocationHint(cur->reg);
1444   // Resolve second part of the hint (if possible) given the current allocation.
1445   unsigned physReg = Hint.second;
1446   if (TargetRegisterInfo::isVirtualRegister(physReg) && vrm_->hasPhys(physReg))
1447     physReg = vrm_->getPhys(physReg);
1448
1449   TargetRegisterClass::iterator I, E;
1450   tie(I, E) = tri_->getAllocationOrder(RC, Hint.first, physReg, *mf_);
1451   assert(I != E && "No allocatable register in this register class!");
1452
1453   // Scan for the first available register.
1454   for (; I != E; ++I) {
1455     unsigned Reg = *I;
1456     // Ignore "downgraded" registers.
1457     if (SkipDGRegs && DowngradedRegs.count(Reg))
1458       continue;
1459     // Skip reserved registers.
1460     if (reservedRegs_.test(Reg))
1461       continue;
1462     // Skip recently allocated registers.
1463     if (isRegAvail(Reg) && (!SkipDGRegs || !isRecentlyUsed(Reg))) {
1464       FreeReg = Reg;
1465       if (FreeReg < inactiveCounts.size())
1466         FreeRegInactiveCount = inactiveCounts[FreeReg];
1467       else
1468         FreeRegInactiveCount = 0;
1469       break;
1470     }
1471   }
1472
1473   // If there are no free regs, or if this reg has the max inactive count,
1474   // return this register.
1475   if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) {
1476     // Remember what register we picked so we can skip it next time.
1477     if (FreeReg != 0) recordRecentlyUsed(FreeReg);
1478     return FreeReg;
1479   }
1480
1481   // Continue scanning the registers, looking for the one with the highest
1482   // inactive count.  Alkis found that this reduced register pressure very
1483   // slightly on X86 (in rev 1.94 of this file), though this should probably be
1484   // reevaluated now.
1485   for (; I != E; ++I) {
1486     unsigned Reg = *I;
1487     // Ignore "downgraded" registers.
1488     if (SkipDGRegs && DowngradedRegs.count(Reg))
1489       continue;
1490     // Skip reserved registers.
1491     if (reservedRegs_.test(Reg))
1492       continue;
1493     if (isRegAvail(Reg) && Reg < inactiveCounts.size() &&
1494         FreeRegInactiveCount < inactiveCounts[Reg] &&
1495         (!SkipDGRegs || !isRecentlyUsed(Reg))) {
1496       FreeReg = Reg;
1497       FreeRegInactiveCount = inactiveCounts[Reg];
1498       if (FreeRegInactiveCount == MaxInactiveCount)
1499         break;    // We found the one with the max inactive count.
1500     }
1501   }
1502
1503   // Remember what register we picked so we can skip it next time.
1504   recordRecentlyUsed(FreeReg);
1505
1506   return FreeReg;
1507 }
1508
1509 /// getFreePhysReg - return a free physical register for this virtual register
1510 /// interval if we have one, otherwise return 0.
1511 unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
1512   SmallVector<unsigned, 256> inactiveCounts;
1513   unsigned MaxInactiveCount = 0;
1514
1515   const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
1516   const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1517
1518   for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1519        i != e; ++i) {
1520     unsigned reg = i->first->reg;
1521     assert(TargetRegisterInfo::isVirtualRegister(reg) &&
1522            "Can only allocate virtual registers!");
1523
1524     // If this is not in a related reg class to the register we're allocating,
1525     // don't check it.
1526     const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
1527     if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1528       reg = vrm_->getPhys(reg);
1529       if (inactiveCounts.size() <= reg)
1530         inactiveCounts.resize(reg+1);
1531       ++inactiveCounts[reg];
1532       MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1533     }
1534   }
1535
1536   // If copy coalescer has assigned a "preferred" register, check if it's
1537   // available first.
1538   unsigned Preference = vrm_->getRegAllocPref(cur->reg);
1539   if (Preference) {
1540     DEBUG(dbgs() << "(preferred: " << tri_->getName(Preference) << ") ");
1541     if (isRegAvail(Preference) &&
1542         RC->contains(Preference))
1543       return Preference;
1544   }
1545
1546   unsigned FreeReg = getFreePhysReg(cur, RC, MaxInactiveCount, inactiveCounts,
1547                                     true);
1548   if (FreeReg)
1549     return FreeReg;
1550   return getFreePhysReg(cur, RC, MaxInactiveCount, inactiveCounts, false);
1551 }
1552
1553 FunctionPass* llvm::createLinearScanRegisterAllocator() {
1554   return new RALinScan();
1555 }