Change the post-RA scheduler to iterate through the
[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.begin()->valno;
253   if (!vni->def || vni->def == ~1U || vni->def == ~0U)
254     return Reg;
255   MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
256   unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
257   if (!CopyMI ||
258       !tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg))
259     return Reg;
260   if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
261     if (!vrm_->isAssignedReg(SrcReg))
262       return Reg;
263     else
264       SrcReg = vrm_->getPhys(SrcReg);
265   }
266   if (Reg == SrcReg)
267     return Reg;
268
269   const TargetRegisterClass *RC = mri_->getRegClass(cur.reg);
270   if (!RC->contains(SrcReg))
271     return Reg;
272
273   // Try to coalesce.
274   if (!li_->conflictsWithPhysRegDef(cur, *vrm_, SrcReg)) {
275     DOUT << "Coalescing: " << cur << " -> " << tri_->getName(SrcReg)
276          << '\n';
277     vrm_->clearVirt(cur.reg);
278     vrm_->assignVirt2Phys(cur.reg, SrcReg);
279     ++NumCoalesce;
280     return SrcReg;
281   }
282
283   return Reg;
284 }
285
286 bool RALinScan::runOnMachineFunction(MachineFunction &fn) {
287   mf_ = &fn;
288   mri_ = &fn.getRegInfo();
289   tm_ = &fn.getTarget();
290   tri_ = tm_->getRegisterInfo();
291   tii_ = tm_->getInstrInfo();
292   allocatableRegs_ = tri_->getAllocatableSet(fn);
293   li_ = &getAnalysis<LiveIntervals>();
294   ls_ = &getAnalysis<LiveStacks>();
295   loopInfo = &getAnalysis<MachineLoopInfo>();
296
297   // We don't run the coalescer here because we have no reason to
298   // interact with it.  If the coalescer requires interaction, it
299   // won't do anything.  If it doesn't require interaction, we assume
300   // it was run as a separate pass.
301
302   // If this is the first function compiled, compute the related reg classes.
303   if (RelatedRegClasses.empty())
304     ComputeRelatedRegClasses();
305   
306   if (!prt_.get()) prt_.reset(new PhysRegTracker(*tri_));
307   vrm_.reset(new VirtRegMap(*mf_));
308   if (!spiller_.get()) spiller_.reset(createSpiller());
309
310   initIntervalSets();
311
312   linearScan();
313
314   // Rewrite spill code and update the PhysRegsUsed set.
315   spiller_->runOnMachineFunction(*mf_, *vrm_);
316   vrm_.reset();  // Free the VirtRegMap
317
318   assert(unhandled_.empty() && "Unhandled live intervals remain!");
319   fixed_.clear();
320   active_.clear();
321   inactive_.clear();
322   handled_.clear();
323
324   return true;
325 }
326
327 /// initIntervalSets - initialize the interval sets.
328 ///
329 void RALinScan::initIntervalSets()
330 {
331   assert(unhandled_.empty() && fixed_.empty() &&
332          active_.empty() && inactive_.empty() &&
333          "interval sets should be empty on initialization");
334
335   handled_.reserve(li_->getNumIntervals());
336
337   for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
338     if (TargetRegisterInfo::isPhysicalRegister(i->second->reg)) {
339       mri_->setPhysRegUsed(i->second->reg);
340       fixed_.push_back(std::make_pair(i->second, i->second->begin()));
341     } else
342       unhandled_.push(i->second);
343   }
344 }
345
346 void RALinScan::linearScan()
347 {
348   // linear scan algorithm
349   DOUT << "********** LINEAR SCAN **********\n";
350   DOUT << "********** Function: " << mf_->getFunction()->getName() << '\n';
351
352   DEBUG(printIntervals("fixed", fixed_.begin(), fixed_.end()));
353
354   while (!unhandled_.empty()) {
355     // pick the interval with the earliest start point
356     LiveInterval* cur = unhandled_.top();
357     unhandled_.pop();
358     ++NumIters;
359     DOUT << "\n*** CURRENT ***: " << *cur << '\n';
360
361     if (!cur->empty()) {
362       processActiveIntervals(cur->beginNumber());
363       processInactiveIntervals(cur->beginNumber());
364
365       assert(TargetRegisterInfo::isVirtualRegister(cur->reg) &&
366              "Can only allocate virtual registers!");
367     }
368
369     // Allocating a virtual register. try to find a free
370     // physical register or spill an interval (possibly this one) in order to
371     // assign it one.
372     assignRegOrStackSlotAtInterval(cur);
373
374     DEBUG(printIntervals("active", active_.begin(), active_.end()));
375     DEBUG(printIntervals("inactive", inactive_.begin(), inactive_.end()));
376   }
377
378   // expire any remaining active intervals
379   while (!active_.empty()) {
380     IntervalPtr &IP = active_.back();
381     unsigned reg = IP.first->reg;
382     DOUT << "\tinterval " << *IP.first << " expired\n";
383     assert(TargetRegisterInfo::isVirtualRegister(reg) &&
384            "Can only allocate virtual registers!");
385     reg = vrm_->getPhys(reg);
386     prt_->delRegUse(reg);
387     active_.pop_back();
388   }
389
390   // expire any remaining inactive intervals
391   DEBUG(for (IntervalPtrs::reverse_iterator
392                i = inactive_.rbegin(); i != inactive_.rend(); ++i)
393         DOUT << "\tinterval " << *i->first << " expired\n");
394   inactive_.clear();
395
396   // Add live-ins to every BB except for entry. Also perform trivial coalescing.
397   MachineFunction::iterator EntryMBB = mf_->begin();
398   SmallVector<MachineBasicBlock*, 8> LiveInMBBs;
399   for (LiveIntervals::iterator i = li_->begin(), e = li_->end(); i != e; ++i) {
400     LiveInterval &cur = *i->second;
401     unsigned Reg = 0;
402     bool isPhys = TargetRegisterInfo::isPhysicalRegister(cur.reg);
403     if (isPhys)
404       Reg = cur.reg;
405     else if (vrm_->isAssignedReg(cur.reg))
406       Reg = attemptTrivialCoalescing(cur, vrm_->getPhys(cur.reg));
407     if (!Reg)
408       continue;
409     // Ignore splited live intervals.
410     if (!isPhys && vrm_->getPreSplitReg(cur.reg))
411       continue;
412     for (LiveInterval::Ranges::const_iterator I = cur.begin(), E = cur.end();
413          I != E; ++I) {
414       const LiveRange &LR = *I;
415       if (li_->findLiveInMBBs(LR.start, LR.end, LiveInMBBs)) {
416         for (unsigned i = 0, e = LiveInMBBs.size(); i != e; ++i)
417           if (LiveInMBBs[i] != EntryMBB)
418             LiveInMBBs[i]->addLiveIn(Reg);
419         LiveInMBBs.clear();
420       }
421     }
422   }
423
424   DOUT << *vrm_;
425 }
426
427 /// processActiveIntervals - expire old intervals and move non-overlapping ones
428 /// to the inactive list.
429 void RALinScan::processActiveIntervals(unsigned CurPoint)
430 {
431   DOUT << "\tprocessing active intervals:\n";
432
433   for (unsigned i = 0, e = active_.size(); i != e; ++i) {
434     LiveInterval *Interval = active_[i].first;
435     LiveInterval::iterator IntervalPos = active_[i].second;
436     unsigned reg = Interval->reg;
437
438     IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
439
440     if (IntervalPos == Interval->end()) {     // Remove expired intervals.
441       DOUT << "\t\tinterval " << *Interval << " expired\n";
442       assert(TargetRegisterInfo::isVirtualRegister(reg) &&
443              "Can only allocate virtual registers!");
444       reg = vrm_->getPhys(reg);
445       prt_->delRegUse(reg);
446
447       // Pop off the end of the list.
448       active_[i] = active_.back();
449       active_.pop_back();
450       --i; --e;
451
452     } else if (IntervalPos->start > CurPoint) {
453       // Move inactive intervals to inactive list.
454       DOUT << "\t\tinterval " << *Interval << " inactive\n";
455       assert(TargetRegisterInfo::isVirtualRegister(reg) &&
456              "Can only allocate virtual registers!");
457       reg = vrm_->getPhys(reg);
458       prt_->delRegUse(reg);
459       // add to inactive.
460       inactive_.push_back(std::make_pair(Interval, IntervalPos));
461
462       // Pop off the end of the list.
463       active_[i] = active_.back();
464       active_.pop_back();
465       --i; --e;
466     } else {
467       // Otherwise, just update the iterator position.
468       active_[i].second = IntervalPos;
469     }
470   }
471 }
472
473 /// processInactiveIntervals - expire old intervals and move overlapping
474 /// ones to the active list.
475 void RALinScan::processInactiveIntervals(unsigned CurPoint)
476 {
477   DOUT << "\tprocessing inactive intervals:\n";
478
479   for (unsigned i = 0, e = inactive_.size(); i != e; ++i) {
480     LiveInterval *Interval = inactive_[i].first;
481     LiveInterval::iterator IntervalPos = inactive_[i].second;
482     unsigned reg = Interval->reg;
483
484     IntervalPos = Interval->advanceTo(IntervalPos, CurPoint);
485
486     if (IntervalPos == Interval->end()) {       // remove expired intervals.
487       DOUT << "\t\tinterval " << *Interval << " expired\n";
488
489       // Pop off the end of the list.
490       inactive_[i] = inactive_.back();
491       inactive_.pop_back();
492       --i; --e;
493     } else if (IntervalPos->start <= CurPoint) {
494       // move re-activated intervals in active list
495       DOUT << "\t\tinterval " << *Interval << " active\n";
496       assert(TargetRegisterInfo::isVirtualRegister(reg) &&
497              "Can only allocate virtual registers!");
498       reg = vrm_->getPhys(reg);
499       prt_->addRegUse(reg);
500       // add to active
501       active_.push_back(std::make_pair(Interval, IntervalPos));
502
503       // Pop off the end of the list.
504       inactive_[i] = inactive_.back();
505       inactive_.pop_back();
506       --i; --e;
507     } else {
508       // Otherwise, just update the iterator position.
509       inactive_[i].second = IntervalPos;
510     }
511   }
512 }
513
514 /// updateSpillWeights - updates the spill weights of the specifed physical
515 /// register and its weight.
516 static void updateSpillWeights(std::vector<float> &Weights,
517                                unsigned reg, float weight,
518                                const TargetRegisterInfo *TRI) {
519   Weights[reg] += weight;
520   for (const unsigned* as = TRI->getAliasSet(reg); *as; ++as)
521     Weights[*as] += weight;
522 }
523
524 static
525 RALinScan::IntervalPtrs::iterator
526 FindIntervalInVector(RALinScan::IntervalPtrs &IP, LiveInterval *LI) {
527   for (RALinScan::IntervalPtrs::iterator I = IP.begin(), E = IP.end();
528        I != E; ++I)
529     if (I->first == LI) return I;
530   return IP.end();
531 }
532
533 static void RevertVectorIteratorsTo(RALinScan::IntervalPtrs &V, unsigned Point){
534   for (unsigned i = 0, e = V.size(); i != e; ++i) {
535     RALinScan::IntervalPtr &IP = V[i];
536     LiveInterval::iterator I = std::upper_bound(IP.first->begin(),
537                                                 IP.second, Point);
538     if (I != IP.first->begin()) --I;
539     IP.second = I;
540   }
541 }
542
543 /// addStackInterval - Create a LiveInterval for stack if the specified live
544 /// interval has been spilled.
545 static void addStackInterval(LiveInterval *cur, LiveStacks *ls_,
546                              LiveIntervals *li_, float &Weight,
547                              VirtRegMap &vrm_) {
548   int SS = vrm_.getStackSlot(cur->reg);
549   if (SS == VirtRegMap::NO_STACK_SLOT)
550     return;
551   LiveInterval &SI = ls_->getOrCreateInterval(SS);
552   SI.weight += Weight;
553
554   VNInfo *VNI;
555   if (SI.hasAtLeastOneValue())
556     VNI = SI.getValNumInfo(0);
557   else
558     VNI = SI.getNextValue(~0U, 0, ls_->getVNInfoAllocator());
559
560   LiveInterval &RI = li_->getInterval(cur->reg);
561   // FIXME: This may be overly conservative.
562   SI.MergeRangesInAsValue(RI, VNI);
563 }
564
565 /// getConflictWeight - Return the number of conflicts between cur
566 /// live interval and defs and uses of Reg weighted by loop depthes.
567 static float getConflictWeight(LiveInterval *cur, unsigned Reg,
568                                   LiveIntervals *li_,
569                                   MachineRegisterInfo *mri_,
570                                   const MachineLoopInfo *loopInfo) {
571   float Conflicts = 0;
572   for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
573          E = mri_->reg_end(); I != E; ++I) {
574     MachineInstr *MI = &*I;
575     if (cur->liveAt(li_->getInstructionIndex(MI))) {
576       unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
577       Conflicts += powf(10.0f, (float)loopDepth);
578     }
579   }
580   return Conflicts;
581 }
582
583 /// findIntervalsToSpill - Determine the intervals to spill for the
584 /// specified interval. It's passed the physical registers whose spill
585 /// weight is the lowest among all the registers whose live intervals
586 /// conflict with the interval.
587 void RALinScan::findIntervalsToSpill(LiveInterval *cur,
588                             std::vector<std::pair<unsigned,float> > &Candidates,
589                             unsigned NumCands,
590                             SmallVector<LiveInterval*, 8> &SpillIntervals) {
591   // We have figured out the *best* register to spill. But there are other
592   // registers that are pretty good as well (spill weight within 3%). Spill
593   // the one that has fewest defs and uses that conflict with cur.
594   float Conflicts[3] = { 0.0f, 0.0f, 0.0f };
595   SmallVector<LiveInterval*, 8> SLIs[3];
596
597   DOUT << "\tConsidering " << NumCands << " candidates: ";
598   DEBUG(for (unsigned i = 0; i != NumCands; ++i)
599           DOUT << tri_->getName(Candidates[i].first) << " ";
600         DOUT << "\n";);
601   
602   // Calculate the number of conflicts of each candidate.
603   for (IntervalPtrs::iterator i = active_.begin(); i != active_.end(); ++i) {
604     unsigned Reg = i->first->reg;
605     unsigned PhysReg = vrm_->getPhys(Reg);
606     if (!cur->overlapsFrom(*i->first, i->second))
607       continue;
608     for (unsigned j = 0; j < NumCands; ++j) {
609       unsigned Candidate = Candidates[j].first;
610       if (tri_->regsOverlap(PhysReg, Candidate)) {
611         if (NumCands > 1)
612           Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
613         SLIs[j].push_back(i->first);
614       }
615     }
616   }
617
618   for (IntervalPtrs::iterator i = inactive_.begin(); i != inactive_.end(); ++i){
619     unsigned Reg = i->first->reg;
620     unsigned PhysReg = vrm_->getPhys(Reg);
621     if (!cur->overlapsFrom(*i->first, i->second-1))
622       continue;
623     for (unsigned j = 0; j < NumCands; ++j) {
624       unsigned Candidate = Candidates[j].first;
625       if (tri_->regsOverlap(PhysReg, Candidate)) {
626         if (NumCands > 1)
627           Conflicts[j] += getConflictWeight(cur, Reg, li_, mri_, loopInfo);
628         SLIs[j].push_back(i->first);
629       }
630     }
631   }
632
633   // Which is the best candidate?
634   unsigned BestCandidate = 0;
635   float MinConflicts = Conflicts[0];
636   for (unsigned i = 1; i != NumCands; ++i) {
637     if (Conflicts[i] < MinConflicts) {
638       BestCandidate = i;
639       MinConflicts = Conflicts[i];
640     }
641   }
642
643   std::copy(SLIs[BestCandidate].begin(), SLIs[BestCandidate].end(),
644             std::back_inserter(SpillIntervals));
645 }
646
647 namespace {
648   struct WeightCompare {
649     typedef std::pair<unsigned, float> RegWeightPair;
650     bool operator()(const RegWeightPair &LHS, const RegWeightPair &RHS) const {
651       return LHS.second < RHS.second;
652     }
653   };
654 }
655
656 static bool weightsAreClose(float w1, float w2) {
657   if (!NewHeuristic)
658     return false;
659
660   float diff = w1 - w2;
661   if (diff <= 0.02f)  // Within 0.02f
662     return true;
663   return (diff / w2) <= 0.05f;  // Within 5%.
664 }
665
666 /// assignRegOrStackSlotAtInterval - assign a register if one is available, or
667 /// spill.
668 void RALinScan::assignRegOrStackSlotAtInterval(LiveInterval* cur)
669 {
670   DOUT << "\tallocating current interval: ";
671
672   // This is an implicitly defined live interval, just assign any register.
673   const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
674   if (cur->empty()) {
675     unsigned physReg = cur->preference;
676     if (!physReg)
677       physReg = *RC->allocation_order_begin(*mf_);
678     DOUT <<  tri_->getName(physReg) << '\n';
679     // Note the register is not really in use.
680     vrm_->assignVirt2Phys(cur->reg, physReg);
681     return;
682   }
683
684   PhysRegTracker backupPrt = *prt_;
685
686   std::vector<std::pair<unsigned, float> > SpillWeightsToAdd;
687   unsigned StartPosition = cur->beginNumber();
688   const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
689
690   // If start of this live interval is defined by a move instruction and its
691   // source is assigned a physical register that is compatible with the target
692   // register class, then we should try to assign it the same register.
693   // This can happen when the move is from a larger register class to a smaller
694   // one, e.g. X86::mov32to32_. These move instructions are not coalescable.
695   if (!cur->preference && cur->hasAtLeastOneValue()) {
696     VNInfo *vni = cur->begin()->valno;
697     if (vni->def && vni->def != ~1U && vni->def != ~0U) {
698       MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
699       unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
700       if (CopyMI &&
701           tii_->isMoveInstr(*CopyMI, SrcReg, DstReg, SrcSubReg, DstSubReg)) {
702         unsigned Reg = 0;
703         if (TargetRegisterInfo::isPhysicalRegister(SrcReg))
704           Reg = SrcReg;
705         else if (vrm_->isAssignedReg(SrcReg))
706           Reg = vrm_->getPhys(SrcReg);
707         if (Reg && allocatableRegs_[Reg] && RC->contains(Reg))
708           cur->preference = Reg;
709       }
710     }
711   }
712
713   // for every interval in inactive we overlap with, mark the
714   // register as not free and update spill weights.
715   for (IntervalPtrs::const_iterator i = inactive_.begin(),
716          e = inactive_.end(); i != e; ++i) {
717     unsigned Reg = i->first->reg;
718     assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
719            "Can only allocate virtual registers!");
720     const TargetRegisterClass *RegRC = mri_->getRegClass(Reg);
721     // If this is not in a related reg class to the register we're allocating, 
722     // don't check it.
723     if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&
724         cur->overlapsFrom(*i->first, i->second-1)) {
725       Reg = vrm_->getPhys(Reg);
726       prt_->addRegUse(Reg);
727       SpillWeightsToAdd.push_back(std::make_pair(Reg, i->first->weight));
728     }
729   }
730   
731   // Speculatively check to see if we can get a register right now.  If not,
732   // we know we won't be able to by adding more constraints.  If so, we can
733   // check to see if it is valid.  Doing an exhaustive search of the fixed_ list
734   // is very bad (it contains all callee clobbered registers for any functions
735   // with a call), so we want to avoid doing that if possible.
736   unsigned physReg = getFreePhysReg(cur);
737   unsigned BestPhysReg = physReg;
738   if (physReg) {
739     // We got a register.  However, if it's in the fixed_ list, we might
740     // conflict with it.  Check to see if we conflict with it or any of its
741     // aliases.
742     SmallSet<unsigned, 8> RegAliases;
743     for (const unsigned *AS = tri_->getAliasSet(physReg); *AS; ++AS)
744       RegAliases.insert(*AS);
745     
746     bool ConflictsWithFixed = false;
747     for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
748       IntervalPtr &IP = fixed_[i];
749       if (physReg == IP.first->reg || RegAliases.count(IP.first->reg)) {
750         // Okay, this reg is on the fixed list.  Check to see if we actually
751         // conflict.
752         LiveInterval *I = IP.first;
753         if (I->endNumber() > StartPosition) {
754           LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
755           IP.second = II;
756           if (II != I->begin() && II->start > StartPosition)
757             --II;
758           if (cur->overlapsFrom(*I, II)) {
759             ConflictsWithFixed = true;
760             break;
761           }
762         }
763       }
764     }
765     
766     // Okay, the register picked by our speculative getFreePhysReg call turned
767     // out to be in use.  Actually add all of the conflicting fixed registers to
768     // prt so we can do an accurate query.
769     if (ConflictsWithFixed) {
770       // For every interval in fixed we overlap with, mark the register as not
771       // free and update spill weights.
772       for (unsigned i = 0, e = fixed_.size(); i != e; ++i) {
773         IntervalPtr &IP = fixed_[i];
774         LiveInterval *I = IP.first;
775
776         const TargetRegisterClass *RegRC = OneClassForEachPhysReg[I->reg];
777         if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader &&       
778             I->endNumber() > StartPosition) {
779           LiveInterval::iterator II = I->advanceTo(IP.second, StartPosition);
780           IP.second = II;
781           if (II != I->begin() && II->start > StartPosition)
782             --II;
783           if (cur->overlapsFrom(*I, II)) {
784             unsigned reg = I->reg;
785             prt_->addRegUse(reg);
786             SpillWeightsToAdd.push_back(std::make_pair(reg, I->weight));
787           }
788         }
789       }
790
791       // Using the newly updated prt_ object, which includes conflicts in the
792       // future, see if there are any registers available.
793       physReg = getFreePhysReg(cur);
794     }
795   }
796     
797   // Restore the physical register tracker, removing information about the
798   // future.
799   *prt_ = backupPrt;
800   
801   // if we find a free register, we are done: assign this virtual to
802   // the free physical register and add this interval to the active
803   // list.
804   if (physReg) {
805     DOUT <<  tri_->getName(physReg) << '\n';
806     vrm_->assignVirt2Phys(cur->reg, physReg);
807     prt_->addRegUse(physReg);
808     active_.push_back(std::make_pair(cur, cur->begin()));
809     handled_.push_back(cur);
810     return;
811   }
812   DOUT << "no free registers\n";
813
814   // Compile the spill weights into an array that is better for scanning.
815   std::vector<float> SpillWeights(tri_->getNumRegs(), 0.0f);
816   for (std::vector<std::pair<unsigned, float> >::iterator
817        I = SpillWeightsToAdd.begin(), E = SpillWeightsToAdd.end(); I != E; ++I)
818     updateSpillWeights(SpillWeights, I->first, I->second, tri_);
819   
820   // for each interval in active, update spill weights.
821   for (IntervalPtrs::const_iterator i = active_.begin(), e = active_.end();
822        i != e; ++i) {
823     unsigned reg = i->first->reg;
824     assert(TargetRegisterInfo::isVirtualRegister(reg) &&
825            "Can only allocate virtual registers!");
826     reg = vrm_->getPhys(reg);
827     updateSpillWeights(SpillWeights, reg, i->first->weight, tri_);
828   }
829  
830   DOUT << "\tassigning stack slot at interval "<< *cur << ":\n";
831
832   // Find a register to spill.
833   float minWeight = HUGE_VALF;
834   unsigned minReg = 0; /*cur->preference*/;  // Try the preferred register first.
835
836   bool Found = false;
837   std::vector<std::pair<unsigned,float> > RegsWeights;
838   if (!minReg || SpillWeights[minReg] == HUGE_VALF)
839     for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
840            e = RC->allocation_order_end(*mf_); i != e; ++i) {
841       unsigned reg = *i;
842       float regWeight = SpillWeights[reg];
843       if (minWeight > regWeight)
844         Found = true;
845       RegsWeights.push_back(std::make_pair(reg, regWeight));
846     }
847   
848   // If we didn't find a register that is spillable, try aliases?
849   if (!Found) {
850     for (TargetRegisterClass::iterator i = RC->allocation_order_begin(*mf_),
851            e = RC->allocation_order_end(*mf_); i != e; ++i) {
852       unsigned reg = *i;
853       // No need to worry about if the alias register size < regsize of RC.
854       // We are going to spill all registers that alias it anyway.
855       for (const unsigned* as = tri_->getAliasSet(reg); *as; ++as)
856         RegsWeights.push_back(std::make_pair(*as, SpillWeights[*as]));
857     }
858   }
859
860   // Sort all potential spill candidates by weight.
861   std::sort(RegsWeights.begin(), RegsWeights.end(), WeightCompare());
862   minReg = RegsWeights[0].first;
863   minWeight = RegsWeights[0].second;
864   if (minWeight == HUGE_VALF) {
865     // All registers must have inf weight. Just grab one!
866     minReg = BestPhysReg ? BestPhysReg : *RC->allocation_order_begin(*mf_);
867     if (cur->weight == HUGE_VALF ||
868         li_->getApproximateInstructionCount(*cur) == 0) {
869       // Spill a physical register around defs and uses.
870       li_->spillPhysRegAroundRegDefsUses(*cur, minReg, *vrm_);
871       assignRegOrStackSlotAtInterval(cur);
872       return;
873     }
874   }
875
876   // Find up to 3 registers to consider as spill candidates.
877   unsigned LastCandidate = RegsWeights.size() >= 3 ? 3 : 1;
878   while (LastCandidate > 1) {
879     if (weightsAreClose(RegsWeights[LastCandidate-1].second, minWeight))
880       break;
881     --LastCandidate;
882   }
883
884   DOUT << "\t\tregister(s) with min weight(s): ";
885   DEBUG(for (unsigned i = 0; i != LastCandidate; ++i)
886           DOUT << tri_->getName(RegsWeights[i].first)
887                << " (" << RegsWeights[i].second << ")\n");
888
889   // if the current has the minimum weight, we need to spill it and
890   // add any added intervals back to unhandled, and restart
891   // linearscan.
892   if (cur->weight != HUGE_VALF && cur->weight <= minWeight) {
893     DOUT << "\t\t\tspilling(c): " << *cur << '\n';
894     float SSWeight;
895     SmallVector<LiveInterval*, 8> spillIs;
896     std::vector<LiveInterval*> added =
897       li_->addIntervalsForSpills(*cur, spillIs, loopInfo, *vrm_, SSWeight);
898     addStackInterval(cur, ls_, li_, SSWeight, *vrm_);
899     if (added.empty())
900       return;  // Early exit if all spills were folded.
901
902     // Merge added with unhandled.  Note that we know that
903     // addIntervalsForSpills returns intervals sorted by their starting
904     // point.
905     for (unsigned i = 0, e = added.size(); i != e; ++i)
906       unhandled_.push(added[i]);
907     return;
908   }
909
910   ++NumBacktracks;
911
912   // push the current interval back to unhandled since we are going
913   // to re-run at least this iteration. Since we didn't modify it it
914   // should go back right in the front of the list
915   unhandled_.push(cur);
916
917   assert(TargetRegisterInfo::isPhysicalRegister(minReg) &&
918          "did not choose a register to spill?");
919
920   // We spill all intervals aliasing the register with
921   // minimum weight, rollback to the interval with the earliest
922   // start point and let the linear scan algorithm run again
923   SmallVector<LiveInterval*, 8> spillIs;
924
925   // Determine which intervals have to be spilled.
926   findIntervalsToSpill(cur, RegsWeights, LastCandidate, spillIs);
927
928   // Set of spilled vregs (used later to rollback properly)
929   SmallSet<unsigned, 8> spilled;
930
931   // The earliest start of a Spilled interval indicates up to where
932   // in handled we need to roll back
933   unsigned earliestStart = cur->beginNumber();
934
935   // Spill live intervals of virtual regs mapped to the physical register we
936   // want to clear (and its aliases).  We only spill those that overlap with the
937   // current interval as the rest do not affect its allocation. we also keep
938   // track of the earliest start of all spilled live intervals since this will
939   // mark our rollback point.
940   std::vector<LiveInterval*> added;
941   while (!spillIs.empty()) {
942     LiveInterval *sli = spillIs.back();
943     spillIs.pop_back();
944     DOUT << "\t\t\tspilling(a): " << *sli << '\n';
945     earliestStart = std::min(earliestStart, sli->beginNumber());
946     float SSWeight;
947     std::vector<LiveInterval*> newIs =
948       li_->addIntervalsForSpills(*sli, spillIs, loopInfo, *vrm_, SSWeight);
949     addStackInterval(sli, ls_, li_, SSWeight, *vrm_);
950     std::copy(newIs.begin(), newIs.end(), std::back_inserter(added));
951     spilled.insert(sli->reg);
952   }
953
954   DOUT << "\t\trolling back to: " << earliestStart << '\n';
955
956   // Scan handled in reverse order up to the earliest start of a
957   // spilled live interval and undo each one, restoring the state of
958   // unhandled.
959   while (!handled_.empty()) {
960     LiveInterval* i = handled_.back();
961     // If this interval starts before t we are done.
962     if (i->beginNumber() < earliestStart)
963       break;
964     DOUT << "\t\t\tundo changes for: " << *i << '\n';
965     handled_.pop_back();
966
967     // When undoing a live interval allocation we must know if it is active or
968     // inactive to properly update the PhysRegTracker and the VirtRegMap.
969     IntervalPtrs::iterator it;
970     if ((it = FindIntervalInVector(active_, i)) != active_.end()) {
971       active_.erase(it);
972       assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
973       if (!spilled.count(i->reg))
974         unhandled_.push(i);
975       prt_->delRegUse(vrm_->getPhys(i->reg));
976       vrm_->clearVirt(i->reg);
977     } else if ((it = FindIntervalInVector(inactive_, i)) != inactive_.end()) {
978       inactive_.erase(it);
979       assert(!TargetRegisterInfo::isPhysicalRegister(i->reg));
980       if (!spilled.count(i->reg))
981         unhandled_.push(i);
982       vrm_->clearVirt(i->reg);
983     } else {
984       assert(TargetRegisterInfo::isVirtualRegister(i->reg) &&
985              "Can only allocate virtual registers!");
986       vrm_->clearVirt(i->reg);
987       unhandled_.push(i);
988     }
989
990     // It interval has a preference, it must be defined by a copy. Clear the
991     // preference now since the source interval allocation may have been undone
992     // as well.
993     i->preference = 0;
994   }
995
996   // Rewind the iterators in the active, inactive, and fixed lists back to the
997   // point we reverted to.
998   RevertVectorIteratorsTo(active_, earliestStart);
999   RevertVectorIteratorsTo(inactive_, earliestStart);
1000   RevertVectorIteratorsTo(fixed_, earliestStart);
1001
1002   // scan the rest and undo each interval that expired after t and
1003   // insert it in active (the next iteration of the algorithm will
1004   // put it in inactive if required)
1005   for (unsigned i = 0, e = handled_.size(); i != e; ++i) {
1006     LiveInterval *HI = handled_[i];
1007     if (!HI->expiredAt(earliestStart) &&
1008         HI->expiredAt(cur->beginNumber())) {
1009       DOUT << "\t\t\tundo changes for: " << *HI << '\n';
1010       active_.push_back(std::make_pair(HI, HI->begin()));
1011       assert(!TargetRegisterInfo::isPhysicalRegister(HI->reg));
1012       prt_->addRegUse(vrm_->getPhys(HI->reg));
1013     }
1014   }
1015
1016   // merge added with unhandled
1017   for (unsigned i = 0, e = added.size(); i != e; ++i)
1018     unhandled_.push(added[i]);
1019 }
1020
1021 /// getFreePhysReg - return a free physical register for this virtual register
1022 /// interval if we have one, otherwise return 0.
1023 unsigned RALinScan::getFreePhysReg(LiveInterval *cur) {
1024   SmallVector<unsigned, 256> inactiveCounts;
1025   unsigned MaxInactiveCount = 0;
1026   
1027   const TargetRegisterClass *RC = mri_->getRegClass(cur->reg);
1028   const TargetRegisterClass *RCLeader = RelatedRegClasses.getLeaderValue(RC);
1029  
1030   for (IntervalPtrs::iterator i = inactive_.begin(), e = inactive_.end();
1031        i != e; ++i) {
1032     unsigned reg = i->first->reg;
1033     assert(TargetRegisterInfo::isVirtualRegister(reg) &&
1034            "Can only allocate virtual registers!");
1035
1036     // If this is not in a related reg class to the register we're allocating, 
1037     // don't check it.
1038     const TargetRegisterClass *RegRC = mri_->getRegClass(reg);
1039     if (RelatedRegClasses.getLeaderValue(RegRC) == RCLeader) {
1040       reg = vrm_->getPhys(reg);
1041       if (inactiveCounts.size() <= reg)
1042         inactiveCounts.resize(reg+1);
1043       ++inactiveCounts[reg];
1044       MaxInactiveCount = std::max(MaxInactiveCount, inactiveCounts[reg]);
1045     }
1046   }
1047
1048   unsigned FreeReg = 0;
1049   unsigned FreeRegInactiveCount = 0;
1050
1051   // If copy coalescer has assigned a "preferred" register, check if it's
1052   // available first.
1053   if (cur->preference) {
1054     if (prt_->isRegAvail(cur->preference) && 
1055         RC->contains(cur->preference)) {
1056       DOUT << "\t\tassigned the preferred register: "
1057            << tri_->getName(cur->preference) << "\n";
1058       return cur->preference;
1059     } else
1060       DOUT << "\t\tunable to assign the preferred register: "
1061            << tri_->getName(cur->preference) << "\n";
1062   }
1063
1064   // Scan for the first available register.
1065   TargetRegisterClass::iterator I = RC->allocation_order_begin(*mf_);
1066   TargetRegisterClass::iterator E = RC->allocation_order_end(*mf_);
1067   assert(I != E && "No allocatable register in this register class!");
1068   for (; I != E; ++I)
1069     if (prt_->isRegAvail(*I)) {
1070       FreeReg = *I;
1071       if (FreeReg < inactiveCounts.size())
1072         FreeRegInactiveCount = inactiveCounts[FreeReg];
1073       else
1074         FreeRegInactiveCount = 0;
1075       break;
1076     }
1077
1078   // If there are no free regs, or if this reg has the max inactive count,
1079   // return this register.
1080   if (FreeReg == 0 || FreeRegInactiveCount == MaxInactiveCount) return FreeReg;
1081   
1082   // Continue scanning the registers, looking for the one with the highest
1083   // inactive count.  Alkis found that this reduced register pressure very
1084   // slightly on X86 (in rev 1.94 of this file), though this should probably be
1085   // reevaluated now.
1086   for (; I != E; ++I) {
1087     unsigned Reg = *I;
1088     if (prt_->isRegAvail(Reg) && Reg < inactiveCounts.size() &&
1089         FreeRegInactiveCount < inactiveCounts[Reg]) {
1090       FreeReg = Reg;
1091       FreeRegInactiveCount = inactiveCounts[Reg];
1092       if (FreeRegInactiveCount == MaxInactiveCount)
1093         break;    // We found the one with the max inactive count.
1094     }
1095   }
1096   
1097   return FreeReg;
1098 }
1099
1100 FunctionPass* llvm::createLinearScanRegisterAllocator() {
1101   return new RALinScan();
1102 }