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