Add a memset loop that LoopIdiomRecognize doesn't recognize.
[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   for (const unsigned *AS = tri_->getOverlaps(Reg); *AS; ++AS) {
937     bool isNew = DowngradedRegs.insert(*AS);
938     (void)isNew; // Silence compiler warning.
939     assert(isNew && "Multiple reloads holding the same register?");
940     DowngradeMap.insert(std::make_pair(li->reg, *AS));
941   }
942   ++NumDowngrade;
943 }
944
945 void RALinScan::UpgradeRegister(unsigned Reg) {
946   if (Reg) {
947     DowngradedRegs.erase(Reg);
948     for (const unsigned *AS = tri_->getAliasSet(Reg); *AS; ++AS)
949       DowngradedRegs.erase(*AS);
950   }
951 }
952
953 namespace {
954   struct LISorter {
955     bool operator()(LiveInterval* A, LiveInterval* B) {
956       return A->beginIndex() < B->beginIndex();
957     }
958   };
959 }
960
961 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
962 /// spill.
963 void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur) {
964   const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
965   DEBUG(dbgs() << "\tallocating current interval from "
966                << RC->getName() << ": ");
967
968   // This is an implicitly defined live interval, just assign any register.
969   if (cur->empty()) {
970     unsigned physReg = vrm_->getRegAllocPref(cur->reg);
971     if (!physReg)
972       physReg = getFirstNonReservedPhysReg(RC);
973     DEBUG(dbgs() <<  tri_->getName(physReg) << '\n');
974     // Note the register is not really in use.
975     vrm_->assignVirt2Phys(cur->reg, physReg);
976     return;
977   }
978
979   backUpRegUses();
980
981   std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
982   SlotIndex StartPosition = cur->beginIndex();
983   const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
984
985   // If start of this live interval is defined by a move instruction and its
986   // source is assigned a physical register that is compatible with the target
987   // register class, then we should try to assign it the same register.
988   // This can happen when the move is from a larger register class to a smaller
989   // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
990   if (!vrm_->getRegAllocPref(cur->reg) && cur->hasAtLeastOneValue()) {
991     VNInfo *vni = cur->begin()->valno;
992     if (!vni->isUnused()) {
993       MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
994       if (CopyMI && CopyMI->isCopy()) {
995         unsigned DstSubReg = CopyMI->getOperand(0).getSubReg();
996         unsigned SrcReg = CopyMI->getOperand(1).getReg();
997         unsigned SrcSubReg = CopyMI->getOperand(1).getSubReg();
998         unsigned Reg = 0;
999         if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
1000           Reg = SrcReg;
1001         else if (vrm_->isAssignedReg(SrcReg))
1002           Reg = vrm_->getPhys(SrcReg);
1003         if (Reg) {
1004           if (SrcSubReg)
1005             Reg = tri_->getSubReg(Reg, SrcSubReg);
1006           if (DstSubReg)
1007             Reg = tri_->getMatchingSuperReg(Reg, DstSubReg, RC);
1008           if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
1009             mri_->setRegAllocationHint(cur->reg, 0, Reg);
1010         }
1011       }
1012     }
1013   }
1014
1015   // For every interval in inactive we overlap with, mark the
1016   // register as not free and update spill weights.
1017   for (IntervalPtrs::const_iterator i = inactive_.begin(),
1018          e = inactive_.end(); i != e; ++i) {
1019     unsigned Reg = i->first->reg;
1020     assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
1021            "Can only allocate virtual registers!");
1022     const TargetRegisterClass *RegRC = mri_->getRegClass(Reg);
1023     // If this is not in a related reg class to the register we're allocating,
1024     // don't check it.
1025     if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
1026         cur->overlapsFrom(*i->first, i->second-1)) {
1027       Reg = vrm_->getPhys(Reg);
1028       addRegUse(Reg);
1029       SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
1030     }
1031   }
1032
1033   // Speculatively check to see if we can get a register right now.  If not,
1034   // we know we won't be able to by adding more constraints.  If so, we can
1035   // check to see if it is valid.  Doing an exhaustive search of the fixed_ list
1036   // is very bad (it contains all callee clobbered registers for any functions
1037   // with a call), so we want to avoid doing that if possible.
1038   unsigned physReg = getFreePhysReg(cur);
1039   unsigned BestPhysReg = physReg;
1040   if (physReg) {
1041     // We got a register.  However, if it's in the fixed_ list, we might
1042     // conflict with it.  Check to see if we conflict with it or any of its
1043     // aliases.
1044     SmallSet<unsigned, 8> RegAliases;
1045     for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
1046       RegAliases.insert(*AS);
1047
1048     bool ConflictsWithFixed = false;
1049     for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1050       IntervalPtr &IP = fixed_[i];
1051       if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
1052         // Okay, this reg is on the fixed list.  Check to see if we actually
1053         // conflict.
1054         LiveInterval *I = IP.first;
1055         if (I->endIndex() > StartPosition) {
1056           LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
1057           IP.second = II;
1058           if (II != I->begin() && II->start > StartPosition)
1059             --II;
1060           if (cur->overlapsFrom(*I, II)) {
1061             ConflictsWithFixed = true;
1062             break;
1063           }
1064         }
1065       }
1066     }
1067
1068     // Okay, the register picked by our speculative getFreePhysReg call turned
1069     // out to be in use.  Actually add all of the conflicting fixed registers to
1070     // regUse_ so we can do an accurate query.
1071     if (ConflictsWithFixed) {
1072       // For every interval in fixed we overlap with, mark the register as not
1073       // free and update spill weights.
1074       for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1075         IntervalPtr &IP = fixed_[i];
1076         LiveInterval *I = IP.first;
1077
1078         const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
1079         if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
1080             I->endIndex() > StartPosition) {
1081           LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
1082           IP.second = II;
1083           if (II != I->begin() && II->start > StartPosition)
1084             --II;
1085           if (cur->overlapsFrom(*I, II)) {
1086             unsigned reg = I->reg;
1087             addRegUse(reg);
1088             SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
1089           }
1090         }
1091       }
1092
1093       // Using the newly updated regUse_ object, which includes conflicts in the
1094       // future, see if there are any registers available.
1095       physReg = getFreePhysReg(cur);
1096     }
1097   }
1098
1099   // Restore the physical register tracker, removing information about the
1100   // future.
1101   restoreRegUses();
1102
1103   // If we find a free register, we are done: assign this virtual to
1104   // the free physical register and add this interval to the active
1105   // list.
1106   if (physReg) {
1107     DEBUG(dbgs() <<  tri_->getName(physReg) << '\n');
1108     vrm_->assignVirt2Phys(cur->reg, physReg);
1109     addRegUse(physReg);
1110     active_.push_back(std::make_pair(cur, cur->begin()));
1111     handled_.push_back(cur);
1112
1113     // "Upgrade" the physical register since it has been allocated.
1114     UpgradeRegister(physReg);
1115     if (LiveInterval *NextReloadLI = hasNextReloadInterval(cur)) {
1116       // "Downgrade" physReg to try to keep physReg from being allocated until
1117       // the next reload from the same SS is allocated.
1118       mri_->setRegAllocationHint(NextReloadLI->reg, 0, physReg);
1119       DowngradeRegister(cur, physReg);
1120     }
1121     return;
1122   }
1123   DEBUG(dbgs() << "no free registers\n");
1124
1125   // Compile the spill weights into an array that is better for scanning.
1126   std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
1127   for (std::vector<std::pair<unsigned, float> >::iterator
1128        I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
1129     updateSpillWeights(SpillWeights, I->first, I->second, RC);
1130
1131   // for each interval in active, update spill weights.
1132   for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
1133        i != e; ++i) {
1134     unsigned reg = i->first->reg;
1135     assert(TargetRegisterInfo::isVirtualRegister(reg) &&
1136            "Can only allocate virtual registers!");
1137     reg = vrm_->getPhys(reg);
1138     updateSpillWeights(SpillWeights, reg, i->first->weight, RC);
1139   }
1140
1141   DEBUG(dbgs() << "\tassigning stack slot at interval "<< *cur << ":\n");
1142
1143   // Find a register to spill.
1144   float minWeight = HUGE_VALF;
1145   unsigned minReg = 0;
1146
1147   bool Found = false;
1148   std::vector<std::pair<unsigned,float> > RegsWeights;
1149   if (!minReg || SpillWeights[minReg] == HUGE_VALF)
1150     for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
1151            e = RC->allocation_order_end(*mf_); i != e; ++i) {
1152       unsigned reg = *i;
1153       float regWeight = SpillWeights[reg];
1154       // Don't even consider reserved regs.
1155       if (reservedRegs_.test(reg))
1156         continue;
1157       // Skip recently allocated registers and reserved registers.
1158       if (minWeight > regWeight && !isRecentlyUsed(reg))
1159         Found = true;
1160       RegsWeights.push_back(std::make_pair(reg, regWeight));
1161     }
1162
1163   // If we didn't find a register that is spillable, try aliases?
1164   if (!Found) {
1165     for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
1166            e = RC->allocation_order_end(*mf_); i != e; ++i) {
1167       unsigned reg = *i;
1168       if (reservedRegs_.test(reg))
1169         continue;
1170       // No need to worry about if the alias register size < regsize of RC.
1171       // We are going to spill all registers that alias it anyway.
1172       for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
1173         RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
1174     }
1175   }
1176
1177   // Sort all potential spill candidates by weight.
1178   std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare(*this));
1179   minReg = RegsWeights[0].first;
1180   minWeight = RegsWeights[0].second;
1181   if (minWeight == HUGE_VALF) {
1182     // All registers must have inf weight. Just grab one!
1183     minReg = BestPhysReg ? BestPhysReg : getFirstNonReservedPhysReg(RC);
1184     if (cur->weight == HUGE_VALF ||
1185         li_->getApproximateInstructionCount(*cur) == 0) {
1186       // Spill a physical register around defs and uses.
1187       if (li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_)) {
1188         // spillPhysRegAroundRegDefsUses may have invalidated iterator stored
1189         // in fixed_. Reset them.
1190         for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
1191           IntervalPtr &IP = fixed_[i];
1192           LiveInterval *I = IP.first;
1193           if (I->reg == minReg || tri_->isSubRegister(minReg, I->reg))
1194             IP.second = I->advanceTo(I->begin(), StartPosition);
1195         }
1196
1197         DowngradedRegs.clear();
1198         assignRegOrStackSlotAtInterval(cur);
1199       } else {
1200         assert(false && "Ran out of registers during register allocation!");
1201         report_fatal_error("Ran out of registers during register allocation!");
1202       }
1203       return;
1204     }
1205   }
1206
1207   // Find up to 3 registers to consider as spill candidates.
1208   unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
1209   while (LastCandidate > 1) {
1210     if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
1211       break;
1212     --LastCandidate;
1213   }
1214
1215   DEBUG({
1216       dbgs() << "\t\tregister(s) with min weight(s): ";
1217
1218       for (unsigned i = 0; i != LastCandidate; ++i)
1219         dbgs() << tri_->getName(RegsWeights[i].first)
1220                << " (" << RegsWeights[i].second << ")\n";
1221     });
1222
1223   // If the current has the minimum weight, we need to spill it and
1224   // add any added intervals back to unhandled, and restart
1225   // linearscan.
1226   if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
1227     DEBUG(dbgs() << "\t\t\tspilling(c): " << *cur << '\n');
1228     SmallVector<LiveInterval*, 8> spillIs, added;
1229     spiller_->spill(cur, added, spillIs);
1230
1231     std::sort(added.begin(), added.end(), LISorter());
1232     if (added.empty())
1233       return;  // Early exit if all spills were folded.
1234
1235     // Merge added with unhandled.  Note that we have already sorted
1236     // intervals returned by addIntervalsForSpills by their starting
1237     // point.
1238     // This also update the NextReloadMap. That is, it adds mapping from a
1239     // register defined by a reload from SS to the next reload from SS in the
1240     // same basic block.
1241     MachineBasicBlock *LastReloadMBB = 0;
1242     LiveInterval *LastReload = 0;
1243     int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1244     for (unsigned i = 0, e = added.size(); i != e; ++i) {
1245       LiveInterval *ReloadLi = added[i];
1246       if (ReloadLi->weight == HUGE_VALF &&
1247           li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1248         SlotIndex ReloadIdx = ReloadLi->beginIndex();
1249         MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1250         int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1251         if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1252           // Last reload of same SS is in the same MBB. We want to try to
1253           // allocate both reloads the same register and make sure the reg
1254           // isn't clobbered in between if at all possible.
1255           assert(LastReload->beginIndex() < ReloadIdx);
1256           NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1257         }
1258         LastReloadMBB = ReloadMBB;
1259         LastReload = ReloadLi;
1260         LastReloadSS = ReloadSS;
1261       }
1262       unhandled_.push(ReloadLi);
1263     }
1264     return;
1265   }
1266
1267   ++NumBacktracks;
1268
1269   // Push the current interval back to unhandled since we are going
1270   // to re-run at least this iteration. Since we didn't modify it it
1271   // should go back right in the front of the list
1272   unhandled_.push(cur);
1273
1274   assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
1275          "did not choose a register to spill?");
1276
1277   // We spill all intervals aliasing the register with
1278   // minimum weight, rollback to the interval with the earliest
1279   // start point and let the linear scan algorithm run again
1280   SmallVector<LiveInterval*, 8> spillIs;
1281
1282   // Determine which intervals have to be spilled.
1283   findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
1284
1285   // Set of spilled vregs (used later to rollback properly)
1286   SmallSet<unsigned, 8> spilled;
1287
1288   // The earliest start of a Spilled interval indicates up to where
1289   // in handled we need to roll back
1290   assert(!spillIs.empty() && "No spill intervals?");
1291   SlotIndex earliestStart = spillIs[0]->beginIndex();
1292
1293   // Spill live intervals of virtual regs mapped to the physical register we
1294   // want to clear (and its aliases).  We only spill those that overlap with the
1295   // current interval as the rest do not affect its allocation. we also keep
1296   // track of the earliest start of all spilled live intervals since this will
1297   // mark our rollback point.
1298   SmallVector<LiveInterval*, 8> added;
1299   while (!spillIs.empty()) {
1300     LiveInterval *sli = spillIs.back();
1301     spillIs.pop_back();
1302     DEBUG(dbgs() << "\t\t\tspilling(a): " << *sli << '\n');
1303     if (sli->beginIndex() < earliestStart)
1304       earliestStart = sli->beginIndex();
1305     spiller_->spill(sli, added, spillIs);
1306     spilled.insert(sli->reg);
1307   }
1308
1309   // Include any added intervals in earliestStart.
1310   for (unsigned i = 0, e = added.size(); i != e; ++i) {
1311     SlotIndex SI = added[i]->beginIndex();
1312     if (SI < earliestStart)
1313       earliestStart = SI;
1314   }
1315
1316   DEBUG(dbgs() << "\t\trolling back to: " << earliestStart << '\n');
1317
1318   // Scan handled in reverse order up to the earliest start of a
1319   // spilled live interval and undo each one, restoring the state of
1320   // unhandled.
1321   while (!handled_.empty()) {
1322     LiveInterval* i = handled_.back();
1323     // If this interval starts before t we are done.
1324     if (!i->empty() && i->beginIndex() < earliestStart)
1325       break;
1326     DEBUG(dbgs() << "\t\t\tundo changes for: " << *i << '\n');
1327     handled_.pop_back();
1328
1329     // When undoing a live interval allocation we must know if it is active or
1330     // inactive to properly update regUse_ and the VirtRegMap.
1331     IntervalPtrs::iterator it;
1332     if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
1333       active_.erase(it);
1334       assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
1335       if (!spilled.count(i->reg))
1336         unhandled_.push(i);
1337       delRegUse(vrm_->getPhys(i->reg));
1338       vrm_->clearVirt(i->reg);
1339     } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
1340       inactive_.erase(it);
1341       assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
1342       if (!spilled.count(i->reg))
1343         unhandled_.push(i);
1344       vrm_->clearVirt(i->reg);
1345     } else {
1346       assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
1347              "Can only allocate virtual registers!");
1348       vrm_->clearVirt(i->reg);
1349       unhandled_.push(i);
1350     }
1351
1352     DenseMap<unsigned, unsigned>::iterator ii = DowngradeMap.find(i->reg);
1353     if (ii == DowngradeMap.end())
1354       // It interval has a preference, it must be defined by a copy. Clear the
1355       // preference now since the source interval allocation may have been
1356       // undone as well.
1357       mri_->setRegAllocationHint(i->reg, 0, 0);
1358     else {
1359       UpgradeRegister(ii->second);
1360     }
1361   }
1362
1363   // Rewind the iterators in the active, inactive, and fixed lists back to the
1364   // point we reverted to.
1365   RevertVectorIteratorsTo(active_, earliestStart);
1366   RevertVectorIteratorsTo(inactive_, earliestStart);
1367   RevertVectorIteratorsTo(fixed_, earliestStart);
1368
1369   // Scan the rest and undo each interval that expired after t and
1370   // insert it in active (the next iteration of the algorithm will
1371   // put it in inactive if required)
1372   for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
1373     LiveInterval *HI = handled_[i];
1374     if (!HI->expiredAt(earliestStart) &&
1375         HI->expiredAt(cur->beginIndex())) {
1376       DEBUG(dbgs() << "\t\t\tundo changes for: " << *HI << '\n');
1377       active_.push_back(std::make_pair(HI, HI->begin()));
1378       assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
1379       addRegUse(vrm_->getPhys(HI->reg));
1380     }
1381   }
1382
1383   // Merge added with unhandled.
1384   // This also update the NextReloadMap. That is, it adds mapping from a
1385   // register defined by a reload from SS to the next reload from SS in the
1386   // same basic block.
1387   MachineBasicBlock *LastReloadMBB = 0;
1388   LiveInterval *LastReload = 0;
1389   int LastReloadSS = VirtRegMap::NO_STACK_SLOT;
1390   std::sort(added.begin(), added.end(), LISorter());
1391   for (unsigned i = 0, e = added.size(); i != e; ++i) {
1392     LiveInterval *ReloadLi = added[i];
1393     if (ReloadLi->weight == HUGE_VALF &&
1394         li_->getApproximateInstructionCount(*ReloadLi) == 0) {
1395       SlotIndex ReloadIdx = ReloadLi->beginIndex();
1396       MachineBasicBlock *ReloadMBB = li_->getMBBFromIndex(ReloadIdx);
1397       int ReloadSS = vrm_->getStackSlot(ReloadLi->reg);
1398       if (LastReloadMBB == ReloadMBB && LastReloadSS == ReloadSS) {
1399         // Last reload of same SS is in the same MBB. We want to try to
1400         // allocate both reloads the same register and make sure the reg
1401         // isn't clobbered in between if at all possible.
1402         assert(LastReload->beginIndex() < ReloadIdx);
1403         NextReloadMap.insert(std::make_pair(LastReload->reg, ReloadLi->reg));
1404       }
1405       LastReloadMBB = ReloadMBB;
1406       LastReload = ReloadLi;
1407       LastReloadSS = ReloadSS;
1408     }
1409     unhandled_.push(ReloadLi);
1410   }
1411 }
1412
1413 unsigned RALinScan::getFreePhysReg(LiveInterval* cur,
1414                                    const TargetRegisterClass *RC,
1415                                    unsigned MaxInactiveCount,
1416                                    SmallVector<unsigned, 256> &inactiveCounts,
1417                                    bool SkipDGRegs) {
1418   unsigned FreeReg = 0;
1419   unsigned FreeRegInactiveCount = 0;
1420
1421   std::pair<unsigned, unsigned> Hint = mri_->getRegAllocationHint(cur->reg);
1422   // Resolve second part of the hint (if possible) given the current allocation.
1423   unsigned physReg = Hint.second;
1424   if (TargetRegisterInfo::isVirtualRegister(physReg) && vrm_->hasPhys(physReg))
1425     physReg = vrm_->getPhys(physReg);
1426
1427   TargetRegisterClass::iterator I, E;
1428   tie(I, E) = tri_->getAllocationOrder(RC, Hint.first, physReg, *mf_);
1429   assert(I != E && "No allocatable register in this register class!");
1430
1431   // Scan for the first available register.
1432   for (; I != E; ++I) {
1433     unsigned Reg = *I;
1434     // Ignore "downgraded" registers.
1435     if (SkipDGRegs && DowngradedRegs.count(Reg))
1436       continue;
1437     // Skip reserved registers.
1438     if (reservedRegs_.test(Reg))
1439       continue;
1440     // Skip recently allocated registers.
1441     if (isRegAvail(Reg) && !isRecentlyUsed(Reg)) {
1442       FreeReg = Reg;
1443       if (FreeReg < inactiveCounts.size())
1444         FreeRegInactiveCount = inactiveCounts[FreeReg];
1445       else
1446         FreeRegInactiveCount = 0;
1447       break;
1448     }
1449   }
1450
1451   // If there are no free regs, or if this reg has the max inactive count,
1452   // return this register.
1453   if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) {
1454     // Remember what register we picked so we can skip it next time.
1455     if (FreeReg != 0) recordRecentlyUsed(FreeReg);
1456     return FreeReg;
1457   }
1458
1459   // Continue scanning the registers, looking for the one with the highest
1460   // inactive count.  Alkis found that this reduced register pressure very
1461   // slightly on X86 (in rev 1.94 of this file), though this should probably be
1462   // reevaluated now.
1463   for (; I != E; ++I) {
1464     unsigned Reg = *I;
1465     // Ignore "downgraded" registers.
1466     if (SkipDGRegs && DowngradedRegs.count(Reg))
1467       continue;
1468     // Skip reserved registers.
1469     if (reservedRegs_.test(Reg))
1470       continue;
1471     if (isRegAvail(Reg) && Reg < inactiveCounts.size() &&
1472         FreeRegInactiveCount < inactiveCounts[Reg] && !isRecentlyUsed(Reg)) {
1473       FreeReg = Reg;
1474       FreeRegInactiveCount = inactiveCounts[Reg];
1475       if (FreeRegInactiveCount == MaxInactiveCount)
1476         break;    // We found the one with the max inactive count.
1477     }
1478   }
1479
1480   // Remember what register we picked so we can skip it next time.
1481   recordRecentlyUsed(FreeReg);
1482
1483   return FreeReg;
1484 }
1485
1486 /// getFreePhysReg - return a free physical register for this virtual register
1487 /// interval if we have one, otherwise return 0.
1488 unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
1489   SmallVector<unsigned, 256> inactiveCounts;
1490   unsigned MaxInactiveCount = 0;
1491
1492   const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
1493   const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1494
1495   for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1496        i != e; ++i) {
1497     unsigned reg = i->first->reg;
1498     assert(TargetRegisterInfo::isVirtualRegister(reg) &&
1499            "Can only allocate virtual registers!");
1500
1501     // If this is not in a related reg class to the register we're allocating,
1502     // don't check it.
1503     const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
1504     if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1505       reg = vrm_->getPhys(reg);
1506       if (inactiveCounts.size() <= reg)
1507         inactiveCounts.resize(reg+1);
1508       ++inactiveCounts[reg];
1509       MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1510     }
1511   }
1512
1513   // If copy coalescer has assigned a "preferred" register, check if it's
1514   // available first.
1515   unsigned Preference = vrm_->getRegAllocPref(cur->reg);
1516   if (Preference) {
1517     DEBUG(dbgs() << "(preferred: " << tri_->getName(Preference) << ") ");
1518     if (isRegAvail(Preference) &&
1519         RC->contains(Preference))
1520       return Preference;
1521   }
1522
1523   if (!DowngradedRegs.empty()) {
1524     unsigned FreeReg = getFreePhysReg(cur, RC, MaxInactiveCount, inactiveCounts,
1525                                       true);
1526     if (FreeReg)
1527       return FreeReg;
1528   }
1529   return getFreePhysReg(cur, RC, MaxInactiveCount, inactiveCounts, false);
1530 }
1531
1532 FunctionPass* llvm::createLinearScanRegisterAllocator() {
1533   return new RALinScan();
1534 }