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