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