Evict local live ranges if they can be reassigned.
[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 "llvm/CodeGen/Passes.h"
17 #include "AllocationOrder.h"
18 #include "InterferenceCache.h"
19 #include "LiveDebugVariables.h"
20 #include "RegAllocBase.h"
21 #include "SpillPlacement.h"
22 #include "Spiller.h"
23 #include "SplitKit.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/CodeGen/CalcSpillWeights.h"
27 #include "llvm/CodeGen/EdgeBundles.h"
28 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
29 #include "llvm/CodeGen/LiveRangeEdit.h"
30 #include "llvm/CodeGen/LiveRegMatrix.h"
31 #include "llvm/CodeGen/LiveStackAnalysis.h"
32 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
33 #include "llvm/CodeGen/MachineDominators.h"
34 #include "llvm/CodeGen/MachineFunctionPass.h"
35 #include "llvm/CodeGen/MachineLoopInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/RegAllocRegistry.h"
38 #include "llvm/CodeGen/VirtRegMap.h"
39 #include "llvm/PassAnalysisSupport.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/Timer.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include <queue>
46
47 using namespace llvm;
48
49 STATISTIC(NumGlobalSplits, "Number of split global live ranges");
50 STATISTIC(NumLocalSplits,  "Number of split local live ranges");
51 STATISTIC(NumEvicted,      "Number of interferences evicted");
52
53 static cl::opt<SplitEditor::ComplementSpillMode>
54 SplitSpillMode("split-spill-mode", cl::Hidden,
55   cl::desc("Spill mode for splitting live ranges"),
56   cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
57              clEnumValN(SplitEditor::SM_Size,  "size",  "Optimize for size"),
58              clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed"),
59              clEnumValEnd),
60   cl::init(SplitEditor::SM_Partition));
61
62 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
63                                        createGreedyRegisterAllocator);
64
65 namespace {
66 class RAGreedy : public MachineFunctionPass,
67                  public RegAllocBase,
68                  private LiveRangeEdit::Delegate {
69
70   // context
71   MachineFunction *MF;
72
73   // analyses
74   SlotIndexes *Indexes;
75   MachineBlockFrequencyInfo *MBFI;
76   MachineDominatorTree *DomTree;
77   MachineLoopInfo *Loops;
78   EdgeBundles *Bundles;
79   SpillPlacement *SpillPlacer;
80   LiveDebugVariables *DebugVars;
81
82   // state
83   OwningPtr<Spiller> SpillerInstance;
84   std::priority_queue<std::pair<unsigned, unsigned> > Queue;
85   unsigned NextCascade;
86
87   // Live ranges pass through a number of stages as we try to allocate them.
88   // Some of the stages may also create new live ranges:
89   //
90   // - Region splitting.
91   // - Per-block splitting.
92   // - Local splitting.
93   // - Spilling.
94   //
95   // Ranges produced by one of the stages skip the previous stages when they are
96   // dequeued. This improves performance because we can skip interference checks
97   // that are unlikely to give any results. It also guarantees that the live
98   // range splitting algorithm terminates, something that is otherwise hard to
99   // ensure.
100   enum LiveRangeStage {
101     /// Newly created live range that has never been queued.
102     RS_New,
103
104     /// Only attempt assignment and eviction. Then requeue as RS_Split.
105     RS_Assign,
106
107     /// Attempt live range splitting if assignment is impossible.
108     RS_Split,
109
110     /// Attempt more aggressive live range splitting that is guaranteed to make
111     /// progress.  This is used for split products that may not be making
112     /// progress.
113     RS_Split2,
114
115     /// Live range will be spilled.  No more splitting will be attempted.
116     RS_Spill,
117
118     /// There is nothing more we can do to this live range.  Abort compilation
119     /// if it can't be assigned.
120     RS_Done
121   };
122
123   static const char *const StageName[];
124
125   // RegInfo - Keep additional information about each live range.
126   struct RegInfo {
127     LiveRangeStage Stage;
128
129     // Cascade - Eviction loop prevention. See canEvictInterference().
130     unsigned Cascade;
131
132     RegInfo() : Stage(RS_New), Cascade(0) {}
133   };
134
135   IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
136
137   LiveRangeStage getStage(const LiveInterval &VirtReg) const {
138     return ExtraRegInfo[VirtReg.reg].Stage;
139   }
140
141   void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
142     ExtraRegInfo.resize(MRI->getNumVirtRegs());
143     ExtraRegInfo[VirtReg.reg].Stage = Stage;
144   }
145
146   template<typename Iterator>
147   void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
148     ExtraRegInfo.resize(MRI->getNumVirtRegs());
149     for (;Begin != End; ++Begin) {
150       unsigned Reg = (*Begin)->reg;
151       if (ExtraRegInfo[Reg].Stage == RS_New)
152         ExtraRegInfo[Reg].Stage = NewStage;
153     }
154   }
155
156   /// Cost of evicting interference.
157   struct EvictionCost {
158     unsigned BrokenHints; ///< Total number of broken hints.
159     float MaxWeight;      ///< Maximum spill weight evicted.
160
161     EvictionCost(unsigned B = 0) : BrokenHints(B), MaxWeight(0) {}
162
163     bool isMax() const { return BrokenHints == ~0u; }
164
165     bool operator<(const EvictionCost &O) const {
166       if (BrokenHints != O.BrokenHints)
167         return BrokenHints < O.BrokenHints;
168       return MaxWeight < O.MaxWeight;
169     }
170   };
171
172   // splitting state.
173   OwningPtr<SplitAnalysis> SA;
174   OwningPtr<SplitEditor> SE;
175
176   /// Cached per-block interference maps
177   InterferenceCache IntfCache;
178
179   /// All basic blocks where the current register has uses.
180   SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
181
182   /// Global live range splitting candidate info.
183   struct GlobalSplitCandidate {
184     // Register intended for assignment, or 0.
185     unsigned PhysReg;
186
187     // SplitKit interval index for this candidate.
188     unsigned IntvIdx;
189
190     // Interference for PhysReg.
191     InterferenceCache::Cursor Intf;
192
193     // Bundles where this candidate should be live.
194     BitVector LiveBundles;
195     SmallVector<unsigned, 8> ActiveBlocks;
196
197     void reset(InterferenceCache &Cache, unsigned Reg) {
198       PhysReg = Reg;
199       IntvIdx = 0;
200       Intf.setPhysReg(Cache, Reg);
201       LiveBundles.clear();
202       ActiveBlocks.clear();
203     }
204
205     // Set B[i] = C for every live bundle where B[i] was NoCand.
206     unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
207       unsigned Count = 0;
208       for (int i = LiveBundles.find_first(); i >= 0;
209            i = LiveBundles.find_next(i))
210         if (B[i] == NoCand) {
211           B[i] = C;
212           Count++;
213         }
214       return Count;
215     }
216   };
217
218   /// Candidate info for for each PhysReg in AllocationOrder.
219   /// This vector never shrinks, but grows to the size of the largest register
220   /// class.
221   SmallVector<GlobalSplitCandidate, 32> GlobalCand;
222
223   enum { NoCand = ~0u };
224
225   /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
226   /// NoCand which indicates the stack interval.
227   SmallVector<unsigned, 32> BundleCand;
228
229 public:
230   RAGreedy();
231
232   /// Return the pass name.
233   virtual const char* getPassName() const {
234     return "Greedy Register Allocator";
235   }
236
237   /// RAGreedy analysis usage.
238   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
239   virtual void releaseMemory();
240   virtual Spiller &spiller() { return *SpillerInstance; }
241   virtual void enqueue(LiveInterval *LI);
242   virtual LiveInterval *dequeue();
243   virtual unsigned selectOrSplit(LiveInterval&,
244                                  SmallVectorImpl<LiveInterval*>&);
245
246   /// Perform register allocation.
247   virtual bool runOnMachineFunction(MachineFunction &mf);
248
249   static char ID;
250
251 private:
252   bool LRE_CanEraseVirtReg(unsigned);
253   void LRE_WillShrinkVirtReg(unsigned);
254   void LRE_DidCloneVirtReg(unsigned, unsigned);
255
256   BlockFrequency calcSpillCost();
257   bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
258   void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
259   void growRegion(GlobalSplitCandidate &Cand);
260   BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate&);
261   bool calcCompactRegion(GlobalSplitCandidate&);
262   void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
263   void calcGapWeights(unsigned, SmallVectorImpl<float>&);
264   unsigned canReassign(LiveInterval &VirtReg, unsigned PhysReg);
265   bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
266   bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
267   void evictInterference(LiveInterval&, unsigned,
268                          SmallVectorImpl<LiveInterval*>&);
269
270   unsigned tryAssign(LiveInterval&, AllocationOrder&,
271                      SmallVectorImpl<LiveInterval*>&);
272   unsigned tryEvict(LiveInterval&, AllocationOrder&,
273                     SmallVectorImpl<LiveInterval*>&, unsigned = ~0u);
274   unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
275                           SmallVectorImpl<LiveInterval*>&);
276   unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
277                          SmallVectorImpl<LiveInterval*>&);
278   unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
279                                SmallVectorImpl<LiveInterval*>&);
280   unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
281     SmallVectorImpl<LiveInterval*>&);
282   unsigned trySplit(LiveInterval&, AllocationOrder&,
283                     SmallVectorImpl<LiveInterval*>&);
284 };
285 } // end anonymous namespace
286
287 char RAGreedy::ID = 0;
288
289 #ifndef NDEBUG
290 const char *const RAGreedy::StageName[] = {
291     "RS_New",
292     "RS_Assign",
293     "RS_Split",
294     "RS_Split2",
295     "RS_Spill",
296     "RS_Done"
297 };
298 #endif
299
300 // Hysteresis to use when comparing floats.
301 // This helps stabilize decisions based on float comparisons.
302 const float Hysteresis = 0.98f;
303
304
305 FunctionPass* llvm::createGreedyRegisterAllocator() {
306   return new RAGreedy();
307 }
308
309 RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
310   initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry());
311   initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
312   initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
313   initializeSlotIndexesPass(*PassRegistry::getPassRegistry());
314   initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry());
315   initializeMachineSchedulerPass(*PassRegistry::getPassRegistry());
316   initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry());
317   initializeLiveStacksPass(*PassRegistry::getPassRegistry());
318   initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry());
319   initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry());
320   initializeVirtRegMapPass(*PassRegistry::getPassRegistry());
321   initializeLiveRegMatrixPass(*PassRegistry::getPassRegistry());
322   initializeEdgeBundlesPass(*PassRegistry::getPassRegistry());
323   initializeSpillPlacementPass(*PassRegistry::getPassRegistry());
324 }
325
326 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
327   AU.setPreservesCFG();
328   AU.addRequired<MachineBlockFrequencyInfo>();
329   AU.addPreserved<MachineBlockFrequencyInfo>();
330   AU.addRequired<AliasAnalysis>();
331   AU.addPreserved<AliasAnalysis>();
332   AU.addRequired<LiveIntervals>();
333   AU.addPreserved<LiveIntervals>();
334   AU.addRequired<SlotIndexes>();
335   AU.addPreserved<SlotIndexes>();
336   AU.addRequired<LiveDebugVariables>();
337   AU.addPreserved<LiveDebugVariables>();
338   AU.addRequired<LiveStacks>();
339   AU.addPreserved<LiveStacks>();
340   AU.addRequired<CalculateSpillWeights>();
341   AU.addRequired<MachineDominatorTree>();
342   AU.addPreserved<MachineDominatorTree>();
343   AU.addRequired<MachineLoopInfo>();
344   AU.addPreserved<MachineLoopInfo>();
345   AU.addRequired<VirtRegMap>();
346   AU.addPreserved<VirtRegMap>();
347   AU.addRequired<LiveRegMatrix>();
348   AU.addPreserved<LiveRegMatrix>();
349   AU.addRequired<EdgeBundles>();
350   AU.addRequired<SpillPlacement>();
351   MachineFunctionPass::getAnalysisUsage(AU);
352 }
353
354
355 //===----------------------------------------------------------------------===//
356 //                     LiveRangeEdit delegate methods
357 //===----------------------------------------------------------------------===//
358
359 bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
360   if (VRM->hasPhys(VirtReg)) {
361     Matrix->unassign(LIS->getInterval(VirtReg));
362     return true;
363   }
364   // Unassigned virtreg is probably in the priority queue.
365   // RegAllocBase will erase it after dequeueing.
366   return false;
367 }
368
369 void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
370   if (!VRM->hasPhys(VirtReg))
371     return;
372
373   // Register is assigned, put it back on the queue for reassignment.
374   LiveInterval &LI = LIS->getInterval(VirtReg);
375   Matrix->unassign(LI);
376   enqueue(&LI);
377 }
378
379 void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
380   // Cloning a register we haven't even heard about yet?  Just ignore it.
381   if (!ExtraRegInfo.inBounds(Old))
382     return;
383
384   // LRE may clone a virtual register because dead code elimination causes it to
385   // be split into connected components. The new components are much smaller
386   // than the original, so they should get a new chance at being assigned.
387   // same stage as the parent.
388   ExtraRegInfo[Old].Stage = RS_Assign;
389   ExtraRegInfo.grow(New);
390   ExtraRegInfo[New] = ExtraRegInfo[Old];
391 }
392
393 void RAGreedy::releaseMemory() {
394   SpillerInstance.reset(0);
395   ExtraRegInfo.clear();
396   GlobalCand.clear();
397 }
398
399 void RAGreedy::enqueue(LiveInterval *LI) {
400   // Prioritize live ranges by size, assigning larger ranges first.
401   // The queue holds (size, reg) pairs.
402   const unsigned Size = LI->getSize();
403   const unsigned Reg = LI->reg;
404   assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
405          "Can only enqueue virtual registers");
406   unsigned Prio;
407
408   ExtraRegInfo.grow(Reg);
409   if (ExtraRegInfo[Reg].Stage == RS_New)
410     ExtraRegInfo[Reg].Stage = RS_Assign;
411
412   if (ExtraRegInfo[Reg].Stage == RS_Split) {
413     // Unsplit ranges that couldn't be allocated immediately are deferred until
414     // everything else has been allocated.
415     Prio = Size;
416   } else {
417     if (ExtraRegInfo[Reg].Stage == RS_Assign && !LI->empty() &&
418         LIS->intervalIsInOneMBB(*LI)) {
419       // Allocate original local ranges in linear instruction order. Since they
420       // are singly defined, this produces optimal coloring in the absence of
421       // global interference and other constraints.
422       Prio = LI->beginIndex().distance(Indexes->getLastIndex());
423     }
424     else {
425       // Allocate global and split ranges in long->short order. Long ranges that
426       // don't fit should be spilled (or split) ASAP so they don't create
427       // interference.  Mark a bit to prioritize global above local ranges.
428       Prio = (1u << 29) + Size;
429     }
430     // Mark a higher bit to prioritize global and local above RS_Split.
431     Prio |= (1u << 31);
432
433     // Boost ranges that have a physical register hint.
434     if (VRM->hasKnownPreference(Reg))
435       Prio |= (1u << 30);
436   }
437
438   Queue.push(std::make_pair(Prio, ~Reg));
439 }
440
441 LiveInterval *RAGreedy::dequeue() {
442   if (Queue.empty())
443     return 0;
444   LiveInterval *LI = &LIS->getInterval(~Queue.top().second);
445   Queue.pop();
446   return LI;
447 }
448
449
450 //===----------------------------------------------------------------------===//
451 //                            Direct Assignment
452 //===----------------------------------------------------------------------===//
453
454 /// tryAssign - Try to assign VirtReg to an available register.
455 unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
456                              AllocationOrder &Order,
457                              SmallVectorImpl<LiveInterval*> &NewVRegs) {
458   Order.rewind();
459   unsigned PhysReg;
460   while ((PhysReg = Order.next()))
461     if (!Matrix->checkInterference(VirtReg, PhysReg))
462       break;
463   if (!PhysReg || Order.isHint())
464     return PhysReg;
465
466   // PhysReg is available, but there may be a better choice.
467
468   // If we missed a simple hint, try to cheaply evict interference from the
469   // preferred register.
470   if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
471     if (Order.isHint(Hint)) {
472       DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
473       EvictionCost MaxCost(1);
474       if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
475         evictInterference(VirtReg, Hint, NewVRegs);
476         return Hint;
477       }
478     }
479
480   // Try to evict interference from a cheaper alternative.
481   unsigned Cost = TRI->getCostPerUse(PhysReg);
482
483   // Most registers have 0 additional cost.
484   if (!Cost)
485     return PhysReg;
486
487   DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
488                << '\n');
489   unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
490   return CheapReg ? CheapReg : PhysReg;
491 }
492
493
494 //===----------------------------------------------------------------------===//
495 //                         Interference eviction
496 //===----------------------------------------------------------------------===//
497
498 unsigned RAGreedy::canReassign(LiveInterval &VirtReg, unsigned PrevReg) {
499   AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
500   unsigned PhysReg;
501   while ((PhysReg = Order.next())) {
502     if (PhysReg == PrevReg)
503       continue;
504
505     MCRegUnitIterator Units(PhysReg, TRI);
506     for (; Units.isValid(); ++Units) {
507       // Instantiate a "subquery", not to be confused with the Queries array.
508       LiveIntervalUnion::Query subQ(&VirtReg, &Matrix->getLiveUnions()[*Units]);
509       if (subQ.checkInterference())
510         break;
511     }
512     // If no units have interference, break out with the current PhysReg.
513     if (!Units.isValid())
514       break;
515   }
516   if (PhysReg)
517     DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
518           << PrintReg(PrevReg, TRI) << " to " << PrintReg(PhysReg, TRI)
519           << '\n');
520   return PhysReg;
521 }
522
523 /// shouldEvict - determine if A should evict the assigned live range B. The
524 /// eviction policy defined by this function together with the allocation order
525 /// defined by enqueue() decides which registers ultimately end up being split
526 /// and spilled.
527 ///
528 /// Cascade numbers are used to prevent infinite loops if this function is a
529 /// cyclic relation.
530 ///
531 /// @param A          The live range to be assigned.
532 /// @param IsHint     True when A is about to be assigned to its preferred
533 ///                   register.
534 /// @param B          The live range to be evicted.
535 /// @param BreaksHint True when B is already assigned to its preferred register.
536 bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
537                            LiveInterval &B, bool BreaksHint) {
538   bool CanSplit = getStage(B) < RS_Spill;
539
540   // Be fairly aggressive about following hints as long as the evictee can be
541   // split.
542   if (CanSplit && IsHint && !BreaksHint)
543     return true;
544
545   return A.weight > B.weight;
546 }
547
548 /// canEvictInterference - Return true if all interferences between VirtReg and
549 /// PhysReg can be evicted.  When OnlyCheap is set, don't do anything
550 ///
551 /// @param VirtReg Live range that is about to be assigned.
552 /// @param PhysReg Desired register for assignment.
553 /// @param IsHint  True when PhysReg is VirtReg's preferred register.
554 /// @param MaxCost Only look for cheaper candidates and update with new cost
555 ///                when returning true.
556 /// @returns True when interference can be evicted cheaper than MaxCost.
557 bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
558                                     bool IsHint, EvictionCost &MaxCost) {
559   // It is only possible to evict virtual register interference.
560   if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
561     return false;
562
563   bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
564
565   // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
566   // involved in an eviction before. If a cascade number was assigned, deny
567   // evicting anything with the same or a newer cascade number. This prevents
568   // infinite eviction loops.
569   //
570   // This works out so a register without a cascade number is allowed to evict
571   // anything, and it can be evicted by anything.
572   unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
573   if (!Cascade)
574     Cascade = NextCascade;
575
576   EvictionCost Cost;
577   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
578     LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
579     // If there is 10 or more interferences, chances are one is heavier.
580     if (Q.collectInterferingVRegs(10) >= 10)
581       return false;
582
583     // Check if any interfering live range is heavier than MaxWeight.
584     for (unsigned i = Q.interferingVRegs().size(); i; --i) {
585       LiveInterval *Intf = Q.interferingVRegs()[i - 1];
586       assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
587              "Only expecting virtual register interference from query");
588       // Never evict spill products. They cannot split or spill.
589       if (getStage(*Intf) == RS_Done)
590         return false;
591       // Once a live range becomes small enough, it is urgent that we find a
592       // register for it. This is indicated by an infinite spill weight. These
593       // urgent live ranges get to evict almost anything.
594       //
595       // Also allow urgent evictions of unspillable ranges from a strictly
596       // larger allocation order.
597       bool Urgent = !VirtReg.isSpillable() &&
598         (Intf->isSpillable() ||
599          RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
600          RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
601       // Only evict older cascades or live ranges without a cascade.
602       unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
603       if (Cascade <= IntfCascade) {
604         if (!Urgent)
605           return false;
606         // We permit breaking cascades for urgent evictions. It should be the
607         // last resort, though, so make it really expensive.
608         Cost.BrokenHints += 10;
609       }
610       // Would this break a satisfied hint?
611       bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
612       // Update eviction cost.
613       Cost.BrokenHints += BreaksHint;
614       Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
615       // Abort if this would be too expensive.
616       if (!(Cost < MaxCost))
617         return false;
618       if (Urgent)
619         continue;
620       // If !MaxCost.isMax(), then we're just looking for a cheap register.
621       // Evicting another local live range in this case could lead to suboptimal
622       // coloring.
623       if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
624           !canReassign(*Intf, PhysReg)) {
625         return false;
626       }
627       // Finally, apply the eviction policy for non-urgent evictions.
628       if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
629         return false;
630     }
631   }
632   MaxCost = Cost;
633   return true;
634 }
635
636 /// evictInterference - Evict any interferring registers that prevent VirtReg
637 /// from being assigned to Physreg. This assumes that canEvictInterference
638 /// returned true.
639 void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
640                                  SmallVectorImpl<LiveInterval*> &NewVRegs) {
641   // Make sure that VirtReg has a cascade number, and assign that cascade
642   // number to every evicted register. These live ranges than then only be
643   // evicted by a newer cascade, preventing infinite loops.
644   unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
645   if (!Cascade)
646     Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
647
648   DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
649                << " interference: Cascade " << Cascade << '\n');
650
651   // Collect all interfering virtregs first.
652   SmallVector<LiveInterval*, 8> Intfs;
653   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
654     LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
655     assert(Q.seenAllInterferences() && "Didn't check all interfererences.");
656     ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
657     Intfs.append(IVR.begin(), IVR.end());
658   }
659
660   // Evict them second. This will invalidate the queries.
661   for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
662     LiveInterval *Intf = Intfs[i];
663     // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
664     if (!VRM->hasPhys(Intf->reg))
665       continue;
666     Matrix->unassign(*Intf);
667     assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
668             VirtReg.isSpillable() < Intf->isSpillable()) &&
669            "Cannot decrease cascade number, illegal eviction");
670     ExtraRegInfo[Intf->reg].Cascade = Cascade;
671     ++NumEvicted;
672     NewVRegs.push_back(Intf);
673   }
674 }
675
676 /// tryEvict - Try to evict all interferences for a physreg.
677 /// @param  VirtReg Currently unassigned virtual register.
678 /// @param  Order   Physregs to try.
679 /// @return         Physreg to assign VirtReg, or 0.
680 unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
681                             AllocationOrder &Order,
682                             SmallVectorImpl<LiveInterval*> &NewVRegs,
683                             unsigned CostPerUseLimit) {
684   NamedRegionTimer T("Evict", TimerGroupName, TimePassesIsEnabled);
685
686   // Keep track of the cheapest interference seen so far.
687   EvictionCost BestCost(~0u);
688   unsigned BestPhys = 0;
689   unsigned OrderLimit = Order.getOrder().size();
690
691   // When we are just looking for a reduced cost per use, don't break any
692   // hints, and only evict smaller spill weights.
693   if (CostPerUseLimit < ~0u) {
694     BestCost.BrokenHints = 0;
695     BestCost.MaxWeight = VirtReg.weight;
696
697     // Check of any registers in RC are below CostPerUseLimit.
698     const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
699     unsigned MinCost = RegClassInfo.getMinCost(RC);
700     if (MinCost >= CostPerUseLimit) {
701       DEBUG(dbgs() << RC->getName() << " minimum cost = " << MinCost
702                    << ", no cheaper registers to be found.\n");
703       return 0;
704     }
705
706     // It is normal for register classes to have a long tail of registers with
707     // the same cost. We don't need to look at them if they're too expensive.
708     if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
709       OrderLimit = RegClassInfo.getLastCostChange(RC);
710       DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
711     }
712   }
713
714   Order.rewind();
715   while (unsigned PhysReg = Order.nextWithDups(OrderLimit)) {
716     if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
717       continue;
718     // The first use of a callee-saved register in a function has cost 1.
719     // Don't start using a CSR when the CostPerUseLimit is low.
720     if (CostPerUseLimit == 1)
721      if (unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg))
722        if (!MRI->isPhysRegUsed(CSR)) {
723          DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
724                       << PrintReg(CSR, TRI) << '\n');
725          continue;
726        }
727
728     if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
729       continue;
730
731     // Best so far.
732     BestPhys = PhysReg;
733
734     // Stop if the hint can be used.
735     if (Order.isHint())
736       break;
737   }
738
739   if (!BestPhys)
740     return 0;
741
742   evictInterference(VirtReg, BestPhys, NewVRegs);
743   return BestPhys;
744 }
745
746
747 //===----------------------------------------------------------------------===//
748 //                              Region Splitting
749 //===----------------------------------------------------------------------===//
750
751 /// addSplitConstraints - Fill out the SplitConstraints vector based on the
752 /// interference pattern in Physreg and its aliases. Add the constraints to
753 /// SpillPlacement and return the static cost of this split in Cost, assuming
754 /// that all preferences in SplitConstraints are met.
755 /// Return false if there are no bundles with positive bias.
756 bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
757                                    BlockFrequency &Cost) {
758   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
759
760   // Reset interference dependent info.
761   SplitConstraints.resize(UseBlocks.size());
762   BlockFrequency StaticCost = 0;
763   for (unsigned i = 0; i != UseBlocks.size(); ++i) {
764     const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
765     SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
766
767     BC.Number = BI.MBB->getNumber();
768     Intf.moveToBlock(BC.Number);
769     BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
770     BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
771     BC.ChangesValue = BI.FirstDef.isValid();
772
773     if (!Intf.hasInterference())
774       continue;
775
776     // Number of spill code instructions to insert.
777     unsigned Ins = 0;
778
779     // Interference for the live-in value.
780     if (BI.LiveIn) {
781       if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number))
782         BC.Entry = SpillPlacement::MustSpill, ++Ins;
783       else if (Intf.first() < BI.FirstInstr)
784         BC.Entry = SpillPlacement::PrefSpill, ++Ins;
785       else if (Intf.first() < BI.LastInstr)
786         ++Ins;
787     }
788
789     // Interference for the live-out value.
790     if (BI.LiveOut) {
791       if (Intf.last() >= SA->getLastSplitPoint(BC.Number))
792         BC.Exit = SpillPlacement::MustSpill, ++Ins;
793       else if (Intf.last() > BI.LastInstr)
794         BC.Exit = SpillPlacement::PrefSpill, ++Ins;
795       else if (Intf.last() > BI.FirstInstr)
796         ++Ins;
797     }
798
799     // Accumulate the total frequency of inserted spill code.
800     while (Ins--)
801       StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
802   }
803   Cost = StaticCost;
804
805   // Add constraints for use-blocks. Note that these are the only constraints
806   // that may add a positive bias, it is downhill from here.
807   SpillPlacer->addConstraints(SplitConstraints);
808   return SpillPlacer->scanActiveBundles();
809 }
810
811
812 /// addThroughConstraints - Add constraints and links to SpillPlacer from the
813 /// live-through blocks in Blocks.
814 void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
815                                      ArrayRef<unsigned> Blocks) {
816   const unsigned GroupSize = 8;
817   SpillPlacement::BlockConstraint BCS[GroupSize];
818   unsigned TBS[GroupSize];
819   unsigned B = 0, T = 0;
820
821   for (unsigned i = 0; i != Blocks.size(); ++i) {
822     unsigned Number = Blocks[i];
823     Intf.moveToBlock(Number);
824
825     if (!Intf.hasInterference()) {
826       assert(T < GroupSize && "Array overflow");
827       TBS[T] = Number;
828       if (++T == GroupSize) {
829         SpillPlacer->addLinks(makeArrayRef(TBS, T));
830         T = 0;
831       }
832       continue;
833     }
834
835     assert(B < GroupSize && "Array overflow");
836     BCS[B].Number = Number;
837
838     // Interference for the live-in value.
839     if (Intf.first() <= Indexes->getMBBStartIdx(Number))
840       BCS[B].Entry = SpillPlacement::MustSpill;
841     else
842       BCS[B].Entry = SpillPlacement::PrefSpill;
843
844     // Interference for the live-out value.
845     if (Intf.last() >= SA->getLastSplitPoint(Number))
846       BCS[B].Exit = SpillPlacement::MustSpill;
847     else
848       BCS[B].Exit = SpillPlacement::PrefSpill;
849
850     if (++B == GroupSize) {
851       ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
852       SpillPlacer->addConstraints(Array);
853       B = 0;
854     }
855   }
856
857   ArrayRef<SpillPlacement::BlockConstraint> Array(BCS, B);
858   SpillPlacer->addConstraints(Array);
859   SpillPlacer->addLinks(makeArrayRef(TBS, T));
860 }
861
862 void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
863   // Keep track of through blocks that have not been added to SpillPlacer.
864   BitVector Todo = SA->getThroughBlocks();
865   SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
866   unsigned AddedTo = 0;
867 #ifndef NDEBUG
868   unsigned Visited = 0;
869 #endif
870
871   for (;;) {
872     ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
873     // Find new through blocks in the periphery of PrefRegBundles.
874     for (int i = 0, e = NewBundles.size(); i != e; ++i) {
875       unsigned Bundle = NewBundles[i];
876       // Look at all blocks connected to Bundle in the full graph.
877       ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
878       for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
879            I != E; ++I) {
880         unsigned Block = *I;
881         if (!Todo.test(Block))
882           continue;
883         Todo.reset(Block);
884         // This is a new through block. Add it to SpillPlacer later.
885         ActiveBlocks.push_back(Block);
886 #ifndef NDEBUG
887         ++Visited;
888 #endif
889       }
890     }
891     // Any new blocks to add?
892     if (ActiveBlocks.size() == AddedTo)
893       break;
894
895     // Compute through constraints from the interference, or assume that all
896     // through blocks prefer spilling when forming compact regions.
897     ArrayRef<unsigned> NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
898     if (Cand.PhysReg)
899       addThroughConstraints(Cand.Intf, NewBlocks);
900     else
901       // Provide a strong negative bias on through blocks to prevent unwanted
902       // liveness on loop backedges.
903       SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
904     AddedTo = ActiveBlocks.size();
905
906     // Perhaps iterating can enable more bundles?
907     SpillPlacer->iterate();
908   }
909   DEBUG(dbgs() << ", v=" << Visited);
910 }
911
912 /// calcCompactRegion - Compute the set of edge bundles that should be live
913 /// when splitting the current live range into compact regions.  Compact
914 /// regions can be computed without looking at interference.  They are the
915 /// regions formed by removing all the live-through blocks from the live range.
916 ///
917 /// Returns false if the current live range is already compact, or if the
918 /// compact regions would form single block regions anyway.
919 bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
920   // Without any through blocks, the live range is already compact.
921   if (!SA->getNumThroughBlocks())
922     return false;
923
924   // Compact regions don't correspond to any physreg.
925   Cand.reset(IntfCache, 0);
926
927   DEBUG(dbgs() << "Compact region bundles");
928
929   // Use the spill placer to determine the live bundles. GrowRegion pretends
930   // that all the through blocks have interference when PhysReg is unset.
931   SpillPlacer->prepare(Cand.LiveBundles);
932
933   // The static split cost will be zero since Cand.Intf reports no interference.
934   BlockFrequency Cost;
935   if (!addSplitConstraints(Cand.Intf, Cost)) {
936     DEBUG(dbgs() << ", none.\n");
937     return false;
938   }
939
940   growRegion(Cand);
941   SpillPlacer->finish();
942
943   if (!Cand.LiveBundles.any()) {
944     DEBUG(dbgs() << ", none.\n");
945     return false;
946   }
947
948   DEBUG({
949     for (int i = Cand.LiveBundles.find_first(); i>=0;
950          i = Cand.LiveBundles.find_next(i))
951     dbgs() << " EB#" << i;
952     dbgs() << ".\n";
953   });
954   return true;
955 }
956
957 /// calcSpillCost - Compute how expensive it would be to split the live range in
958 /// SA around all use blocks instead of forming bundle regions.
959 BlockFrequency RAGreedy::calcSpillCost() {
960   BlockFrequency Cost = 0;
961   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
962   for (unsigned i = 0; i != UseBlocks.size(); ++i) {
963     const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
964     unsigned Number = BI.MBB->getNumber();
965     // We normally only need one spill instruction - a load or a store.
966     Cost += SpillPlacer->getBlockFrequency(Number);
967
968     // Unless the value is redefined in the block.
969     if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
970       Cost += SpillPlacer->getBlockFrequency(Number);
971   }
972   return Cost;
973 }
974
975 /// calcGlobalSplitCost - Return the global split cost of following the split
976 /// pattern in LiveBundles. This cost should be added to the local cost of the
977 /// interference pattern in SplitConstraints.
978 ///
979 BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
980   BlockFrequency GlobalCost = 0;
981   const BitVector &LiveBundles = Cand.LiveBundles;
982   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
983   for (unsigned i = 0; i != UseBlocks.size(); ++i) {
984     const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
985     SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
986     bool RegIn  = LiveBundles[Bundles->getBundle(BC.Number, 0)];
987     bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
988     unsigned Ins = 0;
989
990     if (BI.LiveIn)
991       Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
992     if (BI.LiveOut)
993       Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
994     while (Ins--)
995       GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
996   }
997
998   for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
999     unsigned Number = Cand.ActiveBlocks[i];
1000     bool RegIn  = LiveBundles[Bundles->getBundle(Number, 0)];
1001     bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
1002     if (!RegIn && !RegOut)
1003       continue;
1004     if (RegIn && RegOut) {
1005       // We need double spill code if this block has interference.
1006       Cand.Intf.moveToBlock(Number);
1007       if (Cand.Intf.hasInterference()) {
1008         GlobalCost += SpillPlacer->getBlockFrequency(Number);
1009         GlobalCost += SpillPlacer->getBlockFrequency(Number);
1010       }
1011       continue;
1012     }
1013     // live-in / stack-out or stack-in live-out.
1014     GlobalCost += SpillPlacer->getBlockFrequency(Number);
1015   }
1016   return GlobalCost;
1017 }
1018
1019 /// splitAroundRegion - Split the current live range around the regions
1020 /// determined by BundleCand and GlobalCand.
1021 ///
1022 /// Before calling this function, GlobalCand and BundleCand must be initialized
1023 /// so each bundle is assigned to a valid candidate, or NoCand for the
1024 /// stack-bound bundles.  The shared SA/SE SplitAnalysis and SplitEditor
1025 /// objects must be initialized for the current live range, and intervals
1026 /// created for the used candidates.
1027 ///
1028 /// @param LREdit    The LiveRangeEdit object handling the current split.
1029 /// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1030 ///                  must appear in this list.
1031 void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1032                                  ArrayRef<unsigned> UsedCands) {
1033   // These are the intervals created for new global ranges. We may create more
1034   // intervals for local ranges.
1035   const unsigned NumGlobalIntvs = LREdit.size();
1036   DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
1037   assert(NumGlobalIntvs && "No global intervals configured");
1038
1039   // Isolate even single instructions when dealing with a proper sub-class.
1040   // That guarantees register class inflation for the stack interval because it
1041   // is all copies.
1042   unsigned Reg = SA->getParent().reg;
1043   bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1044
1045   // First handle all the blocks with uses.
1046   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1047   for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1048     const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1049     unsigned Number = BI.MBB->getNumber();
1050     unsigned IntvIn = 0, IntvOut = 0;
1051     SlotIndex IntfIn, IntfOut;
1052     if (BI.LiveIn) {
1053       unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1054       if (CandIn != NoCand) {
1055         GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1056         IntvIn = Cand.IntvIdx;
1057         Cand.Intf.moveToBlock(Number);
1058         IntfIn = Cand.Intf.first();
1059       }
1060     }
1061     if (BI.LiveOut) {
1062       unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1063       if (CandOut != NoCand) {
1064         GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1065         IntvOut = Cand.IntvIdx;
1066         Cand.Intf.moveToBlock(Number);
1067         IntfOut = Cand.Intf.last();
1068       }
1069     }
1070
1071     // Create separate intervals for isolated blocks with multiple uses.
1072     if (!IntvIn && !IntvOut) {
1073       DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
1074       if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1075         SE->splitSingleBlock(BI);
1076       continue;
1077     }
1078
1079     if (IntvIn && IntvOut)
1080       SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1081     else if (IntvIn)
1082       SE->splitRegInBlock(BI, IntvIn, IntfIn);
1083     else
1084       SE->splitRegOutBlock(BI, IntvOut, IntfOut);
1085   }
1086
1087   // Handle live-through blocks. The relevant live-through blocks are stored in
1088   // the ActiveBlocks list with each candidate. We need to filter out
1089   // duplicates.
1090   BitVector Todo = SA->getThroughBlocks();
1091   for (unsigned c = 0; c != UsedCands.size(); ++c) {
1092     ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1093     for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1094       unsigned Number = Blocks[i];
1095       if (!Todo.test(Number))
1096         continue;
1097       Todo.reset(Number);
1098
1099       unsigned IntvIn = 0, IntvOut = 0;
1100       SlotIndex IntfIn, IntfOut;
1101
1102       unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1103       if (CandIn != NoCand) {
1104         GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1105         IntvIn = Cand.IntvIdx;
1106         Cand.Intf.moveToBlock(Number);
1107         IntfIn = Cand.Intf.first();
1108       }
1109
1110       unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1111       if (CandOut != NoCand) {
1112         GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1113         IntvOut = Cand.IntvIdx;
1114         Cand.Intf.moveToBlock(Number);
1115         IntfOut = Cand.Intf.last();
1116       }
1117       if (!IntvIn && !IntvOut)
1118         continue;
1119       SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1120     }
1121   }
1122
1123   ++NumGlobalSplits;
1124
1125   SmallVector<unsigned, 8> IntvMap;
1126   SE->finish(&IntvMap);
1127   DebugVars->splitRegister(Reg, LREdit.regs());
1128
1129   ExtraRegInfo.resize(MRI->getNumVirtRegs());
1130   unsigned OrigBlocks = SA->getNumLiveBlocks();
1131
1132   // Sort out the new intervals created by splitting. We get four kinds:
1133   // - Remainder intervals should not be split again.
1134   // - Candidate intervals can be assigned to Cand.PhysReg.
1135   // - Block-local splits are candidates for local splitting.
1136   // - DCE leftovers should go back on the queue.
1137   for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1138     LiveInterval &Reg = *LREdit.get(i);
1139
1140     // Ignore old intervals from DCE.
1141     if (getStage(Reg) != RS_New)
1142       continue;
1143
1144     // Remainder interval. Don't try splitting again, spill if it doesn't
1145     // allocate.
1146     if (IntvMap[i] == 0) {
1147       setStage(Reg, RS_Spill);
1148       continue;
1149     }
1150
1151     // Global intervals. Allow repeated splitting as long as the number of live
1152     // blocks is strictly decreasing.
1153     if (IntvMap[i] < NumGlobalIntvs) {
1154       if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
1155         DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1156                      << " blocks as original.\n");
1157         // Don't allow repeated splitting as a safe guard against looping.
1158         setStage(Reg, RS_Split2);
1159       }
1160       continue;
1161     }
1162
1163     // Other intervals are treated as new. This includes local intervals created
1164     // for blocks with multiple uses, and anything created by DCE.
1165   }
1166
1167   if (VerifyEnabled)
1168     MF->verify(this, "After splitting live range around region");
1169 }
1170
1171 unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1172                                   SmallVectorImpl<LiveInterval*> &NewVRegs) {
1173   unsigned NumCands = 0;
1174   unsigned BestCand = NoCand;
1175   BlockFrequency BestCost;
1176   SmallVector<unsigned, 8> UsedCands;
1177
1178   // Check if we can split this live range around a compact region.
1179   bool HasCompact = calcCompactRegion(GlobalCand.front());
1180   if (HasCompact) {
1181     // Yes, keep GlobalCand[0] as the compact region candidate.
1182     NumCands = 1;
1183     BestCost = BlockFrequency::getMaxFrequency();
1184   } else {
1185     // No benefit from the compact region, our fallback will be per-block
1186     // splitting. Make sure we find a solution that is cheaper than spilling.
1187     BestCost = calcSpillCost();
1188     DEBUG(dbgs() << "Cost of isolating all blocks = " << BestCost << '\n');
1189   }
1190
1191   Order.rewind();
1192   while (unsigned PhysReg = Order.next()) {
1193     // Discard bad candidates before we run out of interference cache cursors.
1194     // This will only affect register classes with a lot of registers (>32).
1195     if (NumCands == IntfCache.getMaxCursors()) {
1196       unsigned WorstCount = ~0u;
1197       unsigned Worst = 0;
1198       for (unsigned i = 0; i != NumCands; ++i) {
1199         if (i == BestCand || !GlobalCand[i].PhysReg)
1200           continue;
1201         unsigned Count = GlobalCand[i].LiveBundles.count();
1202         if (Count < WorstCount)
1203           Worst = i, WorstCount = Count;
1204       }
1205       --NumCands;
1206       GlobalCand[Worst] = GlobalCand[NumCands];
1207       if (BestCand == NumCands)
1208         BestCand = Worst;
1209     }
1210
1211     if (GlobalCand.size() <= NumCands)
1212       GlobalCand.resize(NumCands+1);
1213     GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1214     Cand.reset(IntfCache, PhysReg);
1215
1216     SpillPlacer->prepare(Cand.LiveBundles);
1217     BlockFrequency Cost;
1218     if (!addSplitConstraints(Cand.Intf, Cost)) {
1219       DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
1220       continue;
1221     }
1222     DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = " << Cost);
1223     if (Cost >= BestCost) {
1224       DEBUG({
1225         if (BestCand == NoCand)
1226           dbgs() << " worse than no bundles\n";
1227         else
1228           dbgs() << " worse than "
1229                  << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1230       });
1231       continue;
1232     }
1233     growRegion(Cand);
1234
1235     SpillPlacer->finish();
1236
1237     // No live bundles, defer to splitSingleBlocks().
1238     if (!Cand.LiveBundles.any()) {
1239       DEBUG(dbgs() << " no bundles.\n");
1240       continue;
1241     }
1242
1243     Cost += calcGlobalSplitCost(Cand);
1244     DEBUG({
1245       dbgs() << ", total = " << Cost << " with bundles";
1246       for (int i = Cand.LiveBundles.find_first(); i>=0;
1247            i = Cand.LiveBundles.find_next(i))
1248         dbgs() << " EB#" << i;
1249       dbgs() << ".\n";
1250     });
1251     if (Cost < BestCost) {
1252       BestCand = NumCands;
1253       BestCost = Cost;
1254     }
1255     ++NumCands;
1256   }
1257
1258   // No solutions found, fall back to single block splitting.
1259   if (!HasCompact && BestCand == NoCand)
1260     return 0;
1261
1262   // Prepare split editor.
1263   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1264   SE->reset(LREdit, SplitSpillMode);
1265
1266   // Assign all edge bundles to the preferred candidate, or NoCand.
1267   BundleCand.assign(Bundles->getNumBundles(), NoCand);
1268
1269   // Assign bundles for the best candidate region.
1270   if (BestCand != NoCand) {
1271     GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1272     if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1273       UsedCands.push_back(BestCand);
1274       Cand.IntvIdx = SE->openIntv();
1275       DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1276                    << B << " bundles, intv " << Cand.IntvIdx << ".\n");
1277       (void)B;
1278     }
1279   }
1280
1281   // Assign bundles for the compact region.
1282   if (HasCompact) {
1283     GlobalSplitCandidate &Cand = GlobalCand.front();
1284     assert(!Cand.PhysReg && "Compact region has no physreg");
1285     if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1286       UsedCands.push_back(0);
1287       Cand.IntvIdx = SE->openIntv();
1288       DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1289                    << Cand.IntvIdx << ".\n");
1290       (void)B;
1291     }
1292   }
1293
1294   splitAroundRegion(LREdit, UsedCands);
1295   return 0;
1296 }
1297
1298
1299 //===----------------------------------------------------------------------===//
1300 //                            Per-Block Splitting
1301 //===----------------------------------------------------------------------===//
1302
1303 /// tryBlockSplit - Split a global live range around every block with uses. This
1304 /// creates a lot of local live ranges, that will be split by tryLocalSplit if
1305 /// they don't allocate.
1306 unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1307                                  SmallVectorImpl<LiveInterval*> &NewVRegs) {
1308   assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1309   unsigned Reg = VirtReg.reg;
1310   bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1311   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1312   SE->reset(LREdit, SplitSpillMode);
1313   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1314   for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1315     const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1316     if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1317       SE->splitSingleBlock(BI);
1318   }
1319   // No blocks were split.
1320   if (LREdit.empty())
1321     return 0;
1322
1323   // We did split for some blocks.
1324   SmallVector<unsigned, 8> IntvMap;
1325   SE->finish(&IntvMap);
1326
1327   // Tell LiveDebugVariables about the new ranges.
1328   DebugVars->splitRegister(Reg, LREdit.regs());
1329
1330   ExtraRegInfo.resize(MRI->getNumVirtRegs());
1331
1332   // Sort out the new intervals created by splitting. The remainder interval
1333   // goes straight to spilling, the new local ranges get to stay RS_New.
1334   for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1335     LiveInterval &LI = *LREdit.get(i);
1336     if (getStage(LI) == RS_New && IntvMap[i] == 0)
1337       setStage(LI, RS_Spill);
1338   }
1339
1340   if (VerifyEnabled)
1341     MF->verify(this, "After splitting live range around basic blocks");
1342   return 0;
1343 }
1344
1345
1346 //===----------------------------------------------------------------------===//
1347 //                         Per-Instruction Splitting
1348 //===----------------------------------------------------------------------===//
1349
1350 /// tryInstructionSplit - Split a live range around individual instructions.
1351 /// This is normally not worthwhile since the spiller is doing essentially the
1352 /// same thing. However, when the live range is in a constrained register
1353 /// class, it may help to insert copies such that parts of the live range can
1354 /// be moved to a larger register class.
1355 ///
1356 /// This is similar to spilling to a larger register class.
1357 unsigned
1358 RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1359                               SmallVectorImpl<LiveInterval*> &NewVRegs) {
1360   // There is no point to this if there are no larger sub-classes.
1361   if (!RegClassInfo.isProperSubClass(MRI->getRegClass(VirtReg.reg)))
1362     return 0;
1363
1364   // Always enable split spill mode, since we're effectively spilling to a
1365   // register.
1366   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1367   SE->reset(LREdit, SplitEditor::SM_Size);
1368
1369   ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1370   if (Uses.size() <= 1)
1371     return 0;
1372
1373   DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1374
1375   // Split around every non-copy instruction.
1376   for (unsigned i = 0; i != Uses.size(); ++i) {
1377     if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
1378       if (MI->isFullCopy()) {
1379         DEBUG(dbgs() << "    skip:\t" << Uses[i] << '\t' << *MI);
1380         continue;
1381       }
1382     SE->openIntv();
1383     SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1384     SlotIndex SegStop  = SE->leaveIntvAfter(Uses[i]);
1385     SE->useIntv(SegStart, SegStop);
1386   }
1387
1388   if (LREdit.empty()) {
1389     DEBUG(dbgs() << "All uses were copies.\n");
1390     return 0;
1391   }
1392
1393   SmallVector<unsigned, 8> IntvMap;
1394   SE->finish(&IntvMap);
1395   DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1396   ExtraRegInfo.resize(MRI->getNumVirtRegs());
1397
1398   // Assign all new registers to RS_Spill. This was the last chance.
1399   setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1400   return 0;
1401 }
1402
1403
1404 //===----------------------------------------------------------------------===//
1405 //                             Local Splitting
1406 //===----------------------------------------------------------------------===//
1407
1408
1409 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1410 /// in order to use PhysReg between two entries in SA->UseSlots.
1411 ///
1412 /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1413 ///
1414 void RAGreedy::calcGapWeights(unsigned PhysReg,
1415                               SmallVectorImpl<float> &GapWeight) {
1416   assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1417   const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1418   ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1419   const unsigned NumGaps = Uses.size()-1;
1420
1421   // Start and end points for the interference check.
1422   SlotIndex StartIdx =
1423     BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1424   SlotIndex StopIdx =
1425     BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
1426
1427   GapWeight.assign(NumGaps, 0.0f);
1428
1429   // Add interference from each overlapping register.
1430   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1431     if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1432           .checkInterference())
1433       continue;
1434
1435     // We know that VirtReg is a continuous interval from FirstInstr to
1436     // LastInstr, so we don't need InterferenceQuery.
1437     //
1438     // Interference that overlaps an instruction is counted in both gaps
1439     // surrounding the instruction. The exception is interference before
1440     // StartIdx and after StopIdx.
1441     //
1442     LiveIntervalUnion::SegmentIter IntI =
1443       Matrix->getLiveUnions()[*Units] .find(StartIdx);
1444     for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1445       // Skip the gaps before IntI.
1446       while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1447         if (++Gap == NumGaps)
1448           break;
1449       if (Gap == NumGaps)
1450         break;
1451
1452       // Update the gaps covered by IntI.
1453       const float weight = IntI.value()->weight;
1454       for (; Gap != NumGaps; ++Gap) {
1455         GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1456         if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1457           break;
1458       }
1459       if (Gap == NumGaps)
1460         break;
1461     }
1462   }
1463
1464   // Add fixed interference.
1465   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1466     const LiveInterval &LI = LIS->getRegUnit(*Units);
1467     LiveInterval::const_iterator I = LI.find(StartIdx);
1468     LiveInterval::const_iterator E = LI.end();
1469
1470     // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1471     for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1472       while (Uses[Gap+1].getBoundaryIndex() < I->start)
1473         if (++Gap == NumGaps)
1474           break;
1475       if (Gap == NumGaps)
1476         break;
1477
1478       for (; Gap != NumGaps; ++Gap) {
1479         GapWeight[Gap] = HUGE_VALF;
1480         if (Uses[Gap+1].getBaseIndex() >= I->end)
1481           break;
1482       }
1483       if (Gap == NumGaps)
1484         break;
1485     }
1486   }
1487 }
1488
1489 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1490 /// basic block.
1491 ///
1492 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1493                                  SmallVectorImpl<LiveInterval*> &NewVRegs) {
1494   assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1495   const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1496
1497   // Note that it is possible to have an interval that is live-in or live-out
1498   // while only covering a single block - A phi-def can use undef values from
1499   // predecessors, and the block could be a single-block loop.
1500   // We don't bother doing anything clever about such a case, we simply assume
1501   // that the interval is continuous from FirstInstr to LastInstr. We should
1502   // make sure that we don't do anything illegal to such an interval, though.
1503
1504   ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1505   if (Uses.size() <= 2)
1506     return 0;
1507   const unsigned NumGaps = Uses.size()-1;
1508
1509   DEBUG({
1510     dbgs() << "tryLocalSplit: ";
1511     for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1512       dbgs() << ' ' << Uses[i];
1513     dbgs() << '\n';
1514   });
1515
1516   // If VirtReg is live across any register mask operands, compute a list of
1517   // gaps with register masks.
1518   SmallVector<unsigned, 8> RegMaskGaps;
1519   if (Matrix->checkRegMaskInterference(VirtReg)) {
1520     // Get regmask slots for the whole block.
1521     ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
1522     DEBUG(dbgs() << RMS.size() << " regmasks in block:");
1523     // Constrain to VirtReg's live range.
1524     unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1525                                    Uses.front().getRegSlot()) - RMS.begin();
1526     unsigned re = RMS.size();
1527     for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
1528       // Look for Uses[i] <= RMS <= Uses[i+1].
1529       assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1530       if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
1531         continue;
1532       // Skip a regmask on the same instruction as the last use. It doesn't
1533       // overlap the live range.
1534       if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1535         break;
1536       DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
1537       RegMaskGaps.push_back(i);
1538       // Advance ri to the next gap. A regmask on one of the uses counts in
1539       // both gaps.
1540       while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1541         ++ri;
1542     }
1543     DEBUG(dbgs() << '\n');
1544   }
1545
1546   // Since we allow local split results to be split again, there is a risk of
1547   // creating infinite loops. It is tempting to require that the new live
1548   // ranges have less instructions than the original. That would guarantee
1549   // convergence, but it is too strict. A live range with 3 instructions can be
1550   // split 2+3 (including the COPY), and we want to allow that.
1551   //
1552   // Instead we use these rules:
1553   //
1554   // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
1555   //    noop split, of course).
1556   // 2. Require progress be made for ranges with getStage() == RS_Split2. All
1557   //    the new ranges must have fewer instructions than before the split.
1558   // 3. New ranges with the same number of instructions are marked RS_Split2,
1559   //    smaller ranges are marked RS_New.
1560   //
1561   // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1562   // excessive splitting and infinite loops.
1563   //
1564   bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
1565
1566   // Best split candidate.
1567   unsigned BestBefore = NumGaps;
1568   unsigned BestAfter = 0;
1569   float BestDiff = 0;
1570
1571   const float blockFreq =
1572     SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
1573     (1.0f / BlockFrequency::getEntryFrequency());
1574   SmallVector<float, 8> GapWeight;
1575
1576   Order.rewind();
1577   while (unsigned PhysReg = Order.next()) {
1578     // Keep track of the largest spill weight that would need to be evicted in
1579     // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1580     calcGapWeights(PhysReg, GapWeight);
1581
1582     // Remove any gaps with regmask clobbers.
1583     if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
1584       for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
1585         GapWeight[RegMaskGaps[i]] = HUGE_VALF;
1586
1587     // Try to find the best sequence of gaps to close.
1588     // The new spill weight must be larger than any gap interference.
1589
1590     // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1591     unsigned SplitBefore = 0, SplitAfter = 1;
1592
1593     // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1594     // It is the spill weight that needs to be evicted.
1595     float MaxGap = GapWeight[0];
1596
1597     for (;;) {
1598       // Live before/after split?
1599       const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1600       const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1601
1602       DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1603                    << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1604                    << " i=" << MaxGap);
1605
1606       // Stop before the interval gets so big we wouldn't be making progress.
1607       if (!LiveBefore && !LiveAfter) {
1608         DEBUG(dbgs() << " all\n");
1609         break;
1610       }
1611       // Should the interval be extended or shrunk?
1612       bool Shrink = true;
1613
1614       // How many gaps would the new range have?
1615       unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1616
1617       // Legally, without causing looping?
1618       bool Legal = !ProgressRequired || NewGaps < NumGaps;
1619
1620       if (Legal && MaxGap < HUGE_VALF) {
1621         // Estimate the new spill weight. Each instruction reads or writes the
1622         // register. Conservatively assume there are no read-modify-write
1623         // instructions.
1624         //
1625         // Try to guess the size of the new interval.
1626         const float EstWeight = normalizeSpillWeight(blockFreq * (NewGaps + 1),
1627                                  Uses[SplitBefore].distance(Uses[SplitAfter]) +
1628                                  (LiveBefore + LiveAfter)*SlotIndex::InstrDist);
1629         // Would this split be possible to allocate?
1630         // Never allocate all gaps, we wouldn't be making progress.
1631         DEBUG(dbgs() << " w=" << EstWeight);
1632         if (EstWeight * Hysteresis >= MaxGap) {
1633           Shrink = false;
1634           float Diff = EstWeight - MaxGap;
1635           if (Diff > BestDiff) {
1636             DEBUG(dbgs() << " (best)");
1637             BestDiff = Hysteresis * Diff;
1638             BestBefore = SplitBefore;
1639             BestAfter = SplitAfter;
1640           }
1641         }
1642       }
1643
1644       // Try to shrink.
1645       if (Shrink) {
1646         if (++SplitBefore < SplitAfter) {
1647           DEBUG(dbgs() << " shrink\n");
1648           // Recompute the max when necessary.
1649           if (GapWeight[SplitBefore - 1] >= MaxGap) {
1650             MaxGap = GapWeight[SplitBefore];
1651             for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1652               MaxGap = std::max(MaxGap, GapWeight[i]);
1653           }
1654           continue;
1655         }
1656         MaxGap = 0;
1657       }
1658
1659       // Try to extend the interval.
1660       if (SplitAfter >= NumGaps) {
1661         DEBUG(dbgs() << " end\n");
1662         break;
1663       }
1664
1665       DEBUG(dbgs() << " extend\n");
1666       MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
1667     }
1668   }
1669
1670   // Didn't find any candidates?
1671   if (BestBefore == NumGaps)
1672     return 0;
1673
1674   DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1675                << '-' << Uses[BestAfter] << ", " << BestDiff
1676                << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1677
1678   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1679   SE->reset(LREdit);
1680
1681   SE->openIntv();
1682   SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1683   SlotIndex SegStop  = SE->leaveIntvAfter(Uses[BestAfter]);
1684   SE->useIntv(SegStart, SegStop);
1685   SmallVector<unsigned, 8> IntvMap;
1686   SE->finish(&IntvMap);
1687   DebugVars->splitRegister(VirtReg.reg, LREdit.regs());
1688
1689   // If the new range has the same number of instructions as before, mark it as
1690   // RS_Split2 so the next split will be forced to make progress. Otherwise,
1691   // leave the new intervals as RS_New so they can compete.
1692   bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1693   bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1694   unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1695   if (NewGaps >= NumGaps) {
1696     DEBUG(dbgs() << "Tagging non-progress ranges: ");
1697     assert(!ProgressRequired && "Didn't make progress when it was required.");
1698     for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1699       if (IntvMap[i] == 1) {
1700         setStage(*LREdit.get(i), RS_Split2);
1701         DEBUG(dbgs() << PrintReg(LREdit.get(i)->reg));
1702       }
1703     DEBUG(dbgs() << '\n');
1704   }
1705   ++NumLocalSplits;
1706
1707   return 0;
1708 }
1709
1710 //===----------------------------------------------------------------------===//
1711 //                          Live Range Splitting
1712 //===----------------------------------------------------------------------===//
1713
1714 /// trySplit - Try to split VirtReg or one of its interferences, making it
1715 /// assignable.
1716 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1717 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1718                             SmallVectorImpl<LiveInterval*>&NewVRegs) {
1719   // Ranges must be Split2 or less.
1720   if (getStage(VirtReg) >= RS_Spill)
1721     return 0;
1722
1723   // Local intervals are handled separately.
1724   if (LIS->intervalIsInOneMBB(VirtReg)) {
1725     NamedRegionTimer T("Local Splitting", TimerGroupName, TimePassesIsEnabled);
1726     SA->analyze(&VirtReg);
1727     unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1728     if (PhysReg || !NewVRegs.empty())
1729       return PhysReg;
1730     return tryInstructionSplit(VirtReg, Order, NewVRegs);
1731   }
1732
1733   NamedRegionTimer T("Global Splitting", TimerGroupName, TimePassesIsEnabled);
1734
1735   SA->analyze(&VirtReg);
1736
1737   // FIXME: SplitAnalysis may repair broken live ranges coming from the
1738   // coalescer. That may cause the range to become allocatable which means that
1739   // tryRegionSplit won't be making progress. This check should be replaced with
1740   // an assertion when the coalescer is fixed.
1741   if (SA->didRepairRange()) {
1742     // VirtReg has changed, so all cached queries are invalid.
1743     Matrix->invalidateVirtRegs();
1744     if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1745       return PhysReg;
1746   }
1747
1748   // First try to split around a region spanning multiple blocks. RS_Split2
1749   // ranges already made dubious progress with region splitting, so they go
1750   // straight to single block splitting.
1751   if (getStage(VirtReg) < RS_Split2) {
1752     unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1753     if (PhysReg || !NewVRegs.empty())
1754       return PhysReg;
1755   }
1756
1757   // Then isolate blocks.
1758   return tryBlockSplit(VirtReg, Order, NewVRegs);
1759 }
1760
1761
1762 //===----------------------------------------------------------------------===//
1763 //                            Main Entry Point
1764 //===----------------------------------------------------------------------===//
1765
1766 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
1767                                  SmallVectorImpl<LiveInterval*> &NewVRegs) {
1768   // First try assigning a free register.
1769   AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo);
1770   if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
1771     return PhysReg;
1772
1773   LiveRangeStage Stage = getStage(VirtReg);
1774   DEBUG(dbgs() << StageName[Stage]
1775                << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
1776
1777   // Try to evict a less worthy live range, but only for ranges from the primary
1778   // queue. The RS_Split ranges already failed to do this, and they should not
1779   // get a second chance until they have been split.
1780   if (Stage != RS_Split)
1781     if (unsigned PhysReg = tryEvict(VirtReg, Order, NewVRegs))
1782       return PhysReg;
1783
1784   assert(NewVRegs.empty() && "Cannot append to existing NewVRegs");
1785
1786   // The first time we see a live range, don't try to split or spill.
1787   // Wait until the second time, when all smaller ranges have been allocated.
1788   // This gives a better picture of the interference to split around.
1789   if (Stage < RS_Split) {
1790     setStage(VirtReg, RS_Split);
1791     DEBUG(dbgs() << "wait for second round\n");
1792     NewVRegs.push_back(&VirtReg);
1793     return 0;
1794   }
1795
1796   // If we couldn't allocate a register from spilling, there is probably some
1797   // invalid inline assembly. The base class wil report it.
1798   if (Stage >= RS_Done || !VirtReg.isSpillable())
1799     return ~0u;
1800
1801   // Try splitting VirtReg or interferences.
1802   unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
1803   if (PhysReg || !NewVRegs.empty())
1804     return PhysReg;
1805
1806   // Finally spill VirtReg itself.
1807   NamedRegionTimer T("Spiller", TimerGroupName, TimePassesIsEnabled);
1808   LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this);
1809   spiller().spill(LRE);
1810   setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
1811
1812   if (VerifyEnabled)
1813     MF->verify(this, "After spilling");
1814
1815   // The live virtual register requesting allocation was spilled, so tell
1816   // the caller not to allocate anything during this round.
1817   return 0;
1818 }
1819
1820 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
1821   DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
1822                << "********** Function: " << mf.getName() << '\n');
1823
1824   MF = &mf;
1825   if (VerifyEnabled)
1826     MF->verify(this, "Before greedy register allocator");
1827
1828   RegAllocBase::init(getAnalysis<VirtRegMap>(),
1829                      getAnalysis<LiveIntervals>(),
1830                      getAnalysis<LiveRegMatrix>());
1831   Indexes = &getAnalysis<SlotIndexes>();
1832   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
1833   DomTree = &getAnalysis<MachineDominatorTree>();
1834   SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
1835   Loops = &getAnalysis<MachineLoopInfo>();
1836   Bundles = &getAnalysis<EdgeBundles>();
1837   SpillPlacer = &getAnalysis<SpillPlacement>();
1838   DebugVars = &getAnalysis<LiveDebugVariables>();
1839
1840   DEBUG(LIS->dump());
1841
1842   SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
1843   SE.reset(new SplitEditor(*SA, *LIS, *VRM, *DomTree, *MBFI));
1844   ExtraRegInfo.clear();
1845   ExtraRegInfo.resize(MRI->getNumVirtRegs());
1846   NextCascade = 1;
1847   IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
1848   GlobalCand.resize(32);  // This will grow as needed.
1849
1850   allocatePhysRegs();
1851   releaseMemory();
1852   return true;
1853 }