1 //===- RegAllocGreedy.cpp - greedy register allocator ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the RAGreedy function pass for register allocation in
10 // optimized builds.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "AllocationOrder.h"
15 #include "InterferenceCache.h"
16 #include "LiveDebugVariables.h"
17 #include "RegAllocBase.h"
18 #include "SpillPlacement.h"
19 #include "SplitKit.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/BitVector.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/IndexedMap.h"
24 #include "llvm/ADT/MapVector.h"
25 #include "llvm/ADT/SetVector.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/Analysis/AliasAnalysis.h"
32 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
33 #include "llvm/CodeGen/CalcSpillWeights.h"
34 #include "llvm/CodeGen/EdgeBundles.h"
35 #include "llvm/CodeGen/LiveInterval.h"
36 #include "llvm/CodeGen/LiveIntervalUnion.h"
37 #include "llvm/CodeGen/LiveIntervals.h"
38 #include "llvm/CodeGen/LiveRangeEdit.h"
39 #include "llvm/CodeGen/LiveRegMatrix.h"
40 #include "llvm/CodeGen/LiveStacks.h"
41 #include "llvm/CodeGen/MachineBasicBlock.h"
42 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
43 #include "llvm/CodeGen/MachineDominators.h"
44 #include "llvm/CodeGen/MachineFrameInfo.h"
45 #include "llvm/CodeGen/MachineFunction.h"
46 #include "llvm/CodeGen/MachineFunctionPass.h"
47 #include "llvm/CodeGen/MachineInstr.h"
48 #include "llvm/CodeGen/MachineLoopInfo.h"
49 #include "llvm/CodeGen/MachineOperand.h"
50 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
51 #include "llvm/CodeGen/MachineRegisterInfo.h"
52 #include "llvm/CodeGen/RegAllocRegistry.h"
53 #include "llvm/CodeGen/RegisterClassInfo.h"
54 #include "llvm/CodeGen/SlotIndexes.h"
55 #include "llvm/CodeGen/Spiller.h"
56 #include "llvm/CodeGen/TargetInstrInfo.h"
57 #include "llvm/CodeGen/TargetRegisterInfo.h"
58 #include "llvm/CodeGen/TargetSubtargetInfo.h"
59 #include "llvm/CodeGen/VirtRegMap.h"
60 #include "llvm/IR/Function.h"
61 #include "llvm/IR/LLVMContext.h"
62 #include "llvm/MC/MCRegisterInfo.h"
63 #include "llvm/Pass.h"
64 #include "llvm/Support/BlockFrequency.h"
65 #include "llvm/Support/BranchProbability.h"
66 #include "llvm/Support/CommandLine.h"
67 #include "llvm/Support/Debug.h"
68 #include "llvm/Support/MathExtras.h"
69 #include "llvm/Support/Timer.h"
70 #include "llvm/Support/raw_ostream.h"
71 #include "llvm/Target/TargetMachine.h"
72 #include <algorithm>
73 #include <cassert>
74 #include <cstdint>
75 #include <memory>
76 #include <queue>
77 #include <tuple>
78 #include <utility>
79 
80 using namespace llvm;
81 
82 #define DEBUG_TYPE "regalloc"
83 
84 STATISTIC(NumGlobalSplits, "Number of split global live ranges");
85 STATISTIC(NumLocalSplits,  "Number of split local live ranges");
86 STATISTIC(NumEvicted,      "Number of interferences evicted");
87 
88 static cl::opt<SplitEditor::ComplementSpillMode> SplitSpillMode(
89     "split-spill-mode", cl::Hidden,
90     cl::desc("Spill mode for splitting live ranges"),
91     cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
92                clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
93                clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed")),
94     cl::init(SplitEditor::SM_Speed));
95 
96 static cl::opt<unsigned>
97 LastChanceRecoloringMaxDepth("lcr-max-depth", cl::Hidden,
98                              cl::desc("Last chance recoloring max depth"),
99                              cl::init(5));
100 
101 static cl::opt<unsigned> LastChanceRecoloringMaxInterference(
102     "lcr-max-interf", cl::Hidden,
103     cl::desc("Last chance recoloring maximum number of considered"
104              " interference at a time"),
105     cl::init(8));
106 
107 static cl::opt<bool> ExhaustiveSearch(
108     "exhaustive-register-search", cl::NotHidden,
109     cl::desc("Exhaustive Search for registers bypassing the depth "
110              "and interference cutoffs of last chance recoloring"),
111     cl::Hidden);
112 
113 static cl::opt<bool> EnableLocalReassignment(
114     "enable-local-reassign", cl::Hidden,
115     cl::desc("Local reassignment can yield better allocation decisions, but "
116              "may be compile time intensive"),
117     cl::init(false));
118 
119 static cl::opt<bool> EnableDeferredSpilling(
120     "enable-deferred-spilling", cl::Hidden,
121     cl::desc("Instead of spilling a variable right away, defer the actual "
122              "code insertion to the end of the allocation. That way the "
123              "allocator might still find a suitable coloring for this "
124              "variable because of other evicted variables."),
125     cl::init(false));
126 
127 // FIXME: Find a good default for this flag and remove the flag.
128 static cl::opt<unsigned>
129 CSRFirstTimeCost("regalloc-csr-first-time-cost",
130               cl::desc("Cost for first time use of callee-saved register."),
131               cl::init(0), cl::Hidden);
132 
133 static cl::opt<bool> ConsiderLocalIntervalCost(
134     "consider-local-interval-cost", cl::Hidden,
135     cl::desc("Consider the cost of local intervals created by a split "
136              "candidate when choosing the best split candidate."),
137     cl::init(false));
138 
139 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
140                                        createGreedyRegisterAllocator);
141 
142 namespace {
143 
144 class RAGreedy : public MachineFunctionPass,
145                  public RegAllocBase,
146                  private LiveRangeEdit::Delegate {
147   // Convenient shortcuts.
148   using PQueue = std::priority_queue<std::pair<unsigned, unsigned>>;
149   using SmallLISet = SmallPtrSet<LiveInterval *, 4>;
150   using SmallVirtRegSet = SmallSet<unsigned, 16>;
151 
152   // context
153   MachineFunction *MF;
154 
155   // Shortcuts to some useful interface.
156   const TargetInstrInfo *TII;
157   const TargetRegisterInfo *TRI;
158   RegisterClassInfo RCI;
159 
160   // analyses
161   SlotIndexes *Indexes;
162   MachineBlockFrequencyInfo *MBFI;
163   MachineDominatorTree *DomTree;
164   MachineLoopInfo *Loops;
165   MachineOptimizationRemarkEmitter *ORE;
166   EdgeBundles *Bundles;
167   SpillPlacement *SpillPlacer;
168   LiveDebugVariables *DebugVars;
169   AliasAnalysis *AA;
170 
171   // state
172   std::unique_ptr<Spiller> SpillerInstance;
173   PQueue Queue;
174   unsigned NextCascade;
175 
176   // Live ranges pass through a number of stages as we try to allocate them.
177   // Some of the stages may also create new live ranges:
178   //
179   // - Region splitting.
180   // - Per-block splitting.
181   // - Local splitting.
182   // - Spilling.
183   //
184   // Ranges produced by one of the stages skip the previous stages when they are
185   // dequeued. This improves performance because we can skip interference checks
186   // that are unlikely to give any results. It also guarantees that the live
187   // range splitting algorithm terminates, something that is otherwise hard to
188   // ensure.
189   enum LiveRangeStage {
190     /// Newly created live range that has never been queued.
191     RS_New,
192 
193     /// Only attempt assignment and eviction. Then requeue as RS_Split.
194     RS_Assign,
195 
196     /// Attempt live range splitting if assignment is impossible.
197     RS_Split,
198 
199     /// Attempt more aggressive live range splitting that is guaranteed to make
200     /// progress.  This is used for split products that may not be making
201     /// progress.
202     RS_Split2,
203 
204     /// Live range will be spilled.  No more splitting will be attempted.
205     RS_Spill,
206 
207 
208     /// Live range is in memory. Because of other evictions, it might get moved
209     /// in a register in the end.
210     RS_Memory,
211 
212     /// There is nothing more we can do to this live range.  Abort compilation
213     /// if it can't be assigned.
214     RS_Done
215   };
216 
217   // Enum CutOffStage to keep a track whether the register allocation failed
218   // because of the cutoffs encountered in last chance recoloring.
219   // Note: This is used as bitmask. New value should be next power of 2.
220   enum CutOffStage {
221     // No cutoffs encountered
222     CO_None = 0,
223 
224     // lcr-max-depth cutoff encountered
225     CO_Depth = 1,
226 
227     // lcr-max-interf cutoff encountered
228     CO_Interf = 2
229   };
230 
231   uint8_t CutOffInfo;
232 
233 #ifndef NDEBUG
234   static const char *const StageName[];
235 #endif
236 
237   // RegInfo - Keep additional information about each live range.
238   struct RegInfo {
239     LiveRangeStage Stage = RS_New;
240 
241     // Cascade - Eviction loop prevention. See canEvictInterference().
242     unsigned Cascade = 0;
243 
244     RegInfo() = default;
245   };
246 
247   IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
248 
249   LiveRangeStage getStage(const LiveInterval &VirtReg) const {
250     return ExtraRegInfo[VirtReg.reg()].Stage;
251   }
252 
253   void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
254     ExtraRegInfo.resize(MRI->getNumVirtRegs());
255     ExtraRegInfo[VirtReg.reg()].Stage = Stage;
256   }
257 
258   template<typename Iterator>
259   void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
260     ExtraRegInfo.resize(MRI->getNumVirtRegs());
261     for (;Begin != End; ++Begin) {
262       unsigned Reg = *Begin;
263       if (ExtraRegInfo[Reg].Stage == RS_New)
264         ExtraRegInfo[Reg].Stage = NewStage;
265     }
266   }
267 
268   /// Cost of evicting interference.
269   struct EvictionCost {
270     unsigned BrokenHints = 0; ///< Total number of broken hints.
271     float MaxWeight = 0;      ///< Maximum spill weight evicted.
272 
273     EvictionCost() = default;
274 
275     bool isMax() const { return BrokenHints == ~0u; }
276 
277     void setMax() { BrokenHints = ~0u; }
278 
279     void setBrokenHints(unsigned NHints) { BrokenHints = NHints; }
280 
281     bool operator<(const EvictionCost &O) const {
282       return std::tie(BrokenHints, MaxWeight) <
283              std::tie(O.BrokenHints, O.MaxWeight);
284     }
285   };
286 
287   /// EvictionTrack - Keeps track of past evictions in order to optimize region
288   /// split decision.
289   class EvictionTrack {
290 
291   public:
292     using EvictorInfo =
293         std::pair<unsigned /* evictor */, unsigned /* physreg */>;
294     using EvicteeInfo = llvm::DenseMap<unsigned /* evictee */, EvictorInfo>;
295 
296   private:
297     /// Each Vreg that has been evicted in the last stage of selectOrSplit will
298     /// be mapped to the evictor Vreg and the PhysReg it was evicted from.
299     EvicteeInfo Evictees;
300 
301   public:
302     /// Clear all eviction information.
303     void clear() { Evictees.clear(); }
304 
305     ///  Clear eviction information for the given evictee Vreg.
306     /// E.g. when Vreg get's a new allocation, the old eviction info is no
307     /// longer relevant.
308     /// \param Evictee The evictee Vreg for whom we want to clear collected
309     /// eviction info.
310     void clearEvicteeInfo(unsigned Evictee) { Evictees.erase(Evictee); }
311 
312     /// Track new eviction.
313     /// The Evictor vreg has evicted the Evictee vreg from Physreg.
314     /// \param PhysReg The physical register Evictee was evicted from.
315     /// \param Evictor The evictor Vreg that evicted Evictee.
316     /// \param Evictee The evictee Vreg.
317     void addEviction(unsigned PhysReg, unsigned Evictor, unsigned Evictee) {
318       Evictees[Evictee].first = Evictor;
319       Evictees[Evictee].second = PhysReg;
320     }
321 
322     /// Return the Evictor Vreg which evicted Evictee Vreg from PhysReg.
323     /// \param Evictee The evictee vreg.
324     /// \return The Evictor vreg which evicted Evictee vreg from PhysReg. 0 if
325     /// nobody has evicted Evictee from PhysReg.
326     EvictorInfo getEvictor(unsigned Evictee) {
327       if (Evictees.count(Evictee)) {
328         return Evictees[Evictee];
329       }
330 
331       return EvictorInfo(0, 0);
332     }
333   };
334 
335   // Keeps track of past evictions in order to optimize region split decision.
336   EvictionTrack LastEvicted;
337 
338   // splitting state.
339   std::unique_ptr<SplitAnalysis> SA;
340   std::unique_ptr<SplitEditor> SE;
341 
342   /// Cached per-block interference maps
343   InterferenceCache IntfCache;
344 
345   /// All basic blocks where the current register has uses.
346   SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
347 
348   /// Global live range splitting candidate info.
349   struct GlobalSplitCandidate {
350     // Register intended for assignment, or 0.
351     unsigned PhysReg;
352 
353     // SplitKit interval index for this candidate.
354     unsigned IntvIdx;
355 
356     // Interference for PhysReg.
357     InterferenceCache::Cursor Intf;
358 
359     // Bundles where this candidate should be live.
360     BitVector LiveBundles;
361     SmallVector<unsigned, 8> ActiveBlocks;
362 
363     void reset(InterferenceCache &Cache, unsigned Reg) {
364       PhysReg = Reg;
365       IntvIdx = 0;
366       Intf.setPhysReg(Cache, Reg);
367       LiveBundles.clear();
368       ActiveBlocks.clear();
369     }
370 
371     // Set B[i] = C for every live bundle where B[i] was NoCand.
372     unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
373       unsigned Count = 0;
374       for (unsigned i : LiveBundles.set_bits())
375         if (B[i] == NoCand) {
376           B[i] = C;
377           Count++;
378         }
379       return Count;
380     }
381   };
382 
383   /// Candidate info for each PhysReg in AllocationOrder.
384   /// This vector never shrinks, but grows to the size of the largest register
385   /// class.
386   SmallVector<GlobalSplitCandidate, 32> GlobalCand;
387 
388   enum : unsigned { NoCand = ~0u };
389 
390   /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
391   /// NoCand which indicates the stack interval.
392   SmallVector<unsigned, 32> BundleCand;
393 
394   /// Callee-save register cost, calculated once per machine function.
395   BlockFrequency CSRCost;
396 
397   /// Run or not the local reassignment heuristic. This information is
398   /// obtained from the TargetSubtargetInfo.
399   bool EnableLocalReassign;
400 
401   /// Enable or not the consideration of the cost of local intervals created
402   /// by a split candidate when choosing the best split candidate.
403   bool EnableAdvancedRASplitCost;
404 
405   /// Set of broken hints that may be reconciled later because of eviction.
406   SmallSetVector<LiveInterval *, 8> SetOfBrokenHints;
407 
408 public:
409   RAGreedy();
410 
411   /// Return the pass name.
412   StringRef getPassName() const override { return "Greedy Register Allocator"; }
413 
414   /// RAGreedy analysis usage.
415   void getAnalysisUsage(AnalysisUsage &AU) const override;
416   void releaseMemory() override;
417   Spiller &spiller() override { return *SpillerInstance; }
418   void enqueue(LiveInterval *LI) override;
419   LiveInterval *dequeue() override;
420   Register selectOrSplit(LiveInterval&, SmallVectorImpl<Register>&) override;
421   void aboutToRemoveInterval(LiveInterval &) override;
422 
423   /// Perform register allocation.
424   bool runOnMachineFunction(MachineFunction &mf) override;
425 
426   MachineFunctionProperties getRequiredProperties() const override {
427     return MachineFunctionProperties().set(
428         MachineFunctionProperties::Property::NoPHIs);
429   }
430 
431   static char ID;
432 
433 private:
434   Register selectOrSplitImpl(LiveInterval &, SmallVectorImpl<Register> &,
435                              SmallVirtRegSet &, unsigned = 0);
436 
437   bool LRE_CanEraseVirtReg(unsigned) override;
438   void LRE_WillShrinkVirtReg(unsigned) override;
439   void LRE_DidCloneVirtReg(unsigned, unsigned) override;
440   void enqueue(PQueue &CurQueue, LiveInterval *LI);
441   LiveInterval *dequeue(PQueue &CurQueue);
442 
443   BlockFrequency calcSpillCost();
444   bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
445   bool addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
446   bool growRegion(GlobalSplitCandidate &Cand);
447   bool splitCanCauseEvictionChain(unsigned Evictee, GlobalSplitCandidate &Cand,
448                                   unsigned BBNumber,
449                                   const AllocationOrder &Order);
450   bool splitCanCauseLocalSpill(unsigned VirtRegToSplit,
451                                GlobalSplitCandidate &Cand, unsigned BBNumber,
452                                const AllocationOrder &Order);
453   BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate &,
454                                      const AllocationOrder &Order,
455                                      bool *CanCauseEvictionChain);
456   bool calcCompactRegion(GlobalSplitCandidate&);
457   void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
458   void calcGapWeights(unsigned, SmallVectorImpl<float>&);
459   Register canReassign(LiveInterval &VirtReg, Register PrevReg);
460   bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
461   bool canEvictInterference(LiveInterval&, Register, bool, EvictionCost&,
462                             const SmallVirtRegSet&);
463   bool canEvictInterferenceInRange(LiveInterval &VirtReg, Register oPhysReg,
464                                    SlotIndex Start, SlotIndex End,
465                                    EvictionCost &MaxCost);
466   unsigned getCheapestEvicteeWeight(const AllocationOrder &Order,
467                                     LiveInterval &VirtReg, SlotIndex Start,
468                                     SlotIndex End, float *BestEvictWeight);
469   void evictInterference(LiveInterval&, Register,
470                          SmallVectorImpl<Register>&);
471   bool mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
472                                   SmallLISet &RecoloringCandidates,
473                                   const SmallVirtRegSet &FixedRegisters);
474 
475   Register tryAssign(LiveInterval&, AllocationOrder&,
476                      SmallVectorImpl<Register>&,
477                      const SmallVirtRegSet&);
478   unsigned tryEvict(LiveInterval&, AllocationOrder&,
479                     SmallVectorImpl<Register>&, unsigned,
480                     const SmallVirtRegSet&);
481   unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
482                           SmallVectorImpl<Register>&);
483   /// Calculate cost of region splitting.
484   unsigned calculateRegionSplitCost(LiveInterval &VirtReg,
485                                     AllocationOrder &Order,
486                                     BlockFrequency &BestCost,
487                                     unsigned &NumCands, bool IgnoreCSR,
488                                     bool *CanCauseEvictionChain = nullptr);
489   /// Perform region splitting.
490   unsigned doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
491                          bool HasCompact,
492                          SmallVectorImpl<Register> &NewVRegs);
493   /// Check other options before using a callee-saved register for the first
494   /// time.
495   unsigned tryAssignCSRFirstTime(LiveInterval &VirtReg, AllocationOrder &Order,
496                                  Register PhysReg, unsigned &CostPerUseLimit,
497                                  SmallVectorImpl<Register> &NewVRegs);
498   void initializeCSRCost();
499   unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
500                          SmallVectorImpl<Register>&);
501   unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
502                                SmallVectorImpl<Register>&);
503   unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
504     SmallVectorImpl<Register>&);
505   unsigned trySplit(LiveInterval&, AllocationOrder&,
506                     SmallVectorImpl<Register>&,
507                     const SmallVirtRegSet&);
508   unsigned tryLastChanceRecoloring(LiveInterval &, AllocationOrder &,
509                                    SmallVectorImpl<Register> &,
510                                    SmallVirtRegSet &, unsigned);
511   bool tryRecoloringCandidates(PQueue &, SmallVectorImpl<Register> &,
512                                SmallVirtRegSet &, unsigned);
513   void tryHintRecoloring(LiveInterval &);
514   void tryHintsRecoloring();
515 
516   /// Model the information carried by one end of a copy.
517   struct HintInfo {
518     /// The frequency of the copy.
519     BlockFrequency Freq;
520     /// The virtual register or physical register.
521     Register Reg;
522     /// Its currently assigned register.
523     /// In case of a physical register Reg == PhysReg.
524     MCRegister PhysReg;
525 
526     HintInfo(BlockFrequency Freq, Register Reg, MCRegister PhysReg)
527         : Freq(Freq), Reg(Reg), PhysReg(PhysReg) {}
528   };
529   using HintsInfo = SmallVector<HintInfo, 4>;
530 
531   BlockFrequency getBrokenHintFreq(const HintsInfo &, unsigned);
532   void collectHintInfo(unsigned, HintsInfo &);
533 
534   bool isUnusedCalleeSavedReg(MCRegister PhysReg) const;
535 
536   /// Compute and report the number of spills and reloads for a loop.
537   void reportNumberOfSplillsReloads(MachineLoop *L, unsigned &Reloads,
538                                     unsigned &FoldedReloads, unsigned &Spills,
539                                     unsigned &FoldedSpills);
540 
541   /// Report the number of spills and reloads for each loop.
542   void reportNumberOfSplillsReloads() {
543     for (MachineLoop *L : *Loops) {
544       unsigned Reloads, FoldedReloads, Spills, FoldedSpills;
545       reportNumberOfSplillsReloads(L, Reloads, FoldedReloads, Spills,
546                                    FoldedSpills);
547     }
548   }
549 };
550 
551 } // end anonymous namespace
552 
553 char RAGreedy::ID = 0;
554 char &llvm::RAGreedyID = RAGreedy::ID;
555 
556 INITIALIZE_PASS_BEGIN(RAGreedy, "greedy",
557                 "Greedy Register Allocator", false, false)
558 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
559 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
560 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
561 INITIALIZE_PASS_DEPENDENCY(RegisterCoalescer)
562 INITIALIZE_PASS_DEPENDENCY(MachineScheduler)
563 INITIALIZE_PASS_DEPENDENCY(LiveStacks)
564 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
565 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
566 INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
567 INITIALIZE_PASS_DEPENDENCY(LiveRegMatrix)
568 INITIALIZE_PASS_DEPENDENCY(EdgeBundles)
569 INITIALIZE_PASS_DEPENDENCY(SpillPlacement)
570 INITIALIZE_PASS_DEPENDENCY(MachineOptimizationRemarkEmitterPass)
571 INITIALIZE_PASS_END(RAGreedy, "greedy",
572                 "Greedy Register Allocator", false, false)
573 
574 #ifndef NDEBUG
575 const char *const RAGreedy::StageName[] = {
576     "RS_New",
577     "RS_Assign",
578     "RS_Split",
579     "RS_Split2",
580     "RS_Spill",
581     "RS_Memory",
582     "RS_Done"
583 };
584 #endif
585 
586 // Hysteresis to use when comparing floats.
587 // This helps stabilize decisions based on float comparisons.
588 const float Hysteresis = (2007 / 2048.0f); // 0.97998046875
589 
590 FunctionPass* llvm::createGreedyRegisterAllocator() {
591   return new RAGreedy();
592 }
593 
594 RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
595 }
596 
597 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
598   AU.setPreservesCFG();
599   AU.addRequired<MachineBlockFrequencyInfo>();
600   AU.addPreserved<MachineBlockFrequencyInfo>();
601   AU.addRequired<AAResultsWrapperPass>();
602   AU.addPreserved<AAResultsWrapperPass>();
603   AU.addRequired<LiveIntervals>();
604   AU.addPreserved<LiveIntervals>();
605   AU.addRequired<SlotIndexes>();
606   AU.addPreserved<SlotIndexes>();
607   AU.addRequired<LiveDebugVariables>();
608   AU.addPreserved<LiveDebugVariables>();
609   AU.addRequired<LiveStacks>();
610   AU.addPreserved<LiveStacks>();
611   AU.addRequired<MachineDominatorTree>();
612   AU.addPreserved<MachineDominatorTree>();
613   AU.addRequired<MachineLoopInfo>();
614   AU.addPreserved<MachineLoopInfo>();
615   AU.addRequired<VirtRegMap>();
616   AU.addPreserved<VirtRegMap>();
617   AU.addRequired<LiveRegMatrix>();
618   AU.addPreserved<LiveRegMatrix>();
619   AU.addRequired<EdgeBundles>();
620   AU.addRequired<SpillPlacement>();
621   AU.addRequired<MachineOptimizationRemarkEmitterPass>();
622   MachineFunctionPass::getAnalysisUsage(AU);
623 }
624 
625 //===----------------------------------------------------------------------===//
626 //                     LiveRangeEdit delegate methods
627 //===----------------------------------------------------------------------===//
628 
629 bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
630   LiveInterval &LI = LIS->getInterval(VirtReg);
631   if (VRM->hasPhys(VirtReg)) {
632     Matrix->unassign(LI);
633     aboutToRemoveInterval(LI);
634     return true;
635   }
636   // Unassigned virtreg is probably in the priority queue.
637   // RegAllocBase will erase it after dequeueing.
638   // Nonetheless, clear the live-range so that the debug
639   // dump will show the right state for that VirtReg.
640   LI.clear();
641   return false;
642 }
643 
644 void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
645   if (!VRM->hasPhys(VirtReg))
646     return;
647 
648   // Register is assigned, put it back on the queue for reassignment.
649   LiveInterval &LI = LIS->getInterval(VirtReg);
650   Matrix->unassign(LI);
651   enqueue(&LI);
652 }
653 
654 void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
655   // Cloning a register we haven't even heard about yet?  Just ignore it.
656   if (!ExtraRegInfo.inBounds(Old))
657     return;
658 
659   // LRE may clone a virtual register because dead code elimination causes it to
660   // be split into connected components. The new components are much smaller
661   // than the original, so they should get a new chance at being assigned.
662   // same stage as the parent.
663   ExtraRegInfo[Old].Stage = RS_Assign;
664   ExtraRegInfo.grow(New);
665   ExtraRegInfo[New] = ExtraRegInfo[Old];
666 }
667 
668 void RAGreedy::releaseMemory() {
669   SpillerInstance.reset();
670   ExtraRegInfo.clear();
671   GlobalCand.clear();
672 }
673 
674 void RAGreedy::enqueue(LiveInterval *LI) { enqueue(Queue, LI); }
675 
676 void RAGreedy::enqueue(PQueue &CurQueue, LiveInterval *LI) {
677   // Prioritize live ranges by size, assigning larger ranges first.
678   // The queue holds (size, reg) pairs.
679   const unsigned Size = LI->getSize();
680   const unsigned Reg = LI->reg();
681   assert(Register::isVirtualRegister(Reg) &&
682          "Can only enqueue virtual registers");
683   unsigned Prio;
684 
685   ExtraRegInfo.grow(Reg);
686   if (ExtraRegInfo[Reg].Stage == RS_New)
687     ExtraRegInfo[Reg].Stage = RS_Assign;
688 
689   if (ExtraRegInfo[Reg].Stage == RS_Split) {
690     // Unsplit ranges that couldn't be allocated immediately are deferred until
691     // everything else has been allocated.
692     Prio = Size;
693   } else if (ExtraRegInfo[Reg].Stage == RS_Memory) {
694     // Memory operand should be considered last.
695     // Change the priority such that Memory operand are assigned in
696     // the reverse order that they came in.
697     // TODO: Make this a member variable and probably do something about hints.
698     static unsigned MemOp = 0;
699     Prio = MemOp++;
700   } else {
701     // Giant live ranges fall back to the global assignment heuristic, which
702     // prevents excessive spilling in pathological cases.
703     bool ReverseLocal = TRI->reverseLocalAssignment();
704     const TargetRegisterClass &RC = *MRI->getRegClass(Reg);
705     bool ForceGlobal = !ReverseLocal &&
706       (Size / SlotIndex::InstrDist) > (2 * RC.getNumRegs());
707 
708     if (ExtraRegInfo[Reg].Stage == RS_Assign && !ForceGlobal && !LI->empty() &&
709         LIS->intervalIsInOneMBB(*LI)) {
710       // Allocate original local ranges in linear instruction order. Since they
711       // are singly defined, this produces optimal coloring in the absence of
712       // global interference and other constraints.
713       if (!ReverseLocal)
714         Prio = LI->beginIndex().getInstrDistance(Indexes->getLastIndex());
715       else {
716         // Allocating bottom up may allow many short LRGs to be assigned first
717         // to one of the cheap registers. This could be much faster for very
718         // large blocks on targets with many physical registers.
719         Prio = Indexes->getZeroIndex().getInstrDistance(LI->endIndex());
720       }
721       Prio |= RC.AllocationPriority << 24;
722     } else {
723       // Allocate global and split ranges in long->short order. Long ranges that
724       // don't fit should be spilled (or split) ASAP so they don't create
725       // interference.  Mark a bit to prioritize global above local ranges.
726       Prio = (1u << 29) + Size;
727     }
728     // Mark a higher bit to prioritize global and local above RS_Split.
729     Prio |= (1u << 31);
730 
731     // Boost ranges that have a physical register hint.
732     if (VRM->hasKnownPreference(Reg))
733       Prio |= (1u << 30);
734   }
735   // The virtual register number is a tie breaker for same-sized ranges.
736   // Give lower vreg numbers higher priority to assign them first.
737   CurQueue.push(std::make_pair(Prio, ~Reg));
738 }
739 
740 LiveInterval *RAGreedy::dequeue() { return dequeue(Queue); }
741 
742 LiveInterval *RAGreedy::dequeue(PQueue &CurQueue) {
743   if (CurQueue.empty())
744     return nullptr;
745   LiveInterval *LI = &LIS->getInterval(~CurQueue.top().second);
746   CurQueue.pop();
747   return LI;
748 }
749 
750 //===----------------------------------------------------------------------===//
751 //                            Direct Assignment
752 //===----------------------------------------------------------------------===//
753 
754 /// tryAssign - Try to assign VirtReg to an available register.
755 Register RAGreedy::tryAssign(LiveInterval &VirtReg,
756                              AllocationOrder &Order,
757                              SmallVectorImpl<Register> &NewVRegs,
758                              const SmallVirtRegSet &FixedRegisters) {
759   Order.rewind();
760   Register PhysReg;
761   while ((PhysReg = Order.next()))
762     if (!Matrix->checkInterference(VirtReg, PhysReg))
763       break;
764   if (!PhysReg || Order.isHint())
765     return PhysReg;
766 
767   // PhysReg is available, but there may be a better choice.
768 
769   // If we missed a simple hint, try to cheaply evict interference from the
770   // preferred register.
771   if (Register Hint = MRI->getSimpleHint(VirtReg.reg()))
772     if (Order.isHint(Hint)) {
773       LLVM_DEBUG(dbgs() << "missed hint " << printReg(Hint, TRI) << '\n');
774       EvictionCost MaxCost;
775       MaxCost.setBrokenHints(1);
776       if (canEvictInterference(VirtReg, Hint, true, MaxCost, FixedRegisters)) {
777         evictInterference(VirtReg, Hint, NewVRegs);
778         return Hint;
779       }
780       // Record the missed hint, we may be able to recover
781       // at the end if the surrounding allocation changed.
782       SetOfBrokenHints.insert(&VirtReg);
783     }
784 
785   // Try to evict interference from a cheaper alternative.
786   unsigned Cost = TRI->getCostPerUse(PhysReg);
787 
788   // Most registers have 0 additional cost.
789   if (!Cost)
790     return PhysReg;
791 
792   LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << " is available at cost "
793                     << Cost << '\n');
794   Register CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost, FixedRegisters);
795   return CheapReg ? CheapReg : PhysReg;
796 }
797 
798 //===----------------------------------------------------------------------===//
799 //                         Interference eviction
800 //===----------------------------------------------------------------------===//
801 
802 Register RAGreedy::canReassign(LiveInterval &VirtReg, Register PrevReg) {
803   AllocationOrder Order(VirtReg.reg(), *VRM, RegClassInfo, Matrix);
804   Register PhysReg;
805   while ((PhysReg = Order.next())) {
806     if (PhysReg == PrevReg)
807       continue;
808 
809     MCRegUnitIterator Units(PhysReg, TRI);
810     for (; Units.isValid(); ++Units) {
811       // Instantiate a "subquery", not to be confused with the Queries array.
812       LiveIntervalUnion::Query subQ(VirtReg, Matrix->getLiveUnions()[*Units]);
813       if (subQ.checkInterference())
814         break;
815     }
816     // If no units have interference, break out with the current PhysReg.
817     if (!Units.isValid())
818       break;
819   }
820   if (PhysReg)
821     LLVM_DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
822                       << printReg(PrevReg, TRI) << " to "
823                       << printReg(PhysReg, TRI) << '\n');
824   return PhysReg;
825 }
826 
827 /// shouldEvict - determine if A should evict the assigned live range B. The
828 /// eviction policy defined by this function together with the allocation order
829 /// defined by enqueue() decides which registers ultimately end up being split
830 /// and spilled.
831 ///
832 /// Cascade numbers are used to prevent infinite loops if this function is a
833 /// cyclic relation.
834 ///
835 /// @param A          The live range to be assigned.
836 /// @param IsHint     True when A is about to be assigned to its preferred
837 ///                   register.
838 /// @param B          The live range to be evicted.
839 /// @param BreaksHint True when B is already assigned to its preferred register.
840 bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
841                            LiveInterval &B, bool BreaksHint) {
842   bool CanSplit = getStage(B) < RS_Spill;
843 
844   // Be fairly aggressive about following hints as long as the evictee can be
845   // split.
846   if (CanSplit && IsHint && !BreaksHint)
847     return true;
848 
849   if (A.weight() > B.weight()) {
850     LLVM_DEBUG(dbgs() << "should evict: " << B << " w= " << B.weight() << '\n');
851     return true;
852   }
853   return false;
854 }
855 
856 /// canEvictInterference - Return true if all interferences between VirtReg and
857 /// PhysReg can be evicted.
858 ///
859 /// @param VirtReg Live range that is about to be assigned.
860 /// @param PhysReg Desired register for assignment.
861 /// @param IsHint  True when PhysReg is VirtReg's preferred register.
862 /// @param MaxCost Only look for cheaper candidates and update with new cost
863 ///                when returning true.
864 /// @returns True when interference can be evicted cheaper than MaxCost.
865 bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, Register PhysReg,
866                                     bool IsHint, EvictionCost &MaxCost,
867                                     const SmallVirtRegSet &FixedRegisters) {
868   // It is only possible to evict virtual register interference.
869   if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
870     return false;
871 
872   bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
873 
874   // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
875   // involved in an eviction before. If a cascade number was assigned, deny
876   // evicting anything with the same or a newer cascade number. This prevents
877   // infinite eviction loops.
878   //
879   // This works out so a register without a cascade number is allowed to evict
880   // anything, and it can be evicted by anything.
881   unsigned Cascade = ExtraRegInfo[VirtReg.reg()].Cascade;
882   if (!Cascade)
883     Cascade = NextCascade;
884 
885   EvictionCost Cost;
886   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
887     LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
888     // If there is 10 or more interferences, chances are one is heavier.
889     if (Q.collectInterferingVRegs(10) >= 10)
890       return false;
891 
892     // Check if any interfering live range is heavier than MaxWeight.
893     for (LiveInterval *Intf : reverse(Q.interferingVRegs())) {
894       assert(Register::isVirtualRegister(Intf->reg()) &&
895              "Only expecting virtual register interference from query");
896 
897       // Do not allow eviction of a virtual register if we are in the middle
898       // of last-chance recoloring and this virtual register is one that we
899       // have scavenged a physical register for.
900       if (FixedRegisters.count(Intf->reg()))
901         return false;
902 
903       // Never evict spill products. They cannot split or spill.
904       if (getStage(*Intf) == RS_Done)
905         return false;
906       // Once a live range becomes small enough, it is urgent that we find a
907       // register for it. This is indicated by an infinite spill weight. These
908       // urgent live ranges get to evict almost anything.
909       //
910       // Also allow urgent evictions of unspillable ranges from a strictly
911       // larger allocation order.
912       bool Urgent =
913           !VirtReg.isSpillable() &&
914           (Intf->isSpillable() ||
915            RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg())) <
916                RegClassInfo.getNumAllocatableRegs(
917                    MRI->getRegClass(Intf->reg())));
918       // Only evict older cascades or live ranges without a cascade.
919       unsigned IntfCascade = ExtraRegInfo[Intf->reg()].Cascade;
920       if (Cascade <= IntfCascade) {
921         if (!Urgent)
922           return false;
923         // We permit breaking cascades for urgent evictions. It should be the
924         // last resort, though, so make it really expensive.
925         Cost.BrokenHints += 10;
926       }
927       // Would this break a satisfied hint?
928       bool BreaksHint = VRM->hasPreferredPhys(Intf->reg());
929       // Update eviction cost.
930       Cost.BrokenHints += BreaksHint;
931       Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight());
932       // Abort if this would be too expensive.
933       if (!(Cost < MaxCost))
934         return false;
935       if (Urgent)
936         continue;
937       // Apply the eviction policy for non-urgent evictions.
938       if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
939         return false;
940       // If !MaxCost.isMax(), then we're just looking for a cheap register.
941       // Evicting another local live range in this case could lead to suboptimal
942       // coloring.
943       if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
944           (!EnableLocalReassign || !canReassign(*Intf, PhysReg))) {
945         return false;
946       }
947     }
948   }
949   MaxCost = Cost;
950   return true;
951 }
952 
953 /// Return true if all interferences between VirtReg and PhysReg between
954 /// Start and End can be evicted.
955 ///
956 /// \param VirtReg Live range that is about to be assigned.
957 /// \param PhysReg Desired register for assignment.
958 /// \param Start   Start of range to look for interferences.
959 /// \param End     End of range to look for interferences.
960 /// \param MaxCost Only look for cheaper candidates and update with new cost
961 ///                when returning true.
962 /// \return True when interference can be evicted cheaper than MaxCost.
963 bool RAGreedy::canEvictInterferenceInRange(LiveInterval &VirtReg,
964                                            Register PhysReg, SlotIndex Start,
965                                            SlotIndex End,
966                                            EvictionCost &MaxCost) {
967   EvictionCost Cost;
968 
969   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
970     LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
971 
972     // Check if any interfering live range is heavier than MaxWeight.
973     for (const LiveInterval *Intf : reverse(Q.interferingVRegs())) {
974       // Check if interference overlast the segment in interest.
975       if (!Intf->overlaps(Start, End))
976         continue;
977 
978       // Cannot evict non virtual reg interference.
979       if (!Register::isVirtualRegister(Intf->reg()))
980         return false;
981       // Never evict spill products. They cannot split or spill.
982       if (getStage(*Intf) == RS_Done)
983         return false;
984 
985       // Would this break a satisfied hint?
986       bool BreaksHint = VRM->hasPreferredPhys(Intf->reg());
987       // Update eviction cost.
988       Cost.BrokenHints += BreaksHint;
989       Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight());
990       // Abort if this would be too expensive.
991       if (!(Cost < MaxCost))
992         return false;
993     }
994   }
995 
996   if (Cost.MaxWeight == 0)
997     return false;
998 
999   MaxCost = Cost;
1000   return true;
1001 }
1002 
1003 /// Return the physical register that will be best
1004 /// candidate for eviction by a local split interval that will be created
1005 /// between Start and End.
1006 ///
1007 /// \param Order            The allocation order
1008 /// \param VirtReg          Live range that is about to be assigned.
1009 /// \param Start            Start of range to look for interferences
1010 /// \param End              End of range to look for interferences
1011 /// \param BestEvictweight  The eviction cost of that eviction
1012 /// \return The PhysReg which is the best candidate for eviction and the
1013 /// eviction cost in BestEvictweight
1014 unsigned RAGreedy::getCheapestEvicteeWeight(const AllocationOrder &Order,
1015                                             LiveInterval &VirtReg,
1016                                             SlotIndex Start, SlotIndex End,
1017                                             float *BestEvictweight) {
1018   EvictionCost BestEvictCost;
1019   BestEvictCost.setMax();
1020   BestEvictCost.MaxWeight = VirtReg.weight();
1021   unsigned BestEvicteePhys = 0;
1022 
1023   // Go over all physical registers and find the best candidate for eviction
1024   for (auto PhysReg : Order.getOrder()) {
1025 
1026     if (!canEvictInterferenceInRange(VirtReg, PhysReg, Start, End,
1027                                      BestEvictCost))
1028       continue;
1029 
1030     // Best so far.
1031     BestEvicteePhys = PhysReg;
1032   }
1033   *BestEvictweight = BestEvictCost.MaxWeight;
1034   return BestEvicteePhys;
1035 }
1036 
1037 /// evictInterference - Evict any interferring registers that prevent VirtReg
1038 /// from being assigned to Physreg. This assumes that canEvictInterference
1039 /// returned true.
1040 void RAGreedy::evictInterference(LiveInterval &VirtReg, Register PhysReg,
1041                                  SmallVectorImpl<Register> &NewVRegs) {
1042   // Make sure that VirtReg has a cascade number, and assign that cascade
1043   // number to every evicted register. These live ranges than then only be
1044   // evicted by a newer cascade, preventing infinite loops.
1045   unsigned Cascade = ExtraRegInfo[VirtReg.reg()].Cascade;
1046   if (!Cascade)
1047     Cascade = ExtraRegInfo[VirtReg.reg()].Cascade = NextCascade++;
1048 
1049   LLVM_DEBUG(dbgs() << "evicting " << printReg(PhysReg, TRI)
1050                     << " interference: Cascade " << Cascade << '\n');
1051 
1052   // Collect all interfering virtregs first.
1053   SmallVector<LiveInterval*, 8> Intfs;
1054   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1055     LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
1056     // We usually have the interfering VRegs cached so collectInterferingVRegs()
1057     // should be fast, we may need to recalculate if when different physregs
1058     // overlap the same register unit so we had different SubRanges queried
1059     // against it.
1060     Q.collectInterferingVRegs();
1061     ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
1062     Intfs.append(IVR.begin(), IVR.end());
1063   }
1064 
1065   // Evict them second. This will invalidate the queries.
1066   for (LiveInterval *Intf : Intfs) {
1067     // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
1068     if (!VRM->hasPhys(Intf->reg()))
1069       continue;
1070 
1071     LastEvicted.addEviction(PhysReg, VirtReg.reg(), Intf->reg());
1072 
1073     Matrix->unassign(*Intf);
1074     assert((ExtraRegInfo[Intf->reg()].Cascade < Cascade ||
1075             VirtReg.isSpillable() < Intf->isSpillable()) &&
1076            "Cannot decrease cascade number, illegal eviction");
1077     ExtraRegInfo[Intf->reg()].Cascade = Cascade;
1078     ++NumEvicted;
1079     NewVRegs.push_back(Intf->reg());
1080   }
1081 }
1082 
1083 /// Returns true if the given \p PhysReg is a callee saved register and has not
1084 /// been used for allocation yet.
1085 bool RAGreedy::isUnusedCalleeSavedReg(MCRegister PhysReg) const {
1086   MCRegister CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg);
1087   if (!CSR)
1088     return false;
1089 
1090   return !Matrix->isPhysRegUsed(PhysReg);
1091 }
1092 
1093 /// tryEvict - Try to evict all interferences for a physreg.
1094 /// @param  VirtReg Currently unassigned virtual register.
1095 /// @param  Order   Physregs to try.
1096 /// @return         Physreg to assign VirtReg, or 0.
1097 unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
1098                             AllocationOrder &Order,
1099                             SmallVectorImpl<Register> &NewVRegs,
1100                             unsigned CostPerUseLimit,
1101                             const SmallVirtRegSet &FixedRegisters) {
1102   NamedRegionTimer T("evict", "Evict", TimerGroupName, TimerGroupDescription,
1103                      TimePassesIsEnabled);
1104 
1105   // Keep track of the cheapest interference seen so far.
1106   EvictionCost BestCost;
1107   BestCost.setMax();
1108   unsigned BestPhys = 0;
1109   unsigned OrderLimit = Order.getOrder().size();
1110 
1111   // When we are just looking for a reduced cost per use, don't break any
1112   // hints, and only evict smaller spill weights.
1113   if (CostPerUseLimit < ~0u) {
1114     BestCost.BrokenHints = 0;
1115     BestCost.MaxWeight = VirtReg.weight();
1116 
1117     // Check of any registers in RC are below CostPerUseLimit.
1118     const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg());
1119     unsigned MinCost = RegClassInfo.getMinCost(RC);
1120     if (MinCost >= CostPerUseLimit) {
1121       LLVM_DEBUG(dbgs() << TRI->getRegClassName(RC) << " minimum cost = "
1122                         << MinCost << ", no cheaper registers to be found.\n");
1123       return 0;
1124     }
1125 
1126     // It is normal for register classes to have a long tail of registers with
1127     // the same cost. We don't need to look at them if they're too expensive.
1128     if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
1129       OrderLimit = RegClassInfo.getLastCostChange(RC);
1130       LLVM_DEBUG(dbgs() << "Only trying the first " << OrderLimit
1131                         << " regs.\n");
1132     }
1133   }
1134 
1135   Order.rewind();
1136   while (MCRegister PhysReg = Order.next(OrderLimit)) {
1137     if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
1138       continue;
1139     // The first use of a callee-saved register in a function has cost 1.
1140     // Don't start using a CSR when the CostPerUseLimit is low.
1141     if (CostPerUseLimit == 1 && isUnusedCalleeSavedReg(PhysReg)) {
1142       LLVM_DEBUG(
1143           dbgs() << printReg(PhysReg, TRI) << " would clobber CSR "
1144                  << printReg(RegClassInfo.getLastCalleeSavedAlias(PhysReg), TRI)
1145                  << '\n');
1146       continue;
1147     }
1148 
1149     if (!canEvictInterference(VirtReg, PhysReg, false, BestCost,
1150                               FixedRegisters))
1151       continue;
1152 
1153     // Best so far.
1154     BestPhys = PhysReg;
1155 
1156     // Stop if the hint can be used.
1157     if (Order.isHint())
1158       break;
1159   }
1160 
1161   if (!BestPhys)
1162     return 0;
1163 
1164   evictInterference(VirtReg, BestPhys, NewVRegs);
1165   return BestPhys;
1166 }
1167 
1168 //===----------------------------------------------------------------------===//
1169 //                              Region Splitting
1170 //===----------------------------------------------------------------------===//
1171 
1172 /// addSplitConstraints - Fill out the SplitConstraints vector based on the
1173 /// interference pattern in Physreg and its aliases. Add the constraints to
1174 /// SpillPlacement and return the static cost of this split in Cost, assuming
1175 /// that all preferences in SplitConstraints are met.
1176 /// Return false if there are no bundles with positive bias.
1177 bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
1178                                    BlockFrequency &Cost) {
1179   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1180 
1181   // Reset interference dependent info.
1182   SplitConstraints.resize(UseBlocks.size());
1183   BlockFrequency StaticCost = 0;
1184   for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1185     const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1186     SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
1187 
1188     BC.Number = BI.MBB->getNumber();
1189     Intf.moveToBlock(BC.Number);
1190     BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
1191     BC.Exit = (BI.LiveOut &&
1192                !LIS->getInstructionFromIndex(BI.LastInstr)->isImplicitDef())
1193                   ? SpillPlacement::PrefReg
1194                   : SpillPlacement::DontCare;
1195     BC.ChangesValue = BI.FirstDef.isValid();
1196 
1197     if (!Intf.hasInterference())
1198       continue;
1199 
1200     // Number of spill code instructions to insert.
1201     unsigned Ins = 0;
1202 
1203     // Interference for the live-in value.
1204     if (BI.LiveIn) {
1205       if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number)) {
1206         BC.Entry = SpillPlacement::MustSpill;
1207         ++Ins;
1208       } else if (Intf.first() < BI.FirstInstr) {
1209         BC.Entry = SpillPlacement::PrefSpill;
1210         ++Ins;
1211       } else if (Intf.first() < BI.LastInstr) {
1212         ++Ins;
1213       }
1214 
1215       // Abort if the spill cannot be inserted at the MBB' start
1216       if (((BC.Entry == SpillPlacement::MustSpill) ||
1217            (BC.Entry == SpillPlacement::PrefSpill)) &&
1218           SlotIndex::isEarlierInstr(BI.FirstInstr,
1219                                     SA->getFirstSplitPoint(BC.Number)))
1220         return false;
1221     }
1222 
1223     // Interference for the live-out value.
1224     if (BI.LiveOut) {
1225       if (Intf.last() >= SA->getLastSplitPoint(BC.Number)) {
1226         BC.Exit = SpillPlacement::MustSpill;
1227         ++Ins;
1228       } else if (Intf.last() > BI.LastInstr) {
1229         BC.Exit = SpillPlacement::PrefSpill;
1230         ++Ins;
1231       } else if (Intf.last() > BI.FirstInstr) {
1232         ++Ins;
1233       }
1234     }
1235 
1236     // Accumulate the total frequency of inserted spill code.
1237     while (Ins--)
1238       StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
1239   }
1240   Cost = StaticCost;
1241 
1242   // Add constraints for use-blocks. Note that these are the only constraints
1243   // that may add a positive bias, it is downhill from here.
1244   SpillPlacer->addConstraints(SplitConstraints);
1245   return SpillPlacer->scanActiveBundles();
1246 }
1247 
1248 /// addThroughConstraints - Add constraints and links to SpillPlacer from the
1249 /// live-through blocks in Blocks.
1250 bool RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
1251                                      ArrayRef<unsigned> Blocks) {
1252   const unsigned GroupSize = 8;
1253   SpillPlacement::BlockConstraint BCS[GroupSize];
1254   unsigned TBS[GroupSize];
1255   unsigned B = 0, T = 0;
1256 
1257   for (unsigned i = 0; i != Blocks.size(); ++i) {
1258     unsigned Number = Blocks[i];
1259     Intf.moveToBlock(Number);
1260 
1261     if (!Intf.hasInterference()) {
1262       assert(T < GroupSize && "Array overflow");
1263       TBS[T] = Number;
1264       if (++T == GroupSize) {
1265         SpillPlacer->addLinks(makeArrayRef(TBS, T));
1266         T = 0;
1267       }
1268       continue;
1269     }
1270 
1271     assert(B < GroupSize && "Array overflow");
1272     BCS[B].Number = Number;
1273 
1274     // Abort if the spill cannot be inserted at the MBB' start
1275     MachineBasicBlock *MBB = MF->getBlockNumbered(Number);
1276     if (!MBB->empty() &&
1277         SlotIndex::isEarlierInstr(LIS->getInstructionIndex(MBB->instr_front()),
1278                                   SA->getFirstSplitPoint(Number)))
1279       return false;
1280     // Interference for the live-in value.
1281     if (Intf.first() <= Indexes->getMBBStartIdx(Number))
1282       BCS[B].Entry = SpillPlacement::MustSpill;
1283     else
1284       BCS[B].Entry = SpillPlacement::PrefSpill;
1285 
1286     // Interference for the live-out value.
1287     if (Intf.last() >= SA->getLastSplitPoint(Number))
1288       BCS[B].Exit = SpillPlacement::MustSpill;
1289     else
1290       BCS[B].Exit = SpillPlacement::PrefSpill;
1291 
1292     if (++B == GroupSize) {
1293       SpillPlacer->addConstraints(makeArrayRef(BCS, B));
1294       B = 0;
1295     }
1296   }
1297 
1298   SpillPlacer->addConstraints(makeArrayRef(BCS, B));
1299   SpillPlacer->addLinks(makeArrayRef(TBS, T));
1300   return true;
1301 }
1302 
1303 bool RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
1304   // Keep track of through blocks that have not been added to SpillPlacer.
1305   BitVector Todo = SA->getThroughBlocks();
1306   SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
1307   unsigned AddedTo = 0;
1308 #ifndef NDEBUG
1309   unsigned Visited = 0;
1310 #endif
1311 
1312   while (true) {
1313     ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
1314     // Find new through blocks in the periphery of PrefRegBundles.
1315     for (int i = 0, e = NewBundles.size(); i != e; ++i) {
1316       unsigned Bundle = NewBundles[i];
1317       // Look at all blocks connected to Bundle in the full graph.
1318       ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
1319       for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
1320            I != E; ++I) {
1321         unsigned Block = *I;
1322         if (!Todo.test(Block))
1323           continue;
1324         Todo.reset(Block);
1325         // This is a new through block. Add it to SpillPlacer later.
1326         ActiveBlocks.push_back(Block);
1327 #ifndef NDEBUG
1328         ++Visited;
1329 #endif
1330       }
1331     }
1332     // Any new blocks to add?
1333     if (ActiveBlocks.size() == AddedTo)
1334       break;
1335 
1336     // Compute through constraints from the interference, or assume that all
1337     // through blocks prefer spilling when forming compact regions.
1338     auto NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
1339     if (Cand.PhysReg) {
1340       if (!addThroughConstraints(Cand.Intf, NewBlocks))
1341         return false;
1342     } else
1343       // Provide a strong negative bias on through blocks to prevent unwanted
1344       // liveness on loop backedges.
1345       SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
1346     AddedTo = ActiveBlocks.size();
1347 
1348     // Perhaps iterating can enable more bundles?
1349     SpillPlacer->iterate();
1350   }
1351   LLVM_DEBUG(dbgs() << ", v=" << Visited);
1352   return true;
1353 }
1354 
1355 /// calcCompactRegion - Compute the set of edge bundles that should be live
1356 /// when splitting the current live range into compact regions.  Compact
1357 /// regions can be computed without looking at interference.  They are the
1358 /// regions formed by removing all the live-through blocks from the live range.
1359 ///
1360 /// Returns false if the current live range is already compact, or if the
1361 /// compact regions would form single block regions anyway.
1362 bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
1363   // Without any through blocks, the live range is already compact.
1364   if (!SA->getNumThroughBlocks())
1365     return false;
1366 
1367   // Compact regions don't correspond to any physreg.
1368   Cand.reset(IntfCache, 0);
1369 
1370   LLVM_DEBUG(dbgs() << "Compact region bundles");
1371 
1372   // Use the spill placer to determine the live bundles. GrowRegion pretends
1373   // that all the through blocks have interference when PhysReg is unset.
1374   SpillPlacer->prepare(Cand.LiveBundles);
1375 
1376   // The static split cost will be zero since Cand.Intf reports no interference.
1377   BlockFrequency Cost;
1378   if (!addSplitConstraints(Cand.Intf, Cost)) {
1379     LLVM_DEBUG(dbgs() << ", none.\n");
1380     return false;
1381   }
1382 
1383   if (!growRegion(Cand)) {
1384     LLVM_DEBUG(dbgs() << ", cannot spill all interferences.\n");
1385     return false;
1386   }
1387 
1388   SpillPlacer->finish();
1389 
1390   if (!Cand.LiveBundles.any()) {
1391     LLVM_DEBUG(dbgs() << ", none.\n");
1392     return false;
1393   }
1394 
1395   LLVM_DEBUG({
1396     for (int i : Cand.LiveBundles.set_bits())
1397       dbgs() << " EB#" << i;
1398     dbgs() << ".\n";
1399   });
1400   return true;
1401 }
1402 
1403 /// calcSpillCost - Compute how expensive it would be to split the live range in
1404 /// SA around all use blocks instead of forming bundle regions.
1405 BlockFrequency RAGreedy::calcSpillCost() {
1406   BlockFrequency Cost = 0;
1407   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1408   for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1409     const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1410     unsigned Number = BI.MBB->getNumber();
1411     // We normally only need one spill instruction - a load or a store.
1412     Cost += SpillPlacer->getBlockFrequency(Number);
1413 
1414     // Unless the value is redefined in the block.
1415     if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
1416       Cost += SpillPlacer->getBlockFrequency(Number);
1417   }
1418   return Cost;
1419 }
1420 
1421 /// Check if splitting Evictee will create a local split interval in
1422 /// basic block number BBNumber that may cause a bad eviction chain. This is
1423 /// intended to prevent bad eviction sequences like:
1424 /// movl	%ebp, 8(%esp)           # 4-byte Spill
1425 /// movl	%ecx, %ebp
1426 /// movl	%ebx, %ecx
1427 /// movl	%edi, %ebx
1428 /// movl	%edx, %edi
1429 /// cltd
1430 /// idivl	%esi
1431 /// movl	%edi, %edx
1432 /// movl	%ebx, %edi
1433 /// movl	%ecx, %ebx
1434 /// movl	%ebp, %ecx
1435 /// movl	16(%esp), %ebp          # 4 - byte Reload
1436 ///
1437 /// Such sequences are created in 2 scenarios:
1438 ///
1439 /// Scenario #1:
1440 /// %0 is evicted from physreg0 by %1.
1441 /// Evictee %0 is intended for region splitting with split candidate
1442 /// physreg0 (the reg %0 was evicted from).
1443 /// Region splitting creates a local interval because of interference with the
1444 /// evictor %1 (normally region splitting creates 2 interval, the "by reg"
1445 /// and "by stack" intervals and local interval created when interference
1446 /// occurs).
1447 /// One of the split intervals ends up evicting %2 from physreg1.
1448 /// Evictee %2 is intended for region splitting with split candidate
1449 /// physreg1.
1450 /// One of the split intervals ends up evicting %3 from physreg2, etc.
1451 ///
1452 /// Scenario #2
1453 /// %0 is evicted from physreg0 by %1.
1454 /// %2 is evicted from physreg2 by %3 etc.
1455 /// Evictee %0 is intended for region splitting with split candidate
1456 /// physreg1.
1457 /// Region splitting creates a local interval because of interference with the
1458 /// evictor %1.
1459 /// One of the split intervals ends up evicting back original evictor %1
1460 /// from physreg0 (the reg %0 was evicted from).
1461 /// Another evictee %2 is intended for region splitting with split candidate
1462 /// physreg1.
1463 /// One of the split intervals ends up evicting %3 from physreg2, etc.
1464 ///
1465 /// \param Evictee  The register considered to be split.
1466 /// \param Cand     The split candidate that determines the physical register
1467 ///                 we are splitting for and the interferences.
1468 /// \param BBNumber The number of a BB for which the region split process will
1469 ///                 create a local split interval.
1470 /// \param Order    The physical registers that may get evicted by a split
1471 ///                 artifact of Evictee.
1472 /// \return True if splitting Evictee may cause a bad eviction chain, false
1473 /// otherwise.
1474 bool RAGreedy::splitCanCauseEvictionChain(unsigned Evictee,
1475                                           GlobalSplitCandidate &Cand,
1476                                           unsigned BBNumber,
1477                                           const AllocationOrder &Order) {
1478   EvictionTrack::EvictorInfo VregEvictorInfo = LastEvicted.getEvictor(Evictee);
1479   unsigned Evictor = VregEvictorInfo.first;
1480   unsigned PhysReg = VregEvictorInfo.second;
1481 
1482   // No actual evictor.
1483   if (!Evictor || !PhysReg)
1484     return false;
1485 
1486   float MaxWeight = 0;
1487   unsigned FutureEvictedPhysReg =
1488       getCheapestEvicteeWeight(Order, LIS->getInterval(Evictee),
1489                                Cand.Intf.first(), Cand.Intf.last(), &MaxWeight);
1490 
1491   // The bad eviction chain occurs when either the split candidate is the
1492   // evicting reg or one of the split artifact will evict the evicting reg.
1493   if ((PhysReg != Cand.PhysReg) && (PhysReg != FutureEvictedPhysReg))
1494     return false;
1495 
1496   Cand.Intf.moveToBlock(BBNumber);
1497 
1498   // Check to see if the Evictor contains interference (with Evictee) in the
1499   // given BB. If so, this interference caused the eviction of Evictee from
1500   // PhysReg. This suggest that we will create a local interval during the
1501   // region split to avoid this interference This local interval may cause a bad
1502   // eviction chain.
1503   if (!LIS->hasInterval(Evictor))
1504     return false;
1505   LiveInterval &EvictorLI = LIS->getInterval(Evictor);
1506   if (EvictorLI.FindSegmentContaining(Cand.Intf.first()) == EvictorLI.end())
1507     return false;
1508 
1509   // Now, check to see if the local interval we will create is going to be
1510   // expensive enough to evict somebody If so, this may cause a bad eviction
1511   // chain.
1512   VirtRegAuxInfo VRAI(*MF, *LIS, VRM, getAnalysis<MachineLoopInfo>(), *MBFI);
1513   float splitArtifactWeight =
1514       VRAI.futureWeight(LIS->getInterval(Evictee),
1515                         Cand.Intf.first().getPrevIndex(), Cand.Intf.last());
1516   if (splitArtifactWeight >= 0 && splitArtifactWeight < MaxWeight)
1517     return false;
1518 
1519   return true;
1520 }
1521 
1522 /// Check if splitting VirtRegToSplit will create a local split interval
1523 /// in basic block number BBNumber that may cause a spill.
1524 ///
1525 /// \param VirtRegToSplit The register considered to be split.
1526 /// \param Cand           The split candidate that determines the physical
1527 ///                       register we are splitting for and the interferences.
1528 /// \param BBNumber       The number of a BB for which the region split process
1529 ///                       will create a local split interval.
1530 /// \param Order          The physical registers that may get evicted by a
1531 ///                       split artifact of VirtRegToSplit.
1532 /// \return True if splitting VirtRegToSplit may cause a spill, false
1533 /// otherwise.
1534 bool RAGreedy::splitCanCauseLocalSpill(unsigned VirtRegToSplit,
1535                                        GlobalSplitCandidate &Cand,
1536                                        unsigned BBNumber,
1537                                        const AllocationOrder &Order) {
1538   Cand.Intf.moveToBlock(BBNumber);
1539 
1540   // Check if the local interval will find a non interfereing assignment.
1541   for (auto PhysReg : Order.getOrder()) {
1542     if (!Matrix->checkInterference(Cand.Intf.first().getPrevIndex(),
1543                                    Cand.Intf.last(), PhysReg))
1544       return false;
1545   }
1546 
1547   // Check if the local interval will evict a cheaper interval.
1548   float CheapestEvictWeight = 0;
1549   unsigned FutureEvictedPhysReg = getCheapestEvicteeWeight(
1550       Order, LIS->getInterval(VirtRegToSplit), Cand.Intf.first(),
1551       Cand.Intf.last(), &CheapestEvictWeight);
1552 
1553   // Have we found an interval that can be evicted?
1554   if (FutureEvictedPhysReg) {
1555     VirtRegAuxInfo VRAI(*MF, *LIS, VRM, getAnalysis<MachineLoopInfo>(), *MBFI);
1556     float splitArtifactWeight =
1557         VRAI.futureWeight(LIS->getInterval(VirtRegToSplit),
1558                           Cand.Intf.first().getPrevIndex(), Cand.Intf.last());
1559     // Will the weight of the local interval be higher than the cheapest evictee
1560     // weight? If so it will evict it and will not cause a spill.
1561     if (splitArtifactWeight >= 0 && splitArtifactWeight > CheapestEvictWeight)
1562       return false;
1563   }
1564 
1565   // The local interval is not able to find non interferencing assignment and
1566   // not able to evict a less worthy interval, therfore, it can cause a spill.
1567   return true;
1568 }
1569 
1570 /// calcGlobalSplitCost - Return the global split cost of following the split
1571 /// pattern in LiveBundles. This cost should be added to the local cost of the
1572 /// interference pattern in SplitConstraints.
1573 ///
1574 BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand,
1575                                              const AllocationOrder &Order,
1576                                              bool *CanCauseEvictionChain) {
1577   BlockFrequency GlobalCost = 0;
1578   const BitVector &LiveBundles = Cand.LiveBundles;
1579   unsigned VirtRegToSplit = SA->getParent().reg();
1580   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1581   for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1582     const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1583     SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
1584     bool RegIn  = LiveBundles[Bundles->getBundle(BC.Number, false)];
1585     bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, true)];
1586     unsigned Ins = 0;
1587 
1588     Cand.Intf.moveToBlock(BC.Number);
1589     // Check wheather a local interval is going to be created during the region
1590     // split. Calculate adavanced spilt cost (cost of local intervals) if option
1591     // is enabled.
1592     if (EnableAdvancedRASplitCost && Cand.Intf.hasInterference() && BI.LiveIn &&
1593         BI.LiveOut && RegIn && RegOut) {
1594 
1595       if (CanCauseEvictionChain &&
1596           splitCanCauseEvictionChain(VirtRegToSplit, Cand, BC.Number, Order)) {
1597         // This interference causes our eviction from this assignment, we might
1598         // evict somebody else and eventually someone will spill, add that cost.
1599         // See splitCanCauseEvictionChain for detailed description of scenarios.
1600         GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1601         GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1602 
1603         *CanCauseEvictionChain = true;
1604 
1605       } else if (splitCanCauseLocalSpill(VirtRegToSplit, Cand, BC.Number,
1606                                          Order)) {
1607         // This interference causes local interval to spill, add that cost.
1608         GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1609         GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1610       }
1611     }
1612 
1613     if (BI.LiveIn)
1614       Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
1615     if (BI.LiveOut)
1616       Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
1617     while (Ins--)
1618       GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1619   }
1620 
1621   for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
1622     unsigned Number = Cand.ActiveBlocks[i];
1623     bool RegIn  = LiveBundles[Bundles->getBundle(Number, false)];
1624     bool RegOut = LiveBundles[Bundles->getBundle(Number, true)];
1625     if (!RegIn && !RegOut)
1626       continue;
1627     if (RegIn && RegOut) {
1628       // We need double spill code if this block has interference.
1629       Cand.Intf.moveToBlock(Number);
1630       if (Cand.Intf.hasInterference()) {
1631         GlobalCost += SpillPlacer->getBlockFrequency(Number);
1632         GlobalCost += SpillPlacer->getBlockFrequency(Number);
1633 
1634         // Check wheather a local interval is going to be created during the
1635         // region split.
1636         if (EnableAdvancedRASplitCost && CanCauseEvictionChain &&
1637             splitCanCauseEvictionChain(VirtRegToSplit, Cand, Number, Order)) {
1638           // This interference cause our eviction from this assignment, we might
1639           // evict somebody else, add that cost.
1640           // See splitCanCauseEvictionChain for detailed description of
1641           // scenarios.
1642           GlobalCost += SpillPlacer->getBlockFrequency(Number);
1643           GlobalCost += SpillPlacer->getBlockFrequency(Number);
1644 
1645           *CanCauseEvictionChain = true;
1646         }
1647       }
1648       continue;
1649     }
1650     // live-in / stack-out or stack-in live-out.
1651     GlobalCost += SpillPlacer->getBlockFrequency(Number);
1652   }
1653   return GlobalCost;
1654 }
1655 
1656 /// splitAroundRegion - Split the current live range around the regions
1657 /// determined by BundleCand and GlobalCand.
1658 ///
1659 /// Before calling this function, GlobalCand and BundleCand must be initialized
1660 /// so each bundle is assigned to a valid candidate, or NoCand for the
1661 /// stack-bound bundles.  The shared SA/SE SplitAnalysis and SplitEditor
1662 /// objects must be initialized for the current live range, and intervals
1663 /// created for the used candidates.
1664 ///
1665 /// @param LREdit    The LiveRangeEdit object handling the current split.
1666 /// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1667 ///                  must appear in this list.
1668 void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1669                                  ArrayRef<unsigned> UsedCands) {
1670   // These are the intervals created for new global ranges. We may create more
1671   // intervals for local ranges.
1672   const unsigned NumGlobalIntvs = LREdit.size();
1673   LLVM_DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs
1674                     << " globals.\n");
1675   assert(NumGlobalIntvs && "No global intervals configured");
1676 
1677   // Isolate even single instructions when dealing with a proper sub-class.
1678   // That guarantees register class inflation for the stack interval because it
1679   // is all copies.
1680   unsigned Reg = SA->getParent().reg();
1681   bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1682 
1683   // First handle all the blocks with uses.
1684   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1685   for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1686     const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1687     unsigned Number = BI.MBB->getNumber();
1688     unsigned IntvIn = 0, IntvOut = 0;
1689     SlotIndex IntfIn, IntfOut;
1690     if (BI.LiveIn) {
1691       unsigned CandIn = BundleCand[Bundles->getBundle(Number, false)];
1692       if (CandIn != NoCand) {
1693         GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1694         IntvIn = Cand.IntvIdx;
1695         Cand.Intf.moveToBlock(Number);
1696         IntfIn = Cand.Intf.first();
1697       }
1698     }
1699     if (BI.LiveOut) {
1700       unsigned CandOut = BundleCand[Bundles->getBundle(Number, true)];
1701       if (CandOut != NoCand) {
1702         GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1703         IntvOut = Cand.IntvIdx;
1704         Cand.Intf.moveToBlock(Number);
1705         IntfOut = Cand.Intf.last();
1706       }
1707     }
1708 
1709     // Create separate intervals for isolated blocks with multiple uses.
1710     if (!IntvIn && !IntvOut) {
1711       LLVM_DEBUG(dbgs() << printMBBReference(*BI.MBB) << " isolated.\n");
1712       if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1713         SE->splitSingleBlock(BI);
1714       continue;
1715     }
1716 
1717     if (IntvIn && IntvOut)
1718       SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1719     else if (IntvIn)
1720       SE->splitRegInBlock(BI, IntvIn, IntfIn);
1721     else
1722       SE->splitRegOutBlock(BI, IntvOut, IntfOut);
1723   }
1724 
1725   // Handle live-through blocks. The relevant live-through blocks are stored in
1726   // the ActiveBlocks list with each candidate. We need to filter out
1727   // duplicates.
1728   BitVector Todo = SA->getThroughBlocks();
1729   for (unsigned c = 0; c != UsedCands.size(); ++c) {
1730     ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1731     for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1732       unsigned Number = Blocks[i];
1733       if (!Todo.test(Number))
1734         continue;
1735       Todo.reset(Number);
1736 
1737       unsigned IntvIn = 0, IntvOut = 0;
1738       SlotIndex IntfIn, IntfOut;
1739 
1740       unsigned CandIn = BundleCand[Bundles->getBundle(Number, false)];
1741       if (CandIn != NoCand) {
1742         GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1743         IntvIn = Cand.IntvIdx;
1744         Cand.Intf.moveToBlock(Number);
1745         IntfIn = Cand.Intf.first();
1746       }
1747 
1748       unsigned CandOut = BundleCand[Bundles->getBundle(Number, true)];
1749       if (CandOut != NoCand) {
1750         GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1751         IntvOut = Cand.IntvIdx;
1752         Cand.Intf.moveToBlock(Number);
1753         IntfOut = Cand.Intf.last();
1754       }
1755       if (!IntvIn && !IntvOut)
1756         continue;
1757       SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1758     }
1759   }
1760 
1761   ++NumGlobalSplits;
1762 
1763   SmallVector<unsigned, 8> IntvMap;
1764   SE->finish(&IntvMap);
1765   DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
1766 
1767   ExtraRegInfo.resize(MRI->getNumVirtRegs());
1768   unsigned OrigBlocks = SA->getNumLiveBlocks();
1769 
1770   // Sort out the new intervals created by splitting. We get four kinds:
1771   // - Remainder intervals should not be split again.
1772   // - Candidate intervals can be assigned to Cand.PhysReg.
1773   // - Block-local splits are candidates for local splitting.
1774   // - DCE leftovers should go back on the queue.
1775   for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1776     LiveInterval &Reg = LIS->getInterval(LREdit.get(i));
1777 
1778     // Ignore old intervals from DCE.
1779     if (getStage(Reg) != RS_New)
1780       continue;
1781 
1782     // Remainder interval. Don't try splitting again, spill if it doesn't
1783     // allocate.
1784     if (IntvMap[i] == 0) {
1785       setStage(Reg, RS_Spill);
1786       continue;
1787     }
1788 
1789     // Global intervals. Allow repeated splitting as long as the number of live
1790     // blocks is strictly decreasing.
1791     if (IntvMap[i] < NumGlobalIntvs) {
1792       if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
1793         LLVM_DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1794                           << " blocks as original.\n");
1795         // Don't allow repeated splitting as a safe guard against looping.
1796         setStage(Reg, RS_Split2);
1797       }
1798       continue;
1799     }
1800 
1801     // Other intervals are treated as new. This includes local intervals created
1802     // for blocks with multiple uses, and anything created by DCE.
1803   }
1804 
1805   if (VerifyEnabled)
1806     MF->verify(this, "After splitting live range around region");
1807 }
1808 
1809 unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1810                                   SmallVectorImpl<Register> &NewVRegs) {
1811   if (!TRI->shouldRegionSplitForVirtReg(*MF, VirtReg))
1812     return 0;
1813   unsigned NumCands = 0;
1814   BlockFrequency SpillCost = calcSpillCost();
1815   BlockFrequency BestCost;
1816 
1817   // Check if we can split this live range around a compact region.
1818   bool HasCompact = calcCompactRegion(GlobalCand.front());
1819   if (HasCompact) {
1820     // Yes, keep GlobalCand[0] as the compact region candidate.
1821     NumCands = 1;
1822     BestCost = BlockFrequency::getMaxFrequency();
1823   } else {
1824     // No benefit from the compact region, our fallback will be per-block
1825     // splitting. Make sure we find a solution that is cheaper than spilling.
1826     BestCost = SpillCost;
1827     LLVM_DEBUG(dbgs() << "Cost of isolating all blocks = ";
1828                MBFI->printBlockFreq(dbgs(), BestCost) << '\n');
1829   }
1830 
1831   bool CanCauseEvictionChain = false;
1832   unsigned BestCand =
1833       calculateRegionSplitCost(VirtReg, Order, BestCost, NumCands,
1834                                false /*IgnoreCSR*/, &CanCauseEvictionChain);
1835 
1836   // Split candidates with compact regions can cause a bad eviction sequence.
1837   // See splitCanCauseEvictionChain for detailed description of scenarios.
1838   // To avoid it, we need to comapre the cost with the spill cost and not the
1839   // current max frequency.
1840   if (HasCompact && (BestCost > SpillCost) && (BestCand != NoCand) &&
1841     CanCauseEvictionChain) {
1842     return 0;
1843   }
1844 
1845   // No solutions found, fall back to single block splitting.
1846   if (!HasCompact && BestCand == NoCand)
1847     return 0;
1848 
1849   return doRegionSplit(VirtReg, BestCand, HasCompact, NewVRegs);
1850 }
1851 
1852 unsigned RAGreedy::calculateRegionSplitCost(LiveInterval &VirtReg,
1853                                             AllocationOrder &Order,
1854                                             BlockFrequency &BestCost,
1855                                             unsigned &NumCands, bool IgnoreCSR,
1856                                             bool *CanCauseEvictionChain) {
1857   unsigned BestCand = NoCand;
1858   Order.rewind();
1859   while (unsigned PhysReg = Order.next()) {
1860     if (IgnoreCSR && isUnusedCalleeSavedReg(PhysReg))
1861       continue;
1862 
1863     // Discard bad candidates before we run out of interference cache cursors.
1864     // This will only affect register classes with a lot of registers (>32).
1865     if (NumCands == IntfCache.getMaxCursors()) {
1866       unsigned WorstCount = ~0u;
1867       unsigned Worst = 0;
1868       for (unsigned i = 0; i != NumCands; ++i) {
1869         if (i == BestCand || !GlobalCand[i].PhysReg)
1870           continue;
1871         unsigned Count = GlobalCand[i].LiveBundles.count();
1872         if (Count < WorstCount) {
1873           Worst = i;
1874           WorstCount = Count;
1875         }
1876       }
1877       --NumCands;
1878       GlobalCand[Worst] = GlobalCand[NumCands];
1879       if (BestCand == NumCands)
1880         BestCand = Worst;
1881     }
1882 
1883     if (GlobalCand.size() <= NumCands)
1884       GlobalCand.resize(NumCands+1);
1885     GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1886     Cand.reset(IntfCache, PhysReg);
1887 
1888     SpillPlacer->prepare(Cand.LiveBundles);
1889     BlockFrequency Cost;
1890     if (!addSplitConstraints(Cand.Intf, Cost)) {
1891       LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << "\tno positive bundles\n");
1892       continue;
1893     }
1894     LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << "\tstatic = ";
1895                MBFI->printBlockFreq(dbgs(), Cost));
1896     if (Cost >= BestCost) {
1897       LLVM_DEBUG({
1898         if (BestCand == NoCand)
1899           dbgs() << " worse than no bundles\n";
1900         else
1901           dbgs() << " worse than "
1902                  << printReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1903       });
1904       continue;
1905     }
1906     if (!growRegion(Cand)) {
1907       LLVM_DEBUG(dbgs() << ", cannot spill all interferences.\n");
1908       continue;
1909     }
1910 
1911     SpillPlacer->finish();
1912 
1913     // No live bundles, defer to splitSingleBlocks().
1914     if (!Cand.LiveBundles.any()) {
1915       LLVM_DEBUG(dbgs() << " no bundles.\n");
1916       continue;
1917     }
1918 
1919     bool HasEvictionChain = false;
1920     Cost += calcGlobalSplitCost(Cand, Order, &HasEvictionChain);
1921     LLVM_DEBUG({
1922       dbgs() << ", total = ";
1923       MBFI->printBlockFreq(dbgs(), Cost) << " with bundles";
1924       for (int i : Cand.LiveBundles.set_bits())
1925         dbgs() << " EB#" << i;
1926       dbgs() << ".\n";
1927     });
1928     if (Cost < BestCost) {
1929       BestCand = NumCands;
1930       BestCost = Cost;
1931       // See splitCanCauseEvictionChain for detailed description of bad
1932       // eviction chain scenarios.
1933       if (CanCauseEvictionChain)
1934         *CanCauseEvictionChain = HasEvictionChain;
1935     }
1936     ++NumCands;
1937   }
1938 
1939   if (CanCauseEvictionChain && BestCand != NoCand) {
1940     // See splitCanCauseEvictionChain for detailed description of bad
1941     // eviction chain scenarios.
1942     LLVM_DEBUG(dbgs() << "Best split candidate of vreg "
1943                       << printReg(VirtReg.reg(), TRI) << "  may ");
1944     if (!(*CanCauseEvictionChain))
1945       LLVM_DEBUG(dbgs() << "not ");
1946     LLVM_DEBUG(dbgs() << "cause bad eviction chain\n");
1947   }
1948 
1949   return BestCand;
1950 }
1951 
1952 unsigned RAGreedy::doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
1953                                  bool HasCompact,
1954                                  SmallVectorImpl<Register> &NewVRegs) {
1955   SmallVector<unsigned, 8> UsedCands;
1956   // Prepare split editor.
1957   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
1958   SE->reset(LREdit, SplitSpillMode);
1959 
1960   // Assign all edge bundles to the preferred candidate, or NoCand.
1961   BundleCand.assign(Bundles->getNumBundles(), NoCand);
1962 
1963   // Assign bundles for the best candidate region.
1964   if (BestCand != NoCand) {
1965     GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1966     if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1967       UsedCands.push_back(BestCand);
1968       Cand.IntvIdx = SE->openIntv();
1969       LLVM_DEBUG(dbgs() << "Split for " << printReg(Cand.PhysReg, TRI) << " in "
1970                         << B << " bundles, intv " << Cand.IntvIdx << ".\n");
1971       (void)B;
1972     }
1973   }
1974 
1975   // Assign bundles for the compact region.
1976   if (HasCompact) {
1977     GlobalSplitCandidate &Cand = GlobalCand.front();
1978     assert(!Cand.PhysReg && "Compact region has no physreg");
1979     if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1980       UsedCands.push_back(0);
1981       Cand.IntvIdx = SE->openIntv();
1982       LLVM_DEBUG(dbgs() << "Split for compact region in " << B
1983                         << " bundles, intv " << Cand.IntvIdx << ".\n");
1984       (void)B;
1985     }
1986   }
1987 
1988   splitAroundRegion(LREdit, UsedCands);
1989   return 0;
1990 }
1991 
1992 //===----------------------------------------------------------------------===//
1993 //                            Per-Block Splitting
1994 //===----------------------------------------------------------------------===//
1995 
1996 /// tryBlockSplit - Split a global live range around every block with uses. This
1997 /// creates a lot of local live ranges, that will be split by tryLocalSplit if
1998 /// they don't allocate.
1999 unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
2000                                  SmallVectorImpl<Register> &NewVRegs) {
2001   assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
2002   Register Reg = VirtReg.reg();
2003   bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
2004   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
2005   SE->reset(LREdit, SplitSpillMode);
2006   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
2007   for (unsigned i = 0; i != UseBlocks.size(); ++i) {
2008     const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
2009     if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
2010       SE->splitSingleBlock(BI);
2011   }
2012   // No blocks were split.
2013   if (LREdit.empty())
2014     return 0;
2015 
2016   // We did split for some blocks.
2017   SmallVector<unsigned, 8> IntvMap;
2018   SE->finish(&IntvMap);
2019 
2020   // Tell LiveDebugVariables about the new ranges.
2021   DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
2022 
2023   ExtraRegInfo.resize(MRI->getNumVirtRegs());
2024 
2025   // Sort out the new intervals created by splitting. The remainder interval
2026   // goes straight to spilling, the new local ranges get to stay RS_New.
2027   for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
2028     LiveInterval &LI = LIS->getInterval(LREdit.get(i));
2029     if (getStage(LI) == RS_New && IntvMap[i] == 0)
2030       setStage(LI, RS_Spill);
2031   }
2032 
2033   if (VerifyEnabled)
2034     MF->verify(this, "After splitting live range around basic blocks");
2035   return 0;
2036 }
2037 
2038 //===----------------------------------------------------------------------===//
2039 //                         Per-Instruction Splitting
2040 //===----------------------------------------------------------------------===//
2041 
2042 /// Get the number of allocatable registers that match the constraints of \p Reg
2043 /// on \p MI and that are also in \p SuperRC.
2044 static unsigned getNumAllocatableRegsForConstraints(
2045     const MachineInstr *MI, unsigned Reg, const TargetRegisterClass *SuperRC,
2046     const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
2047     const RegisterClassInfo &RCI) {
2048   assert(SuperRC && "Invalid register class");
2049 
2050   const TargetRegisterClass *ConstrainedRC =
2051       MI->getRegClassConstraintEffectForVReg(Reg, SuperRC, TII, TRI,
2052                                              /* ExploreBundle */ true);
2053   if (!ConstrainedRC)
2054     return 0;
2055   return RCI.getNumAllocatableRegs(ConstrainedRC);
2056 }
2057 
2058 /// tryInstructionSplit - Split a live range around individual instructions.
2059 /// This is normally not worthwhile since the spiller is doing essentially the
2060 /// same thing. However, when the live range is in a constrained register
2061 /// class, it may help to insert copies such that parts of the live range can
2062 /// be moved to a larger register class.
2063 ///
2064 /// This is similar to spilling to a larger register class.
2065 unsigned
2066 RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
2067                               SmallVectorImpl<Register> &NewVRegs) {
2068   const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg());
2069   // There is no point to this if there are no larger sub-classes.
2070   if (!RegClassInfo.isProperSubClass(CurRC))
2071     return 0;
2072 
2073   // Always enable split spill mode, since we're effectively spilling to a
2074   // register.
2075   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
2076   SE->reset(LREdit, SplitEditor::SM_Size);
2077 
2078   ArrayRef<SlotIndex> Uses = SA->getUseSlots();
2079   if (Uses.size() <= 1)
2080     return 0;
2081 
2082   LLVM_DEBUG(dbgs() << "Split around " << Uses.size()
2083                     << " individual instrs.\n");
2084 
2085   const TargetRegisterClass *SuperRC =
2086       TRI->getLargestLegalSuperClass(CurRC, *MF);
2087   unsigned SuperRCNumAllocatableRegs = RCI.getNumAllocatableRegs(SuperRC);
2088   // Split around every non-copy instruction if this split will relax
2089   // the constraints on the virtual register.
2090   // Otherwise, splitting just inserts uncoalescable copies that do not help
2091   // the allocation.
2092   for (unsigned i = 0; i != Uses.size(); ++i) {
2093     if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
2094       if (MI->isFullCopy() ||
2095           SuperRCNumAllocatableRegs ==
2096               getNumAllocatableRegsForConstraints(MI, VirtReg.reg(), SuperRC,
2097                                                   TII, TRI, RCI)) {
2098         LLVM_DEBUG(dbgs() << "    skip:\t" << Uses[i] << '\t' << *MI);
2099         continue;
2100       }
2101     SE->openIntv();
2102     SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
2103     SlotIndex SegStop  = SE->leaveIntvAfter(Uses[i]);
2104     SE->useIntv(SegStart, SegStop);
2105   }
2106 
2107   if (LREdit.empty()) {
2108     LLVM_DEBUG(dbgs() << "All uses were copies.\n");
2109     return 0;
2110   }
2111 
2112   SmallVector<unsigned, 8> IntvMap;
2113   SE->finish(&IntvMap);
2114   DebugVars->splitRegister(VirtReg.reg(), LREdit.regs(), *LIS);
2115   ExtraRegInfo.resize(MRI->getNumVirtRegs());
2116 
2117   // Assign all new registers to RS_Spill. This was the last chance.
2118   setStage(LREdit.begin(), LREdit.end(), RS_Spill);
2119   return 0;
2120 }
2121 
2122 //===----------------------------------------------------------------------===//
2123 //                             Local Splitting
2124 //===----------------------------------------------------------------------===//
2125 
2126 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
2127 /// in order to use PhysReg between two entries in SA->UseSlots.
2128 ///
2129 /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
2130 ///
2131 void RAGreedy::calcGapWeights(unsigned PhysReg,
2132                               SmallVectorImpl<float> &GapWeight) {
2133   assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
2134   const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
2135   ArrayRef<SlotIndex> Uses = SA->getUseSlots();
2136   const unsigned NumGaps = Uses.size()-1;
2137 
2138   // Start and end points for the interference check.
2139   SlotIndex StartIdx =
2140     BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
2141   SlotIndex StopIdx =
2142     BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
2143 
2144   GapWeight.assign(NumGaps, 0.0f);
2145 
2146   // Add interference from each overlapping register.
2147   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
2148     if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
2149           .checkInterference())
2150       continue;
2151 
2152     // We know that VirtReg is a continuous interval from FirstInstr to
2153     // LastInstr, so we don't need InterferenceQuery.
2154     //
2155     // Interference that overlaps an instruction is counted in both gaps
2156     // surrounding the instruction. The exception is interference before
2157     // StartIdx and after StopIdx.
2158     //
2159     LiveIntervalUnion::SegmentIter IntI =
2160       Matrix->getLiveUnions()[*Units] .find(StartIdx);
2161     for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
2162       // Skip the gaps before IntI.
2163       while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
2164         if (++Gap == NumGaps)
2165           break;
2166       if (Gap == NumGaps)
2167         break;
2168 
2169       // Update the gaps covered by IntI.
2170       const float weight = IntI.value()->weight();
2171       for (; Gap != NumGaps; ++Gap) {
2172         GapWeight[Gap] = std::max(GapWeight[Gap], weight);
2173         if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
2174           break;
2175       }
2176       if (Gap == NumGaps)
2177         break;
2178     }
2179   }
2180 
2181   // Add fixed interference.
2182   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
2183     const LiveRange &LR = LIS->getRegUnit(*Units);
2184     LiveRange::const_iterator I = LR.find(StartIdx);
2185     LiveRange::const_iterator E = LR.end();
2186 
2187     // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
2188     for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
2189       while (Uses[Gap+1].getBoundaryIndex() < I->start)
2190         if (++Gap == NumGaps)
2191           break;
2192       if (Gap == NumGaps)
2193         break;
2194 
2195       for (; Gap != NumGaps; ++Gap) {
2196         GapWeight[Gap] = huge_valf;
2197         if (Uses[Gap+1].getBaseIndex() >= I->end)
2198           break;
2199       }
2200       if (Gap == NumGaps)
2201         break;
2202     }
2203   }
2204 }
2205 
2206 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
2207 /// basic block.
2208 ///
2209 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
2210                                  SmallVectorImpl<Register> &NewVRegs) {
2211   // TODO: the function currently only handles a single UseBlock; it should be
2212   // possible to generalize.
2213   if (SA->getUseBlocks().size() != 1)
2214     return 0;
2215 
2216   const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
2217 
2218   // Note that it is possible to have an interval that is live-in or live-out
2219   // while only covering a single block - A phi-def can use undef values from
2220   // predecessors, and the block could be a single-block loop.
2221   // We don't bother doing anything clever about such a case, we simply assume
2222   // that the interval is continuous from FirstInstr to LastInstr. We should
2223   // make sure that we don't do anything illegal to such an interval, though.
2224 
2225   ArrayRef<SlotIndex> Uses = SA->getUseSlots();
2226   if (Uses.size() <= 2)
2227     return 0;
2228   const unsigned NumGaps = Uses.size()-1;
2229 
2230   LLVM_DEBUG({
2231     dbgs() << "tryLocalSplit: ";
2232     for (unsigned i = 0, e = Uses.size(); i != e; ++i)
2233       dbgs() << ' ' << Uses[i];
2234     dbgs() << '\n';
2235   });
2236 
2237   // If VirtReg is live across any register mask operands, compute a list of
2238   // gaps with register masks.
2239   SmallVector<unsigned, 8> RegMaskGaps;
2240   if (Matrix->checkRegMaskInterference(VirtReg)) {
2241     // Get regmask slots for the whole block.
2242     ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
2243     LLVM_DEBUG(dbgs() << RMS.size() << " regmasks in block:");
2244     // Constrain to VirtReg's live range.
2245     unsigned ri =
2246         llvm::lower_bound(RMS, Uses.front().getRegSlot()) - RMS.begin();
2247     unsigned re = RMS.size();
2248     for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
2249       // Look for Uses[i] <= RMS <= Uses[i+1].
2250       assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
2251       if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
2252         continue;
2253       // Skip a regmask on the same instruction as the last use. It doesn't
2254       // overlap the live range.
2255       if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
2256         break;
2257       LLVM_DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-'
2258                         << Uses[i + 1]);
2259       RegMaskGaps.push_back(i);
2260       // Advance ri to the next gap. A regmask on one of the uses counts in
2261       // both gaps.
2262       while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
2263         ++ri;
2264     }
2265     LLVM_DEBUG(dbgs() << '\n');
2266   }
2267 
2268   // Since we allow local split results to be split again, there is a risk of
2269   // creating infinite loops. It is tempting to require that the new live
2270   // ranges have less instructions than the original. That would guarantee
2271   // convergence, but it is too strict. A live range with 3 instructions can be
2272   // split 2+3 (including the COPY), and we want to allow that.
2273   //
2274   // Instead we use these rules:
2275   //
2276   // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
2277   //    noop split, of course).
2278   // 2. Require progress be made for ranges with getStage() == RS_Split2. All
2279   //    the new ranges must have fewer instructions than before the split.
2280   // 3. New ranges with the same number of instructions are marked RS_Split2,
2281   //    smaller ranges are marked RS_New.
2282   //
2283   // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
2284   // excessive splitting and infinite loops.
2285   //
2286   bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
2287 
2288   // Best split candidate.
2289   unsigned BestBefore = NumGaps;
2290   unsigned BestAfter = 0;
2291   float BestDiff = 0;
2292 
2293   const float blockFreq =
2294     SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
2295     (1.0f / MBFI->getEntryFreq());
2296   SmallVector<float, 8> GapWeight;
2297 
2298   Order.rewind();
2299   while (unsigned PhysReg = Order.next()) {
2300     // Keep track of the largest spill weight that would need to be evicted in
2301     // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
2302     calcGapWeights(PhysReg, GapWeight);
2303 
2304     // Remove any gaps with regmask clobbers.
2305     if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
2306       for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
2307         GapWeight[RegMaskGaps[i]] = huge_valf;
2308 
2309     // Try to find the best sequence of gaps to close.
2310     // The new spill weight must be larger than any gap interference.
2311 
2312     // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
2313     unsigned SplitBefore = 0, SplitAfter = 1;
2314 
2315     // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
2316     // It is the spill weight that needs to be evicted.
2317     float MaxGap = GapWeight[0];
2318 
2319     while (true) {
2320       // Live before/after split?
2321       const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
2322       const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
2323 
2324       LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << ' ' << Uses[SplitBefore]
2325                         << '-' << Uses[SplitAfter] << " i=" << MaxGap);
2326 
2327       // Stop before the interval gets so big we wouldn't be making progress.
2328       if (!LiveBefore && !LiveAfter) {
2329         LLVM_DEBUG(dbgs() << " all\n");
2330         break;
2331       }
2332       // Should the interval be extended or shrunk?
2333       bool Shrink = true;
2334 
2335       // How many gaps would the new range have?
2336       unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
2337 
2338       // Legally, without causing looping?
2339       bool Legal = !ProgressRequired || NewGaps < NumGaps;
2340 
2341       if (Legal && MaxGap < huge_valf) {
2342         // Estimate the new spill weight. Each instruction reads or writes the
2343         // register. Conservatively assume there are no read-modify-write
2344         // instructions.
2345         //
2346         // Try to guess the size of the new interval.
2347         const float EstWeight = normalizeSpillWeight(
2348             blockFreq * (NewGaps + 1),
2349             Uses[SplitBefore].distance(Uses[SplitAfter]) +
2350                 (LiveBefore + LiveAfter) * SlotIndex::InstrDist,
2351             1);
2352         // Would this split be possible to allocate?
2353         // Never allocate all gaps, we wouldn't be making progress.
2354         LLVM_DEBUG(dbgs() << " w=" << EstWeight);
2355         if (EstWeight * Hysteresis >= MaxGap) {
2356           Shrink = false;
2357           float Diff = EstWeight - MaxGap;
2358           if (Diff > BestDiff) {
2359             LLVM_DEBUG(dbgs() << " (best)");
2360             BestDiff = Hysteresis * Diff;
2361             BestBefore = SplitBefore;
2362             BestAfter = SplitAfter;
2363           }
2364         }
2365       }
2366 
2367       // Try to shrink.
2368       if (Shrink) {
2369         if (++SplitBefore < SplitAfter) {
2370           LLVM_DEBUG(dbgs() << " shrink\n");
2371           // Recompute the max when necessary.
2372           if (GapWeight[SplitBefore - 1] >= MaxGap) {
2373             MaxGap = GapWeight[SplitBefore];
2374             for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
2375               MaxGap = std::max(MaxGap, GapWeight[i]);
2376           }
2377           continue;
2378         }
2379         MaxGap = 0;
2380       }
2381 
2382       // Try to extend the interval.
2383       if (SplitAfter >= NumGaps) {
2384         LLVM_DEBUG(dbgs() << " end\n");
2385         break;
2386       }
2387 
2388       LLVM_DEBUG(dbgs() << " extend\n");
2389       MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
2390     }
2391   }
2392 
2393   // Didn't find any candidates?
2394   if (BestBefore == NumGaps)
2395     return 0;
2396 
2397   LLVM_DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore] << '-'
2398                     << Uses[BestAfter] << ", " << BestDiff << ", "
2399                     << (BestAfter - BestBefore + 1) << " instrs\n");
2400 
2401   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
2402   SE->reset(LREdit);
2403 
2404   SE->openIntv();
2405   SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
2406   SlotIndex SegStop  = SE->leaveIntvAfter(Uses[BestAfter]);
2407   SE->useIntv(SegStart, SegStop);
2408   SmallVector<unsigned, 8> IntvMap;
2409   SE->finish(&IntvMap);
2410   DebugVars->splitRegister(VirtReg.reg(), LREdit.regs(), *LIS);
2411 
2412   // If the new range has the same number of instructions as before, mark it as
2413   // RS_Split2 so the next split will be forced to make progress. Otherwise,
2414   // leave the new intervals as RS_New so they can compete.
2415   bool LiveBefore = BestBefore != 0 || BI.LiveIn;
2416   bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
2417   unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
2418   if (NewGaps >= NumGaps) {
2419     LLVM_DEBUG(dbgs() << "Tagging non-progress ranges: ");
2420     assert(!ProgressRequired && "Didn't make progress when it was required.");
2421     for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
2422       if (IntvMap[i] == 1) {
2423         setStage(LIS->getInterval(LREdit.get(i)), RS_Split2);
2424         LLVM_DEBUG(dbgs() << printReg(LREdit.get(i)));
2425       }
2426     LLVM_DEBUG(dbgs() << '\n');
2427   }
2428   ++NumLocalSplits;
2429 
2430   return 0;
2431 }
2432 
2433 //===----------------------------------------------------------------------===//
2434 //                          Live Range Splitting
2435 //===----------------------------------------------------------------------===//
2436 
2437 /// trySplit - Try to split VirtReg or one of its interferences, making it
2438 /// assignable.
2439 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
2440 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
2441                             SmallVectorImpl<Register> &NewVRegs,
2442                             const SmallVirtRegSet &FixedRegisters) {
2443   // Ranges must be Split2 or less.
2444   if (getStage(VirtReg) >= RS_Spill)
2445     return 0;
2446 
2447   // Local intervals are handled separately.
2448   if (LIS->intervalIsInOneMBB(VirtReg)) {
2449     NamedRegionTimer T("local_split", "Local Splitting", TimerGroupName,
2450                        TimerGroupDescription, TimePassesIsEnabled);
2451     SA->analyze(&VirtReg);
2452     Register PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
2453     if (PhysReg || !NewVRegs.empty())
2454       return PhysReg;
2455     return tryInstructionSplit(VirtReg, Order, NewVRegs);
2456   }
2457 
2458   NamedRegionTimer T("global_split", "Global Splitting", TimerGroupName,
2459                      TimerGroupDescription, TimePassesIsEnabled);
2460 
2461   SA->analyze(&VirtReg);
2462 
2463   // FIXME: SplitAnalysis may repair broken live ranges coming from the
2464   // coalescer. That may cause the range to become allocatable which means that
2465   // tryRegionSplit won't be making progress. This check should be replaced with
2466   // an assertion when the coalescer is fixed.
2467   if (SA->didRepairRange()) {
2468     // VirtReg has changed, so all cached queries are invalid.
2469     Matrix->invalidateVirtRegs();
2470     if (Register PhysReg = tryAssign(VirtReg, Order, NewVRegs, FixedRegisters))
2471       return PhysReg;
2472   }
2473 
2474   // First try to split around a region spanning multiple blocks. RS_Split2
2475   // ranges already made dubious progress with region splitting, so they go
2476   // straight to single block splitting.
2477   if (getStage(VirtReg) < RS_Split2) {
2478     unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
2479     if (PhysReg || !NewVRegs.empty())
2480       return PhysReg;
2481   }
2482 
2483   // Then isolate blocks.
2484   return tryBlockSplit(VirtReg, Order, NewVRegs);
2485 }
2486 
2487 //===----------------------------------------------------------------------===//
2488 //                          Last Chance Recoloring
2489 //===----------------------------------------------------------------------===//
2490 
2491 /// Return true if \p reg has any tied def operand.
2492 static bool hasTiedDef(MachineRegisterInfo *MRI, unsigned reg) {
2493   for (const MachineOperand &MO : MRI->def_operands(reg))
2494     if (MO.isTied())
2495       return true;
2496 
2497   return false;
2498 }
2499 
2500 /// mayRecolorAllInterferences - Check if the virtual registers that
2501 /// interfere with \p VirtReg on \p PhysReg (or one of its aliases) may be
2502 /// recolored to free \p PhysReg.
2503 /// When true is returned, \p RecoloringCandidates has been augmented with all
2504 /// the live intervals that need to be recolored in order to free \p PhysReg
2505 /// for \p VirtReg.
2506 /// \p FixedRegisters contains all the virtual registers that cannot be
2507 /// recolored.
2508 bool
2509 RAGreedy::mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
2510                                      SmallLISet &RecoloringCandidates,
2511                                      const SmallVirtRegSet &FixedRegisters) {
2512   const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg());
2513 
2514   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
2515     LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
2516     // If there is LastChanceRecoloringMaxInterference or more interferences,
2517     // chances are one would not be recolorable.
2518     if (Q.collectInterferingVRegs(LastChanceRecoloringMaxInterference) >=
2519         LastChanceRecoloringMaxInterference && !ExhaustiveSearch) {
2520       LLVM_DEBUG(dbgs() << "Early abort: too many interferences.\n");
2521       CutOffInfo |= CO_Interf;
2522       return false;
2523     }
2524     for (LiveInterval *Intf : reverse(Q.interferingVRegs())) {
2525       // If Intf is done and sit on the same register class as VirtReg,
2526       // it would not be recolorable as it is in the same state as VirtReg.
2527       // However, if VirtReg has tied defs and Intf doesn't, then
2528       // there is still a point in examining if it can be recolorable.
2529       if (((getStage(*Intf) == RS_Done &&
2530             MRI->getRegClass(Intf->reg()) == CurRC) &&
2531            !(hasTiedDef(MRI, VirtReg.reg()) &&
2532              !hasTiedDef(MRI, Intf->reg()))) ||
2533           FixedRegisters.count(Intf->reg())) {
2534         LLVM_DEBUG(
2535             dbgs() << "Early abort: the interference is not recolorable.\n");
2536         return false;
2537       }
2538       RecoloringCandidates.insert(Intf);
2539     }
2540   }
2541   return true;
2542 }
2543 
2544 /// tryLastChanceRecoloring - Try to assign a color to \p VirtReg by recoloring
2545 /// its interferences.
2546 /// Last chance recoloring chooses a color for \p VirtReg and recolors every
2547 /// virtual register that was using it. The recoloring process may recursively
2548 /// use the last chance recoloring. Therefore, when a virtual register has been
2549 /// assigned a color by this mechanism, it is marked as Fixed, i.e., it cannot
2550 /// be last-chance-recolored again during this recoloring "session".
2551 /// E.g.,
2552 /// Let
2553 /// vA can use {R1, R2    }
2554 /// vB can use {    R2, R3}
2555 /// vC can use {R1        }
2556 /// Where vA, vB, and vC cannot be split anymore (they are reloads for
2557 /// instance) and they all interfere.
2558 ///
2559 /// vA is assigned R1
2560 /// vB is assigned R2
2561 /// vC tries to evict vA but vA is already done.
2562 /// Regular register allocation fails.
2563 ///
2564 /// Last chance recoloring kicks in:
2565 /// vC does as if vA was evicted => vC uses R1.
2566 /// vC is marked as fixed.
2567 /// vA needs to find a color.
2568 /// None are available.
2569 /// vA cannot evict vC: vC is a fixed virtual register now.
2570 /// vA does as if vB was evicted => vA uses R2.
2571 /// vB needs to find a color.
2572 /// R3 is available.
2573 /// Recoloring => vC = R1, vA = R2, vB = R3
2574 ///
2575 /// \p Order defines the preferred allocation order for \p VirtReg.
2576 /// \p NewRegs will contain any new virtual register that have been created
2577 /// (split, spill) during the process and that must be assigned.
2578 /// \p FixedRegisters contains all the virtual registers that cannot be
2579 /// recolored.
2580 /// \p Depth gives the current depth of the last chance recoloring.
2581 /// \return a physical register that can be used for VirtReg or ~0u if none
2582 /// exists.
2583 unsigned RAGreedy::tryLastChanceRecoloring(LiveInterval &VirtReg,
2584                                            AllocationOrder &Order,
2585                                            SmallVectorImpl<Register> &NewVRegs,
2586                                            SmallVirtRegSet &FixedRegisters,
2587                                            unsigned Depth) {
2588   if (!TRI->shouldUseLastChanceRecoloringForVirtReg(*MF, VirtReg))
2589     return ~0u;
2590 
2591   LLVM_DEBUG(dbgs() << "Try last chance recoloring for " << VirtReg << '\n');
2592   // Ranges must be Done.
2593   assert((getStage(VirtReg) >= RS_Done || !VirtReg.isSpillable()) &&
2594          "Last chance recoloring should really be last chance");
2595   // Set the max depth to LastChanceRecoloringMaxDepth.
2596   // We may want to reconsider that if we end up with a too large search space
2597   // for target with hundreds of registers.
2598   // Indeed, in that case we may want to cut the search space earlier.
2599   if (Depth >= LastChanceRecoloringMaxDepth && !ExhaustiveSearch) {
2600     LLVM_DEBUG(dbgs() << "Abort because max depth has been reached.\n");
2601     CutOffInfo |= CO_Depth;
2602     return ~0u;
2603   }
2604 
2605   // Set of Live intervals that will need to be recolored.
2606   SmallLISet RecoloringCandidates;
2607   // Record the original mapping virtual register to physical register in case
2608   // the recoloring fails.
2609   DenseMap<Register, Register> VirtRegToPhysReg;
2610   // Mark VirtReg as fixed, i.e., it will not be recolored pass this point in
2611   // this recoloring "session".
2612   assert(!FixedRegisters.count(VirtReg.reg()));
2613   FixedRegisters.insert(VirtReg.reg());
2614   SmallVector<Register, 4> CurrentNewVRegs;
2615 
2616   Order.rewind();
2617   while (Register PhysReg = Order.next()) {
2618     LLVM_DEBUG(dbgs() << "Try to assign: " << VirtReg << " to "
2619                       << printReg(PhysReg, TRI) << '\n');
2620     RecoloringCandidates.clear();
2621     VirtRegToPhysReg.clear();
2622     CurrentNewVRegs.clear();
2623 
2624     // It is only possible to recolor virtual register interference.
2625     if (Matrix->checkInterference(VirtReg, PhysReg) >
2626         LiveRegMatrix::IK_VirtReg) {
2627       LLVM_DEBUG(
2628           dbgs() << "Some interferences are not with virtual registers.\n");
2629 
2630       continue;
2631     }
2632 
2633     // Early give up on this PhysReg if it is obvious we cannot recolor all
2634     // the interferences.
2635     if (!mayRecolorAllInterferences(PhysReg, VirtReg, RecoloringCandidates,
2636                                     FixedRegisters)) {
2637       LLVM_DEBUG(dbgs() << "Some interferences cannot be recolored.\n");
2638       continue;
2639     }
2640 
2641     // RecoloringCandidates contains all the virtual registers that interfer
2642     // with VirtReg on PhysReg (or one of its aliases).
2643     // Enqueue them for recoloring and perform the actual recoloring.
2644     PQueue RecoloringQueue;
2645     for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2646                               EndIt = RecoloringCandidates.end();
2647          It != EndIt; ++It) {
2648       Register ItVirtReg = (*It)->reg();
2649       enqueue(RecoloringQueue, *It);
2650       assert(VRM->hasPhys(ItVirtReg) &&
2651              "Interferences are supposed to be with allocated variables");
2652 
2653       // Record the current allocation.
2654       VirtRegToPhysReg[ItVirtReg] = VRM->getPhys(ItVirtReg);
2655       // unset the related struct.
2656       Matrix->unassign(**It);
2657     }
2658 
2659     // Do as if VirtReg was assigned to PhysReg so that the underlying
2660     // recoloring has the right information about the interferes and
2661     // available colors.
2662     Matrix->assign(VirtReg, PhysReg);
2663 
2664     // Save the current recoloring state.
2665     // If we cannot recolor all the interferences, we will have to start again
2666     // at this point for the next physical register.
2667     SmallVirtRegSet SaveFixedRegisters(FixedRegisters);
2668     if (tryRecoloringCandidates(RecoloringQueue, CurrentNewVRegs,
2669                                 FixedRegisters, Depth)) {
2670       // Push the queued vregs into the main queue.
2671       for (Register NewVReg : CurrentNewVRegs)
2672         NewVRegs.push_back(NewVReg);
2673       // Do not mess up with the global assignment process.
2674       // I.e., VirtReg must be unassigned.
2675       Matrix->unassign(VirtReg);
2676       return PhysReg;
2677     }
2678 
2679     LLVM_DEBUG(dbgs() << "Fail to assign: " << VirtReg << " to "
2680                       << printReg(PhysReg, TRI) << '\n');
2681 
2682     // The recoloring attempt failed, undo the changes.
2683     FixedRegisters = SaveFixedRegisters;
2684     Matrix->unassign(VirtReg);
2685 
2686     // For a newly created vreg which is also in RecoloringCandidates,
2687     // don't add it to NewVRegs because its physical register will be restored
2688     // below. Other vregs in CurrentNewVRegs are created by calling
2689     // selectOrSplit and should be added into NewVRegs.
2690     for (SmallVectorImpl<Register>::iterator Next = CurrentNewVRegs.begin(),
2691                                              End = CurrentNewVRegs.end();
2692          Next != End; ++Next) {
2693       if (RecoloringCandidates.count(&LIS->getInterval(*Next)))
2694         continue;
2695       NewVRegs.push_back(*Next);
2696     }
2697 
2698     for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2699                               EndIt = RecoloringCandidates.end();
2700          It != EndIt; ++It) {
2701       Register ItVirtReg = (*It)->reg();
2702       if (VRM->hasPhys(ItVirtReg))
2703         Matrix->unassign(**It);
2704       Register ItPhysReg = VirtRegToPhysReg[ItVirtReg];
2705       Matrix->assign(**It, ItPhysReg);
2706     }
2707   }
2708 
2709   // Last chance recoloring did not worked either, give up.
2710   return ~0u;
2711 }
2712 
2713 /// tryRecoloringCandidates - Try to assign a new color to every register
2714 /// in \RecoloringQueue.
2715 /// \p NewRegs will contain any new virtual register created during the
2716 /// recoloring process.
2717 /// \p FixedRegisters[in/out] contains all the registers that have been
2718 /// recolored.
2719 /// \return true if all virtual registers in RecoloringQueue were successfully
2720 /// recolored, false otherwise.
2721 bool RAGreedy::tryRecoloringCandidates(PQueue &RecoloringQueue,
2722                                        SmallVectorImpl<Register> &NewVRegs,
2723                                        SmallVirtRegSet &FixedRegisters,
2724                                        unsigned Depth) {
2725   while (!RecoloringQueue.empty()) {
2726     LiveInterval *LI = dequeue(RecoloringQueue);
2727     LLVM_DEBUG(dbgs() << "Try to recolor: " << *LI << '\n');
2728     Register PhysReg = selectOrSplitImpl(*LI, NewVRegs, FixedRegisters,
2729                                          Depth + 1);
2730     // When splitting happens, the live-range may actually be empty.
2731     // In that case, this is okay to continue the recoloring even
2732     // if we did not find an alternative color for it. Indeed,
2733     // there will not be anything to color for LI in the end.
2734     if (PhysReg == ~0u || (!PhysReg && !LI->empty()))
2735       return false;
2736 
2737     if (!PhysReg) {
2738       assert(LI->empty() && "Only empty live-range do not require a register");
2739       LLVM_DEBUG(dbgs() << "Recoloring of " << *LI
2740                         << " succeeded. Empty LI.\n");
2741       continue;
2742     }
2743     LLVM_DEBUG(dbgs() << "Recoloring of " << *LI
2744                       << " succeeded with: " << printReg(PhysReg, TRI) << '\n');
2745 
2746     Matrix->assign(*LI, PhysReg);
2747     FixedRegisters.insert(LI->reg());
2748   }
2749   return true;
2750 }
2751 
2752 //===----------------------------------------------------------------------===//
2753 //                            Main Entry Point
2754 //===----------------------------------------------------------------------===//
2755 
2756 Register RAGreedy::selectOrSplit(LiveInterval &VirtReg,
2757                                  SmallVectorImpl<Register> &NewVRegs) {
2758   CutOffInfo = CO_None;
2759   LLVMContext &Ctx = MF->getFunction().getContext();
2760   SmallVirtRegSet FixedRegisters;
2761   Register Reg = selectOrSplitImpl(VirtReg, NewVRegs, FixedRegisters);
2762   if (Reg == ~0U && (CutOffInfo != CO_None)) {
2763     uint8_t CutOffEncountered = CutOffInfo & (CO_Depth | CO_Interf);
2764     if (CutOffEncountered == CO_Depth)
2765       Ctx.emitError("register allocation failed: maximum depth for recoloring "
2766                     "reached. Use -fexhaustive-register-search to skip "
2767                     "cutoffs");
2768     else if (CutOffEncountered == CO_Interf)
2769       Ctx.emitError("register allocation failed: maximum interference for "
2770                     "recoloring reached. Use -fexhaustive-register-search "
2771                     "to skip cutoffs");
2772     else if (CutOffEncountered == (CO_Depth | CO_Interf))
2773       Ctx.emitError("register allocation failed: maximum interference and "
2774                     "depth for recoloring reached. Use "
2775                     "-fexhaustive-register-search to skip cutoffs");
2776   }
2777   return Reg;
2778 }
2779 
2780 /// Using a CSR for the first time has a cost because it causes push|pop
2781 /// to be added to prologue|epilogue. Splitting a cold section of the live
2782 /// range can have lower cost than using the CSR for the first time;
2783 /// Spilling a live range in the cold path can have lower cost than using
2784 /// the CSR for the first time. Returns the physical register if we decide
2785 /// to use the CSR; otherwise return 0.
2786 unsigned RAGreedy::tryAssignCSRFirstTime(LiveInterval &VirtReg,
2787                                          AllocationOrder &Order,
2788                                          Register PhysReg,
2789                                          unsigned &CostPerUseLimit,
2790                                          SmallVectorImpl<Register> &NewVRegs) {
2791   if (getStage(VirtReg) == RS_Spill && VirtReg.isSpillable()) {
2792     // We choose spill over using the CSR for the first time if the spill cost
2793     // is lower than CSRCost.
2794     SA->analyze(&VirtReg);
2795     if (calcSpillCost() >= CSRCost)
2796       return PhysReg;
2797 
2798     // We are going to spill, set CostPerUseLimit to 1 to make sure that
2799     // we will not use a callee-saved register in tryEvict.
2800     CostPerUseLimit = 1;
2801     return 0;
2802   }
2803   if (getStage(VirtReg) < RS_Split) {
2804     // We choose pre-splitting over using the CSR for the first time if
2805     // the cost of splitting is lower than CSRCost.
2806     SA->analyze(&VirtReg);
2807     unsigned NumCands = 0;
2808     BlockFrequency BestCost = CSRCost; // Don't modify CSRCost.
2809     unsigned BestCand = calculateRegionSplitCost(VirtReg, Order, BestCost,
2810                                                  NumCands, true /*IgnoreCSR*/);
2811     if (BestCand == NoCand)
2812       // Use the CSR if we can't find a region split below CSRCost.
2813       return PhysReg;
2814 
2815     // Perform the actual pre-splitting.
2816     doRegionSplit(VirtReg, BestCand, false/*HasCompact*/, NewVRegs);
2817     return 0;
2818   }
2819   return PhysReg;
2820 }
2821 
2822 void RAGreedy::aboutToRemoveInterval(LiveInterval &LI) {
2823   // Do not keep invalid information around.
2824   SetOfBrokenHints.remove(&LI);
2825 }
2826 
2827 void RAGreedy::initializeCSRCost() {
2828   // We use the larger one out of the command-line option and the value report
2829   // by TRI.
2830   CSRCost = BlockFrequency(
2831       std::max((unsigned)CSRFirstTimeCost, TRI->getCSRFirstUseCost()));
2832   if (!CSRCost.getFrequency())
2833     return;
2834 
2835   // Raw cost is relative to Entry == 2^14; scale it appropriately.
2836   uint64_t ActualEntry = MBFI->getEntryFreq();
2837   if (!ActualEntry) {
2838     CSRCost = 0;
2839     return;
2840   }
2841   uint64_t FixedEntry = 1 << 14;
2842   if (ActualEntry < FixedEntry)
2843     CSRCost *= BranchProbability(ActualEntry, FixedEntry);
2844   else if (ActualEntry <= UINT32_MAX)
2845     // Invert the fraction and divide.
2846     CSRCost /= BranchProbability(FixedEntry, ActualEntry);
2847   else
2848     // Can't use BranchProbability in general, since it takes 32-bit numbers.
2849     CSRCost = CSRCost.getFrequency() * (ActualEntry / FixedEntry);
2850 }
2851 
2852 /// Collect the hint info for \p Reg.
2853 /// The results are stored into \p Out.
2854 /// \p Out is not cleared before being populated.
2855 void RAGreedy::collectHintInfo(unsigned Reg, HintsInfo &Out) {
2856   for (const MachineInstr &Instr : MRI->reg_nodbg_instructions(Reg)) {
2857     if (!Instr.isFullCopy())
2858       continue;
2859     // Look for the other end of the copy.
2860     Register OtherReg = Instr.getOperand(0).getReg();
2861     if (OtherReg == Reg) {
2862       OtherReg = Instr.getOperand(1).getReg();
2863       if (OtherReg == Reg)
2864         continue;
2865     }
2866     // Get the current assignment.
2867     Register OtherPhysReg = Register::isPhysicalRegister(OtherReg)
2868                                 ? OtherReg
2869                                 : VRM->getPhys(OtherReg);
2870     // Push the collected information.
2871     Out.push_back(HintInfo(MBFI->getBlockFreq(Instr.getParent()), OtherReg,
2872                            OtherPhysReg));
2873   }
2874 }
2875 
2876 /// Using the given \p List, compute the cost of the broken hints if
2877 /// \p PhysReg was used.
2878 /// \return The cost of \p List for \p PhysReg.
2879 BlockFrequency RAGreedy::getBrokenHintFreq(const HintsInfo &List,
2880                                            unsigned PhysReg) {
2881   BlockFrequency Cost = 0;
2882   for (const HintInfo &Info : List) {
2883     if (Info.PhysReg != PhysReg)
2884       Cost += Info.Freq;
2885   }
2886   return Cost;
2887 }
2888 
2889 /// Using the register assigned to \p VirtReg, try to recolor
2890 /// all the live ranges that are copy-related with \p VirtReg.
2891 /// The recoloring is then propagated to all the live-ranges that have
2892 /// been recolored and so on, until no more copies can be coalesced or
2893 /// it is not profitable.
2894 /// For a given live range, profitability is determined by the sum of the
2895 /// frequencies of the non-identity copies it would introduce with the old
2896 /// and new register.
2897 void RAGreedy::tryHintRecoloring(LiveInterval &VirtReg) {
2898   // We have a broken hint, check if it is possible to fix it by
2899   // reusing PhysReg for the copy-related live-ranges. Indeed, we evicted
2900   // some register and PhysReg may be available for the other live-ranges.
2901   SmallSet<unsigned, 4> Visited;
2902   SmallVector<unsigned, 2> RecoloringCandidates;
2903   HintsInfo Info;
2904   unsigned Reg = VirtReg.reg();
2905   Register PhysReg = VRM->getPhys(Reg);
2906   // Start the recoloring algorithm from the input live-interval, then
2907   // it will propagate to the ones that are copy-related with it.
2908   Visited.insert(Reg);
2909   RecoloringCandidates.push_back(Reg);
2910 
2911   LLVM_DEBUG(dbgs() << "Trying to reconcile hints for: " << printReg(Reg, TRI)
2912                     << '(' << printReg(PhysReg, TRI) << ")\n");
2913 
2914   do {
2915     Reg = RecoloringCandidates.pop_back_val();
2916 
2917     // We cannot recolor physical register.
2918     if (Register::isPhysicalRegister(Reg))
2919       continue;
2920 
2921     assert(VRM->hasPhys(Reg) && "We have unallocated variable!!");
2922 
2923     // Get the live interval mapped with this virtual register to be able
2924     // to check for the interference with the new color.
2925     LiveInterval &LI = LIS->getInterval(Reg);
2926     Register CurrPhys = VRM->getPhys(Reg);
2927     // Check that the new color matches the register class constraints and
2928     // that it is free for this live range.
2929     if (CurrPhys != PhysReg && (!MRI->getRegClass(Reg)->contains(PhysReg) ||
2930                                 Matrix->checkInterference(LI, PhysReg)))
2931       continue;
2932 
2933     LLVM_DEBUG(dbgs() << printReg(Reg, TRI) << '(' << printReg(CurrPhys, TRI)
2934                       << ") is recolorable.\n");
2935 
2936     // Gather the hint info.
2937     Info.clear();
2938     collectHintInfo(Reg, Info);
2939     // Check if recoloring the live-range will increase the cost of the
2940     // non-identity copies.
2941     if (CurrPhys != PhysReg) {
2942       LLVM_DEBUG(dbgs() << "Checking profitability:\n");
2943       BlockFrequency OldCopiesCost = getBrokenHintFreq(Info, CurrPhys);
2944       BlockFrequency NewCopiesCost = getBrokenHintFreq(Info, PhysReg);
2945       LLVM_DEBUG(dbgs() << "Old Cost: " << OldCopiesCost.getFrequency()
2946                         << "\nNew Cost: " << NewCopiesCost.getFrequency()
2947                         << '\n');
2948       if (OldCopiesCost < NewCopiesCost) {
2949         LLVM_DEBUG(dbgs() << "=> Not profitable.\n");
2950         continue;
2951       }
2952       // At this point, the cost is either cheaper or equal. If it is
2953       // equal, we consider this is profitable because it may expose
2954       // more recoloring opportunities.
2955       LLVM_DEBUG(dbgs() << "=> Profitable.\n");
2956       // Recolor the live-range.
2957       Matrix->unassign(LI);
2958       Matrix->assign(LI, PhysReg);
2959     }
2960     // Push all copy-related live-ranges to keep reconciling the broken
2961     // hints.
2962     for (const HintInfo &HI : Info) {
2963       if (Visited.insert(HI.Reg).second)
2964         RecoloringCandidates.push_back(HI.Reg);
2965     }
2966   } while (!RecoloringCandidates.empty());
2967 }
2968 
2969 /// Try to recolor broken hints.
2970 /// Broken hints may be repaired by recoloring when an evicted variable
2971 /// freed up a register for a larger live-range.
2972 /// Consider the following example:
2973 /// BB1:
2974 ///   a =
2975 ///   b =
2976 /// BB2:
2977 ///   ...
2978 ///   = b
2979 ///   = a
2980 /// Let us assume b gets split:
2981 /// BB1:
2982 ///   a =
2983 ///   b =
2984 /// BB2:
2985 ///   c = b
2986 ///   ...
2987 ///   d = c
2988 ///   = d
2989 ///   = a
2990 /// Because of how the allocation work, b, c, and d may be assigned different
2991 /// colors. Now, if a gets evicted later:
2992 /// BB1:
2993 ///   a =
2994 ///   st a, SpillSlot
2995 ///   b =
2996 /// BB2:
2997 ///   c = b
2998 ///   ...
2999 ///   d = c
3000 ///   = d
3001 ///   e = ld SpillSlot
3002 ///   = e
3003 /// This is likely that we can assign the same register for b, c, and d,
3004 /// getting rid of 2 copies.
3005 void RAGreedy::tryHintsRecoloring() {
3006   for (LiveInterval *LI : SetOfBrokenHints) {
3007     assert(Register::isVirtualRegister(LI->reg()) &&
3008            "Recoloring is possible only for virtual registers");
3009     // Some dead defs may be around (e.g., because of debug uses).
3010     // Ignore those.
3011     if (!VRM->hasPhys(LI->reg()))
3012       continue;
3013     tryHintRecoloring(*LI);
3014   }
3015 }
3016 
3017 Register RAGreedy::selectOrSplitImpl(LiveInterval &VirtReg,
3018                                      SmallVectorImpl<Register> &NewVRegs,
3019                                      SmallVirtRegSet &FixedRegisters,
3020                                      unsigned Depth) {
3021   unsigned CostPerUseLimit = ~0u;
3022   // First try assigning a free register.
3023   AllocationOrder Order(VirtReg.reg(), *VRM, RegClassInfo, Matrix);
3024   if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs, FixedRegisters)) {
3025     // If VirtReg got an assignment, the eviction info is no longre relevant.
3026     LastEvicted.clearEvicteeInfo(VirtReg.reg());
3027     // When NewVRegs is not empty, we may have made decisions such as evicting
3028     // a virtual register, go with the earlier decisions and use the physical
3029     // register.
3030     if (CSRCost.getFrequency() && isUnusedCalleeSavedReg(PhysReg) &&
3031         NewVRegs.empty()) {
3032       Register CSRReg = tryAssignCSRFirstTime(VirtReg, Order, PhysReg,
3033                                               CostPerUseLimit, NewVRegs);
3034       if (CSRReg || !NewVRegs.empty())
3035         // Return now if we decide to use a CSR or create new vregs due to
3036         // pre-splitting.
3037         return CSRReg;
3038     } else
3039       return PhysReg;
3040   }
3041 
3042   LiveRangeStage Stage = getStage(VirtReg);
3043   LLVM_DEBUG(dbgs() << StageName[Stage] << " Cascade "
3044                     << ExtraRegInfo[VirtReg.reg()].Cascade << '\n');
3045 
3046   // Try to evict a less worthy live range, but only for ranges from the primary
3047   // queue. The RS_Split ranges already failed to do this, and they should not
3048   // get a second chance until they have been split.
3049   if (Stage != RS_Split)
3050     if (Register PhysReg =
3051             tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit,
3052                      FixedRegisters)) {
3053       Register Hint = MRI->getSimpleHint(VirtReg.reg());
3054       // If VirtReg has a hint and that hint is broken record this
3055       // virtual register as a recoloring candidate for broken hint.
3056       // Indeed, since we evicted a variable in its neighborhood it is
3057       // likely we can at least partially recolor some of the
3058       // copy-related live-ranges.
3059       if (Hint && Hint != PhysReg)
3060         SetOfBrokenHints.insert(&VirtReg);
3061       // If VirtReg eviction someone, the eviction info for it as an evictee is
3062       // no longre relevant.
3063       LastEvicted.clearEvicteeInfo(VirtReg.reg());
3064       return PhysReg;
3065     }
3066 
3067   assert((NewVRegs.empty() || Depth) && "Cannot append to existing NewVRegs");
3068 
3069   // The first time we see a live range, don't try to split or spill.
3070   // Wait until the second time, when all smaller ranges have been allocated.
3071   // This gives a better picture of the interference to split around.
3072   if (Stage < RS_Split) {
3073     setStage(VirtReg, RS_Split);
3074     LLVM_DEBUG(dbgs() << "wait for second round\n");
3075     NewVRegs.push_back(VirtReg.reg());
3076     return 0;
3077   }
3078 
3079   if (Stage < RS_Spill) {
3080     // Try splitting VirtReg or interferences.
3081     unsigned NewVRegSizeBefore = NewVRegs.size();
3082     Register PhysReg = trySplit(VirtReg, Order, NewVRegs, FixedRegisters);
3083     if (PhysReg || (NewVRegs.size() - NewVRegSizeBefore)) {
3084       // If VirtReg got split, the eviction info is no longer relevant.
3085       LastEvicted.clearEvicteeInfo(VirtReg.reg());
3086       return PhysReg;
3087     }
3088   }
3089 
3090   // If we couldn't allocate a register from spilling, there is probably some
3091   // invalid inline assembly. The base class will report it.
3092   if (Stage >= RS_Done || !VirtReg.isSpillable())
3093     return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters,
3094                                    Depth);
3095 
3096   // Finally spill VirtReg itself.
3097   if ((EnableDeferredSpilling ||
3098        TRI->shouldUseDeferredSpillingForVirtReg(*MF, VirtReg)) &&
3099       getStage(VirtReg) < RS_Memory) {
3100     // TODO: This is experimental and in particular, we do not model
3101     // the live range splitting done by spilling correctly.
3102     // We would need a deep integration with the spiller to do the
3103     // right thing here. Anyway, that is still good for early testing.
3104     setStage(VirtReg, RS_Memory);
3105     LLVM_DEBUG(dbgs() << "Do as if this register is in memory\n");
3106     NewVRegs.push_back(VirtReg.reg());
3107   } else {
3108     NamedRegionTimer T("spill", "Spiller", TimerGroupName,
3109                        TimerGroupDescription, TimePassesIsEnabled);
3110     LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
3111     spiller().spill(LRE);
3112     setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
3113 
3114     // Tell LiveDebugVariables about the new ranges. Ranges not being covered by
3115     // the new regs are kept in LDV (still mapping to the old register), until
3116     // we rewrite spilled locations in LDV at a later stage.
3117     DebugVars->splitRegister(VirtReg.reg(), LRE.regs(), *LIS);
3118 
3119     if (VerifyEnabled)
3120       MF->verify(this, "After spilling");
3121   }
3122 
3123   // The live virtual register requesting allocation was spilled, so tell
3124   // the caller not to allocate anything during this round.
3125   return 0;
3126 }
3127 
3128 void RAGreedy::reportNumberOfSplillsReloads(MachineLoop *L, unsigned &Reloads,
3129                                             unsigned &FoldedReloads,
3130                                             unsigned &Spills,
3131                                             unsigned &FoldedSpills) {
3132   Reloads = 0;
3133   FoldedReloads = 0;
3134   Spills = 0;
3135   FoldedSpills = 0;
3136 
3137   // Sum up the spill and reloads in subloops.
3138   for (MachineLoop *SubLoop : *L) {
3139     unsigned SubReloads;
3140     unsigned SubFoldedReloads;
3141     unsigned SubSpills;
3142     unsigned SubFoldedSpills;
3143 
3144     reportNumberOfSplillsReloads(SubLoop, SubReloads, SubFoldedReloads,
3145                                  SubSpills, SubFoldedSpills);
3146     Reloads += SubReloads;
3147     FoldedReloads += SubFoldedReloads;
3148     Spills += SubSpills;
3149     FoldedSpills += SubFoldedSpills;
3150   }
3151 
3152   const MachineFrameInfo &MFI = MF->getFrameInfo();
3153   int FI;
3154 
3155   for (MachineBasicBlock *MBB : L->getBlocks())
3156     // Handle blocks that were not included in subloops.
3157     if (Loops->getLoopFor(MBB) == L)
3158       for (MachineInstr &MI : *MBB) {
3159         SmallVector<const MachineMemOperand *, 2> Accesses;
3160         auto isSpillSlotAccess = [&MFI](const MachineMemOperand *A) {
3161           return MFI.isSpillSlotObjectIndex(
3162               cast<FixedStackPseudoSourceValue>(A->getPseudoValue())
3163                   ->getFrameIndex());
3164         };
3165 
3166         if (TII->isLoadFromStackSlot(MI, FI) && MFI.isSpillSlotObjectIndex(FI))
3167           ++Reloads;
3168         else if (TII->hasLoadFromStackSlot(MI, Accesses) &&
3169                  llvm::any_of(Accesses, isSpillSlotAccess))
3170           ++FoldedReloads;
3171         else if (TII->isStoreToStackSlot(MI, FI) &&
3172                  MFI.isSpillSlotObjectIndex(FI))
3173           ++Spills;
3174         else if (TII->hasStoreToStackSlot(MI, Accesses) &&
3175                  llvm::any_of(Accesses, isSpillSlotAccess))
3176           ++FoldedSpills;
3177       }
3178 
3179   if (Reloads || FoldedReloads || Spills || FoldedSpills) {
3180     using namespace ore;
3181 
3182     ORE->emit([&]() {
3183       MachineOptimizationRemarkMissed R(DEBUG_TYPE, "LoopSpillReload",
3184                                         L->getStartLoc(), L->getHeader());
3185       if (Spills)
3186         R << NV("NumSpills", Spills) << " spills ";
3187       if (FoldedSpills)
3188         R << NV("NumFoldedSpills", FoldedSpills) << " folded spills ";
3189       if (Reloads)
3190         R << NV("NumReloads", Reloads) << " reloads ";
3191       if (FoldedReloads)
3192         R << NV("NumFoldedReloads", FoldedReloads) << " folded reloads ";
3193       R << "generated in loop";
3194       return R;
3195     });
3196   }
3197 }
3198 
3199 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
3200   LLVM_DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
3201                     << "********** Function: " << mf.getName() << '\n');
3202 
3203   MF = &mf;
3204   TRI = MF->getSubtarget().getRegisterInfo();
3205   TII = MF->getSubtarget().getInstrInfo();
3206   RCI.runOnMachineFunction(mf);
3207 
3208   EnableLocalReassign = EnableLocalReassignment ||
3209                         MF->getSubtarget().enableRALocalReassignment(
3210                             MF->getTarget().getOptLevel());
3211 
3212   EnableAdvancedRASplitCost =
3213       ConsiderLocalIntervalCost.getNumOccurrences()
3214           ? ConsiderLocalIntervalCost
3215           : MF->getSubtarget().enableAdvancedRASplitCost();
3216 
3217   if (VerifyEnabled)
3218     MF->verify(this, "Before greedy register allocator");
3219 
3220   RegAllocBase::init(getAnalysis<VirtRegMap>(),
3221                      getAnalysis<LiveIntervals>(),
3222                      getAnalysis<LiveRegMatrix>());
3223   Indexes = &getAnalysis<SlotIndexes>();
3224   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
3225   DomTree = &getAnalysis<MachineDominatorTree>();
3226   ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
3227   SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
3228   Loops = &getAnalysis<MachineLoopInfo>();
3229   Bundles = &getAnalysis<EdgeBundles>();
3230   SpillPlacer = &getAnalysis<SpillPlacement>();
3231   DebugVars = &getAnalysis<LiveDebugVariables>();
3232   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3233 
3234   initializeCSRCost();
3235 
3236   calculateSpillWeightsAndHints(*LIS, mf, VRM, *Loops, *MBFI);
3237 
3238   LLVM_DEBUG(LIS->dump());
3239 
3240   SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
3241   SE.reset(new SplitEditor(*SA, *AA, *LIS, *VRM, *DomTree, *MBFI));
3242   ExtraRegInfo.clear();
3243   ExtraRegInfo.resize(MRI->getNumVirtRegs());
3244   NextCascade = 1;
3245   IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
3246   GlobalCand.resize(32);  // This will grow as needed.
3247   SetOfBrokenHints.clear();
3248   LastEvicted.clear();
3249 
3250   allocatePhysRegs();
3251   tryHintsRecoloring();
3252   postOptimization();
3253   reportNumberOfSplillsReloads();
3254 
3255   releaseMemory();
3256   return true;
3257 }
3258