Precompute block frequencies, pow() isn't free.
[oota-llvm.git] / lib / CodeGen / RegAllocGreedy.cpp
1 //===-- RegAllocGreedy.cpp - greedy 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 defines the RAGreedy function pass for register allocation in
11 // optimized builds.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "regalloc"
16 #include "AllocationOrder.h"
17 #include "LiveIntervalUnion.h"
18 #include "LiveRangeEdit.h"
19 #include "RegAllocBase.h"
20 #include "Spiller.h"
21 #include "SpillPlacement.h"
22 #include "SplitKit.h"
23 #include "VirtRegMap.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/Function.h"
27 #include "llvm/PassAnalysisSupport.h"
28 #include "llvm/CodeGen/CalcSpillWeights.h"
29 #include "llvm/CodeGen/EdgeBundles.h"
30 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
31 #include "llvm/CodeGen/LiveStackAnalysis.h"
32 #include "llvm/CodeGen/MachineDominators.h"
33 #include "llvm/CodeGen/MachineFunctionPass.h"
34 #include "llvm/CodeGen/MachineLoopInfo.h"
35 #include "llvm/CodeGen/MachineLoopRanges.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/Passes.h"
38 #include "llvm/CodeGen/RegAllocRegistry.h"
39 #include "llvm/CodeGen/RegisterCoalescer.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Support/Timer.h"
45
46 #include <queue>
47
48 using namespace llvm;
49
50 STATISTIC(NumGlobalSplits, "Number of split global live ranges");
51 STATISTIC(NumLocalSplits,  "Number of split local live ranges");
52 STATISTIC(NumReassigned,   "Number of interferences reassigned");
53 STATISTIC(NumEvicted,      "Number of interferences evicted");
54
55 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
56                                        createGreedyRegisterAllocator);
57
58 namespace {
59 class RAGreedy : public MachineFunctionPass, public RegAllocBase {
60   // context
61   MachineFunction *MF;
62   BitVector ReservedRegs;
63
64   // analyses
65   SlotIndexes *Indexes;
66   LiveStacks *LS;
67   MachineDominatorTree *DomTree;
68   MachineLoopInfo *Loops;
69   MachineLoopRanges *LoopRanges;
70   EdgeBundles *Bundles;
71   SpillPlacement *SpillPlacer;
72
73   // state
74   std::auto_ptr<Spiller> SpillerInstance;
75   std::priority_queue<std::pair<unsigned, unsigned> > Queue;
76
77   // Live ranges pass through a number of stages as we try to allocate them.
78   // Some of the stages may also create new live ranges:
79   //
80   // - Region splitting.
81   // - Per-block splitting.
82   // - Local splitting.
83   // - Spilling.
84   //
85   // Ranges produced by one of the stages skip the previous stages when they are
86   // dequeued. This improves performance because we can skip interference checks
87   // that are unlikely to give any results. It also guarantees that the live
88   // range splitting algorithm terminates, something that is otherwise hard to
89   // ensure.
90   enum LiveRangeStage {
91     RS_Original, ///< Never seen before, never split.
92     RS_Second,   ///< Second time in the queue.
93     RS_Region,   ///< Produced by region splitting.
94     RS_Block,    ///< Produced by per-block splitting.
95     RS_Local,    ///< Produced by local splitting.
96     RS_Spill     ///< Produced by spilling.
97   };
98
99   IndexedMap<unsigned char, VirtReg2IndexFunctor> LRStage;
100
101   LiveRangeStage getStage(const LiveInterval &VirtReg) const {
102     return LiveRangeStage(LRStage[VirtReg.reg]);
103   }
104
105   template<typename Iterator>
106   void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
107     LRStage.resize(MRI->getNumVirtRegs());
108     for (;Begin != End; ++Begin)
109       LRStage[(*Begin)->reg] = NewStage;
110   }
111
112   // splitting state.
113   std::auto_ptr<SplitAnalysis> SA;
114   std::auto_ptr<SplitEditor> SE;
115
116   /// All basic blocks where the current register is live.
117   SmallVector<SpillPlacement::BlockConstraint, 8> SpillConstraints;
118
119   /// For every instruction in SA->UseSlots, store the previous non-copy
120   /// instruction.
121   SmallVector<SlotIndex, 8> PrevSlot;
122
123 public:
124   RAGreedy();
125
126   /// Return the pass name.
127   virtual const char* getPassName() const {
128     return "Greedy Register Allocator";
129   }
130
131   /// RAGreedy analysis usage.
132   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
133   virtual void releaseMemory();
134   virtual Spiller &spiller() { return *SpillerInstance; }
135   virtual void enqueue(LiveInterval *LI);
136   virtual LiveInterval *dequeue();
137   virtual unsigned selectOrSplit(LiveInterval&,
138                                  SmallVectorImpl<LiveInterval*>&);
139
140   /// Perform register allocation.
141   virtual bool runOnMachineFunction(MachineFunction &mf);
142
143   static char ID;
144
145 private:
146   bool checkUncachedInterference(LiveInterval&, unsigned);
147   LiveInterval *getSingleInterference(LiveInterval&, unsigned);
148   bool reassignVReg(LiveInterval &InterferingVReg, unsigned OldPhysReg);
149   float calcInterferenceInfo(LiveInterval&, unsigned);
150   float calcGlobalSplitCost(const BitVector&);
151   void splitAroundRegion(LiveInterval&, unsigned, const BitVector&,
152                          SmallVectorImpl<LiveInterval*>&);
153   void calcGapWeights(unsigned, SmallVectorImpl<float>&);
154   SlotIndex getPrevMappedIndex(const MachineInstr*);
155   void calcPrevSlots();
156   unsigned nextSplitPoint(unsigned);
157   bool canEvictInterference(LiveInterval&, unsigned, unsigned, float&);
158
159   unsigned tryReassign(LiveInterval&, AllocationOrder&,
160                               SmallVectorImpl<LiveInterval*>&);
161   unsigned tryEvict(LiveInterval&, AllocationOrder&,
162                     SmallVectorImpl<LiveInterval*>&);
163   unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
164                           SmallVectorImpl<LiveInterval*>&);
165   unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
166     SmallVectorImpl<LiveInterval*>&);
167   unsigned trySplit(LiveInterval&, AllocationOrder&,
168                     SmallVectorImpl<LiveInterval*>&);
169 };
170 } // end anonymous namespace
171
172 char RAGreedy::ID = 0;
173
174 FunctionPass* llvm::createGreedyRegisterAllocator() {
175   return new RAGreedy();
176 }
177
178 RAGreedy::RAGreedy(): MachineFunctionPass(ID), LRStage(RS_Original) {
179   initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
180   initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
181   initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
182   initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry());
183   initializeRegisterCoalescerAnalysisGroup(*PassRegistry::getPassRegistry());
184   initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
185   initializeLiveStacksPass(*PassRegistry::getPassRegistry());
186   initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
187   initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
188   initializeMachineLoopRangesPass(*PassRegistry::getPassRegistry());
189   initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
190   initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
191   initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
192 }
193
194 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
195   AU.setPreservesCFG();
196   AU.addRequired<AliasAnalysis>();
197   AU.addPreserved<AliasAnalysis>();
198   AU.addRequired<LiveIntervals>();
199   AU.addRequired<SlotIndexes>();
200   AU.addPreserved<SlotIndexes>();
201   if (StrongPHIElim)
202     AU.addRequiredID(StrongPHIEliminationID);
203   AU.addRequiredTransitive<RegisterCoalescer>();
204   AU.addRequired<CalculateSpillWeights>();
205   AU.addRequired<LiveStacks>();
206   AU.addPreserved<LiveStacks>();
207   AU.addRequired<MachineDominatorTree>();
208   AU.addPreserved<MachineDominatorTree>();
209   AU.addRequired<MachineLoopInfo>();
210   AU.addPreserved<MachineLoopInfo>();
211   AU.addRequired<MachineLoopRanges>();
212   AU.addPreserved<MachineLoopRanges>();
213   AU.addRequired<VirtRegMap>();
214   AU.addPreserved<VirtRegMap>();
215   AU.addRequired<EdgeBundles>();
216   AU.addRequired<SpillPlacement>();
217   MachineFunctionPass::getAnalysisUsage(AU);
218 }
219
220 void RAGreedy::releaseMemory() {
221   SpillerInstance.reset(0);
222   LRStage.clear();
223   RegAllocBase::releaseMemory();
224 }
225
226 void RAGreedy::enqueue(LiveInterval *LI) {
227   // Prioritize live ranges by size, assigning larger ranges first.
228   // The queue holds (size, reg) pairs.
229   const unsigned Size = LI->getSize();
230   const unsigned Reg = LI->reg;
231   assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
232          "Can only enqueue virtual registers");
233   unsigned Prio;
234
235   LRStage.grow(Reg);
236   if (LRStage[Reg] == RS_Original)
237     // 1st generation ranges are handled first, long -> short.
238     Prio = (1u << 31) + Size;
239   else
240     // Repeat offenders are handled second, short -> long
241     Prio = (1u << 30) - Size;
242
243   // Boost ranges that have a physical register hint.
244   const unsigned Hint = VRM->getRegAllocPref(Reg);
245   if (TargetRegisterInfo::isPhysicalRegister(Hint))
246     Prio |= (1u << 30);
247
248   Queue.push(std::make_pair(Prio, Reg));
249 }
250
251 LiveInterval *RAGreedy::dequeue() {
252   if (Queue.empty())
253     return 0;
254   LiveInterval *LI = &LIS->getInterval(Queue.top().second);
255   Queue.pop();
256   return LI;
257 }
258
259 //===----------------------------------------------------------------------===//
260 //                         Register Reassignment
261 //===----------------------------------------------------------------------===//
262
263 // Check interference without using the cache.
264 bool RAGreedy::checkUncachedInterference(LiveInterval &VirtReg,
265                                          unsigned PhysReg) {
266   for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
267     LiveIntervalUnion::Query subQ(&VirtReg, &PhysReg2LiveUnion[*AliasI]);
268     if (subQ.checkInterference())
269       return true;
270   }
271   return false;
272 }
273
274 /// getSingleInterference - Return the single interfering virtual register
275 /// assigned to PhysReg. Return 0 if more than one virtual register is
276 /// interfering.
277 LiveInterval *RAGreedy::getSingleInterference(LiveInterval &VirtReg,
278                                               unsigned PhysReg) {
279   // Check physreg and aliases.
280   LiveInterval *Interference = 0;
281   for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
282     LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
283     if (Q.checkInterference()) {
284       if (Interference)
285         return 0;
286       if (Q.collectInterferingVRegs(2) > 1)
287         return 0;
288       Interference = Q.interferingVRegs().front();
289     }
290   }
291   return Interference;
292 }
293
294 // Attempt to reassign this virtual register to a different physical register.
295 //
296 // FIXME: we are not yet caching these "second-level" interferences discovered
297 // in the sub-queries. These interferences can change with each call to
298 // selectOrSplit. However, we could implement a "may-interfere" cache that
299 // could be conservatively dirtied when we reassign or split.
300 //
301 // FIXME: This may result in a lot of alias queries. We could summarize alias
302 // live intervals in their parent register's live union, but it's messy.
303 bool RAGreedy::reassignVReg(LiveInterval &InterferingVReg,
304                             unsigned WantedPhysReg) {
305   assert(TargetRegisterInfo::isVirtualRegister(InterferingVReg.reg) &&
306          "Can only reassign virtual registers");
307   assert(TRI->regsOverlap(WantedPhysReg, VRM->getPhys(InterferingVReg.reg)) &&
308          "inconsistent phys reg assigment");
309
310   AllocationOrder Order(InterferingVReg.reg, *VRM, ReservedRegs);
311   while (unsigned PhysReg = Order.next()) {
312     // Don't reassign to a WantedPhysReg alias.
313     if (TRI->regsOverlap(PhysReg, WantedPhysReg))
314       continue;
315
316     if (checkUncachedInterference(InterferingVReg, PhysReg))
317       continue;
318
319     // Reassign the interfering virtual reg to this physical reg.
320     unsigned OldAssign = VRM->getPhys(InterferingVReg.reg);
321     DEBUG(dbgs() << "reassigning: " << InterferingVReg << " from " <<
322           TRI->getName(OldAssign) << " to " << TRI->getName(PhysReg) << '\n');
323     unassign(InterferingVReg, OldAssign);
324     assign(InterferingVReg, PhysReg);
325     ++NumReassigned;
326     return true;
327   }
328   return false;
329 }
330
331 /// tryReassign - Try to reassign a single interference to a different physreg.
332 /// @param  VirtReg Currently unassigned virtual register.
333 /// @param  Order   Physregs to try.
334 /// @return         Physreg to assign VirtReg, or 0.
335 unsigned RAGreedy::tryReassign(LiveInterval &VirtReg, AllocationOrder &Order,
336                                SmallVectorImpl<LiveInterval*> &NewVRegs){
337   NamedRegionTimer T("Reassign", TimerGroupName, TimePassesIsEnabled);
338
339   Order.rewind();
340   while (unsigned PhysReg = Order.next()) {
341     LiveInterval *InterferingVReg = getSingleInterference(VirtReg, PhysReg);
342     if (!InterferingVReg)
343       continue;
344     if (TargetRegisterInfo::isPhysicalRegister(InterferingVReg->reg))
345       continue;
346     if (reassignVReg(*InterferingVReg, PhysReg))
347       return PhysReg;
348   }
349   return 0;
350 }
351
352
353 //===----------------------------------------------------------------------===//
354 //                         Interference eviction
355 //===----------------------------------------------------------------------===//
356
357 /// canEvict - Return true if all interferences between VirtReg and PhysReg can
358 /// be evicted. Set maxWeight to the maximal spill weight of an interference.
359 bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
360                                     unsigned Size, float &MaxWeight) {
361   float Weight = 0;
362   for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) {
363     LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
364     // If there is 10 or more interferences, chances are one is smaller.
365     if (Q.collectInterferingVRegs(10) >= 10)
366       return false;
367
368     // CHeck if any interfering live range is shorter than VirtReg.
369     for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
370       LiveInterval *Intf = Q.interferingVRegs()[i];
371       if (TargetRegisterInfo::isPhysicalRegister(Intf->reg))
372         return false;
373       if (Intf->getSize() <= Size)
374         return false;
375       Weight = std::max(Weight, Intf->weight);
376     }
377   }
378   MaxWeight = Weight;
379   return true;
380 }
381
382 /// tryEvict - Try to evict all interferences for a physreg.
383 /// @param  VirtReg Currently unassigned virtual register.
384 /// @param  Order   Physregs to try.
385 /// @return         Physreg to assign VirtReg, or 0.
386 unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
387                             AllocationOrder &Order,
388                             SmallVectorImpl<LiveInterval*> &NewVRegs){
389   NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
390
391   // We can only evict interference if all interfering registers are virtual and
392   // longer than VirtReg.
393   const unsigned Size = VirtReg.getSize();
394
395   // Keep track of the lightest single interference seen so far.
396   float BestWeight = 0;
397   unsigned BestPhys = 0;
398
399   Order.rewind();
400   while (unsigned PhysReg = Order.next()) {
401     float Weight = 0;
402     if (!canEvictInterference(VirtReg, PhysReg, Size, Weight))
403       continue;
404
405     // This is an eviction candidate.
406     DEBUG(dbgs() << "max " << PrintReg(PhysReg, TRI) << " interference = "
407                  << Weight << '\n');
408     if (BestPhys && Weight >= BestWeight)
409       continue;
410
411     // Best so far.
412     BestPhys = PhysReg;
413     BestWeight = Weight;
414     // Stop if the hint can be used.
415     if (Order.isHint(PhysReg))
416       break;
417   }
418
419   if (!BestPhys)
420     return 0;
421
422   DEBUG(dbgs() << "evicting " << PrintReg(BestPhys, TRI) << " interference\n");
423   for (const unsigned *AliasI = TRI->getOverlaps(BestPhys); *AliasI; ++AliasI) {
424     LiveIntervalUnion::Query &Q = query(VirtReg, *AliasI);
425     assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
426     for (unsigned i = 0, e = Q.interferingVRegs().size(); i != e; ++i) {
427       LiveInterval *Intf = Q.interferingVRegs()[i];
428       unassign(*Intf, VRM->getPhys(Intf->reg));
429       ++NumEvicted;
430       NewVRegs.push_back(Intf);
431     }
432   }
433   return BestPhys;
434 }
435
436
437 //===----------------------------------------------------------------------===//
438 //                              Region Splitting
439 //===----------------------------------------------------------------------===//
440
441 /// calcInterferenceInfo - Compute per-block outgoing and ingoing constraints
442 /// when considering interference from PhysReg. Also compute an optimistic local
443 /// cost of this interference pattern.
444 ///
445 /// The final cost of a split is the local cost + global cost of preferences
446 /// broken by SpillPlacement.
447 ///
448 float RAGreedy::calcInterferenceInfo(LiveInterval &VirtReg, unsigned PhysReg) {
449   // Reset interference dependent info.
450   SpillConstraints.resize(SA->LiveBlocks.size());
451   for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
452     SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
453     SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
454     BC.Number = BI.MBB->getNumber();
455     BC.Entry = (BI.Uses && BI.LiveIn) ?
456       SpillPlacement::PrefReg : SpillPlacement::DontCare;
457     BC.Exit = (BI.Uses && BI.LiveOut) ?
458       SpillPlacement::PrefReg : SpillPlacement::DontCare;
459     BI.OverlapEntry = BI.OverlapExit = false;
460   }
461
462   // Add interference info from each PhysReg alias.
463   for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
464     if (!query(VirtReg, *AI).checkInterference())
465       continue;
466     LiveIntervalUnion::SegmentIter IntI =
467       PhysReg2LiveUnion[*AI].find(VirtReg.beginIndex());
468     if (!IntI.valid())
469       continue;
470
471     // Determine which blocks have interference live in or after the last split
472     // point.
473     for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
474       SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
475       SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
476
477       // Skip interference-free blocks.
478       if (IntI.start() >= BI.Stop)
479         continue;
480
481       // Is the interference live-in?
482       if (BI.LiveIn) {
483         IntI.advanceTo(BI.Start);
484         if (!IntI.valid())
485           break;
486         if (IntI.start() <= BI.Start)
487           BC.Entry = SpillPlacement::MustSpill;
488       }
489
490       // Is the interference overlapping the last split point?
491       if (BI.LiveOut) {
492         if (IntI.stop() < BI.LastSplitPoint)
493           IntI.advanceTo(BI.LastSplitPoint.getPrevSlot());
494         if (!IntI.valid())
495           break;
496         if (IntI.start() < BI.Stop)
497           BC.Exit = SpillPlacement::MustSpill;
498       }
499     }
500
501     // Rewind iterator and check other interferences.
502     IntI.find(VirtReg.beginIndex());
503     for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
504       SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
505       SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
506
507       // Skip interference-free blocks.
508       if (IntI.start() >= BI.Stop)
509         continue;
510
511       // Handle transparent blocks with interference separately.
512       // Transparent blocks never incur any fixed cost.
513       if (BI.LiveThrough && !BI.Uses) {
514         IntI.advanceTo(BI.Start);
515         if (!IntI.valid())
516           break;
517         if (IntI.start() >= BI.Stop)
518           continue;
519
520         if (BC.Entry != SpillPlacement::MustSpill)
521           BC.Entry = SpillPlacement::PrefSpill;
522         if (BC.Exit != SpillPlacement::MustSpill)
523           BC.Exit = SpillPlacement::PrefSpill;
524         continue;
525       }
526
527       // Now we only have blocks with uses left.
528       // Check if the interference overlaps the uses.
529       assert(BI.Uses && "Non-transparent block without any uses");
530
531       // Check interference on entry.
532       if (BI.LiveIn && BC.Entry != SpillPlacement::MustSpill) {
533         IntI.advanceTo(BI.Start);
534         if (!IntI.valid())
535           break;
536         // Not live in, but before the first use.
537         if (IntI.start() < BI.FirstUse) {
538           BC.Entry = SpillPlacement::PrefSpill;
539           // If the block contains a kill from an earlier split, never split
540           // again in the same block.
541           if (!BI.LiveThrough && !SA->isOriginalEndpoint(BI.Kill))
542             BC.Entry = SpillPlacement::MustSpill;
543         }
544       }
545
546       // Does interference overlap the uses in the entry segment
547       // [FirstUse;Kill)?
548       if (BI.LiveIn && !BI.OverlapEntry) {
549         IntI.advanceTo(BI.FirstUse);
550         if (!IntI.valid())
551           break;
552         // A live-through interval has no kill.
553         // Check [FirstUse;LastUse) instead.
554         if (IntI.start() < (BI.LiveThrough ? BI.LastUse : BI.Kill))
555           BI.OverlapEntry = true;
556       }
557
558       // Does interference overlap the uses in the exit segment [Def;LastUse)?
559       if (BI.LiveOut && !BI.LiveThrough && !BI.OverlapExit) {
560         IntI.advanceTo(BI.Def);
561         if (!IntI.valid())
562           break;
563         if (IntI.start() < BI.LastUse)
564           BI.OverlapExit = true;
565       }
566
567       // Check interference on exit.
568       if (BI.LiveOut && BC.Exit != SpillPlacement::MustSpill) {
569         // Check interference between LastUse and Stop.
570         if (BC.Exit != SpillPlacement::PrefSpill) {
571           IntI.advanceTo(BI.LastUse);
572           if (!IntI.valid())
573             break;
574           if (IntI.start() < BI.Stop) {
575             BC.Exit = SpillPlacement::PrefSpill;
576             // Avoid splitting twice in the same block.
577             if (!BI.LiveThrough && !SA->isOriginalEndpoint(BI.Def))
578               BC.Exit = SpillPlacement::MustSpill;
579           }
580         }
581       }
582     }
583   }
584
585   // Accumulate a local cost of this interference pattern.
586   float LocalCost = 0;
587   for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
588     SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
589     if (!BI.Uses)
590       continue;
591     SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
592     unsigned Inserts = 0;
593
594     // Do we need spill code for the entry segment?
595     if (BI.LiveIn)
596       Inserts += BI.OverlapEntry || BC.Entry != SpillPlacement::PrefReg;
597
598     // For the exit segment?
599     if (BI.LiveOut)
600       Inserts += BI.OverlapExit || BC.Exit != SpillPlacement::PrefReg;
601
602     // The local cost of spill code in this block is the block frequency times
603     // the number of spill instructions inserted.
604     if (Inserts)
605       LocalCost += Inserts * SpillPlacer->getBlockFrequency(BC.Number);
606   }
607   DEBUG(dbgs() << "Local cost of " << PrintReg(PhysReg, TRI) << " = "
608                << LocalCost << '\n');
609   return LocalCost;
610 }
611
612 /// calcGlobalSplitCost - Return the global split cost of following the split
613 /// pattern in LiveBundles. This cost should be added to the local cost of the
614 /// interference pattern in SpillConstraints.
615 ///
616 float RAGreedy::calcGlobalSplitCost(const BitVector &LiveBundles) {
617   float GlobalCost = 0;
618   for (unsigned i = 0, e = SpillConstraints.size(); i != e; ++i) {
619     SpillPlacement::BlockConstraint &BC = SpillConstraints[i];
620     unsigned Inserts = 0;
621     // Broken entry preference?
622     Inserts += LiveBundles[Bundles->getBundle(BC.Number, 0)] !=
623                  (BC.Entry == SpillPlacement::PrefReg);
624     // Broken exit preference?
625     Inserts += LiveBundles[Bundles->getBundle(BC.Number, 1)] !=
626                  (BC.Exit == SpillPlacement::PrefReg);
627     if (Inserts)
628       GlobalCost += Inserts * SpillPlacer->getBlockFrequency(BC.Number);
629   }
630   DEBUG(dbgs() << "Global cost = " << GlobalCost << '\n');
631   return GlobalCost;
632 }
633
634 /// splitAroundRegion - Split VirtReg around the region determined by
635 /// LiveBundles. Make an effort to avoid interference from PhysReg.
636 ///
637 /// The 'register' interval is going to contain as many uses as possible while
638 /// avoiding interference. The 'stack' interval is the complement constructed by
639 /// SplitEditor. It will contain the rest.
640 ///
641 void RAGreedy::splitAroundRegion(LiveInterval &VirtReg, unsigned PhysReg,
642                                  const BitVector &LiveBundles,
643                                  SmallVectorImpl<LiveInterval*> &NewVRegs) {
644   DEBUG({
645     dbgs() << "Splitting around region for " << PrintReg(PhysReg, TRI)
646            << " with bundles";
647     for (int i = LiveBundles.find_first(); i>=0; i = LiveBundles.find_next(i))
648       dbgs() << " EB#" << i;
649     dbgs() << ".\n";
650   });
651
652   // First compute interference ranges in the live blocks.
653   typedef std::pair<SlotIndex, SlotIndex> IndexPair;
654   SmallVector<IndexPair, 8> InterferenceRanges;
655   InterferenceRanges.resize(SA->LiveBlocks.size());
656   for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
657     if (!query(VirtReg, *AI).checkInterference())
658       continue;
659     LiveIntervalUnion::SegmentIter IntI =
660       PhysReg2LiveUnion[*AI].find(VirtReg.beginIndex());
661     if (!IntI.valid())
662       continue;
663     for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
664       const SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
665       IndexPair &IP = InterferenceRanges[i];
666
667       // Skip interference-free blocks.
668       if (IntI.start() >= BI.Stop)
669         continue;
670
671       // First interference in block.
672       if (BI.LiveIn) {
673         IntI.advanceTo(BI.Start);
674         if (!IntI.valid())
675           break;
676         if (IntI.start() >= BI.Stop)
677           continue;
678         if (!IP.first.isValid() || IntI.start() < IP.first)
679           IP.first = IntI.start();
680       }
681
682       // Last interference in block.
683       if (BI.LiveOut) {
684         IntI.advanceTo(BI.Stop);
685         if (!IntI.valid() || IntI.start() >= BI.Stop)
686           --IntI;
687         if (IntI.stop() <= BI.Start)
688           continue;
689         if (!IP.second.isValid() || IntI.stop() > IP.second)
690           IP.second = IntI.stop();
691       }
692     }
693   }
694
695   SmallVector<LiveInterval*, 4> SpillRegs;
696   LiveRangeEdit LREdit(VirtReg, NewVRegs, SpillRegs);
697   SE->reset(LREdit);
698
699   // Create the main cross-block interval.
700   SE->openIntv();
701
702   // First add all defs that are live out of a block.
703   for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
704     SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
705     bool RegIn  = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
706     bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
707
708     // Should the register be live out?
709     if (!BI.LiveOut || !RegOut)
710       continue;
711
712     IndexPair &IP = InterferenceRanges[i];
713     DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " -> EB#"
714                  << Bundles->getBundle(BI.MBB->getNumber(), 1)
715                  << " intf [" << IP.first << ';' << IP.second << ')');
716
717     // The interference interval should either be invalid or overlap MBB.
718     assert((!IP.first.isValid() || IP.first < BI.Stop) && "Bad interference");
719     assert((!IP.second.isValid() || IP.second > BI.Start)
720            && "Bad interference");
721
722     // Check interference leaving the block.
723     if (!IP.second.isValid()) {
724       // Block is interference-free.
725       DEBUG(dbgs() << ", no interference");
726       if (!BI.Uses) {
727         assert(BI.LiveThrough && "No uses, but not live through block?");
728         // Block is live-through without interference.
729         DEBUG(dbgs() << ", no uses"
730                      << (RegIn ? ", live-through.\n" : ", stack in.\n"));
731         if (!RegIn)
732           SE->enterIntvAtEnd(*BI.MBB);
733         continue;
734       }
735       if (!BI.LiveThrough) {
736         DEBUG(dbgs() << ", not live-through.\n");
737         SE->useIntv(SE->enterIntvBefore(BI.Def), BI.Stop);
738         continue;
739       }
740       if (!RegIn) {
741         // Block is live-through, but entry bundle is on the stack.
742         // Reload just before the first use.
743         DEBUG(dbgs() << ", not live-in, enter before first use.\n");
744         SE->useIntv(SE->enterIntvBefore(BI.FirstUse), BI.Stop);
745         continue;
746       }
747       DEBUG(dbgs() << ", live-through.\n");
748       continue;
749     }
750
751     // Block has interference.
752     DEBUG(dbgs() << ", interference to " << IP.second);
753
754     if (!BI.LiveThrough && IP.second <= BI.Def) {
755       // The interference doesn't reach the outgoing segment.
756       DEBUG(dbgs() << " doesn't affect def from " << BI.Def << '\n');
757       SE->useIntv(BI.Def, BI.Stop);
758       continue;
759     }
760
761
762     if (!BI.Uses) {
763       // No uses in block, avoid interference by reloading as late as possible.
764       DEBUG(dbgs() << ", no uses.\n");
765       SlotIndex SegStart = SE->enterIntvAtEnd(*BI.MBB);
766       assert(SegStart >= IP.second && "Couldn't avoid interference");
767       continue;
768     }
769
770     if (IP.second.getBoundaryIndex() < BI.LastUse) {
771       // There are interference-free uses at the end of the block.
772       // Find the first use that can get the live-out register.
773       SmallVectorImpl<SlotIndex>::const_iterator UI =
774         std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
775                          IP.second.getBoundaryIndex());
776       assert(UI != SA->UseSlots.end() && "Couldn't find last use");
777       SlotIndex Use = *UI;
778       assert(Use <= BI.LastUse && "Couldn't find last use");
779       // Only attempt a split befroe the last split point.
780       if (Use.getBaseIndex() <= BI.LastSplitPoint) {
781         DEBUG(dbgs() << ", free use at " << Use << ".\n");
782         SlotIndex SegStart = SE->enterIntvBefore(Use);
783         assert(SegStart >= IP.second && "Couldn't avoid interference");
784         assert(SegStart < BI.LastSplitPoint && "Impossible split point");
785         SE->useIntv(SegStart, BI.Stop);
786         continue;
787       }
788     }
789
790     // Interference is after the last use.
791     DEBUG(dbgs() << " after last use.\n");
792     SlotIndex SegStart = SE->enterIntvAtEnd(*BI.MBB);
793     assert(SegStart >= IP.second && "Couldn't avoid interference");
794   }
795
796   // Now all defs leading to live bundles are handled, do everything else.
797   for (unsigned i = 0, e = SA->LiveBlocks.size(); i != e; ++i) {
798     SplitAnalysis::BlockInfo &BI = SA->LiveBlocks[i];
799     bool RegIn  = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 0)];
800     bool RegOut = LiveBundles[Bundles->getBundle(BI.MBB->getNumber(), 1)];
801
802     // Is the register live-in?
803     if (!BI.LiveIn || !RegIn)
804       continue;
805
806     // We have an incoming register. Check for interference.
807     IndexPair &IP = InterferenceRanges[i];
808
809     DEBUG(dbgs() << "EB#" << Bundles->getBundle(BI.MBB->getNumber(), 0)
810                  << " -> BB#" << BI.MBB->getNumber());
811
812     // Check interference entering the block.
813     if (!IP.first.isValid()) {
814       // Block is interference-free.
815       DEBUG(dbgs() << ", no interference");
816       if (!BI.Uses) {
817         assert(BI.LiveThrough && "No uses, but not live through block?");
818         // Block is live-through without interference.
819         if (RegOut) {
820           DEBUG(dbgs() << ", no uses, live-through.\n");
821           SE->useIntv(BI.Start, BI.Stop);
822         } else {
823           DEBUG(dbgs() << ", no uses, stack-out.\n");
824           SE->leaveIntvAtTop(*BI.MBB);
825         }
826         continue;
827       }
828       if (!BI.LiveThrough) {
829         DEBUG(dbgs() << ", killed in block.\n");
830         SE->useIntv(BI.Start, SE->leaveIntvAfter(BI.Kill));
831         continue;
832       }
833       if (!RegOut) {
834         // Block is live-through, but exit bundle is on the stack.
835         // Spill immediately after the last use.
836         if (BI.LastUse < BI.LastSplitPoint) {
837           DEBUG(dbgs() << ", uses, stack-out.\n");
838           SE->useIntv(BI.Start, SE->leaveIntvAfter(BI.LastUse));
839           continue;
840         }
841         // The last use is after the last split point, it is probably an
842         // indirect jump.
843         DEBUG(dbgs() << ", uses at " << BI.LastUse << " after split point "
844                      << BI.LastSplitPoint << ", stack-out.\n");
845         SlotIndex SegEnd = SE->leaveIntvBefore(BI.LastSplitPoint);
846         SE->useIntv(BI.Start, SegEnd);
847         // Run a double interval from the split to the last use.
848         // This makes it possible to spill the complement without affecting the
849         // indirect branch.
850         SE->overlapIntv(SegEnd, BI.LastUse);
851         continue;
852       }
853       // Register is live-through.
854       DEBUG(dbgs() << ", uses, live-through.\n");
855       SE->useIntv(BI.Start, BI.Stop);
856       continue;
857     }
858
859     // Block has interference.
860     DEBUG(dbgs() << ", interference from " << IP.first);
861
862     if (!BI.LiveThrough && IP.first >= BI.Kill) {
863       // The interference doesn't reach the outgoing segment.
864       DEBUG(dbgs() << " doesn't affect kill at " << BI.Kill << '\n');
865       SE->useIntv(BI.Start, BI.Kill);
866       continue;
867     }
868
869     if (!BI.Uses) {
870       // No uses in block, avoid interference by spilling as soon as possible.
871       DEBUG(dbgs() << ", no uses.\n");
872       SlotIndex SegEnd = SE->leaveIntvAtTop(*BI.MBB);
873       assert(SegEnd <= IP.first && "Couldn't avoid interference");
874       continue;
875     }
876     if (IP.first.getBaseIndex() > BI.FirstUse) {
877       // There are interference-free uses at the beginning of the block.
878       // Find the last use that can get the register.
879       SmallVectorImpl<SlotIndex>::const_iterator UI =
880         std::lower_bound(SA->UseSlots.begin(), SA->UseSlots.end(),
881                          IP.first.getBaseIndex());
882       assert(UI != SA->UseSlots.begin() && "Couldn't find first use");
883       SlotIndex Use = (--UI)->getBoundaryIndex();
884       DEBUG(dbgs() << ", free use at " << *UI << ".\n");
885       SlotIndex SegEnd = SE->leaveIntvAfter(Use);
886       assert(SegEnd <= IP.first && "Couldn't avoid interference");
887       SE->useIntv(BI.Start, SegEnd);
888       continue;
889     }
890
891     // Interference is before the first use.
892     DEBUG(dbgs() << " before first use.\n");
893     SlotIndex SegEnd = SE->leaveIntvAtTop(*BI.MBB);
894     assert(SegEnd <= IP.first && "Couldn't avoid interference");
895   }
896
897   SE->closeIntv();
898
899   // FIXME: Should we be more aggressive about splitting the stack region into
900   // per-block segments? The current approach allows the stack region to
901   // separate into connected components. Some components may be allocatable.
902   SE->finish();
903   ++NumGlobalSplits;
904
905   if (VerifyEnabled) {
906     MF->verify(this, "After splitting live range around region");
907
908 #ifndef NDEBUG
909     // Make sure that at least one of the new intervals can allocate to PhysReg.
910     // That was the whole point of splitting the live range.
911     bool found = false;
912     for (LiveRangeEdit::iterator I = LREdit.begin(), E = LREdit.end(); I != E;
913          ++I)
914       if (!checkUncachedInterference(**I, PhysReg)) {
915         found = true;
916         break;
917       }
918     assert(found && "No allocatable intervals after pointless splitting");
919 #endif
920   }
921 }
922
923 unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
924                                   SmallVectorImpl<LiveInterval*> &NewVRegs) {
925   BitVector LiveBundles, BestBundles;
926   float BestCost = 0;
927   unsigned BestReg = 0;
928   Order.rewind();
929   while (unsigned PhysReg = Order.next()) {
930     float Cost = calcInterferenceInfo(VirtReg, PhysReg);
931     if (BestReg && Cost >= BestCost)
932       continue;
933
934     SpillPlacer->placeSpills(SpillConstraints, LiveBundles);
935     // No live bundles, defer to splitSingleBlocks().
936     if (!LiveBundles.any())
937       continue;
938
939     Cost += calcGlobalSplitCost(LiveBundles);
940     if (!BestReg || Cost < BestCost) {
941       BestReg = PhysReg;
942       BestCost = Cost;
943       BestBundles.swap(LiveBundles);
944     }
945   }
946
947   if (!BestReg)
948     return 0;
949
950   splitAroundRegion(VirtReg, BestReg, BestBundles, NewVRegs);
951   setStage(NewVRegs.begin(), NewVRegs.end(), RS_Region);
952   return 0;
953 }
954
955
956 //===----------------------------------------------------------------------===//
957 //                             Local Splitting
958 //===----------------------------------------------------------------------===//
959
960
961 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
962 /// in order to use PhysReg between two entries in SA->UseSlots.
963 ///
964 /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
965 ///
966 void RAGreedy::calcGapWeights(unsigned PhysReg,
967                               SmallVectorImpl<float> &GapWeight) {
968   assert(SA->LiveBlocks.size() == 1 && "Not a local interval");
969   const SplitAnalysis::BlockInfo &BI = SA->LiveBlocks.front();
970   const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
971   const unsigned NumGaps = Uses.size()-1;
972
973   // Start and end points for the interference check.
974   SlotIndex StartIdx = BI.LiveIn ? BI.FirstUse.getBaseIndex() : BI.FirstUse;
975   SlotIndex StopIdx = BI.LiveOut ? BI.LastUse.getBoundaryIndex() : BI.LastUse;
976
977   GapWeight.assign(NumGaps, 0.0f);
978
979   // Add interference from each overlapping register.
980   for (const unsigned *AI = TRI->getOverlaps(PhysReg); *AI; ++AI) {
981     if (!query(const_cast<LiveInterval&>(SA->getParent()), *AI)
982            .checkInterference())
983       continue;
984
985     // We know that VirtReg is a continuous interval from FirstUse to LastUse,
986     // so we don't need InterferenceQuery.
987     //
988     // Interference that overlaps an instruction is counted in both gaps
989     // surrounding the instruction. The exception is interference before
990     // StartIdx and after StopIdx.
991     //
992     LiveIntervalUnion::SegmentIter IntI = PhysReg2LiveUnion[*AI].find(StartIdx);
993     for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
994       // Skip the gaps before IntI.
995       while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
996         if (++Gap == NumGaps)
997           break;
998       if (Gap == NumGaps)
999         break;
1000
1001       // Update the gaps covered by IntI.
1002       const float weight = IntI.value()->weight;
1003       for (; Gap != NumGaps; ++Gap) {
1004         GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1005         if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1006           break;
1007       }
1008       if (Gap == NumGaps)
1009         break;
1010     }
1011   }
1012 }
1013
1014 /// getPrevMappedIndex - Return the slot index of the last non-copy instruction
1015 /// before MI that has a slot index. If MI is the first mapped instruction in
1016 /// its block, return the block start index instead.
1017 ///
1018 SlotIndex RAGreedy::getPrevMappedIndex(const MachineInstr *MI) {
1019   assert(MI && "Missing MachineInstr");
1020   const MachineBasicBlock *MBB = MI->getParent();
1021   MachineBasicBlock::const_iterator B = MBB->begin(), I = MI;
1022   while (I != B)
1023     if (!(--I)->isDebugValue() && !I->isCopy())
1024       return Indexes->getInstructionIndex(I);
1025   return Indexes->getMBBStartIdx(MBB);
1026 }
1027
1028 /// calcPrevSlots - Fill in the PrevSlot array with the index of the previous
1029 /// real non-copy instruction for each instruction in SA->UseSlots.
1030 ///
1031 void RAGreedy::calcPrevSlots() {
1032   const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1033   PrevSlot.clear();
1034   PrevSlot.reserve(Uses.size());
1035   for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
1036     const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]);
1037     PrevSlot.push_back(getPrevMappedIndex(MI).getDefIndex());
1038   }
1039 }
1040
1041 /// nextSplitPoint - Find the next index into SA->UseSlots > i such that it may
1042 /// be beneficial to split before UseSlots[i].
1043 ///
1044 /// 0 is always a valid split point
1045 unsigned RAGreedy::nextSplitPoint(unsigned i) {
1046   const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1047   const unsigned Size = Uses.size();
1048   assert(i != Size && "No split points after the end");
1049   // Allow split before i when Uses[i] is not adjacent to the previous use.
1050   while (++i != Size && PrevSlot[i].getBaseIndex() <= Uses[i-1].getBaseIndex())
1051     ;
1052   return i;
1053 }
1054
1055 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1056 /// basic block.
1057 ///
1058 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1059                                  SmallVectorImpl<LiveInterval*> &NewVRegs) {
1060   assert(SA->LiveBlocks.size() == 1 && "Not a local interval");
1061   const SplitAnalysis::BlockInfo &BI = SA->LiveBlocks.front();
1062
1063   // Note that it is possible to have an interval that is live-in or live-out
1064   // while only covering a single block - A phi-def can use undef values from
1065   // predecessors, and the block could be a single-block loop.
1066   // We don't bother doing anything clever about such a case, we simply assume
1067   // that the interval is continuous from FirstUse to LastUse. We should make
1068   // sure that we don't do anything illegal to such an interval, though.
1069
1070   const SmallVectorImpl<SlotIndex> &Uses = SA->UseSlots;
1071   if (Uses.size() <= 2)
1072     return 0;
1073   const unsigned NumGaps = Uses.size()-1;
1074
1075   DEBUG({
1076     dbgs() << "tryLocalSplit: ";
1077     for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1078       dbgs() << ' ' << SA->UseSlots[i];
1079     dbgs() << '\n';
1080   });
1081
1082   // For every use, find the previous mapped non-copy instruction.
1083   // We use this to detect valid split points, and to estimate new interval
1084   // sizes.
1085   calcPrevSlots();
1086
1087   unsigned BestBefore = NumGaps;
1088   unsigned BestAfter = 0;
1089   float BestDiff = 0;
1090
1091   const float blockFreq = SpillPlacer->getBlockFrequency(BI.MBB->getNumber());
1092   SmallVector<float, 8> GapWeight;
1093
1094   Order.rewind();
1095   while (unsigned PhysReg = Order.next()) {
1096     // Keep track of the largest spill weight that would need to be evicted in
1097     // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1098     calcGapWeights(PhysReg, GapWeight);
1099
1100     // Try to find the best sequence of gaps to close.
1101     // The new spill weight must be larger than any gap interference.
1102
1103     // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1104     unsigned SplitBefore = 0, SplitAfter = nextSplitPoint(1) - 1;
1105
1106     // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1107     // It is the spill weight that needs to be evicted.
1108     float MaxGap = GapWeight[0];
1109     for (unsigned i = 1; i != SplitAfter; ++i)
1110       MaxGap = std::max(MaxGap, GapWeight[i]);
1111
1112     for (;;) {
1113       // Live before/after split?
1114       const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1115       const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1116
1117       DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1118                    << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1119                    << " i=" << MaxGap);
1120
1121       // Stop before the interval gets so big we wouldn't be making progress.
1122       if (!LiveBefore && !LiveAfter) {
1123         DEBUG(dbgs() << " all\n");
1124         break;
1125       }
1126       // Should the interval be extended or shrunk?
1127       bool Shrink = true;
1128       if (MaxGap < HUGE_VALF) {
1129         // Estimate the new spill weight.
1130         //
1131         // Each instruction reads and writes the register, except the first
1132         // instr doesn't read when !FirstLive, and the last instr doesn't write
1133         // when !LastLive.
1134         //
1135         // We will be inserting copies before and after, so the total number of
1136         // reads and writes is 2 * EstUses.
1137         //
1138         const unsigned EstUses = 2*(SplitAfter - SplitBefore) +
1139                                  2*(LiveBefore + LiveAfter);
1140
1141         // Try to guess the size of the new interval. This should be trivial,
1142         // but the slot index of an inserted copy can be a lot smaller than the
1143         // instruction it is inserted before if there are many dead indexes
1144         // between them.
1145         //
1146         // We measure the distance from the instruction before SplitBefore to
1147         // get a conservative estimate.
1148         //
1149         // The final distance can still be different if inserting copies
1150         // triggers a slot index renumbering.
1151         //
1152         const float EstWeight = normalizeSpillWeight(blockFreq * EstUses,
1153                               PrevSlot[SplitBefore].distance(Uses[SplitAfter]));
1154         // Would this split be possible to allocate?
1155         // Never allocate all gaps, we wouldn't be making progress.
1156         float Diff = EstWeight - MaxGap;
1157         DEBUG(dbgs() << " w=" << EstWeight << " d=" << Diff);
1158         if (Diff > 0) {
1159           Shrink = false;
1160           if (Diff > BestDiff) {
1161             DEBUG(dbgs() << " (best)");
1162             BestDiff = Diff;
1163             BestBefore = SplitBefore;
1164             BestAfter = SplitAfter;
1165           }
1166         }
1167       }
1168
1169       // Try to shrink.
1170       if (Shrink) {
1171         SplitBefore = nextSplitPoint(SplitBefore);
1172         if (SplitBefore < SplitAfter) {
1173           DEBUG(dbgs() << " shrink\n");
1174           // Recompute the max when necessary.
1175           if (GapWeight[SplitBefore - 1] >= MaxGap) {
1176             MaxGap = GapWeight[SplitBefore];
1177             for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1178               MaxGap = std::max(MaxGap, GapWeight[i]);
1179           }
1180           continue;
1181         }
1182         MaxGap = 0;
1183       }
1184
1185       // Try to extend the interval.
1186       if (SplitAfter >= NumGaps) {
1187         DEBUG(dbgs() << " end\n");
1188         break;
1189       }
1190
1191       DEBUG(dbgs() << " extend\n");
1192       for (unsigned e = nextSplitPoint(SplitAfter + 1) - 1;
1193            SplitAfter != e; ++SplitAfter)
1194         MaxGap = std::max(MaxGap, GapWeight[SplitAfter]);
1195           continue;
1196     }
1197   }
1198
1199   // Didn't find any candidates?
1200   if (BestBefore == NumGaps)
1201     return 0;
1202
1203   DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1204                << '-' << Uses[BestAfter] << ", " << BestDiff
1205                << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1206
1207   SmallVector<LiveInterval*, 4> SpillRegs;
1208   LiveRangeEdit LREdit(VirtReg, NewVRegs, SpillRegs);
1209   SE->reset(LREdit);
1210
1211   SE->openIntv();
1212   SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1213   SlotIndex SegStop  = SE->leaveIntvAfter(Uses[BestAfter]);
1214   SE->useIntv(SegStart, SegStop);
1215   SE->closeIntv();
1216   SE->finish();
1217   setStage(NewVRegs.begin(), NewVRegs.end(), RS_Local);
1218   ++NumLocalSplits;
1219
1220   return 0;
1221 }
1222
1223 //===----------------------------------------------------------------------===//
1224 //                          Live Range Splitting
1225 //===----------------------------------------------------------------------===//
1226
1227 /// trySplit - Try to split VirtReg or one of its interferences, making it
1228 /// assignable.
1229 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1230 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1231                             SmallVectorImpl<LiveInterval*>&NewVRegs) {
1232   // Local intervals are handled separately.
1233   if (LIS->intervalIsInOneMBB(VirtReg)) {
1234     NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
1235     SA->analyze(&VirtReg);
1236     return tryLocalSplit(VirtReg, Order, NewVRegs);
1237   }
1238
1239   NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
1240
1241   // Don't iterate global splitting.
1242   // Move straight to spilling if this range was produced by a global split.
1243   LiveRangeStage Stage = getStage(VirtReg);
1244   if (Stage >= RS_Block)
1245     return 0;
1246
1247   SA->analyze(&VirtReg);
1248
1249   // First try to split around a region spanning multiple blocks.
1250   if (Stage < RS_Region) {
1251     unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1252     if (PhysReg || !NewVRegs.empty())
1253       return PhysReg;
1254   }
1255
1256   // Then isolate blocks with multiple uses.
1257   if (Stage < RS_Block) {
1258     SplitAnalysis::BlockPtrSet Blocks;
1259     if (SA->getMultiUseBlocks(Blocks)) {
1260       SmallVector<LiveInterval*, 4> SpillRegs;
1261       LiveRangeEdit LREdit(VirtReg, NewVRegs, SpillRegs);
1262       SE->reset(LREdit);
1263       SE->splitSingleBlocks(Blocks);
1264       setStage(NewVRegs.begin(), NewVRegs.end(), RS_Block);
1265       if (VerifyEnabled)
1266         MF->verify(this, "After splitting live range around basic blocks");
1267     }
1268   }
1269
1270   // Don't assign any physregs.
1271   return 0;
1272 }
1273
1274
1275 //===----------------------------------------------------------------------===//
1276 //                            Main Entry Point
1277 //===----------------------------------------------------------------------===//
1278
1279 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
1280                                  SmallVectorImpl<LiveInterval*> &NewVRegs) {
1281   LiveRangeStage Stage = getStage(VirtReg);
1282   if (Stage == RS_Original)
1283     LRStage[VirtReg.reg] = RS_Second;
1284
1285   // First try assigning a free register.
1286   AllocationOrder Order(VirtReg.reg, *VRM, ReservedRegs);
1287   while (unsigned PhysReg = Order.next()) {
1288     if (!checkPhysRegInterference(VirtReg, PhysReg))
1289       return PhysReg;
1290   }
1291
1292   if (unsigned PhysReg = tryReassign(VirtReg, Order, NewVRegs))
1293     return PhysReg;
1294
1295   if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1296     return PhysReg;
1297
1298   assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1299
1300   // The first time we see a live range, don't try to split or spill.
1301   // Wait until the second time, when all smaller ranges have been allocated.
1302   // This gives a better picture of the interference to split around.
1303   if (Stage == RS_Original) {
1304     NewVRegs.push_back(&VirtReg);
1305     return 0;
1306   }
1307
1308   assert(Stage < RS_Spill && "Cannot allocate after spilling");
1309
1310   // Try splitting VirtReg or interferences.
1311   unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1312   if (PhysReg || !NewVRegs.empty())
1313     return PhysReg;
1314
1315   // Finally spill VirtReg itself.
1316   NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
1317   SmallVector<LiveInterval*, 1> pendingSpills;
1318   spiller().spill(&VirtReg, NewVRegs, pendingSpills);
1319
1320   // The live virtual register requesting allocation was spilled, so tell
1321   // the caller not to allocate anything during this round.
1322   return 0;
1323 }
1324
1325 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1326   DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1327                << "********** Function: "
1328                << ((Value*)mf.getFunction())->getName() << '\n');
1329
1330   MF = &mf;
1331   if (VerifyEnabled)
1332     MF->verify(this, "Before greedy register allocator");
1333
1334   RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>());
1335   Indexes = &getAnalysis<SlotIndexes>();
1336   DomTree = &getAnalysis<MachineDominatorTree>();
1337   ReservedRegs = TRI->getReservedRegs(*MF);
1338   SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
1339   Loops = &getAnalysis<MachineLoopInfo>();
1340   LoopRanges = &getAnalysis<MachineLoopRanges>();
1341   Bundles = &getAnalysis<EdgeBundles>();
1342   SpillPlacer = &getAnalysis<SpillPlacement>();
1343
1344   SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
1345   SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree));
1346   LRStage.clear();
1347   LRStage.resize(MRI->getNumVirtRegs());
1348
1349   allocatePhysRegs();
1350   addMBBLiveIns(MF);
1351   LIS->addKillFlags();
1352
1353   // Run rewriter
1354   {
1355     NamedRegionTimer T("Rewriter", TimerGroupName, TimePassesIsEnabled);
1356     VRM->rewrite(Indexes);
1357   }
1358
1359   // The pass output is in VirtRegMap. Release all the transient data.
1360   releaseMemory();
1361
1362   return true;
1363 }