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