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