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