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