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