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