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