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