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