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