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