Any debug info symbol is only valid if atleast one compile unit is seen.
[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 "PhysRegTracker.h"
16 #include "VirtRegMap.h"
17 #include "llvm/Function.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/CodeGen/LiveStackAnalysis.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/RegAllocRegistry.h"
26 #include "llvm/CodeGen/RegisterCoalescer.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetOptions.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/ADT/EquivalenceClasses.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/Compiler.h"
37 #include <algorithm>
38 #include <set>
39 #include <queue>
40 #include <memory>
41 #include <cmath>
42 using namespace llvm;
43
44 STATISTIC(NumIters     , "Number of iterations performed");
45 STATISTIC(NumBacktracks, "Number of times we had to backtrack");
46 STATISTIC(NumCoalesce,   "Number of copies coalesced");
47
48 static cl::opt<bool>
49 NewHeuristic("new-spilling-heuristic",
50              cl::desc("Use new spilling heuristic"),
51              cl::init(false), cl::Hidden);
52
53 static cl::opt<bool>
54 PreSplitIntervals("pre-alloc-split",
55                   cl::desc("Pre-register allocation live interval splitting"),
56                   cl::init(false), cl::Hidden);
57
58 static RegisterRegAlloc
59 linearscanRegAlloc("linearscan", "linear scan register allocator",
60                    createLinearScanRegisterAllocator);
61
62 namespace {
63   struct VISIBILITY_HIDDEN RALinScan : public MachineFunctionPass {
64     static char ID;
65     RALinScan() : MachineFunctionPass(&ID) {}
66
67     typedef std::pair<LiveInterval*, LiveInterval::iterator> IntervalPtr;
68     typedef SmallVector<IntervalPtr, 32> IntervalPtrs;
69   private:
70     /// RelatedRegClasses - This structure is built the first time a function is
71     /// compiled, and keeps track of which register classes have registers that
72     /// belong to multiple classes or have aliases that are in other classes.
73     EquivalenceClasses<const TargetRegisterClass*> RelatedRegClasses;
74     DenseMap<unsigned, const TargetRegisterClass*> OneClassForEachPhysReg;
75
76     MachineFunction* mf_;
77     MachineRegisterInfo* mri_;
78     const TargetMachine* tm_;
79     const TargetRegisterInfo* tri_;
80     const TargetInstrInfo* tii_;
81     BitVector allocatableRegs_;
82     LiveIntervals* li_;
83     LiveStacks* ls_;
84     const MachineLoopInfo *loopInfo;
85
86     /// handled_ - Intervals are added to the handled_ set in the order of their
87     /// start value.  This is uses for backtracking.
88     std::vector<LiveInterval*> handled_;
89
90     /// fixed_ - Intervals that correspond to machine registers.
91     ///
92     IntervalPtrs fixed_;
93
94     /// active_ - Intervals that are currently being processed, and which have a
95     /// live range active for the current point.
96     IntervalPtrs active_;
97
98     /// inactive_ - Intervals that are currently being processed, but which have
99     /// a hold at the current point.
100     IntervalPtrs inactive_;
101
102     typedef std::priority_queue<LiveInterval*,
103                                 SmallVector<LiveInterval*, 64>,
104                                 greater_ptr<LiveInterval> > IntervalHeap;
105     IntervalHeap unhandled_;
106     std::auto_ptr<PhysRegTracker> prt_;
107     std::auto_ptr<VirtRegMap> vrm_;
108     std::auto_ptr<Spiller> spiller_;
109
110   public:
111     virtual const char* getPassName() const {
112       return "Linear Scan Register Allocator";
113     }
114
115     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
116       AU.addRequired<LiveIntervals>();
117       if (StrongPHIElim)
118         AU.addRequiredID(StrongPHIEliminationID);
119       // Make sure PassManager knows which analyses to make available
120       // to coalescing and which analyses coalescing invalidates.
121       AU.addRequiredTransitive<RegisterCoalescer>();
122       if (PreSplitIntervals)
123         AU.addRequiredID(PreAllocSplittingID);
124       AU.addRequired<LiveStacks>();
125       AU.addPreserved<LiveStacks>();
126       AU.addRequired<MachineLoopInfo>();
127       AU.addPreserved<MachineLoopInfo>();
128       AU.addPreservedID(MachineDominatorsID);
129       MachineFunctionPass::getAnalysisUsage(AU);
130     }
131
132     /// runOnMachineFunction - register allocate the whole function
133     bool runOnMachineFunction(MachineFunction&);
134
135   private:
136     /// linearScan - the linear scan algorithm
137     void linearScan();
138
139     /// initIntervalSets - initialize the interval sets.
140     ///
141     void initIntervalSets();
142
143     /// processActiveIntervals - expire old intervals and move non-overlapping
144     /// ones to the inactive list.
145     void processActiveIntervals(unsigned CurPoint);
146
147     /// processInactiveIntervals - expire old intervals and move overlapping
148     /// ones to the active list.
149     void processInactiveIntervals(unsigned CurPoint);
150
151     /// assignRegOrStackSlotAtInterval - assign a register if one
152     /// is available, or spill.
153     void assignRegOrStackSlotAtInterval(LiveInterval* cur);
154
155     /// findIntervalsToSpill - Determine the intervals to spill for the
156     /// specified interval. It's passed the physical registers whose spill
157     /// weight is the lowest among all the registers whose live intervals
158     /// conflict with the interval.
159     void findIntervalsToSpill(LiveInterval *cur,
160                             std::vector<std::pair<unsigned,float> > &Candidates,
161                             unsigned NumCands,
162                             SmallVector<LiveInterval*, 8> &SpillIntervals);
163
164     /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
165     /// try allocate the definition the same register as the source register
166     /// if the register is not defined during live time of the interval. This
167     /// eliminate a copy. This is used to coalesce copies which were not
168     /// coalesced away before allocation either due to dest and src being in
169     /// different register classes or because the coalescer was overly
170     /// conservative.
171     unsigned attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg);
172
173     ///
174     /// register handling helpers
175     ///
176
177     /// getFreePhysReg - return a free physical register for this virtual
178     /// register interval if we have one, otherwise return 0.
179     unsigned getFreePhysReg(LiveInterval* cur);
180
181     /// assignVirt2StackSlot - assigns this virtual register to a
182     /// stack slot. returns the stack slot
183     int assignVirt2StackSlot(unsigned virtReg);
184
185     void ComputeRelatedRegClasses();
186
187     template <typename ItTy>
188     void printIntervals(const char* const str, ItTy i, ItTy e) const {
189       if (str) DOUT << str << " intervals:\n";
190       for (; i != e; ++i) {
191         DOUT << "\t" << *i->first << " -> ";
192         unsigned reg = i->first->reg;
193         if (TargetRegisterInfo::isVirtualRegister(reg)) {
194           reg = vrm_->getPhys(reg);
195         }
196         DOUT << tri_->getName(reg) << '\n';
197       }
198     }
199   };
200   char RALinScan::ID = 0;
201 }
202
203 static RegisterPass<RALinScan>
204 X("linearscan-regalloc", "Linear Scan Register Allocator");
205
206 void RALinScan::ComputeRelatedRegClasses() {
207   const TargetRegisterInfo &TRI = *tri_;
208   
209   // First pass, add all reg classes to the union, and determine at least one
210   // reg class that each register is in.
211   bool HasAliases = false;
212   for (TargetRegisterInfo::regclass_iterator RCI = TRI.regclass_begin(),
213        E = TRI.regclass_end(); RCI != E; ++RCI) {
214     RelatedRegClasses.insert(*RCI);
215     for (TargetRegisterClass::iterator I = (*RCI)->begin(), E = (*RCI)->end();
216          I != E; ++I) {
217       HasAliases = HasAliases || *TRI.getAliasSet(*I) != 0;
218       
219       const TargetRegisterClass *&PRC = OneClassForEachPhysReg[*I];
220       if (PRC) {
221         // Already processed this register.  Just make sure we know that
222         // multiple register classes share a register.
223         RelatedRegClasses.unionSets(PRC, *RCI);
224       } else {
225         PRC = *RCI;
226       }
227     }
228   }
229   
230   // Second pass, now that we know conservatively what register classes each reg
231   // belongs to, add info about aliases.  We don't need to do this for targets
232   // without register aliases.
233   if (HasAliases)
234     for (DenseMap<unsigned, const TargetRegisterClass*>::iterator
235          I = OneClassForEachPhysReg.begin(), E = OneClassForEachPhysReg.end();
236          I != E; ++I)
237       for (const unsigned *AS = TRI.getAliasSet(I->first); *AS; ++AS)
238         RelatedRegClasses.unionSets(I->second, OneClassForEachPhysReg[*AS]);
239 }
240
241 /// attemptTrivialCoalescing - If a simple interval is defined by a copy,
242 /// try allocate the definition the same register as the source register
243 /// if the register is not defined during live time of the interval. This
244 /// eliminate a copy. This is used to coalesce copies which were not
245 /// coalesced away before allocation either due to dest and src being in
246 /// different register classes or because the coalescer was overly
247 /// conservative.
248 unsigned RALinScan::attemptTrivialCoalescing(LiveInterval &cur, unsigned Reg) {
249   if ((cur.preference && cur.preference == Reg) || !cur.containsOneValue())
250     return Reg;
251
252   VNInfo *vni = cur.getValNumInfo(0);
253   if (!vni->def || vni->def == ~1U || vni->def == ~0U)
254     return Reg;
255   MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
256   unsigned SrcReg, DstReg;
257   if (!CopyMI || !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg))
258     return Reg;
259   if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
260     if (!vrm_->isAssignedReg(SrcReg))
261       return Reg;
262     else
263       SrcReg = vrm_->getPhys(SrcReg);
264   }
265   if (Reg == SrcReg)
266     return Reg;
267
268   const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
269   if (!RC->contains(SrcReg))
270     return Reg;
271
272   // Try to coalesce.
273   if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
274     DOUT << "Coalescing: " << cur << " -> " << tri_->getName(SrcReg)
275          << '\n';
276     vrm_->clearVirt(cur.reg);
277     vrm_->assignVirt2Phys(cur.reg, SrcReg);
278     ++NumCoalesce;
279     return SrcReg;
280   }
281
282   return Reg;
283 }
284
285 bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
286   mf_ = &fn;
287   mri_ = &fn.getRegInfo();
288   tm_ = &fn.getTarget();
289   tri_ = tm_->getRegisterInfo();
290   tii_ = tm_->getInstrInfo();
291   allocatableRegs_ = tri_->getAllocatableSet(fn);
292   li_ = &getAnalysis<LiveIntervals>();
293   ls_ = &getAnalysis<LiveStacks>();
294   loopInfo = &getAnalysis<MachineLoopInfo>();
295
296   // We don't run the coalescer here because we have no reason to
297   // interact with it.  If the coalescer requires interaction, it
298   // won't do anything.  If it doesn't require interaction, we assume
299   // it was run as a separate pass.
300
301   // If this is the first function compiled, compute the related reg classes.
302   if (RelatedRegClasses.empty())
303     ComputeRelatedRegClasses();
304   
305   if (!prt_.get()) prt_.reset(new PhysRegTracker(*tri_));
306   vrm_.reset(new VirtRegMap(*mf_));
307   if (!spiller_.get()) spiller_.reset(createSpiller());
308
309   initIntervalSets();
310
311   linearScan();
312
313   // Rewrite spill code and update the PhysRegsUsed set.
314   spiller_->runOnMachineFunction(*mf_, *vrm_);
315   vrm_.reset();  // Free the VirtRegMap
316
317   assert(unhandled_.empty() && "Unhandled live intervals remain!");
318   fixed_.clear();
319   active_.clear();
320   inactive_.clear();
321   handled_.clear();
322
323   return true;
324 }
325
326 /// initIntervalSets - initialize the interval sets.
327 ///
328 void RALinScan::initIntervalSets()
329 {
330   assert(unhandled_.empty() && fixed_.empty() &&
331          active_.empty() && inactive_.empty() &&
332          "interval sets should be empty on initialization");
333
334   handled_.reserve(li_->getNumIntervals());
335
336   for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
337     if (TargetRegisterInfo::isPhysicalRegister(i->second->reg)) {
338       mri_->setPhysRegUsed(i->second->reg);
339       fixed_.push_back(std::make_pair(i->second, i->second->begin()));
340     } else
341       unhandled_.push(i->second);
342   }
343 }
344
345 void RALinScan::linearScan()
346 {
347   // linear scan algorithm
348   DOUT << "********** LINEAR SCAN **********\n";
349   DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
350
351   DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
352
353   while (!unhandled_.empty()) {
354     // pick the interval with the earliest start point
355     LiveInterval* cur = unhandled_.top();
356     unhandled_.pop();
357     ++NumIters;
358     DOUT << "\n*** CURRENT ***: " << *cur << '\n';
359
360     if (!cur->empty()) {
361       processActiveIntervals(cur->beginNumber());
362       processInactiveIntervals(cur->beginNumber());
363
364       assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
365              "Can only allocate virtual registers!");
366     }
367
368     // Allocating a virtual register. try to find a free
369     // physical register or spill an interval (possibly this one) in order to
370     // assign it one.
371     assignRegOrStackSlotAtInterval(cur);
372
373     DEBUG(printIntervals("active", active_.begin(), active_.end()));
374     DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
375   }
376
377   // expire any remaining active intervals
378   while (!active_.empty()) {
379     IntervalPtr &IP = active_.back();
380     unsigned reg = IP.first->reg;
381     DOUT << "\tinterval " << *IP.first << " expired\n";
382     assert(TargetRegisterInfo::isVirtualRegister(reg) &&
383            "Can only allocate virtual registers!");
384     reg = vrm_->getPhys(reg);
385     prt_->delRegUse(reg);
386     active_.pop_back();
387   }
388
389   // expire any remaining inactive intervals
390   DEBUG(for (IntervalPtrs::reverse_iterator
391                i = inactive_.rbegin(); i != inactive_.rend(); ++i)
392         DOUT << "\tinterval " << *i->first << " expired\n");
393   inactive_.clear();
394
395   // Add live-ins to every BB except for entry. Also perform trivial coalescing.
396   MachineFunction::iterator EntryMBB = mf_->begin();
397   SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
398   for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
399     LiveInterval &cur = *i->second;
400     unsigned Reg = 0;
401     bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
402     if (isPhys)
403       Reg = cur.reg;
404     else if (vrm_->isAssignedReg(cur.reg))
405       Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
406     if (!Reg)
407       continue;
408     // Ignore splited live intervals.
409     if (!isPhys && vrm_->getPreSplitReg(cur.reg))
410       continue;
411     for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
412          I != E; ++I) {
413       const LiveRange &LR = *I;
414       if (li_->findLiveInMBBs(LR.start, LR.end, LiveInMBBs)) {
415         for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
416           if (LiveInMBBs[i] != EntryMBB)
417             LiveInMBBs[i]->addLiveIn(Reg);
418         LiveInMBBs.clear();
419       }
420     }
421   }
422
423   DOUT << *vrm_;
424 }
425
426 /// processActiveIntervals - expire old intervals and move non-overlapping ones
427 /// to the inactive list.
428 void RALinScan::processActiveIntervals(unsigned CurPoint)
429 {
430   DOUT << "\tprocessing active intervals:\n";
431
432   for (unsigned i = 0, e = active_.size(); i != e; ++i) {
433     LiveInterval *Interval = active_[i].first;
434     LiveInterval::iterator IntervalPos = active_[i].second;
435     unsigned reg = Interval->reg;
436
437     IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
438
439     if (IntervalPos == Interval->end()) {     // Remove expired intervals.
440       DOUT << "\t\tinterval " << *Interval << " expired\n";
441       assert(TargetRegisterInfo::isVirtualRegister(reg) &&
442              "Can only allocate virtual registers!");
443       reg = vrm_->getPhys(reg);
444       prt_->delRegUse(reg);
445
446       // Pop off the end of the list.
447       active_[i] = active_.back();
448       active_.pop_back();
449       --i; --e;
450
451     } else if (IntervalPos->start > CurPoint) {
452       // Move inactive intervals to inactive list.
453       DOUT << "\t\tinterval " << *Interval << " inactive\n";
454       assert(TargetRegisterInfo::isVirtualRegister(reg) &&
455              "Can only allocate virtual registers!");
456       reg = vrm_->getPhys(reg);
457       prt_->delRegUse(reg);
458       // add to inactive.
459       inactive_.push_back(std::make_pair(Interval, IntervalPos));
460
461       // Pop off the end of the list.
462       active_[i] = active_.back();
463       active_.pop_back();
464       --i; --e;
465     } else {
466       // Otherwise, just update the iterator position.
467       active_[i].second = IntervalPos;
468     }
469   }
470 }
471
472 /// processInactiveIntervals - expire old intervals and move overlapping
473 /// ones to the active list.
474 void RALinScan::processInactiveIntervals(unsigned CurPoint)
475 {
476   DOUT << "\tprocessing inactive intervals:\n";
477
478   for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
479     LiveInterval *Interval = inactive_[i].first;
480     LiveInterval::iterator IntervalPos = inactive_[i].second;
481     unsigned reg = Interval->reg;
482
483     IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
484
485     if (IntervalPos == Interval->end()) {       // remove expired intervals.
486       DOUT << "\t\tinterval " << *Interval << " expired\n";
487
488       // Pop off the end of the list.
489       inactive_[i] = inactive_.back();
490       inactive_.pop_back();
491       --i; --e;
492     } else if (IntervalPos->start <= CurPoint) {
493       // move re-activated intervals in active list
494       DOUT << "\t\tinterval " << *Interval << " active\n";
495       assert(TargetRegisterInfo::isVirtualRegister(reg) &&
496              "Can only allocate virtual registers!");
497       reg = vrm_->getPhys(reg);
498       prt_->addRegUse(reg);
499       // add to active
500       active_.push_back(std::make_pair(Interval, IntervalPos));
501
502       // Pop off the end of the list.
503       inactive_[i] = inactive_.back();
504       inactive_.pop_back();
505       --i; --e;
506     } else {
507       // Otherwise, just update the iterator position.
508       inactive_[i].second = IntervalPos;
509     }
510   }
511 }
512
513 /// updateSpillWeights - updates the spill weights of the specifed physical
514 /// register and its weight.
515 static void updateSpillWeights(std::vector<float> &Weights,
516                                unsigned reg, float weight,
517                                const TargetRegisterInfo *TRI) {
518   Weights[reg] += weight;
519   for (const unsigned* as = TRI->getAliasSet(reg); *as; ++as)
520     Weights[*as] += weight;
521 }
522
523 static
524 RALinScan::IntervalPtrs::iterator
525 FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
526   for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
527        I != E; ++I)
528     if (I->first == LI) return I;
529   return IP.end();
530 }
531
532 static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
533   for (unsigned i = 0, e = V.size(); i != e; ++i) {
534     RALinScan::IntervalPtr &IP = V[i];
535     LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
536                                                 IP.second, Point);
537     if (I != IP.first->begin()) --I;
538     IP.second = I;
539   }
540 }
541
542 /// addStackInterval - Create a LiveInterval for stack if the specified live
543 /// interval has been spilled.
544 static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
545                              LiveIntervals *li_, float &Weight,
546                              VirtRegMap &vrm_) {
547   int SS = vrm_.getStackSlot(cur->reg);
548   if (SS == VirtRegMap::NO_STACK_SLOT)
549     return;
550   LiveInterval &SI = ls_->getOrCreateInterval(SS);
551   SI.weight += Weight;
552
553   VNInfo *VNI;
554   if (SI.hasAtLeastOneValue())
555     VNI = SI.getValNumInfo(0);
556   else
557     VNI = SI.getNextValue(~0U, 0, ls_->getVNInfoAllocator());
558
559   LiveInterval &RI = li_->getInterval(cur->reg);
560   // FIXME: This may be overly conservative.
561   SI.MergeRangesInAsValue(RI, VNI);
562 }
563
564 /// getConflictWeight - Return the number of conflicts between cur
565 /// live interval and defs and uses of Reg weighted by loop depthes.
566 static float getConflictWeight(LiveInterval *cur, unsigned Reg,
567                                   LiveIntervals *li_,
568                                   MachineRegisterInfo *mri_,
569                                   const MachineLoopInfo *loopInfo) {
570   float Conflicts = 0;
571   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
572          E = mri_->reg_end(); I != E; ++I) {
573     MachineInstr *MI = &*I;
574     if (cur->liveAt(li_->getInstructionIndex(MI))) {
575       unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
576       Conflicts += powf(10.0f, (float)loopDepth);
577     }
578   }
579   return Conflicts;
580 }
581
582 /// findIntervalsToSpill - Determine the intervals to spill for the
583 /// specified interval. It's passed the physical registers whose spill
584 /// weight is the lowest among all the registers whose live intervals
585 /// conflict with the interval.
586 void RALinScan::findIntervalsToSpill(LiveInterval *cur,
587                             std::vector<std::pair<unsigned,float> > &Candidates,
588                             unsigned NumCands,
589                             SmallVector<LiveInterval*, 8> &SpillIntervals) {
590   // We have figured out the *best* register to spill. But there are other
591   // registers that are pretty good as well (spill weight within 3%). Spill
592   // the one that has fewest defs and uses that conflict with cur.
593   float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
594   SmallVector<LiveInterval*, 8> SLIs[3];
595
596   DOUT << "\tConsidering " << NumCands << " candidates: ";
597   DEBUG(for (unsigned i = 0; i != NumCands; ++i)
598           DOUT << tri_->getName(Candidates[i].first) << " ";
599         DOUT << "\n";);
600   
601   // Calculate the number of conflicts of each candidate.
602   for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
603     unsigned Reg = i->first->reg;
604     unsigned PhysReg = vrm_->getPhys(Reg);
605     if (!cur->overlapsFrom(*i->first, i->second))
606       continue;
607     for (unsigned j = 0; j < NumCands; ++j) {
608       unsigned Candidate = Candidates[j].first;
609       if (tri_->regsOverlap(PhysReg, Candidate)) {
610         if (NumCands > 1)
611           Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
612         SLIs[j].push_back(i->first);
613       }
614     }
615   }
616
617   for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
618     unsigned Reg = i->first->reg;
619     unsigned PhysReg = vrm_->getPhys(Reg);
620     if (!cur->overlapsFrom(*i->first, i->second-1))
621       continue;
622     for (unsigned j = 0; j < NumCands; ++j) {
623       unsigned Candidate = Candidates[j].first;
624       if (tri_->regsOverlap(PhysReg, Candidate)) {
625         if (NumCands > 1)
626           Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
627         SLIs[j].push_back(i->first);
628       }
629     }
630   }
631
632   // Which is the best candidate?
633   unsigned BestCandidate = 0;
634   float MinConflicts = Conflicts[0];
635   for (unsigned i = 1; i != NumCands; ++i) {
636     if (Conflicts[i] < MinConflicts) {
637       BestCandidate = i;
638       MinConflicts = Conflicts[i];
639     }
640   }
641
642   std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
643             std::back_inserter(SpillIntervals));
644 }
645
646 namespace {
647   struct WeightCompare {
648     typedef std::pair<unsigned, float> RegWeightPair;
649     bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
650       return LHS.second < RHS.second;
651     }
652   };
653 }
654
655 static bool weightsAreClose(float w1, float w2) {
656   if (!NewHeuristic)
657     return false;
658
659   float diff = w1 - w2;
660   if (diff <= 0.02f)  // Within 0.02f
661     return true;
662   return (diff / w2) <= 0.05f;  // Within 5%.
663 }
664
665 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
666 /// spill.
667 void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
668 {
669   DOUT << "\tallocating current interval: ";
670
671   // This is an implicitly defined live interval, just assign any register.
672   const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
673   if (cur->empty()) {
674     unsigned physReg = cur->preference;
675     if (!physReg)
676       physReg = *RC->allocation_order_begin(*mf_);
677     DOUT <<  tri_->getName(physReg) << '\n';
678     // Note the register is not really in use.
679     vrm_->assignVirt2Phys(cur->reg, physReg);
680     return;
681   }
682
683   PhysRegTracker backupPrt = *prt_;
684
685   std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
686   unsigned StartPosition = cur->beginNumber();
687   const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
688
689   // If this live interval is defined by a move instruction and its source is
690   // assigned a physical register that is compatible with the target register
691   // class, then we should try to assign it the same register.
692   // This can happen when the move is from a larger register class to a smaller
693   // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
694   if (!cur->preference && cur->containsOneValue()) {
695     VNInfo *vni = cur->getValNumInfo(0);
696     if (vni->def && vni->def != ~1U && vni->def != ~0U) {
697       MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
698       unsigned SrcReg, DstReg;
699       if (CopyMI && tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
700         unsigned Reg = 0;
701         if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
702           Reg = SrcReg;
703         else if (vrm_->isAssignedReg(SrcReg))
704           Reg = vrm_->getPhys(SrcReg);
705         if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
706           cur->preference = Reg;
707       }
708     }
709   }
710
711   // for every interval in inactive we overlap with, mark the
712   // register as not free and update spill weights.
713   for (IntervalPtrs::const_iterator i = inactive_.begin(),
714          e = inactive_.end(); i != e; ++i) {
715     unsigned Reg = i->first->reg;
716     assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
717            "Can only allocate virtual registers!");
718     const TargetRegisterClass *RegRC = mri_->getRegClass(Reg);
719     // If this is not in a related reg class to the register we're allocating, 
720     // don't check it.
721     if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
722         cur->overlapsFrom(*i->first, i->second-1)) {
723       Reg = vrm_->getPhys(Reg);
724       prt_->addRegUse(Reg);
725       SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
726     }
727   }
728   
729   // Speculatively check to see if we can get a register right now.  If not,
730   // we know we won't be able to by adding more constraints.  If so, we can
731   // check to see if it is valid.  Doing an exhaustive search of the fixed_ list
732   // is very bad (it contains all callee clobbered registers for any functions
733   // with a call), so we want to avoid doing that if possible.
734   unsigned physReg = getFreePhysReg(cur);
735   unsigned BestPhysReg = physReg;
736   if (physReg) {
737     // We got a register.  However, if it's in the fixed_ list, we might
738     // conflict with it.  Check to see if we conflict with it or any of its
739     // aliases.
740     SmallSet<unsigned, 8> RegAliases;
741     for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
742       RegAliases.insert(*AS);
743     
744     bool ConflictsWithFixed = false;
745     for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
746       IntervalPtr &IP = fixed_[i];
747       if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
748         // Okay, this reg is on the fixed list.  Check to see if we actually
749         // conflict.
750         LiveInterval *I = IP.first;
751         if (I->endNumber() > StartPosition) {
752           LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
753           IP.second = II;
754           if (II != I->begin() && II->start > StartPosition)
755             --II;
756           if (cur->overlapsFrom(*I, II)) {
757             ConflictsWithFixed = true;
758             break;
759           }
760         }
761       }
762     }
763     
764     // Okay, the register picked by our speculative getFreePhysReg call turned
765     // out to be in use.  Actually add all of the conflicting fixed registers to
766     // prt so we can do an accurate query.
767     if (ConflictsWithFixed) {
768       // For every interval in fixed we overlap with, mark the register as not
769       // free and update spill weights.
770       for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
771         IntervalPtr &IP = fixed_[i];
772         LiveInterval *I = IP.first;
773
774         const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
775         if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&       
776             I->endNumber() > StartPosition) {
777           LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
778           IP.second = II;
779           if (II != I->begin() && II->start > StartPosition)
780             --II;
781           if (cur->overlapsFrom(*I, II)) {
782             unsigned reg = I->reg;
783             prt_->addRegUse(reg);
784             SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
785           }
786         }
787       }
788
789       // Using the newly updated prt_ object, which includes conflicts in the
790       // future, see if there are any registers available.
791       physReg = getFreePhysReg(cur);
792     }
793   }
794     
795   // Restore the physical register tracker, removing information about the
796   // future.
797   *prt_ = backupPrt;
798   
799   // if we find a free register, we are done: assign this virtual to
800   // the free physical register and add this interval to the active
801   // list.
802   if (physReg) {
803     DOUT <<  tri_->getName(physReg) << '\n';
804     vrm_->assignVirt2Phys(cur->reg, physReg);
805     prt_->addRegUse(physReg);
806     active_.push_back(std::make_pair(cur, cur->begin()));
807     handled_.push_back(cur);
808     return;
809   }
810   DOUT << "no free registers\n";
811
812   // Compile the spill weights into an array that is better for scanning.
813   std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
814   for (std::vector<std::pair<unsigned, float> >::iterator
815        I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
816     updateSpillWeights(SpillWeights, I->first, I->second, tri_);
817   
818   // for each interval in active, update spill weights.
819   for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
820        i != e; ++i) {
821     unsigned reg = i->first->reg;
822     assert(TargetRegisterInfo::isVirtualRegister(reg) &&
823            "Can only allocate virtual registers!");
824     reg = vrm_->getPhys(reg);
825     updateSpillWeights(SpillWeights, reg, i->first->weight, tri_);
826   }
827  
828   DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
829
830   // Find a register to spill.
831   float minWeight = HUGE_VALF;
832   unsigned minReg = 0; /*cur->preference*/;  // Try the preferred register first.
833
834   bool Found = false;
835   std::vector<std::pair<unsigned,float> > RegsWeights;
836   if (!minReg || SpillWeights[minReg] == HUGE_VALF)
837     for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
838            e = RC->allocation_order_end(*mf_); i != e; ++i) {
839       unsigned reg = *i;
840       float regWeight = SpillWeights[reg];
841       if (minWeight > regWeight)
842         Found = true;
843       RegsWeights.push_back(std::make_pair(reg, regWeight));
844     }
845   
846   // If we didn't find a register that is spillable, try aliases?
847   if (!Found) {
848     for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
849            e = RC->allocation_order_end(*mf_); i != e; ++i) {
850       unsigned reg = *i;
851       // No need to worry about if the alias register size < regsize of RC.
852       // We are going to spill all registers that alias it anyway.
853       for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
854         RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
855     }
856   }
857
858   // Sort all potential spill candidates by weight.
859   std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare());
860   minReg = RegsWeights[0].first;
861   minWeight = RegsWeights[0].second;
862   if (minWeight == HUGE_VALF) {
863     // All registers must have inf weight. Just grab one!
864     minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
865     if (cur->weight == HUGE_VALF ||
866         li_->getApproximateInstructionCount(*cur) == 0) {
867       // Spill a physical register around defs and uses.
868       li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_);
869       assignRegOrStackSlotAtInterval(cur);
870       return;
871     }
872   }
873
874   // Find up to 3 registers to consider as spill candidates.
875   unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
876   while (LastCandidate > 1) {
877     if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
878       break;
879     --LastCandidate;
880   }
881
882   DOUT << "\t\tregister(s) with min weight(s): ";
883   DEBUG(for (unsigned i = 0; i != LastCandidate; ++i)
884           DOUT << tri_->getName(RegsWeights[i].first)
885                << " (" << RegsWeights[i].second << ")\n");
886
887   // if the current has the minimum weight, we need to spill it and
888   // add any added intervals back to unhandled, and restart
889   // linearscan.
890   if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
891     DOUT << "\t\t\tspilling(c): " << *cur << '\n';
892     float SSWeight;
893     SmallVector<LiveInterval*, 8> spillIs;
894     std::vector<LiveInterval*> added =
895       li_->addIntervalsForSpills(*cur, spillIs, loopInfo, *vrm_, SSWeight);
896     addStackInterval(cur, ls_, li_, SSWeight, *vrm_);
897     if (added.empty())
898       return;  // Early exit if all spills were folded.
899
900     // Merge added with unhandled.  Note that we know that
901     // addIntervalsForSpills returns intervals sorted by their starting
902     // point.
903     for (unsigned i = 0, e = added.size(); i != e; ++i)
904       unhandled_.push(added[i]);
905     return;
906   }
907
908   ++NumBacktracks;
909
910   // push the current interval back to unhandled since we are going
911   // to re-run at least this iteration. Since we didn't modify it it
912   // should go back right in the front of the list
913   unhandled_.push(cur);
914
915   assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
916          "did not choose a register to spill?");
917
918   // We spill all intervals aliasing the register with
919   // minimum weight, rollback to the interval with the earliest
920   // start point and let the linear scan algorithm run again
921   SmallVector<LiveInterval*, 8> spillIs;
922
923   // Determine which intervals have to be spilled.
924   findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
925
926   // Set of spilled vregs (used later to rollback properly)
927   SmallSet<unsigned, 8> spilled;
928
929   // The earliest start of a Spilled interval indicates up to where
930   // in handled we need to roll back
931   unsigned earliestStart = cur->beginNumber();
932
933   // Spill live intervals of virtual regs mapped to the physical register we
934   // want to clear (and its aliases).  We only spill those that overlap with the
935   // current interval as the rest do not affect its allocation. we also keep
936   // track of the earliest start of all spilled live intervals since this will
937   // mark our rollback point.
938   std::vector<LiveInterval*> added;
939   while (!spillIs.empty()) {
940     LiveInterval *sli = spillIs.back();
941     spillIs.pop_back();
942     DOUT << "\t\t\tspilling(a): " << *sli << '\n';
943     earliestStart = std::min(earliestStart, sli->beginNumber());
944     float SSWeight;
945     std::vector<LiveInterval*> newIs =
946       li_->addIntervalsForSpills(*sli, spillIs, loopInfo, *vrm_, SSWeight);
947     addStackInterval(sli, ls_, li_, SSWeight, *vrm_);
948     std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
949     spilled.insert(sli->reg);
950   }
951
952   DOUT << "\t\trolling back to: " << earliestStart << '\n';
953
954   // Scan handled in reverse order up to the earliest start of a
955   // spilled live interval and undo each one, restoring the state of
956   // unhandled.
957   while (!handled_.empty()) {
958     LiveInterval* i = handled_.back();
959     // If this interval starts before t we are done.
960     if (i->beginNumber() < earliestStart)
961       break;
962     DOUT << "\t\t\tundo changes for: " << *i << '\n';
963     handled_.pop_back();
964
965     // When undoing a live interval allocation we must know if it is active or
966     // inactive to properly update the PhysRegTracker and the VirtRegMap.
967     IntervalPtrs::iterator it;
968     if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
969       active_.erase(it);
970       assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
971       if (!spilled.count(i->reg))
972         unhandled_.push(i);
973       prt_->delRegUse(vrm_->getPhys(i->reg));
974       vrm_->clearVirt(i->reg);
975     } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
976       inactive_.erase(it);
977       assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
978       if (!spilled.count(i->reg))
979         unhandled_.push(i);
980       vrm_->clearVirt(i->reg);
981     } else {
982       assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
983              "Can only allocate virtual registers!");
984       vrm_->clearVirt(i->reg);
985       unhandled_.push(i);
986     }
987
988     // It interval has a preference, it must be defined by a copy. Clear the
989     // preference now since the source interval allocation may have been undone
990     // as well.
991     i->preference = 0;
992   }
993
994   // Rewind the iterators in the active, inactive, and fixed lists back to the
995   // point we reverted to.
996   RevertVectorIteratorsTo(active_, earliestStart);
997   RevertVectorIteratorsTo(inactive_, earliestStart);
998   RevertVectorIteratorsTo(fixed_, earliestStart);
999
1000   // scan the rest and undo each interval that expired after t and
1001   // insert it in active (the next iteration of the algorithm will
1002   // put it in inactive if required)
1003   for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
1004     LiveInterval *HI = handled_[i];
1005     if (!HI->expiredAt(earliestStart) &&
1006         HI->expiredAt(cur->beginNumber())) {
1007       DOUT << "\t\t\tundo changes for: " << *HI << '\n';
1008       active_.push_back(std::make_pair(HI, HI->begin()));
1009       assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
1010       prt_->addRegUse(vrm_->getPhys(HI->reg));
1011     }
1012   }
1013
1014   // merge added with unhandled
1015   for (unsigned i = 0, e = added.size(); i != e; ++i)
1016     unhandled_.push(added[i]);
1017 }
1018
1019 /// getFreePhysReg - return a free physical register for this virtual register
1020 /// interval if we have one, otherwise return 0.
1021 unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
1022   SmallVector<unsigned, 256> inactiveCounts;
1023   unsigned MaxInactiveCount = 0;
1024   
1025   const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
1026   const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1027  
1028   for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1029        i != e; ++i) {
1030     unsigned reg = i->first->reg;
1031     assert(TargetRegisterInfo::isVirtualRegister(reg) &&
1032            "Can only allocate virtual registers!");
1033
1034     // If this is not in a related reg class to the register we're allocating, 
1035     // don't check it.
1036     const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
1037     if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1038       reg = vrm_->getPhys(reg);
1039       if (inactiveCounts.size() <= reg)
1040         inactiveCounts.resize(reg+1);
1041       ++inactiveCounts[reg];
1042       MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1043     }
1044   }
1045
1046   unsigned FreeReg = 0;
1047   unsigned FreeRegInactiveCount = 0;
1048
1049   // If copy coalescer has assigned a "preferred" register, check if it's
1050   // available first.
1051   if (cur->preference) {
1052     if (prt_->isRegAvail(cur->preference) && 
1053         RC->contains(cur->preference)) {
1054       DOUT << "\t\tassigned the preferred register: "
1055            << tri_->getName(cur->preference) << "\n";
1056       return cur->preference;
1057     } else
1058       DOUT << "\t\tunable to assign the preferred register: "
1059            << tri_->getName(cur->preference) << "\n";
1060   }
1061
1062   // Scan for the first available register.
1063   TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
1064   TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
1065   assert(I != E && "No allocatable register in this register class!");
1066   for (; I != E; ++I)
1067     if (prt_->isRegAvail(*I)) {
1068       FreeReg = *I;
1069       if (FreeReg < inactiveCounts.size())
1070         FreeRegInactiveCount = inactiveCounts[FreeReg];
1071       else
1072         FreeRegInactiveCount = 0;
1073       break;
1074     }
1075
1076   // If there are no free regs, or if this reg has the max inactive count,
1077   // return this register.
1078   if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
1079   
1080   // Continue scanning the registers, looking for the one with the highest
1081   // inactive count.  Alkis found that this reduced register pressure very
1082   // slightly on X86 (in rev 1.94 of this file), though this should probably be
1083   // reevaluated now.
1084   for (; I != E; ++I) {
1085     unsigned Reg = *I;
1086     if (prt_->isRegAvail(Reg) && Reg < inactiveCounts.size() &&
1087         FreeRegInactiveCount < inactiveCounts[Reg]) {
1088       FreeReg = Reg;
1089       FreeRegInactiveCount = inactiveCounts[Reg];
1090       if (FreeRegInactiveCount == MaxInactiveCount)
1091         break;    // We found the one with the max inactive count.
1092     }
1093   }
1094   
1095   return FreeReg;
1096 }
1097
1098 FunctionPass* llvm::createLinearScanRegisterAllocator() {
1099   return new RALinScan();
1100 }