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