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