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