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 "RegAllocGreedy.h"
15 #include "AllocationOrder.h"
16 #include "InterferenceCache.h"
17 #include "LiveDebugVariables.h"
18 #include "RegAllocBase.h"
19 #include "RegAllocEvictionAdvisor.h"
20 #include "SpillPlacement.h"
21 #include "SplitKit.h"
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/ADT/BitVector.h"
24 #include "llvm/ADT/IndexedMap.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/DebugInfoMetadata.h"
61 #include "llvm/IR/Function.h"
62 #include "llvm/IR/LLVMContext.h"
63 #include "llvm/InitializePasses.h"
64 #include "llvm/MC/MCRegisterInfo.h"
65 #include "llvm/Pass.h"
66 #include "llvm/Support/BlockFrequency.h"
67 #include "llvm/Support/BranchProbability.h"
68 #include "llvm/Support/CommandLine.h"
69 #include "llvm/Support/Debug.h"
70 #include "llvm/Support/MathExtras.h"
71 #include "llvm/Support/Timer.h"
72 #include "llvm/Support/raw_ostream.h"
73 #include <algorithm>
74 #include <cassert>
75 #include <cstdint>
76 #include <utility>
77 
78 using namespace llvm;
79 
80 #define DEBUG_TYPE "regalloc"
81 
82 STATISTIC(NumGlobalSplits, "Number of split global live ranges");
83 STATISTIC(NumLocalSplits,  "Number of split local live ranges");
84 STATISTIC(NumEvicted,      "Number of interferences evicted");
85 
86 static cl::opt<SplitEditor::ComplementSpillMode> SplitSpillMode(
87     "split-spill-mode", cl::Hidden,
88     cl::desc("Spill mode for splitting live ranges"),
89     cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
90                clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
91                clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed")),
92     cl::init(SplitEditor::SM_Speed));
93 
94 static cl::opt<unsigned>
95 LastChanceRecoloringMaxDepth("lcr-max-depth", cl::Hidden,
96                              cl::desc("Last chance recoloring max depth"),
97                              cl::init(5));
98 
99 static cl::opt<unsigned> LastChanceRecoloringMaxInterference(
100     "lcr-max-interf", cl::Hidden,
101     cl::desc("Last chance recoloring maximum number of considered"
102              " interference at a time"),
103     cl::init(8));
104 
105 static cl::opt<bool> ExhaustiveSearch(
106     "exhaustive-register-search", cl::NotHidden,
107     cl::desc("Exhaustive Search for registers bypassing the depth "
108              "and interference cutoffs of last chance recoloring"),
109     cl::Hidden);
110 
111 static cl::opt<bool> EnableDeferredSpilling(
112     "enable-deferred-spilling", cl::Hidden,
113     cl::desc("Instead of spilling a variable right away, defer the actual "
114              "code insertion to the end of the allocation. That way the "
115              "allocator might still find a suitable coloring for this "
116              "variable because of other evicted variables."),
117     cl::init(false));
118 
119 // FIXME: Find a good default for this flag and remove the flag.
120 static cl::opt<unsigned>
121 CSRFirstTimeCost("regalloc-csr-first-time-cost",
122               cl::desc("Cost for first time use of callee-saved register."),
123               cl::init(0), cl::Hidden);
124 
125 static cl::opt<unsigned long> GrowRegionComplexityBudget(
126     "grow-region-complexity-budget",
127     cl::desc("growRegion() does not scale with the number of BB edges, so "
128              "limit its budget and bail out once we reach the limit."),
129     cl::init(10000), cl::Hidden);
130 
131 static cl::opt<bool> GreedyRegClassPriorityTrumpsGlobalness(
132     "greedy-regclass-priority-trumps-globalness",
133     cl::desc("Change the greedy register allocator's live range priority "
134              "calculation to make the AllocationPriority of the register class "
135              "more important then whether the range is global"),
136     cl::Hidden);
137 
138 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
139                                        createGreedyRegisterAllocator);
140 
141 char RAGreedy::ID = 0;
142 char &llvm::RAGreedyID = RAGreedy::ID;
143 
144 INITIALIZE_PASS_BEGIN(RAGreedy, "greedy",
145                 "Greedy Register Allocator", false, false)
146 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
147 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
148 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
149 INITIALIZE_PASS_DEPENDENCY(RegisterCoalescer)
150 INITIALIZE_PASS_DEPENDENCY(MachineScheduler)
151 INITIALIZE_PASS_DEPENDENCY(LiveStacks)
152 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
153 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
154 INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
155 INITIALIZE_PASS_DEPENDENCY(LiveRegMatrix)
156 INITIALIZE_PASS_DEPENDENCY(EdgeBundles)
157 INITIALIZE_PASS_DEPENDENCY(SpillPlacement)
158 INITIALIZE_PASS_DEPENDENCY(MachineOptimizationRemarkEmitterPass)
159 INITIALIZE_PASS_DEPENDENCY(RegAllocEvictionAdvisorAnalysis)
160 INITIALIZE_PASS_END(RAGreedy, "greedy",
161                 "Greedy Register Allocator", false, false)
162 
163 #ifndef NDEBUG
164 const char *const RAGreedy::StageName[] = {
165     "RS_New",
166     "RS_Assign",
167     "RS_Split",
168     "RS_Split2",
169     "RS_Spill",
170     "RS_Memory",
171     "RS_Done"
172 };
173 #endif
174 
175 // Hysteresis to use when comparing floats.
176 // This helps stabilize decisions based on float comparisons.
177 const float Hysteresis = (2007 / 2048.0f); // 0.97998046875
178 
179 FunctionPass* llvm::createGreedyRegisterAllocator() {
180   return new RAGreedy();
181 }
182 
183 namespace llvm {
184 FunctionPass* createGreedyRegisterAllocator(
185   std::function<bool(const TargetRegisterInfo &TRI,
186                      const TargetRegisterClass &RC)> Ftor);
187 
188 }
189 
190 FunctionPass* llvm::createGreedyRegisterAllocator(
191   std::function<bool(const TargetRegisterInfo &TRI,
192                      const TargetRegisterClass &RC)> Ftor) {
193   return new RAGreedy(Ftor);
194 }
195 
196 RAGreedy::RAGreedy(RegClassFilterFunc F):
197   MachineFunctionPass(ID),
198   RegAllocBase(F) {
199 }
200 
201 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
202   AU.setPreservesCFG();
203   AU.addRequired<MachineBlockFrequencyInfo>();
204   AU.addPreserved<MachineBlockFrequencyInfo>();
205   AU.addRequired<AAResultsWrapperPass>();
206   AU.addPreserved<AAResultsWrapperPass>();
207   AU.addRequired<LiveIntervals>();
208   AU.addPreserved<LiveIntervals>();
209   AU.addRequired<SlotIndexes>();
210   AU.addPreserved<SlotIndexes>();
211   AU.addRequired<LiveDebugVariables>();
212   AU.addPreserved<LiveDebugVariables>();
213   AU.addRequired<LiveStacks>();
214   AU.addPreserved<LiveStacks>();
215   AU.addRequired<MachineDominatorTree>();
216   AU.addPreserved<MachineDominatorTree>();
217   AU.addRequired<MachineLoopInfo>();
218   AU.addPreserved<MachineLoopInfo>();
219   AU.addRequired<VirtRegMap>();
220   AU.addPreserved<VirtRegMap>();
221   AU.addRequired<LiveRegMatrix>();
222   AU.addPreserved<LiveRegMatrix>();
223   AU.addRequired<EdgeBundles>();
224   AU.addRequired<SpillPlacement>();
225   AU.addRequired<MachineOptimizationRemarkEmitterPass>();
226   AU.addRequired<RegAllocEvictionAdvisorAnalysis>();
227   MachineFunctionPass::getAnalysisUsage(AU);
228 }
229 
230 //===----------------------------------------------------------------------===//
231 //                     LiveRangeEdit delegate methods
232 //===----------------------------------------------------------------------===//
233 
234 bool RAGreedy::LRE_CanEraseVirtReg(Register VirtReg) {
235   LiveInterval &LI = LIS->getInterval(VirtReg);
236   if (VRM->hasPhys(VirtReg)) {
237     Matrix->unassign(LI);
238     aboutToRemoveInterval(LI);
239     return true;
240   }
241   // Unassigned virtreg is probably in the priority queue.
242   // RegAllocBase will erase it after dequeueing.
243   // Nonetheless, clear the live-range so that the debug
244   // dump will show the right state for that VirtReg.
245   LI.clear();
246   return false;
247 }
248 
249 void RAGreedy::LRE_WillShrinkVirtReg(Register VirtReg) {
250   if (!VRM->hasPhys(VirtReg))
251     return;
252 
253   // Register is assigned, put it back on the queue for reassignment.
254   LiveInterval &LI = LIS->getInterval(VirtReg);
255   Matrix->unassign(LI);
256   RegAllocBase::enqueue(&LI);
257 }
258 
259 void RAGreedy::LRE_DidCloneVirtReg(Register New, Register Old) {
260   ExtraInfo->LRE_DidCloneVirtReg(New, Old);
261 }
262 
263 void RAGreedy::ExtraRegInfo::LRE_DidCloneVirtReg(Register New, Register Old) {
264   // Cloning a register we haven't even heard about yet?  Just ignore it.
265   if (!Info.inBounds(Old))
266     return;
267 
268   // LRE may clone a virtual register because dead code elimination causes it to
269   // be split into connected components. The new components are much smaller
270   // than the original, so they should get a new chance at being assigned.
271   // same stage as the parent.
272   Info[Old].Stage = RS_Assign;
273   Info.grow(New.id());
274   Info[New] = Info[Old];
275 }
276 
277 void RAGreedy::releaseMemory() {
278   SpillerInstance.reset();
279   GlobalCand.clear();
280 }
281 
282 void RAGreedy::enqueueImpl(const LiveInterval *LI) { enqueue(Queue, LI); }
283 
284 void RAGreedy::enqueue(PQueue &CurQueue, const LiveInterval *LI) {
285   // Prioritize live ranges by size, assigning larger ranges first.
286   // The queue holds (size, reg) pairs.
287   const unsigned Size = LI->getSize();
288   const Register Reg = LI->reg();
289   assert(Reg.isVirtual() && "Can only enqueue virtual registers");
290   unsigned Prio;
291 
292   auto Stage = ExtraInfo->getOrInitStage(Reg);
293   if (Stage == RS_New) {
294     Stage = RS_Assign;
295     ExtraInfo->setStage(Reg, Stage);
296   }
297   if (Stage == RS_Split) {
298     // Unsplit ranges that couldn't be allocated immediately are deferred until
299     // everything else has been allocated.
300     Prio = Size;
301   } else if (Stage == RS_Memory) {
302     // Memory operand should be considered last.
303     // Change the priority such that Memory operand are assigned in
304     // the reverse order that they came in.
305     // TODO: Make this a member variable and probably do something about hints.
306     static unsigned MemOp = 0;
307     Prio = MemOp++;
308   } else {
309     // Giant live ranges fall back to the global assignment heuristic, which
310     // prevents excessive spilling in pathological cases.
311     bool ReverseLocal = TRI->reverseLocalAssignment();
312     const TargetRegisterClass &RC = *MRI->getRegClass(Reg);
313     bool ForceGlobal =
314         !ReverseLocal && (Size / SlotIndex::InstrDist) >
315                              (2 * RegClassInfo.getNumAllocatableRegs(&RC));
316     unsigned GlobalBit = 0;
317 
318     if (Stage == RS_Assign && !ForceGlobal && !LI->empty() &&
319         LIS->intervalIsInOneMBB(*LI)) {
320       // Allocate original local ranges in linear instruction order. Since they
321       // are singly defined, this produces optimal coloring in the absence of
322       // global interference and other constraints.
323       if (!ReverseLocal)
324         Prio = LI->beginIndex().getInstrDistance(Indexes->getLastIndex());
325       else {
326         // Allocating bottom up may allow many short LRGs to be assigned first
327         // to one of the cheap registers. This could be much faster for very
328         // large blocks on targets with many physical registers.
329         Prio = Indexes->getZeroIndex().getInstrDistance(LI->endIndex());
330       }
331     } else {
332       // Allocate global and split ranges in long->short order. Long ranges that
333       // don't fit should be spilled (or split) ASAP so they don't create
334       // interference.  Mark a bit to prioritize global above local ranges.
335       Prio = Size;
336       GlobalBit = 1;
337     }
338     if (RegClassPriorityTrumpsGlobalness)
339       Prio |= RC.AllocationPriority << 25 | GlobalBit << 24;
340     else
341       Prio |= GlobalBit << 29 | RC.AllocationPriority << 24;
342 
343     // Mark a higher bit to prioritize global and local above RS_Split.
344     Prio |= (1u << 31);
345 
346     // Boost ranges that have a physical register hint.
347     if (VRM->hasKnownPreference(Reg))
348       Prio |= (1u << 30);
349   }
350   // The virtual register number is a tie breaker for same-sized ranges.
351   // Give lower vreg numbers higher priority to assign them first.
352   CurQueue.push(std::make_pair(Prio, ~Reg));
353 }
354 
355 const LiveInterval *RAGreedy::dequeue() { return dequeue(Queue); }
356 
357 const LiveInterval *RAGreedy::dequeue(PQueue &CurQueue) {
358   if (CurQueue.empty())
359     return nullptr;
360   LiveInterval *LI = &LIS->getInterval(~CurQueue.top().second);
361   CurQueue.pop();
362   return LI;
363 }
364 
365 //===----------------------------------------------------------------------===//
366 //                            Direct Assignment
367 //===----------------------------------------------------------------------===//
368 
369 /// tryAssign - Try to assign VirtReg to an available register.
370 MCRegister RAGreedy::tryAssign(const LiveInterval &VirtReg,
371                                AllocationOrder &Order,
372                                SmallVectorImpl<Register> &NewVRegs,
373                                const SmallVirtRegSet &FixedRegisters) {
374   MCRegister PhysReg;
375   for (auto I = Order.begin(), E = Order.end(); I != E && !PhysReg; ++I) {
376     assert(*I);
377     if (!Matrix->checkInterference(VirtReg, *I)) {
378       if (I.isHint())
379         return *I;
380       else
381         PhysReg = *I;
382     }
383   }
384   if (!PhysReg.isValid())
385     return PhysReg;
386 
387   // PhysReg is available, but there may be a better choice.
388 
389   // If we missed a simple hint, try to cheaply evict interference from the
390   // preferred register.
391   if (Register Hint = MRI->getSimpleHint(VirtReg.reg()))
392     if (Order.isHint(Hint)) {
393       MCRegister PhysHint = Hint.asMCReg();
394       LLVM_DEBUG(dbgs() << "missed hint " << printReg(PhysHint, TRI) << '\n');
395 
396       if (EvictAdvisor->canEvictHintInterference(VirtReg, PhysHint,
397                                                  FixedRegisters)) {
398         evictInterference(VirtReg, PhysHint, NewVRegs);
399         return PhysHint;
400       }
401       // Record the missed hint, we may be able to recover
402       // at the end if the surrounding allocation changed.
403       SetOfBrokenHints.insert(&VirtReg);
404     }
405 
406   // Try to evict interference from a cheaper alternative.
407   uint8_t Cost = RegCosts[PhysReg];
408 
409   // Most registers have 0 additional cost.
410   if (!Cost)
411     return PhysReg;
412 
413   LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << " is available at cost "
414                     << (unsigned)Cost << '\n');
415   MCRegister CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost, FixedRegisters);
416   return CheapReg ? CheapReg : PhysReg;
417 }
418 
419 //===----------------------------------------------------------------------===//
420 //                         Interference eviction
421 //===----------------------------------------------------------------------===//
422 
423 Register RegAllocEvictionAdvisor::canReassign(const LiveInterval &VirtReg,
424                                               Register PrevReg) const {
425   auto Order =
426       AllocationOrder::create(VirtReg.reg(), *VRM, RegClassInfo, Matrix);
427   MCRegister PhysReg;
428   for (auto I = Order.begin(), E = Order.end(); I != E && !PhysReg; ++I) {
429     if ((*I).id() == PrevReg.id())
430       continue;
431 
432     MCRegUnitIterator Units(*I, TRI);
433     for (; Units.isValid(); ++Units) {
434       // Instantiate a "subquery", not to be confused with the Queries array.
435       LiveIntervalUnion::Query subQ(VirtReg, Matrix->getLiveUnions()[*Units]);
436       if (subQ.checkInterference())
437         break;
438     }
439     // If no units have interference, break out with the current PhysReg.
440     if (!Units.isValid())
441       PhysReg = *I;
442   }
443   if (PhysReg)
444     LLVM_DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
445                       << printReg(PrevReg, TRI) << " to "
446                       << printReg(PhysReg, TRI) << '\n');
447   return PhysReg;
448 }
449 
450 /// evictInterference - Evict any interferring registers that prevent VirtReg
451 /// from being assigned to Physreg. This assumes that canEvictInterference
452 /// returned true.
453 void RAGreedy::evictInterference(const LiveInterval &VirtReg,
454                                  MCRegister PhysReg,
455                                  SmallVectorImpl<Register> &NewVRegs) {
456   // Make sure that VirtReg has a cascade number, and assign that cascade
457   // number to every evicted register. These live ranges than then only be
458   // evicted by a newer cascade, preventing infinite loops.
459   unsigned Cascade = ExtraInfo->getOrAssignNewCascade(VirtReg.reg());
460 
461   LLVM_DEBUG(dbgs() << "evicting " << printReg(PhysReg, TRI)
462                     << " interference: Cascade " << Cascade << '\n');
463 
464   // Collect all interfering virtregs first.
465   SmallVector<const LiveInterval *, 8> Intfs;
466   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
467     LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
468     // We usually have the interfering VRegs cached so collectInterferingVRegs()
469     // should be fast, we may need to recalculate if when different physregs
470     // overlap the same register unit so we had different SubRanges queried
471     // against it.
472     ArrayRef<const LiveInterval *> IVR = Q.interferingVRegs();
473     Intfs.append(IVR.begin(), IVR.end());
474   }
475 
476   // Evict them second. This will invalidate the queries.
477   for (const LiveInterval *Intf : Intfs) {
478     // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
479     if (!VRM->hasPhys(Intf->reg()))
480       continue;
481 
482     LastEvicted.addEviction(PhysReg, VirtReg.reg(), Intf->reg());
483 
484     Matrix->unassign(*Intf);
485     assert((ExtraInfo->getCascade(Intf->reg()) < Cascade ||
486             VirtReg.isSpillable() < Intf->isSpillable()) &&
487            "Cannot decrease cascade number, illegal eviction");
488     ExtraInfo->setCascade(Intf->reg(), Cascade);
489     ++NumEvicted;
490     NewVRegs.push_back(Intf->reg());
491   }
492 }
493 
494 /// Returns true if the given \p PhysReg is a callee saved register and has not
495 /// been used for allocation yet.
496 bool RegAllocEvictionAdvisor::isUnusedCalleeSavedReg(MCRegister PhysReg) const {
497   MCRegister CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg);
498   if (!CSR)
499     return false;
500 
501   return !Matrix->isPhysRegUsed(PhysReg);
502 }
503 
504 Optional<unsigned>
505 RegAllocEvictionAdvisor::getOrderLimit(const LiveInterval &VirtReg,
506                                        const AllocationOrder &Order,
507                                        unsigned CostPerUseLimit) const {
508   unsigned OrderLimit = Order.getOrder().size();
509 
510   if (CostPerUseLimit < uint8_t(~0u)) {
511     // Check of any registers in RC are below CostPerUseLimit.
512     const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg());
513     uint8_t MinCost = RegClassInfo.getMinCost(RC);
514     if (MinCost >= CostPerUseLimit) {
515       LLVM_DEBUG(dbgs() << TRI->getRegClassName(RC) << " minimum cost = "
516                         << MinCost << ", no cheaper registers to be found.\n");
517       return None;
518     }
519 
520     // It is normal for register classes to have a long tail of registers with
521     // the same cost. We don't need to look at them if they're too expensive.
522     if (RegCosts[Order.getOrder().back()] >= CostPerUseLimit) {
523       OrderLimit = RegClassInfo.getLastCostChange(RC);
524       LLVM_DEBUG(dbgs() << "Only trying the first " << OrderLimit
525                         << " regs.\n");
526     }
527   }
528   return OrderLimit;
529 }
530 
531 bool RegAllocEvictionAdvisor::canAllocatePhysReg(unsigned CostPerUseLimit,
532                                                  MCRegister PhysReg) const {
533   if (RegCosts[PhysReg] >= CostPerUseLimit)
534     return false;
535   // The first use of a callee-saved register in a function has cost 1.
536   // Don't start using a CSR when the CostPerUseLimit is low.
537   if (CostPerUseLimit == 1 && isUnusedCalleeSavedReg(PhysReg)) {
538     LLVM_DEBUG(
539         dbgs() << printReg(PhysReg, TRI) << " would clobber CSR "
540                << printReg(RegClassInfo.getLastCalleeSavedAlias(PhysReg), TRI)
541                << '\n');
542     return false;
543   }
544   return true;
545 }
546 
547 /// tryEvict - Try to evict all interferences for a physreg.
548 /// @param  VirtReg Currently unassigned virtual register.
549 /// @param  Order   Physregs to try.
550 /// @return         Physreg to assign VirtReg, or 0.
551 MCRegister RAGreedy::tryEvict(const LiveInterval &VirtReg,
552                               AllocationOrder &Order,
553                               SmallVectorImpl<Register> &NewVRegs,
554                               uint8_t CostPerUseLimit,
555                               const SmallVirtRegSet &FixedRegisters) {
556   NamedRegionTimer T("evict", "Evict", TimerGroupName, TimerGroupDescription,
557                      TimePassesIsEnabled);
558 
559   MCRegister BestPhys = EvictAdvisor->tryFindEvictionCandidate(
560       VirtReg, Order, CostPerUseLimit, FixedRegisters);
561   if (BestPhys.isValid())
562     evictInterference(VirtReg, BestPhys, NewVRegs);
563   return BestPhys;
564 }
565 
566 //===----------------------------------------------------------------------===//
567 //                              Region Splitting
568 //===----------------------------------------------------------------------===//
569 
570 /// addSplitConstraints - Fill out the SplitConstraints vector based on the
571 /// interference pattern in Physreg and its aliases. Add the constraints to
572 /// SpillPlacement and return the static cost of this split in Cost, assuming
573 /// that all preferences in SplitConstraints are met.
574 /// Return false if there are no bundles with positive bias.
575 bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
576                                    BlockFrequency &Cost) {
577   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
578 
579   // Reset interference dependent info.
580   SplitConstraints.resize(UseBlocks.size());
581   BlockFrequency StaticCost = 0;
582   for (unsigned I = 0; I != UseBlocks.size(); ++I) {
583     const SplitAnalysis::BlockInfo &BI = UseBlocks[I];
584     SpillPlacement::BlockConstraint &BC = SplitConstraints[I];
585 
586     BC.Number = BI.MBB->getNumber();
587     Intf.moveToBlock(BC.Number);
588     BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
589     BC.Exit = (BI.LiveOut &&
590                !LIS->getInstructionFromIndex(BI.LastInstr)->isImplicitDef())
591                   ? SpillPlacement::PrefReg
592                   : SpillPlacement::DontCare;
593     BC.ChangesValue = BI.FirstDef.isValid();
594 
595     if (!Intf.hasInterference())
596       continue;
597 
598     // Number of spill code instructions to insert.
599     unsigned Ins = 0;
600 
601     // Interference for the live-in value.
602     if (BI.LiveIn) {
603       if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number)) {
604         BC.Entry = SpillPlacement::MustSpill;
605         ++Ins;
606       } else if (Intf.first() < BI.FirstInstr) {
607         BC.Entry = SpillPlacement::PrefSpill;
608         ++Ins;
609       } else if (Intf.first() < BI.LastInstr) {
610         ++Ins;
611       }
612 
613       // Abort if the spill cannot be inserted at the MBB' start
614       if (((BC.Entry == SpillPlacement::MustSpill) ||
615            (BC.Entry == SpillPlacement::PrefSpill)) &&
616           SlotIndex::isEarlierInstr(BI.FirstInstr,
617                                     SA->getFirstSplitPoint(BC.Number)))
618         return false;
619     }
620 
621     // Interference for the live-out value.
622     if (BI.LiveOut) {
623       if (Intf.last() >= SA->getLastSplitPoint(BC.Number)) {
624         BC.Exit = SpillPlacement::MustSpill;
625         ++Ins;
626       } else if (Intf.last() > BI.LastInstr) {
627         BC.Exit = SpillPlacement::PrefSpill;
628         ++Ins;
629       } else if (Intf.last() > BI.FirstInstr) {
630         ++Ins;
631       }
632     }
633 
634     // Accumulate the total frequency of inserted spill code.
635     while (Ins--)
636       StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
637   }
638   Cost = StaticCost;
639 
640   // Add constraints for use-blocks. Note that these are the only constraints
641   // that may add a positive bias, it is downhill from here.
642   SpillPlacer->addConstraints(SplitConstraints);
643   return SpillPlacer->scanActiveBundles();
644 }
645 
646 /// addThroughConstraints - Add constraints and links to SpillPlacer from the
647 /// live-through blocks in Blocks.
648 bool RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
649                                      ArrayRef<unsigned> Blocks) {
650   const unsigned GroupSize = 8;
651   SpillPlacement::BlockConstraint BCS[GroupSize];
652   unsigned TBS[GroupSize];
653   unsigned B = 0, T = 0;
654 
655   for (unsigned Number : Blocks) {
656     Intf.moveToBlock(Number);
657 
658     if (!Intf.hasInterference()) {
659       assert(T < GroupSize && "Array overflow");
660       TBS[T] = Number;
661       if (++T == GroupSize) {
662         SpillPlacer->addLinks(makeArrayRef(TBS, T));
663         T = 0;
664       }
665       continue;
666     }
667 
668     assert(B < GroupSize && "Array overflow");
669     BCS[B].Number = Number;
670 
671     // Abort if the spill cannot be inserted at the MBB' start
672     MachineBasicBlock *MBB = MF->getBlockNumbered(Number);
673     auto FirstNonDebugInstr = MBB->getFirstNonDebugInstr();
674     if (FirstNonDebugInstr != MBB->end() &&
675         SlotIndex::isEarlierInstr(LIS->getInstructionIndex(*FirstNonDebugInstr),
676                                   SA->getFirstSplitPoint(Number)))
677       return false;
678     // Interference for the live-in value.
679     if (Intf.first() <= Indexes->getMBBStartIdx(Number))
680       BCS[B].Entry = SpillPlacement::MustSpill;
681     else
682       BCS[B].Entry = SpillPlacement::PrefSpill;
683 
684     // Interference for the live-out value.
685     if (Intf.last() >= SA->getLastSplitPoint(Number))
686       BCS[B].Exit = SpillPlacement::MustSpill;
687     else
688       BCS[B].Exit = SpillPlacement::PrefSpill;
689 
690     if (++B == GroupSize) {
691       SpillPlacer->addConstraints(makeArrayRef(BCS, B));
692       B = 0;
693     }
694   }
695 
696   SpillPlacer->addConstraints(makeArrayRef(BCS, B));
697   SpillPlacer->addLinks(makeArrayRef(TBS, T));
698   return true;
699 }
700 
701 bool RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
702   // Keep track of through blocks that have not been added to SpillPlacer.
703   BitVector Todo = SA->getThroughBlocks();
704   SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
705   unsigned AddedTo = 0;
706 #ifndef NDEBUG
707   unsigned Visited = 0;
708 #endif
709 
710   unsigned long Budget = GrowRegionComplexityBudget;
711   while (true) {
712     ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
713     // Find new through blocks in the periphery of PrefRegBundles.
714     for (unsigned Bundle : NewBundles) {
715       // Look at all blocks connected to Bundle in the full graph.
716       ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
717       // Limit compilation time by bailing out after we use all our budget.
718       if (Blocks.size() >= Budget)
719         return false;
720       Budget -= Blocks.size();
721       for (unsigned Block : Blocks) {
722         if (!Todo.test(Block))
723           continue;
724         Todo.reset(Block);
725         // This is a new through block. Add it to SpillPlacer later.
726         ActiveBlocks.push_back(Block);
727 #ifndef NDEBUG
728         ++Visited;
729 #endif
730       }
731     }
732     // Any new blocks to add?
733     if (ActiveBlocks.size() == AddedTo)
734       break;
735 
736     // Compute through constraints from the interference, or assume that all
737     // through blocks prefer spilling when forming compact regions.
738     auto NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
739     if (Cand.PhysReg) {
740       if (!addThroughConstraints(Cand.Intf, NewBlocks))
741         return false;
742     } else
743       // Provide a strong negative bias on through blocks to prevent unwanted
744       // liveness on loop backedges.
745       SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
746     AddedTo = ActiveBlocks.size();
747 
748     // Perhaps iterating can enable more bundles?
749     SpillPlacer->iterate();
750   }
751   LLVM_DEBUG(dbgs() << ", v=" << Visited);
752   return true;
753 }
754 
755 /// calcCompactRegion - Compute the set of edge bundles that should be live
756 /// when splitting the current live range into compact regions.  Compact
757 /// regions can be computed without looking at interference.  They are the
758 /// regions formed by removing all the live-through blocks from the live range.
759 ///
760 /// Returns false if the current live range is already compact, or if the
761 /// compact regions would form single block regions anyway.
762 bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
763   // Without any through blocks, the live range is already compact.
764   if (!SA->getNumThroughBlocks())
765     return false;
766 
767   // Compact regions don't correspond to any physreg.
768   Cand.reset(IntfCache, MCRegister::NoRegister);
769 
770   LLVM_DEBUG(dbgs() << "Compact region bundles");
771 
772   // Use the spill placer to determine the live bundles. GrowRegion pretends
773   // that all the through blocks have interference when PhysReg is unset.
774   SpillPlacer->prepare(Cand.LiveBundles);
775 
776   // The static split cost will be zero since Cand.Intf reports no interference.
777   BlockFrequency Cost;
778   if (!addSplitConstraints(Cand.Intf, Cost)) {
779     LLVM_DEBUG(dbgs() << ", none.\n");
780     return false;
781   }
782 
783   if (!growRegion(Cand)) {
784     LLVM_DEBUG(dbgs() << ", cannot spill all interferences.\n");
785     return false;
786   }
787 
788   SpillPlacer->finish();
789 
790   if (!Cand.LiveBundles.any()) {
791     LLVM_DEBUG(dbgs() << ", none.\n");
792     return false;
793   }
794 
795   LLVM_DEBUG({
796     for (int I : Cand.LiveBundles.set_bits())
797       dbgs() << " EB#" << I;
798     dbgs() << ".\n";
799   });
800   return true;
801 }
802 
803 /// calcSpillCost - Compute how expensive it would be to split the live range in
804 /// SA around all use blocks instead of forming bundle regions.
805 BlockFrequency RAGreedy::calcSpillCost() {
806   BlockFrequency Cost = 0;
807   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
808   for (const SplitAnalysis::BlockInfo &BI : UseBlocks) {
809     unsigned Number = BI.MBB->getNumber();
810     // We normally only need one spill instruction - a load or a store.
811     Cost += SpillPlacer->getBlockFrequency(Number);
812 
813     // Unless the value is redefined in the block.
814     if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
815       Cost += SpillPlacer->getBlockFrequency(Number);
816   }
817   return Cost;
818 }
819 
820 /// calcGlobalSplitCost - Return the global split cost of following the split
821 /// pattern in LiveBundles. This cost should be added to the local cost of the
822 /// interference pattern in SplitConstraints.
823 ///
824 BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand,
825                                              const AllocationOrder &Order) {
826   BlockFrequency GlobalCost = 0;
827   const BitVector &LiveBundles = Cand.LiveBundles;
828   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
829   for (unsigned I = 0; I != UseBlocks.size(); ++I) {
830     const SplitAnalysis::BlockInfo &BI = UseBlocks[I];
831     SpillPlacement::BlockConstraint &BC = SplitConstraints[I];
832     bool RegIn  = LiveBundles[Bundles->getBundle(BC.Number, false)];
833     bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, true)];
834     unsigned Ins = 0;
835 
836     Cand.Intf.moveToBlock(BC.Number);
837 
838     if (BI.LiveIn)
839       Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
840     if (BI.LiveOut)
841       Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
842     while (Ins--)
843       GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
844   }
845 
846   for (unsigned Number : Cand.ActiveBlocks) {
847     bool RegIn  = LiveBundles[Bundles->getBundle(Number, false)];
848     bool RegOut = LiveBundles[Bundles->getBundle(Number, true)];
849     if (!RegIn && !RegOut)
850       continue;
851     if (RegIn && RegOut) {
852       // We need double spill code if this block has interference.
853       Cand.Intf.moveToBlock(Number);
854       if (Cand.Intf.hasInterference()) {
855         GlobalCost += SpillPlacer->getBlockFrequency(Number);
856         GlobalCost += SpillPlacer->getBlockFrequency(Number);
857       }
858       continue;
859     }
860     // live-in / stack-out or stack-in live-out.
861     GlobalCost += SpillPlacer->getBlockFrequency(Number);
862   }
863   return GlobalCost;
864 }
865 
866 /// splitAroundRegion - Split the current live range around the regions
867 /// determined by BundleCand and GlobalCand.
868 ///
869 /// Before calling this function, GlobalCand and BundleCand must be initialized
870 /// so each bundle is assigned to a valid candidate, or NoCand for the
871 /// stack-bound bundles.  The shared SA/SE SplitAnalysis and SplitEditor
872 /// objects must be initialized for the current live range, and intervals
873 /// created for the used candidates.
874 ///
875 /// @param LREdit    The LiveRangeEdit object handling the current split.
876 /// @param UsedCands List of used GlobalCand entries. Every BundleCand value
877 ///                  must appear in this list.
878 void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
879                                  ArrayRef<unsigned> UsedCands) {
880   // These are the intervals created for new global ranges. We may create more
881   // intervals for local ranges.
882   const unsigned NumGlobalIntvs = LREdit.size();
883   LLVM_DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs
884                     << " globals.\n");
885   assert(NumGlobalIntvs && "No global intervals configured");
886 
887   // Isolate even single instructions when dealing with a proper sub-class.
888   // That guarantees register class inflation for the stack interval because it
889   // is all copies.
890   Register Reg = SA->getParent().reg();
891   bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
892 
893   // First handle all the blocks with uses.
894   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
895   for (const SplitAnalysis::BlockInfo &BI : UseBlocks) {
896     unsigned Number = BI.MBB->getNumber();
897     unsigned IntvIn = 0, IntvOut = 0;
898     SlotIndex IntfIn, IntfOut;
899     if (BI.LiveIn) {
900       unsigned CandIn = BundleCand[Bundles->getBundle(Number, false)];
901       if (CandIn != NoCand) {
902         GlobalSplitCandidate &Cand = GlobalCand[CandIn];
903         IntvIn = Cand.IntvIdx;
904         Cand.Intf.moveToBlock(Number);
905         IntfIn = Cand.Intf.first();
906       }
907     }
908     if (BI.LiveOut) {
909       unsigned CandOut = BundleCand[Bundles->getBundle(Number, true)];
910       if (CandOut != NoCand) {
911         GlobalSplitCandidate &Cand = GlobalCand[CandOut];
912         IntvOut = Cand.IntvIdx;
913         Cand.Intf.moveToBlock(Number);
914         IntfOut = Cand.Intf.last();
915       }
916     }
917 
918     // Create separate intervals for isolated blocks with multiple uses.
919     if (!IntvIn && !IntvOut) {
920       LLVM_DEBUG(dbgs() << printMBBReference(*BI.MBB) << " isolated.\n");
921       if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
922         SE->splitSingleBlock(BI);
923       continue;
924     }
925 
926     if (IntvIn && IntvOut)
927       SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
928     else if (IntvIn)
929       SE->splitRegInBlock(BI, IntvIn, IntfIn);
930     else
931       SE->splitRegOutBlock(BI, IntvOut, IntfOut);
932   }
933 
934   // Handle live-through blocks. The relevant live-through blocks are stored in
935   // the ActiveBlocks list with each candidate. We need to filter out
936   // duplicates.
937   BitVector Todo = SA->getThroughBlocks();
938   for (unsigned UsedCand : UsedCands) {
939     ArrayRef<unsigned> Blocks = GlobalCand[UsedCand].ActiveBlocks;
940     for (unsigned Number : Blocks) {
941       if (!Todo.test(Number))
942         continue;
943       Todo.reset(Number);
944 
945       unsigned IntvIn = 0, IntvOut = 0;
946       SlotIndex IntfIn, IntfOut;
947 
948       unsigned CandIn = BundleCand[Bundles->getBundle(Number, false)];
949       if (CandIn != NoCand) {
950         GlobalSplitCandidate &Cand = GlobalCand[CandIn];
951         IntvIn = Cand.IntvIdx;
952         Cand.Intf.moveToBlock(Number);
953         IntfIn = Cand.Intf.first();
954       }
955 
956       unsigned CandOut = BundleCand[Bundles->getBundle(Number, true)];
957       if (CandOut != NoCand) {
958         GlobalSplitCandidate &Cand = GlobalCand[CandOut];
959         IntvOut = Cand.IntvIdx;
960         Cand.Intf.moveToBlock(Number);
961         IntfOut = Cand.Intf.last();
962       }
963       if (!IntvIn && !IntvOut)
964         continue;
965       SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
966     }
967   }
968 
969   ++NumGlobalSplits;
970 
971   SmallVector<unsigned, 8> IntvMap;
972   SE->finish(&IntvMap);
973   DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
974 
975   unsigned OrigBlocks = SA->getNumLiveBlocks();
976 
977   // Sort out the new intervals created by splitting. We get four kinds:
978   // - Remainder intervals should not be split again.
979   // - Candidate intervals can be assigned to Cand.PhysReg.
980   // - Block-local splits are candidates for local splitting.
981   // - DCE leftovers should go back on the queue.
982   for (unsigned I = 0, E = LREdit.size(); I != E; ++I) {
983     const LiveInterval &Reg = LIS->getInterval(LREdit.get(I));
984 
985     // Ignore old intervals from DCE.
986     if (ExtraInfo->getOrInitStage(Reg.reg()) != RS_New)
987       continue;
988 
989     // Remainder interval. Don't try splitting again, spill if it doesn't
990     // allocate.
991     if (IntvMap[I] == 0) {
992       ExtraInfo->setStage(Reg, RS_Spill);
993       continue;
994     }
995 
996     // Global intervals. Allow repeated splitting as long as the number of live
997     // blocks is strictly decreasing.
998     if (IntvMap[I] < NumGlobalIntvs) {
999       if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
1000         LLVM_DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1001                           << " blocks as original.\n");
1002         // Don't allow repeated splitting as a safe guard against looping.
1003         ExtraInfo->setStage(Reg, RS_Split2);
1004       }
1005       continue;
1006     }
1007 
1008     // Other intervals are treated as new. This includes local intervals created
1009     // for blocks with multiple uses, and anything created by DCE.
1010   }
1011 
1012   if (VerifyEnabled)
1013     MF->verify(this, "After splitting live range around region");
1014 }
1015 
1016 MCRegister RAGreedy::tryRegionSplit(const LiveInterval &VirtReg,
1017                                     AllocationOrder &Order,
1018                                     SmallVectorImpl<Register> &NewVRegs) {
1019   if (!TRI->shouldRegionSplitForVirtReg(*MF, VirtReg))
1020     return MCRegister::NoRegister;
1021   unsigned NumCands = 0;
1022   BlockFrequency SpillCost = calcSpillCost();
1023   BlockFrequency BestCost;
1024 
1025   // Check if we can split this live range around a compact region.
1026   bool HasCompact = calcCompactRegion(GlobalCand.front());
1027   if (HasCompact) {
1028     // Yes, keep GlobalCand[0] as the compact region candidate.
1029     NumCands = 1;
1030     BestCost = BlockFrequency::getMaxFrequency();
1031   } else {
1032     // No benefit from the compact region, our fallback will be per-block
1033     // splitting. Make sure we find a solution that is cheaper than spilling.
1034     BestCost = SpillCost;
1035     LLVM_DEBUG(dbgs() << "Cost of isolating all blocks = ";
1036                MBFI->printBlockFreq(dbgs(), BestCost) << '\n');
1037   }
1038 
1039   unsigned BestCand = calculateRegionSplitCost(VirtReg, Order, BestCost,
1040                                                NumCands, false /*IgnoreCSR*/);
1041 
1042   // No solutions found, fall back to single block splitting.
1043   if (!HasCompact && BestCand == NoCand)
1044     return MCRegister::NoRegister;
1045 
1046   return doRegionSplit(VirtReg, BestCand, HasCompact, NewVRegs);
1047 }
1048 
1049 unsigned RAGreedy::calculateRegionSplitCost(const LiveInterval &VirtReg,
1050                                             AllocationOrder &Order,
1051                                             BlockFrequency &BestCost,
1052                                             unsigned &NumCands,
1053                                             bool IgnoreCSR) {
1054   unsigned BestCand = NoCand;
1055   for (MCPhysReg PhysReg : Order) {
1056     assert(PhysReg);
1057     if (IgnoreCSR && EvictAdvisor->isUnusedCalleeSavedReg(PhysReg))
1058       continue;
1059 
1060     // Discard bad candidates before we run out of interference cache cursors.
1061     // This will only affect register classes with a lot of registers (>32).
1062     if (NumCands == IntfCache.getMaxCursors()) {
1063       unsigned WorstCount = ~0u;
1064       unsigned Worst = 0;
1065       for (unsigned CandIndex = 0; CandIndex != NumCands; ++CandIndex) {
1066         if (CandIndex == BestCand || !GlobalCand[CandIndex].PhysReg)
1067           continue;
1068         unsigned Count = GlobalCand[CandIndex].LiveBundles.count();
1069         if (Count < WorstCount) {
1070           Worst = CandIndex;
1071           WorstCount = Count;
1072         }
1073       }
1074       --NumCands;
1075       GlobalCand[Worst] = GlobalCand[NumCands];
1076       if (BestCand == NumCands)
1077         BestCand = Worst;
1078     }
1079 
1080     if (GlobalCand.size() <= NumCands)
1081       GlobalCand.resize(NumCands+1);
1082     GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1083     Cand.reset(IntfCache, PhysReg);
1084 
1085     SpillPlacer->prepare(Cand.LiveBundles);
1086     BlockFrequency Cost;
1087     if (!addSplitConstraints(Cand.Intf, Cost)) {
1088       LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << "\tno positive bundles\n");
1089       continue;
1090     }
1091     LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << "\tstatic = ";
1092                MBFI->printBlockFreq(dbgs(), Cost));
1093     if (Cost >= BestCost) {
1094       LLVM_DEBUG({
1095         if (BestCand == NoCand)
1096           dbgs() << " worse than no bundles\n";
1097         else
1098           dbgs() << " worse than "
1099                  << printReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1100       });
1101       continue;
1102     }
1103     if (!growRegion(Cand)) {
1104       LLVM_DEBUG(dbgs() << ", cannot spill all interferences.\n");
1105       continue;
1106     }
1107 
1108     SpillPlacer->finish();
1109 
1110     // No live bundles, defer to splitSingleBlocks().
1111     if (!Cand.LiveBundles.any()) {
1112       LLVM_DEBUG(dbgs() << " no bundles.\n");
1113       continue;
1114     }
1115 
1116     Cost += calcGlobalSplitCost(Cand, Order);
1117     LLVM_DEBUG({
1118       dbgs() << ", total = ";
1119       MBFI->printBlockFreq(dbgs(), Cost) << " with bundles";
1120       for (int I : Cand.LiveBundles.set_bits())
1121         dbgs() << " EB#" << I;
1122       dbgs() << ".\n";
1123     });
1124     if (Cost < BestCost) {
1125       BestCand = NumCands;
1126       BestCost = Cost;
1127     }
1128     ++NumCands;
1129   }
1130 
1131   return BestCand;
1132 }
1133 
1134 unsigned RAGreedy::doRegionSplit(const LiveInterval &VirtReg, unsigned BestCand,
1135                                  bool HasCompact,
1136                                  SmallVectorImpl<Register> &NewVRegs) {
1137   SmallVector<unsigned, 8> UsedCands;
1138   // Prepare split editor.
1139   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
1140   SE->reset(LREdit, SplitSpillMode);
1141 
1142   // Assign all edge bundles to the preferred candidate, or NoCand.
1143   BundleCand.assign(Bundles->getNumBundles(), NoCand);
1144 
1145   // Assign bundles for the best candidate region.
1146   if (BestCand != NoCand) {
1147     GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1148     if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1149       UsedCands.push_back(BestCand);
1150       Cand.IntvIdx = SE->openIntv();
1151       LLVM_DEBUG(dbgs() << "Split for " << printReg(Cand.PhysReg, TRI) << " in "
1152                         << B << " bundles, intv " << Cand.IntvIdx << ".\n");
1153       (void)B;
1154     }
1155   }
1156 
1157   // Assign bundles for the compact region.
1158   if (HasCompact) {
1159     GlobalSplitCandidate &Cand = GlobalCand.front();
1160     assert(!Cand.PhysReg && "Compact region has no physreg");
1161     if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1162       UsedCands.push_back(0);
1163       Cand.IntvIdx = SE->openIntv();
1164       LLVM_DEBUG(dbgs() << "Split for compact region in " << B
1165                         << " bundles, intv " << Cand.IntvIdx << ".\n");
1166       (void)B;
1167     }
1168   }
1169 
1170   splitAroundRegion(LREdit, UsedCands);
1171   return 0;
1172 }
1173 
1174 //===----------------------------------------------------------------------===//
1175 //                            Per-Block Splitting
1176 //===----------------------------------------------------------------------===//
1177 
1178 /// tryBlockSplit - Split a global live range around every block with uses. This
1179 /// creates a lot of local live ranges, that will be split by tryLocalSplit if
1180 /// they don't allocate.
1181 unsigned RAGreedy::tryBlockSplit(const LiveInterval &VirtReg,
1182                                  AllocationOrder &Order,
1183                                  SmallVectorImpl<Register> &NewVRegs) {
1184   assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1185   Register Reg = VirtReg.reg();
1186   bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1187   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
1188   SE->reset(LREdit, SplitSpillMode);
1189   ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1190   for (const SplitAnalysis::BlockInfo &BI : UseBlocks) {
1191     if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1192       SE->splitSingleBlock(BI);
1193   }
1194   // No blocks were split.
1195   if (LREdit.empty())
1196     return 0;
1197 
1198   // We did split for some blocks.
1199   SmallVector<unsigned, 8> IntvMap;
1200   SE->finish(&IntvMap);
1201 
1202   // Tell LiveDebugVariables about the new ranges.
1203   DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
1204 
1205   // Sort out the new intervals created by splitting. The remainder interval
1206   // goes straight to spilling, the new local ranges get to stay RS_New.
1207   for (unsigned I = 0, E = LREdit.size(); I != E; ++I) {
1208     const LiveInterval &LI = LIS->getInterval(LREdit.get(I));
1209     if (ExtraInfo->getOrInitStage(LI.reg()) == RS_New && IntvMap[I] == 0)
1210       ExtraInfo->setStage(LI, RS_Spill);
1211   }
1212 
1213   if (VerifyEnabled)
1214     MF->verify(this, "After splitting live range around basic blocks");
1215   return 0;
1216 }
1217 
1218 //===----------------------------------------------------------------------===//
1219 //                         Per-Instruction Splitting
1220 //===----------------------------------------------------------------------===//
1221 
1222 /// Get the number of allocatable registers that match the constraints of \p Reg
1223 /// on \p MI and that are also in \p SuperRC.
1224 static unsigned getNumAllocatableRegsForConstraints(
1225     const MachineInstr *MI, Register Reg, const TargetRegisterClass *SuperRC,
1226     const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
1227     const RegisterClassInfo &RCI) {
1228   assert(SuperRC && "Invalid register class");
1229 
1230   const TargetRegisterClass *ConstrainedRC =
1231       MI->getRegClassConstraintEffectForVReg(Reg, SuperRC, TII, TRI,
1232                                              /* ExploreBundle */ true);
1233   if (!ConstrainedRC)
1234     return 0;
1235   return RCI.getNumAllocatableRegs(ConstrainedRC);
1236 }
1237 
1238 /// tryInstructionSplit - Split a live range around individual instructions.
1239 /// This is normally not worthwhile since the spiller is doing essentially the
1240 /// same thing. However, when the live range is in a constrained register
1241 /// class, it may help to insert copies such that parts of the live range can
1242 /// be moved to a larger register class.
1243 ///
1244 /// This is similar to spilling to a larger register class.
1245 unsigned RAGreedy::tryInstructionSplit(const LiveInterval &VirtReg,
1246                                        AllocationOrder &Order,
1247                                        SmallVectorImpl<Register> &NewVRegs) {
1248   const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg());
1249   // There is no point to this if there are no larger sub-classes.
1250   if (!RegClassInfo.isProperSubClass(CurRC))
1251     return 0;
1252 
1253   // Always enable split spill mode, since we're effectively spilling to a
1254   // register.
1255   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
1256   SE->reset(LREdit, SplitEditor::SM_Size);
1257 
1258   ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1259   if (Uses.size() <= 1)
1260     return 0;
1261 
1262   LLVM_DEBUG(dbgs() << "Split around " << Uses.size()
1263                     << " individual instrs.\n");
1264 
1265   const TargetRegisterClass *SuperRC =
1266       TRI->getLargestLegalSuperClass(CurRC, *MF);
1267   unsigned SuperRCNumAllocatableRegs =
1268       RegClassInfo.getNumAllocatableRegs(SuperRC);
1269   // Split around every non-copy instruction if this split will relax
1270   // the constraints on the virtual register.
1271   // Otherwise, splitting just inserts uncoalescable copies that do not help
1272   // the allocation.
1273   for (const SlotIndex Use : Uses) {
1274     if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Use))
1275       if (MI->isFullCopy() ||
1276           SuperRCNumAllocatableRegs ==
1277               getNumAllocatableRegsForConstraints(MI, VirtReg.reg(), SuperRC,
1278                                                   TII, TRI, RegClassInfo)) {
1279         LLVM_DEBUG(dbgs() << "    skip:\t" << Use << '\t' << *MI);
1280         continue;
1281       }
1282     SE->openIntv();
1283     SlotIndex SegStart = SE->enterIntvBefore(Use);
1284     SlotIndex SegStop = SE->leaveIntvAfter(Use);
1285     SE->useIntv(SegStart, SegStop);
1286   }
1287 
1288   if (LREdit.empty()) {
1289     LLVM_DEBUG(dbgs() << "All uses were copies.\n");
1290     return 0;
1291   }
1292 
1293   SmallVector<unsigned, 8> IntvMap;
1294   SE->finish(&IntvMap);
1295   DebugVars->splitRegister(VirtReg.reg(), LREdit.regs(), *LIS);
1296   // Assign all new registers to RS_Spill. This was the last chance.
1297   ExtraInfo->setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1298   return 0;
1299 }
1300 
1301 //===----------------------------------------------------------------------===//
1302 //                             Local Splitting
1303 //===----------------------------------------------------------------------===//
1304 
1305 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1306 /// in order to use PhysReg between two entries in SA->UseSlots.
1307 ///
1308 /// GapWeight[I] represents the gap between UseSlots[I] and UseSlots[I + 1].
1309 ///
1310 void RAGreedy::calcGapWeights(MCRegister PhysReg,
1311                               SmallVectorImpl<float> &GapWeight) {
1312   assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1313   const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1314   ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1315   const unsigned NumGaps = Uses.size()-1;
1316 
1317   // Start and end points for the interference check.
1318   SlotIndex StartIdx =
1319     BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1320   SlotIndex StopIdx =
1321     BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
1322 
1323   GapWeight.assign(NumGaps, 0.0f);
1324 
1325   // Add interference from each overlapping register.
1326   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1327     if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1328           .checkInterference())
1329       continue;
1330 
1331     // We know that VirtReg is a continuous interval from FirstInstr to
1332     // LastInstr, so we don't need InterferenceQuery.
1333     //
1334     // Interference that overlaps an instruction is counted in both gaps
1335     // surrounding the instruction. The exception is interference before
1336     // StartIdx and after StopIdx.
1337     //
1338     LiveIntervalUnion::SegmentIter IntI =
1339       Matrix->getLiveUnions()[*Units] .find(StartIdx);
1340     for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1341       // Skip the gaps before IntI.
1342       while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1343         if (++Gap == NumGaps)
1344           break;
1345       if (Gap == NumGaps)
1346         break;
1347 
1348       // Update the gaps covered by IntI.
1349       const float weight = IntI.value()->weight();
1350       for (; Gap != NumGaps; ++Gap) {
1351         GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1352         if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1353           break;
1354       }
1355       if (Gap == NumGaps)
1356         break;
1357     }
1358   }
1359 
1360   // Add fixed interference.
1361   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1362     const LiveRange &LR = LIS->getRegUnit(*Units);
1363     LiveRange::const_iterator I = LR.find(StartIdx);
1364     LiveRange::const_iterator E = LR.end();
1365 
1366     // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1367     for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1368       while (Uses[Gap+1].getBoundaryIndex() < I->start)
1369         if (++Gap == NumGaps)
1370           break;
1371       if (Gap == NumGaps)
1372         break;
1373 
1374       for (; Gap != NumGaps; ++Gap) {
1375         GapWeight[Gap] = huge_valf;
1376         if (Uses[Gap+1].getBaseIndex() >= I->end)
1377           break;
1378       }
1379       if (Gap == NumGaps)
1380         break;
1381     }
1382   }
1383 }
1384 
1385 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1386 /// basic block.
1387 ///
1388 unsigned RAGreedy::tryLocalSplit(const LiveInterval &VirtReg,
1389                                  AllocationOrder &Order,
1390                                  SmallVectorImpl<Register> &NewVRegs) {
1391   // TODO: the function currently only handles a single UseBlock; it should be
1392   // possible to generalize.
1393   if (SA->getUseBlocks().size() != 1)
1394     return 0;
1395 
1396   const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1397 
1398   // Note that it is possible to have an interval that is live-in or live-out
1399   // while only covering a single block - A phi-def can use undef values from
1400   // predecessors, and the block could be a single-block loop.
1401   // We don't bother doing anything clever about such a case, we simply assume
1402   // that the interval is continuous from FirstInstr to LastInstr. We should
1403   // make sure that we don't do anything illegal to such an interval, though.
1404 
1405   ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1406   if (Uses.size() <= 2)
1407     return 0;
1408   const unsigned NumGaps = Uses.size()-1;
1409 
1410   LLVM_DEBUG({
1411     dbgs() << "tryLocalSplit: ";
1412     for (const auto &Use : Uses)
1413       dbgs() << ' ' << Use;
1414     dbgs() << '\n';
1415   });
1416 
1417   // If VirtReg is live across any register mask operands, compute a list of
1418   // gaps with register masks.
1419   SmallVector<unsigned, 8> RegMaskGaps;
1420   if (Matrix->checkRegMaskInterference(VirtReg)) {
1421     // Get regmask slots for the whole block.
1422     ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
1423     LLVM_DEBUG(dbgs() << RMS.size() << " regmasks in block:");
1424     // Constrain to VirtReg's live range.
1425     unsigned RI =
1426         llvm::lower_bound(RMS, Uses.front().getRegSlot()) - RMS.begin();
1427     unsigned RE = RMS.size();
1428     for (unsigned I = 0; I != NumGaps && RI != RE; ++I) {
1429       // Look for Uses[I] <= RMS <= Uses[I + 1].
1430       assert(!SlotIndex::isEarlierInstr(RMS[RI], Uses[I]));
1431       if (SlotIndex::isEarlierInstr(Uses[I + 1], RMS[RI]))
1432         continue;
1433       // Skip a regmask on the same instruction as the last use. It doesn't
1434       // overlap the live range.
1435       if (SlotIndex::isSameInstr(Uses[I + 1], RMS[RI]) && I + 1 == NumGaps)
1436         break;
1437       LLVM_DEBUG(dbgs() << ' ' << RMS[RI] << ':' << Uses[I] << '-'
1438                         << Uses[I + 1]);
1439       RegMaskGaps.push_back(I);
1440       // Advance ri to the next gap. A regmask on one of the uses counts in
1441       // both gaps.
1442       while (RI != RE && SlotIndex::isEarlierInstr(RMS[RI], Uses[I + 1]))
1443         ++RI;
1444     }
1445     LLVM_DEBUG(dbgs() << '\n');
1446   }
1447 
1448   // Since we allow local split results to be split again, there is a risk of
1449   // creating infinite loops. It is tempting to require that the new live
1450   // ranges have less instructions than the original. That would guarantee
1451   // convergence, but it is too strict. A live range with 3 instructions can be
1452   // split 2+3 (including the COPY), and we want to allow that.
1453   //
1454   // Instead we use these rules:
1455   //
1456   // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
1457   //    noop split, of course).
1458   // 2. Require progress be made for ranges with getStage() == RS_Split2. All
1459   //    the new ranges must have fewer instructions than before the split.
1460   // 3. New ranges with the same number of instructions are marked RS_Split2,
1461   //    smaller ranges are marked RS_New.
1462   //
1463   // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1464   // excessive splitting and infinite loops.
1465   //
1466   bool ProgressRequired = ExtraInfo->getStage(VirtReg) >= RS_Split2;
1467 
1468   // Best split candidate.
1469   unsigned BestBefore = NumGaps;
1470   unsigned BestAfter = 0;
1471   float BestDiff = 0;
1472 
1473   const float blockFreq =
1474     SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
1475     (1.0f / MBFI->getEntryFreq());
1476   SmallVector<float, 8> GapWeight;
1477 
1478   for (MCPhysReg PhysReg : Order) {
1479     assert(PhysReg);
1480     // Keep track of the largest spill weight that would need to be evicted in
1481     // order to make use of PhysReg between UseSlots[I] and UseSlots[I + 1].
1482     calcGapWeights(PhysReg, GapWeight);
1483 
1484     // Remove any gaps with regmask clobbers.
1485     if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
1486       for (unsigned I = 0, E = RegMaskGaps.size(); I != E; ++I)
1487         GapWeight[RegMaskGaps[I]] = huge_valf;
1488 
1489     // Try to find the best sequence of gaps to close.
1490     // The new spill weight must be larger than any gap interference.
1491 
1492     // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1493     unsigned SplitBefore = 0, SplitAfter = 1;
1494 
1495     // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1496     // It is the spill weight that needs to be evicted.
1497     float MaxGap = GapWeight[0];
1498 
1499     while (true) {
1500       // Live before/after split?
1501       const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1502       const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1503 
1504       LLVM_DEBUG(dbgs() << printReg(PhysReg, TRI) << ' ' << Uses[SplitBefore]
1505                         << '-' << Uses[SplitAfter] << " I=" << MaxGap);
1506 
1507       // Stop before the interval gets so big we wouldn't be making progress.
1508       if (!LiveBefore && !LiveAfter) {
1509         LLVM_DEBUG(dbgs() << " all\n");
1510         break;
1511       }
1512       // Should the interval be extended or shrunk?
1513       bool Shrink = true;
1514 
1515       // How many gaps would the new range have?
1516       unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1517 
1518       // Legally, without causing looping?
1519       bool Legal = !ProgressRequired || NewGaps < NumGaps;
1520 
1521       if (Legal && MaxGap < huge_valf) {
1522         // Estimate the new spill weight. Each instruction reads or writes the
1523         // register. Conservatively assume there are no read-modify-write
1524         // instructions.
1525         //
1526         // Try to guess the size of the new interval.
1527         const float EstWeight = normalizeSpillWeight(
1528             blockFreq * (NewGaps + 1),
1529             Uses[SplitBefore].distance(Uses[SplitAfter]) +
1530                 (LiveBefore + LiveAfter) * SlotIndex::InstrDist,
1531             1);
1532         // Would this split be possible to allocate?
1533         // Never allocate all gaps, we wouldn't be making progress.
1534         LLVM_DEBUG(dbgs() << " w=" << EstWeight);
1535         if (EstWeight * Hysteresis >= MaxGap) {
1536           Shrink = false;
1537           float Diff = EstWeight - MaxGap;
1538           if (Diff > BestDiff) {
1539             LLVM_DEBUG(dbgs() << " (best)");
1540             BestDiff = Hysteresis * Diff;
1541             BestBefore = SplitBefore;
1542             BestAfter = SplitAfter;
1543           }
1544         }
1545       }
1546 
1547       // Try to shrink.
1548       if (Shrink) {
1549         if (++SplitBefore < SplitAfter) {
1550           LLVM_DEBUG(dbgs() << " shrink\n");
1551           // Recompute the max when necessary.
1552           if (GapWeight[SplitBefore - 1] >= MaxGap) {
1553             MaxGap = GapWeight[SplitBefore];
1554             for (unsigned I = SplitBefore + 1; I != SplitAfter; ++I)
1555               MaxGap = std::max(MaxGap, GapWeight[I]);
1556           }
1557           continue;
1558         }
1559         MaxGap = 0;
1560       }
1561 
1562       // Try to extend the interval.
1563       if (SplitAfter >= NumGaps) {
1564         LLVM_DEBUG(dbgs() << " end\n");
1565         break;
1566       }
1567 
1568       LLVM_DEBUG(dbgs() << " extend\n");
1569       MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
1570     }
1571   }
1572 
1573   // Didn't find any candidates?
1574   if (BestBefore == NumGaps)
1575     return 0;
1576 
1577   LLVM_DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore] << '-'
1578                     << Uses[BestAfter] << ", " << BestDiff << ", "
1579                     << (BestAfter - BestBefore + 1) << " instrs\n");
1580 
1581   LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
1582   SE->reset(LREdit);
1583 
1584   SE->openIntv();
1585   SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1586   SlotIndex SegStop  = SE->leaveIntvAfter(Uses[BestAfter]);
1587   SE->useIntv(SegStart, SegStop);
1588   SmallVector<unsigned, 8> IntvMap;
1589   SE->finish(&IntvMap);
1590   DebugVars->splitRegister(VirtReg.reg(), LREdit.regs(), *LIS);
1591   // If the new range has the same number of instructions as before, mark it as
1592   // RS_Split2 so the next split will be forced to make progress. Otherwise,
1593   // leave the new intervals as RS_New so they can compete.
1594   bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1595   bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1596   unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1597   if (NewGaps >= NumGaps) {
1598     LLVM_DEBUG(dbgs() << "Tagging non-progress ranges:");
1599     assert(!ProgressRequired && "Didn't make progress when it was required.");
1600     for (unsigned I = 0, E = IntvMap.size(); I != E; ++I)
1601       if (IntvMap[I] == 1) {
1602         ExtraInfo->setStage(LIS->getInterval(LREdit.get(I)), RS_Split2);
1603         LLVM_DEBUG(dbgs() << ' ' << printReg(LREdit.get(I)));
1604       }
1605     LLVM_DEBUG(dbgs() << '\n');
1606   }
1607   ++NumLocalSplits;
1608 
1609   return 0;
1610 }
1611 
1612 //===----------------------------------------------------------------------===//
1613 //                          Live Range Splitting
1614 //===----------------------------------------------------------------------===//
1615 
1616 /// trySplit - Try to split VirtReg or one of its interferences, making it
1617 /// assignable.
1618 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1619 unsigned RAGreedy::trySplit(const LiveInterval &VirtReg, AllocationOrder &Order,
1620                             SmallVectorImpl<Register> &NewVRegs,
1621                             const SmallVirtRegSet &FixedRegisters) {
1622   // Ranges must be Split2 or less.
1623   if (ExtraInfo->getStage(VirtReg) >= RS_Spill)
1624     return 0;
1625 
1626   // Local intervals are handled separately.
1627   if (LIS->intervalIsInOneMBB(VirtReg)) {
1628     NamedRegionTimer T("local_split", "Local Splitting", TimerGroupName,
1629                        TimerGroupDescription, TimePassesIsEnabled);
1630     SA->analyze(&VirtReg);
1631     Register PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1632     if (PhysReg || !NewVRegs.empty())
1633       return PhysReg;
1634     return tryInstructionSplit(VirtReg, Order, NewVRegs);
1635   }
1636 
1637   NamedRegionTimer T("global_split", "Global Splitting", TimerGroupName,
1638                      TimerGroupDescription, TimePassesIsEnabled);
1639 
1640   SA->analyze(&VirtReg);
1641 
1642   // First try to split around a region spanning multiple blocks. RS_Split2
1643   // ranges already made dubious progress with region splitting, so they go
1644   // straight to single block splitting.
1645   if (ExtraInfo->getStage(VirtReg) < RS_Split2) {
1646     MCRegister PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
1647     if (PhysReg || !NewVRegs.empty())
1648       return PhysReg;
1649   }
1650 
1651   // Then isolate blocks.
1652   return tryBlockSplit(VirtReg, Order, NewVRegs);
1653 }
1654 
1655 //===----------------------------------------------------------------------===//
1656 //                          Last Chance Recoloring
1657 //===----------------------------------------------------------------------===//
1658 
1659 /// Return true if \p reg has any tied def operand.
1660 static bool hasTiedDef(MachineRegisterInfo *MRI, unsigned reg) {
1661   for (const MachineOperand &MO : MRI->def_operands(reg))
1662     if (MO.isTied())
1663       return true;
1664 
1665   return false;
1666 }
1667 
1668 /// Return true if the existing assignment of \p Intf overlaps, but is not the
1669 /// same, as \p PhysReg.
1670 static bool assignedRegPartiallyOverlaps(const TargetRegisterInfo &TRI,
1671                                          const VirtRegMap &VRM,
1672                                          MCRegister PhysReg,
1673                                          const LiveInterval &Intf) {
1674   MCRegister AssignedReg = VRM.getPhys(Intf.reg());
1675   if (PhysReg == AssignedReg)
1676     return false;
1677   return TRI.regsOverlap(PhysReg, AssignedReg);
1678 }
1679 
1680 /// mayRecolorAllInterferences - Check if the virtual registers that
1681 /// interfere with \p VirtReg on \p PhysReg (or one of its aliases) may be
1682 /// recolored to free \p PhysReg.
1683 /// When true is returned, \p RecoloringCandidates has been augmented with all
1684 /// the live intervals that need to be recolored in order to free \p PhysReg
1685 /// for \p VirtReg.
1686 /// \p FixedRegisters contains all the virtual registers that cannot be
1687 /// recolored.
1688 bool RAGreedy::mayRecolorAllInterferences(
1689     MCRegister PhysReg, const LiveInterval &VirtReg,
1690     SmallLISet &RecoloringCandidates, const SmallVirtRegSet &FixedRegisters) {
1691   const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg());
1692 
1693   for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1694     LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
1695     // If there is LastChanceRecoloringMaxInterference or more interferences,
1696     // chances are one would not be recolorable.
1697     if (Q.interferingVRegs(LastChanceRecoloringMaxInterference).size() >=
1698             LastChanceRecoloringMaxInterference &&
1699         !ExhaustiveSearch) {
1700       LLVM_DEBUG(dbgs() << "Early abort: too many interferences.\n");
1701       CutOffInfo |= CO_Interf;
1702       return false;
1703     }
1704     for (const LiveInterval *Intf : reverse(Q.interferingVRegs())) {
1705       // If Intf is done and sits on the same register class as VirtReg, it
1706       // would not be recolorable as it is in the same state as
1707       // VirtReg. However there are at least two exceptions.
1708       //
1709       // If VirtReg has tied defs and Intf doesn't, then
1710       // there is still a point in examining if it can be recolorable.
1711       //
1712       // Additionally, if the register class has overlapping tuple members, it
1713       // may still be recolorable using a different tuple. This is more likely
1714       // if the existing assignment aliases with the candidate.
1715       //
1716       if (((ExtraInfo->getStage(*Intf) == RS_Done &&
1717             MRI->getRegClass(Intf->reg()) == CurRC &&
1718             !assignedRegPartiallyOverlaps(*TRI, *VRM, PhysReg, *Intf)) &&
1719            !(hasTiedDef(MRI, VirtReg.reg()) &&
1720              !hasTiedDef(MRI, Intf->reg()))) ||
1721           FixedRegisters.count(Intf->reg())) {
1722         LLVM_DEBUG(
1723             dbgs() << "Early abort: the interference is not recolorable.\n");
1724         return false;
1725       }
1726       RecoloringCandidates.insert(Intf);
1727     }
1728   }
1729   return true;
1730 }
1731 
1732 /// tryLastChanceRecoloring - Try to assign a color to \p VirtReg by recoloring
1733 /// its interferences.
1734 /// Last chance recoloring chooses a color for \p VirtReg and recolors every
1735 /// virtual register that was using it. The recoloring process may recursively
1736 /// use the last chance recoloring. Therefore, when a virtual register has been
1737 /// assigned a color by this mechanism, it is marked as Fixed, i.e., it cannot
1738 /// be last-chance-recolored again during this recoloring "session".
1739 /// E.g.,
1740 /// Let
1741 /// vA can use {R1, R2    }
1742 /// vB can use {    R2, R3}
1743 /// vC can use {R1        }
1744 /// Where vA, vB, and vC cannot be split anymore (they are reloads for
1745 /// instance) and they all interfere.
1746 ///
1747 /// vA is assigned R1
1748 /// vB is assigned R2
1749 /// vC tries to evict vA but vA is already done.
1750 /// Regular register allocation fails.
1751 ///
1752 /// Last chance recoloring kicks in:
1753 /// vC does as if vA was evicted => vC uses R1.
1754 /// vC is marked as fixed.
1755 /// vA needs to find a color.
1756 /// None are available.
1757 /// vA cannot evict vC: vC is a fixed virtual register now.
1758 /// vA does as if vB was evicted => vA uses R2.
1759 /// vB needs to find a color.
1760 /// R3 is available.
1761 /// Recoloring => vC = R1, vA = R2, vB = R3
1762 ///
1763 /// \p Order defines the preferred allocation order for \p VirtReg.
1764 /// \p NewRegs will contain any new virtual register that have been created
1765 /// (split, spill) during the process and that must be assigned.
1766 /// \p FixedRegisters contains all the virtual registers that cannot be
1767 /// recolored.
1768 ///
1769 /// \p RecolorStack tracks the original assignments of successfully recolored
1770 /// registers.
1771 ///
1772 /// \p Depth gives the current depth of the last chance recoloring.
1773 /// \return a physical register that can be used for VirtReg or ~0u if none
1774 /// exists.
1775 unsigned RAGreedy::tryLastChanceRecoloring(const LiveInterval &VirtReg,
1776                                            AllocationOrder &Order,
1777                                            SmallVectorImpl<Register> &NewVRegs,
1778                                            SmallVirtRegSet &FixedRegisters,
1779                                            RecoloringStack &RecolorStack,
1780                                            unsigned Depth) {
1781   if (!TRI->shouldUseLastChanceRecoloringForVirtReg(*MF, VirtReg))
1782     return ~0u;
1783 
1784   LLVM_DEBUG(dbgs() << "Try last chance recoloring for " << VirtReg << '\n');
1785 
1786   const ssize_t EntryStackSize = RecolorStack.size();
1787 
1788   // Ranges must be Done.
1789   assert((ExtraInfo->getStage(VirtReg) >= RS_Done || !VirtReg.isSpillable()) &&
1790          "Last chance recoloring should really be last chance");
1791   // Set the max depth to LastChanceRecoloringMaxDepth.
1792   // We may want to reconsider that if we end up with a too large search space
1793   // for target with hundreds of registers.
1794   // Indeed, in that case we may want to cut the search space earlier.
1795   if (Depth >= LastChanceRecoloringMaxDepth && !ExhaustiveSearch) {
1796     LLVM_DEBUG(dbgs() << "Abort because max depth has been reached.\n");
1797     CutOffInfo |= CO_Depth;
1798     return ~0u;
1799   }
1800 
1801   // Set of Live intervals that will need to be recolored.
1802   SmallLISet RecoloringCandidates;
1803 
1804   // Mark VirtReg as fixed, i.e., it will not be recolored pass this point in
1805   // this recoloring "session".
1806   assert(!FixedRegisters.count(VirtReg.reg()));
1807   FixedRegisters.insert(VirtReg.reg());
1808   SmallVector<Register, 4> CurrentNewVRegs;
1809 
1810   for (MCRegister PhysReg : Order) {
1811     assert(PhysReg.isValid());
1812     LLVM_DEBUG(dbgs() << "Try to assign: " << VirtReg << " to "
1813                       << printReg(PhysReg, TRI) << '\n');
1814     RecoloringCandidates.clear();
1815     CurrentNewVRegs.clear();
1816 
1817     // It is only possible to recolor virtual register interference.
1818     if (Matrix->checkInterference(VirtReg, PhysReg) >
1819         LiveRegMatrix::IK_VirtReg) {
1820       LLVM_DEBUG(
1821           dbgs() << "Some interferences are not with virtual registers.\n");
1822 
1823       continue;
1824     }
1825 
1826     // Early give up on this PhysReg if it is obvious we cannot recolor all
1827     // the interferences.
1828     if (!mayRecolorAllInterferences(PhysReg, VirtReg, RecoloringCandidates,
1829                                     FixedRegisters)) {
1830       LLVM_DEBUG(dbgs() << "Some interferences cannot be recolored.\n");
1831       continue;
1832     }
1833 
1834     // RecoloringCandidates contains all the virtual registers that interfere
1835     // with VirtReg on PhysReg (or one of its aliases). Enqueue them for
1836     // recoloring and perform the actual recoloring.
1837     PQueue RecoloringQueue;
1838     for (const LiveInterval *RC : RecoloringCandidates) {
1839       Register ItVirtReg = RC->reg();
1840       enqueue(RecoloringQueue, RC);
1841       assert(VRM->hasPhys(ItVirtReg) &&
1842              "Interferences are supposed to be with allocated variables");
1843 
1844       // Record the current allocation.
1845       RecolorStack.push_back(std::make_pair(RC, VRM->getPhys(ItVirtReg)));
1846 
1847       // unset the related struct.
1848       Matrix->unassign(*RC);
1849     }
1850 
1851     // Do as if VirtReg was assigned to PhysReg so that the underlying
1852     // recoloring has the right information about the interferes and
1853     // available colors.
1854     Matrix->assign(VirtReg, PhysReg);
1855 
1856     // Save the current recoloring state.
1857     // If we cannot recolor all the interferences, we will have to start again
1858     // at this point for the next physical register.
1859     SmallVirtRegSet SaveFixedRegisters(FixedRegisters);
1860     if (tryRecoloringCandidates(RecoloringQueue, CurrentNewVRegs,
1861                                 FixedRegisters, RecolorStack, Depth)) {
1862       // Push the queued vregs into the main queue.
1863       for (Register NewVReg : CurrentNewVRegs)
1864         NewVRegs.push_back(NewVReg);
1865       // Do not mess up with the global assignment process.
1866       // I.e., VirtReg must be unassigned.
1867       Matrix->unassign(VirtReg);
1868       return PhysReg;
1869     }
1870 
1871     LLVM_DEBUG(dbgs() << "Fail to assign: " << VirtReg << " to "
1872                       << printReg(PhysReg, TRI) << '\n');
1873 
1874     // The recoloring attempt failed, undo the changes.
1875     FixedRegisters = SaveFixedRegisters;
1876     Matrix->unassign(VirtReg);
1877 
1878     // For a newly created vreg which is also in RecoloringCandidates,
1879     // don't add it to NewVRegs because its physical register will be restored
1880     // below. Other vregs in CurrentNewVRegs are created by calling
1881     // selectOrSplit and should be added into NewVRegs.
1882     for (Register &R : CurrentNewVRegs) {
1883       if (RecoloringCandidates.count(&LIS->getInterval(R)))
1884         continue;
1885       NewVRegs.push_back(R);
1886     }
1887 
1888     // Roll back our unsuccessful recoloring. Also roll back any successful
1889     // recolorings in any recursive recoloring attempts, since it's possible
1890     // they would have introduced conflicts with assignments we will be
1891     // restoring further up the stack. Perform all unassignments prior to
1892     // reassigning, since sub-recolorings may have conflicted with the registers
1893     // we are going to restore to their original assignments.
1894     for (ssize_t I = RecolorStack.size() - 1; I >= EntryStackSize; --I) {
1895       const LiveInterval *LI;
1896       MCRegister PhysReg;
1897       std::tie(LI, PhysReg) = RecolorStack[I];
1898 
1899       if (VRM->hasPhys(LI->reg()))
1900         Matrix->unassign(*LI);
1901     }
1902 
1903     for (size_t I = EntryStackSize; I != RecolorStack.size(); ++I) {
1904       const LiveInterval *LI;
1905       MCRegister PhysReg;
1906       std::tie(LI, PhysReg) = RecolorStack[I];
1907       Matrix->assign(*LI, PhysReg);
1908     }
1909 
1910     // Pop the stack of recoloring attempts.
1911     RecolorStack.resize(EntryStackSize);
1912   }
1913 
1914   // Last chance recoloring did not worked either, give up.
1915   return ~0u;
1916 }
1917 
1918 /// tryRecoloringCandidates - Try to assign a new color to every register
1919 /// in \RecoloringQueue.
1920 /// \p NewRegs will contain any new virtual register created during the
1921 /// recoloring process.
1922 /// \p FixedRegisters[in/out] contains all the registers that have been
1923 /// recolored.
1924 /// \return true if all virtual registers in RecoloringQueue were successfully
1925 /// recolored, false otherwise.
1926 bool RAGreedy::tryRecoloringCandidates(PQueue &RecoloringQueue,
1927                                        SmallVectorImpl<Register> &NewVRegs,
1928                                        SmallVirtRegSet &FixedRegisters,
1929                                        RecoloringStack &RecolorStack,
1930                                        unsigned Depth) {
1931   while (!RecoloringQueue.empty()) {
1932     const LiveInterval *LI = dequeue(RecoloringQueue);
1933     LLVM_DEBUG(dbgs() << "Try to recolor: " << *LI << '\n');
1934     MCRegister PhysReg = selectOrSplitImpl(*LI, NewVRegs, FixedRegisters,
1935                                            RecolorStack, Depth + 1);
1936     // When splitting happens, the live-range may actually be empty.
1937     // In that case, this is okay to continue the recoloring even
1938     // if we did not find an alternative color for it. Indeed,
1939     // there will not be anything to color for LI in the end.
1940     if (PhysReg == ~0u || (!PhysReg && !LI->empty()))
1941       return false;
1942 
1943     if (!PhysReg) {
1944       assert(LI->empty() && "Only empty live-range do not require a register");
1945       LLVM_DEBUG(dbgs() << "Recoloring of " << *LI
1946                         << " succeeded. Empty LI.\n");
1947       continue;
1948     }
1949     LLVM_DEBUG(dbgs() << "Recoloring of " << *LI
1950                       << " succeeded with: " << printReg(PhysReg, TRI) << '\n');
1951 
1952     Matrix->assign(*LI, PhysReg);
1953     FixedRegisters.insert(LI->reg());
1954   }
1955   return true;
1956 }
1957 
1958 //===----------------------------------------------------------------------===//
1959 //                            Main Entry Point
1960 //===----------------------------------------------------------------------===//
1961 
1962 MCRegister RAGreedy::selectOrSplit(const LiveInterval &VirtReg,
1963                                    SmallVectorImpl<Register> &NewVRegs) {
1964   CutOffInfo = CO_None;
1965   LLVMContext &Ctx = MF->getFunction().getContext();
1966   SmallVirtRegSet FixedRegisters;
1967   RecoloringStack RecolorStack;
1968   MCRegister Reg =
1969       selectOrSplitImpl(VirtReg, NewVRegs, FixedRegisters, RecolorStack);
1970   if (Reg == ~0U && (CutOffInfo != CO_None)) {
1971     uint8_t CutOffEncountered = CutOffInfo & (CO_Depth | CO_Interf);
1972     if (CutOffEncountered == CO_Depth)
1973       Ctx.emitError("register allocation failed: maximum depth for recoloring "
1974                     "reached. Use -fexhaustive-register-search to skip "
1975                     "cutoffs");
1976     else if (CutOffEncountered == CO_Interf)
1977       Ctx.emitError("register allocation failed: maximum interference for "
1978                     "recoloring reached. Use -fexhaustive-register-search "
1979                     "to skip cutoffs");
1980     else if (CutOffEncountered == (CO_Depth | CO_Interf))
1981       Ctx.emitError("register allocation failed: maximum interference and "
1982                     "depth for recoloring reached. Use "
1983                     "-fexhaustive-register-search to skip cutoffs");
1984   }
1985   return Reg;
1986 }
1987 
1988 /// Using a CSR for the first time has a cost because it causes push|pop
1989 /// to be added to prologue|epilogue. Splitting a cold section of the live
1990 /// range can have lower cost than using the CSR for the first time;
1991 /// Spilling a live range in the cold path can have lower cost than using
1992 /// the CSR for the first time. Returns the physical register if we decide
1993 /// to use the CSR; otherwise return 0.
1994 MCRegister RAGreedy::tryAssignCSRFirstTime(
1995     const LiveInterval &VirtReg, AllocationOrder &Order, MCRegister PhysReg,
1996     uint8_t &CostPerUseLimit, SmallVectorImpl<Register> &NewVRegs) {
1997   if (ExtraInfo->getStage(VirtReg) == RS_Spill && VirtReg.isSpillable()) {
1998     // We choose spill over using the CSR for the first time if the spill cost
1999     // is lower than CSRCost.
2000     SA->analyze(&VirtReg);
2001     if (calcSpillCost() >= CSRCost)
2002       return PhysReg;
2003 
2004     // We are going to spill, set CostPerUseLimit to 1 to make sure that
2005     // we will not use a callee-saved register in tryEvict.
2006     CostPerUseLimit = 1;
2007     return 0;
2008   }
2009   if (ExtraInfo->getStage(VirtReg) < RS_Split) {
2010     // We choose pre-splitting over using the CSR for the first time if
2011     // the cost of splitting is lower than CSRCost.
2012     SA->analyze(&VirtReg);
2013     unsigned NumCands = 0;
2014     BlockFrequency BestCost = CSRCost; // Don't modify CSRCost.
2015     unsigned BestCand = calculateRegionSplitCost(VirtReg, Order, BestCost,
2016                                                  NumCands, true /*IgnoreCSR*/);
2017     if (BestCand == NoCand)
2018       // Use the CSR if we can't find a region split below CSRCost.
2019       return PhysReg;
2020 
2021     // Perform the actual pre-splitting.
2022     doRegionSplit(VirtReg, BestCand, false/*HasCompact*/, NewVRegs);
2023     return 0;
2024   }
2025   return PhysReg;
2026 }
2027 
2028 void RAGreedy::aboutToRemoveInterval(const LiveInterval &LI) {
2029   // Do not keep invalid information around.
2030   SetOfBrokenHints.remove(&LI);
2031 }
2032 
2033 void RAGreedy::initializeCSRCost() {
2034   // We use the larger one out of the command-line option and the value report
2035   // by TRI.
2036   CSRCost = BlockFrequency(
2037       std::max((unsigned)CSRFirstTimeCost, TRI->getCSRFirstUseCost()));
2038   if (!CSRCost.getFrequency())
2039     return;
2040 
2041   // Raw cost is relative to Entry == 2^14; scale it appropriately.
2042   uint64_t ActualEntry = MBFI->getEntryFreq();
2043   if (!ActualEntry) {
2044     CSRCost = 0;
2045     return;
2046   }
2047   uint64_t FixedEntry = 1 << 14;
2048   if (ActualEntry < FixedEntry)
2049     CSRCost *= BranchProbability(ActualEntry, FixedEntry);
2050   else if (ActualEntry <= UINT32_MAX)
2051     // Invert the fraction and divide.
2052     CSRCost /= BranchProbability(FixedEntry, ActualEntry);
2053   else
2054     // Can't use BranchProbability in general, since it takes 32-bit numbers.
2055     CSRCost = CSRCost.getFrequency() * (ActualEntry / FixedEntry);
2056 }
2057 
2058 /// Collect the hint info for \p Reg.
2059 /// The results are stored into \p Out.
2060 /// \p Out is not cleared before being populated.
2061 void RAGreedy::collectHintInfo(Register Reg, HintsInfo &Out) {
2062   for (const MachineInstr &Instr : MRI->reg_nodbg_instructions(Reg)) {
2063     if (!Instr.isFullCopy())
2064       continue;
2065     // Look for the other end of the copy.
2066     Register OtherReg = Instr.getOperand(0).getReg();
2067     if (OtherReg == Reg) {
2068       OtherReg = Instr.getOperand(1).getReg();
2069       if (OtherReg == Reg)
2070         continue;
2071     }
2072     // Get the current assignment.
2073     MCRegister OtherPhysReg =
2074         OtherReg.isPhysical() ? OtherReg.asMCReg() : VRM->getPhys(OtherReg);
2075     // Push the collected information.
2076     Out.push_back(HintInfo(MBFI->getBlockFreq(Instr.getParent()), OtherReg,
2077                            OtherPhysReg));
2078   }
2079 }
2080 
2081 /// Using the given \p List, compute the cost of the broken hints if
2082 /// \p PhysReg was used.
2083 /// \return The cost of \p List for \p PhysReg.
2084 BlockFrequency RAGreedy::getBrokenHintFreq(const HintsInfo &List,
2085                                            MCRegister PhysReg) {
2086   BlockFrequency Cost = 0;
2087   for (const HintInfo &Info : List) {
2088     if (Info.PhysReg != PhysReg)
2089       Cost += Info.Freq;
2090   }
2091   return Cost;
2092 }
2093 
2094 /// Using the register assigned to \p VirtReg, try to recolor
2095 /// all the live ranges that are copy-related with \p VirtReg.
2096 /// The recoloring is then propagated to all the live-ranges that have
2097 /// been recolored and so on, until no more copies can be coalesced or
2098 /// it is not profitable.
2099 /// For a given live range, profitability is determined by the sum of the
2100 /// frequencies of the non-identity copies it would introduce with the old
2101 /// and new register.
2102 void RAGreedy::tryHintRecoloring(const LiveInterval &VirtReg) {
2103   // We have a broken hint, check if it is possible to fix it by
2104   // reusing PhysReg for the copy-related live-ranges. Indeed, we evicted
2105   // some register and PhysReg may be available for the other live-ranges.
2106   SmallSet<Register, 4> Visited;
2107   SmallVector<unsigned, 2> RecoloringCandidates;
2108   HintsInfo Info;
2109   Register Reg = VirtReg.reg();
2110   MCRegister PhysReg = VRM->getPhys(Reg);
2111   // Start the recoloring algorithm from the input live-interval, then
2112   // it will propagate to the ones that are copy-related with it.
2113   Visited.insert(Reg);
2114   RecoloringCandidates.push_back(Reg);
2115 
2116   LLVM_DEBUG(dbgs() << "Trying to reconcile hints for: " << printReg(Reg, TRI)
2117                     << '(' << printReg(PhysReg, TRI) << ")\n");
2118 
2119   do {
2120     Reg = RecoloringCandidates.pop_back_val();
2121 
2122     // We cannot recolor physical register.
2123     if (Register::isPhysicalRegister(Reg))
2124       continue;
2125 
2126     // This may be a skipped class
2127     if (!VRM->hasPhys(Reg)) {
2128       assert(!ShouldAllocateClass(*TRI, *MRI->getRegClass(Reg)) &&
2129              "We have an unallocated variable which should have been handled");
2130       continue;
2131     }
2132 
2133     // Get the live interval mapped with this virtual register to be able
2134     // to check for the interference with the new color.
2135     LiveInterval &LI = LIS->getInterval(Reg);
2136     MCRegister CurrPhys = VRM->getPhys(Reg);
2137     // Check that the new color matches the register class constraints and
2138     // that it is free for this live range.
2139     if (CurrPhys != PhysReg && (!MRI->getRegClass(Reg)->contains(PhysReg) ||
2140                                 Matrix->checkInterference(LI, PhysReg)))
2141       continue;
2142 
2143     LLVM_DEBUG(dbgs() << printReg(Reg, TRI) << '(' << printReg(CurrPhys, TRI)
2144                       << ") is recolorable.\n");
2145 
2146     // Gather the hint info.
2147     Info.clear();
2148     collectHintInfo(Reg, Info);
2149     // Check if recoloring the live-range will increase the cost of the
2150     // non-identity copies.
2151     if (CurrPhys != PhysReg) {
2152       LLVM_DEBUG(dbgs() << "Checking profitability:\n");
2153       BlockFrequency OldCopiesCost = getBrokenHintFreq(Info, CurrPhys);
2154       BlockFrequency NewCopiesCost = getBrokenHintFreq(Info, PhysReg);
2155       LLVM_DEBUG(dbgs() << "Old Cost: " << OldCopiesCost.getFrequency()
2156                         << "\nNew Cost: " << NewCopiesCost.getFrequency()
2157                         << '\n');
2158       if (OldCopiesCost < NewCopiesCost) {
2159         LLVM_DEBUG(dbgs() << "=> Not profitable.\n");
2160         continue;
2161       }
2162       // At this point, the cost is either cheaper or equal. If it is
2163       // equal, we consider this is profitable because it may expose
2164       // more recoloring opportunities.
2165       LLVM_DEBUG(dbgs() << "=> Profitable.\n");
2166       // Recolor the live-range.
2167       Matrix->unassign(LI);
2168       Matrix->assign(LI, PhysReg);
2169     }
2170     // Push all copy-related live-ranges to keep reconciling the broken
2171     // hints.
2172     for (const HintInfo &HI : Info) {
2173       if (Visited.insert(HI.Reg).second)
2174         RecoloringCandidates.push_back(HI.Reg);
2175     }
2176   } while (!RecoloringCandidates.empty());
2177 }
2178 
2179 /// Try to recolor broken hints.
2180 /// Broken hints may be repaired by recoloring when an evicted variable
2181 /// freed up a register for a larger live-range.
2182 /// Consider the following example:
2183 /// BB1:
2184 ///   a =
2185 ///   b =
2186 /// BB2:
2187 ///   ...
2188 ///   = b
2189 ///   = a
2190 /// Let us assume b gets split:
2191 /// BB1:
2192 ///   a =
2193 ///   b =
2194 /// BB2:
2195 ///   c = b
2196 ///   ...
2197 ///   d = c
2198 ///   = d
2199 ///   = a
2200 /// Because of how the allocation work, b, c, and d may be assigned different
2201 /// colors. Now, if a gets evicted later:
2202 /// BB1:
2203 ///   a =
2204 ///   st a, SpillSlot
2205 ///   b =
2206 /// BB2:
2207 ///   c = b
2208 ///   ...
2209 ///   d = c
2210 ///   = d
2211 ///   e = ld SpillSlot
2212 ///   = e
2213 /// This is likely that we can assign the same register for b, c, and d,
2214 /// getting rid of 2 copies.
2215 void RAGreedy::tryHintsRecoloring() {
2216   for (const LiveInterval *LI : SetOfBrokenHints) {
2217     assert(Register::isVirtualRegister(LI->reg()) &&
2218            "Recoloring is possible only for virtual registers");
2219     // Some dead defs may be around (e.g., because of debug uses).
2220     // Ignore those.
2221     if (!VRM->hasPhys(LI->reg()))
2222       continue;
2223     tryHintRecoloring(*LI);
2224   }
2225 }
2226 
2227 MCRegister RAGreedy::selectOrSplitImpl(const LiveInterval &VirtReg,
2228                                        SmallVectorImpl<Register> &NewVRegs,
2229                                        SmallVirtRegSet &FixedRegisters,
2230                                        RecoloringStack &RecolorStack,
2231                                        unsigned Depth) {
2232   uint8_t CostPerUseLimit = uint8_t(~0u);
2233   // First try assigning a free register.
2234   auto Order =
2235       AllocationOrder::create(VirtReg.reg(), *VRM, RegClassInfo, Matrix);
2236   if (MCRegister PhysReg =
2237           tryAssign(VirtReg, Order, NewVRegs, FixedRegisters)) {
2238     // If VirtReg got an assignment, the eviction info is no longer relevant.
2239     LastEvicted.clearEvicteeInfo(VirtReg.reg());
2240     // When NewVRegs is not empty, we may have made decisions such as evicting
2241     // a virtual register, go with the earlier decisions and use the physical
2242     // register.
2243     if (CSRCost.getFrequency() &&
2244         EvictAdvisor->isUnusedCalleeSavedReg(PhysReg) && NewVRegs.empty()) {
2245       MCRegister CSRReg = tryAssignCSRFirstTime(VirtReg, Order, PhysReg,
2246                                                 CostPerUseLimit, NewVRegs);
2247       if (CSRReg || !NewVRegs.empty())
2248         // Return now if we decide to use a CSR or create new vregs due to
2249         // pre-splitting.
2250         return CSRReg;
2251     } else
2252       return PhysReg;
2253   }
2254 
2255   LiveRangeStage Stage = ExtraInfo->getStage(VirtReg);
2256   LLVM_DEBUG(dbgs() << StageName[Stage] << " Cascade "
2257                     << ExtraInfo->getCascade(VirtReg.reg()) << '\n');
2258 
2259   // Try to evict a less worthy live range, but only for ranges from the primary
2260   // queue. The RS_Split ranges already failed to do this, and they should not
2261   // get a second chance until they have been split.
2262   if (Stage != RS_Split)
2263     if (Register PhysReg =
2264             tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit,
2265                      FixedRegisters)) {
2266       Register Hint = MRI->getSimpleHint(VirtReg.reg());
2267       // If VirtReg has a hint and that hint is broken record this
2268       // virtual register as a recoloring candidate for broken hint.
2269       // Indeed, since we evicted a variable in its neighborhood it is
2270       // likely we can at least partially recolor some of the
2271       // copy-related live-ranges.
2272       if (Hint && Hint != PhysReg)
2273         SetOfBrokenHints.insert(&VirtReg);
2274       // If VirtReg eviction someone, the eviction info for it as an evictee is
2275       // no longer relevant.
2276       LastEvicted.clearEvicteeInfo(VirtReg.reg());
2277       return PhysReg;
2278     }
2279 
2280   assert((NewVRegs.empty() || Depth) && "Cannot append to existing NewVRegs");
2281 
2282   // The first time we see a live range, don't try to split or spill.
2283   // Wait until the second time, when all smaller ranges have been allocated.
2284   // This gives a better picture of the interference to split around.
2285   if (Stage < RS_Split) {
2286     ExtraInfo->setStage(VirtReg, RS_Split);
2287     LLVM_DEBUG(dbgs() << "wait for second round\n");
2288     NewVRegs.push_back(VirtReg.reg());
2289     return 0;
2290   }
2291 
2292   if (Stage < RS_Spill) {
2293     // Try splitting VirtReg or interferences.
2294     unsigned NewVRegSizeBefore = NewVRegs.size();
2295     Register PhysReg = trySplit(VirtReg, Order, NewVRegs, FixedRegisters);
2296     if (PhysReg || (NewVRegs.size() - NewVRegSizeBefore)) {
2297       // If VirtReg got split, the eviction info is no longer relevant.
2298       LastEvicted.clearEvicteeInfo(VirtReg.reg());
2299       return PhysReg;
2300     }
2301   }
2302 
2303   // If we couldn't allocate a register from spilling, there is probably some
2304   // invalid inline assembly. The base class will report it.
2305   if (Stage >= RS_Done || !VirtReg.isSpillable()) {
2306     return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters,
2307                                    RecolorStack, Depth);
2308   }
2309 
2310   // Finally spill VirtReg itself.
2311   if ((EnableDeferredSpilling ||
2312        TRI->shouldUseDeferredSpillingForVirtReg(*MF, VirtReg)) &&
2313       ExtraInfo->getStage(VirtReg) < RS_Memory) {
2314     // TODO: This is experimental and in particular, we do not model
2315     // the live range splitting done by spilling correctly.
2316     // We would need a deep integration with the spiller to do the
2317     // right thing here. Anyway, that is still good for early testing.
2318     ExtraInfo->setStage(VirtReg, RS_Memory);
2319     LLVM_DEBUG(dbgs() << "Do as if this register is in memory\n");
2320     NewVRegs.push_back(VirtReg.reg());
2321   } else {
2322     NamedRegionTimer T("spill", "Spiller", TimerGroupName,
2323                        TimerGroupDescription, TimePassesIsEnabled);
2324     LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
2325     spiller().spill(LRE);
2326     ExtraInfo->setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
2327 
2328     // Tell LiveDebugVariables about the new ranges. Ranges not being covered by
2329     // the new regs are kept in LDV (still mapping to the old register), until
2330     // we rewrite spilled locations in LDV at a later stage.
2331     DebugVars->splitRegister(VirtReg.reg(), LRE.regs(), *LIS);
2332 
2333     if (VerifyEnabled)
2334       MF->verify(this, "After spilling");
2335   }
2336 
2337   // The live virtual register requesting allocation was spilled, so tell
2338   // the caller not to allocate anything during this round.
2339   return 0;
2340 }
2341 
2342 void RAGreedy::RAGreedyStats::report(MachineOptimizationRemarkMissed &R) {
2343   using namespace ore;
2344   if (Spills) {
2345     R << NV("NumSpills", Spills) << " spills ";
2346     R << NV("TotalSpillsCost", SpillsCost) << " total spills cost ";
2347   }
2348   if (FoldedSpills) {
2349     R << NV("NumFoldedSpills", FoldedSpills) << " folded spills ";
2350     R << NV("TotalFoldedSpillsCost", FoldedSpillsCost)
2351       << " total folded spills cost ";
2352   }
2353   if (Reloads) {
2354     R << NV("NumReloads", Reloads) << " reloads ";
2355     R << NV("TotalReloadsCost", ReloadsCost) << " total reloads cost ";
2356   }
2357   if (FoldedReloads) {
2358     R << NV("NumFoldedReloads", FoldedReloads) << " folded reloads ";
2359     R << NV("TotalFoldedReloadsCost", FoldedReloadsCost)
2360       << " total folded reloads cost ";
2361   }
2362   if (ZeroCostFoldedReloads)
2363     R << NV("NumZeroCostFoldedReloads", ZeroCostFoldedReloads)
2364       << " zero cost folded reloads ";
2365   if (Copies) {
2366     R << NV("NumVRCopies", Copies) << " virtual registers copies ";
2367     R << NV("TotalCopiesCost", CopiesCost) << " total copies cost ";
2368   }
2369 }
2370 
2371 RAGreedy::RAGreedyStats RAGreedy::computeStats(MachineBasicBlock &MBB) {
2372   RAGreedyStats Stats;
2373   const MachineFrameInfo &MFI = MF->getFrameInfo();
2374   int FI;
2375 
2376   auto isSpillSlotAccess = [&MFI](const MachineMemOperand *A) {
2377     return MFI.isSpillSlotObjectIndex(cast<FixedStackPseudoSourceValue>(
2378         A->getPseudoValue())->getFrameIndex());
2379   };
2380   auto isPatchpointInstr = [](const MachineInstr &MI) {
2381     return MI.getOpcode() == TargetOpcode::PATCHPOINT ||
2382            MI.getOpcode() == TargetOpcode::STACKMAP ||
2383            MI.getOpcode() == TargetOpcode::STATEPOINT;
2384   };
2385   for (MachineInstr &MI : MBB) {
2386     if (MI.isCopy()) {
2387       MachineOperand &Dest = MI.getOperand(0);
2388       MachineOperand &Src = MI.getOperand(1);
2389       if (Dest.isReg() && Src.isReg() && Dest.getReg().isVirtual() &&
2390           Src.getReg().isVirtual())
2391         ++Stats.Copies;
2392       continue;
2393     }
2394 
2395     SmallVector<const MachineMemOperand *, 2> Accesses;
2396     if (TII->isLoadFromStackSlot(MI, FI) && MFI.isSpillSlotObjectIndex(FI)) {
2397       ++Stats.Reloads;
2398       continue;
2399     }
2400     if (TII->isStoreToStackSlot(MI, FI) && MFI.isSpillSlotObjectIndex(FI)) {
2401       ++Stats.Spills;
2402       continue;
2403     }
2404     if (TII->hasLoadFromStackSlot(MI, Accesses) &&
2405         llvm::any_of(Accesses, isSpillSlotAccess)) {
2406       if (!isPatchpointInstr(MI)) {
2407         Stats.FoldedReloads += Accesses.size();
2408         continue;
2409       }
2410       // For statepoint there may be folded and zero cost folded stack reloads.
2411       std::pair<unsigned, unsigned> NonZeroCostRange =
2412           TII->getPatchpointUnfoldableRange(MI);
2413       SmallSet<unsigned, 16> FoldedReloads;
2414       SmallSet<unsigned, 16> ZeroCostFoldedReloads;
2415       for (unsigned Idx = 0, E = MI.getNumOperands(); Idx < E; ++Idx) {
2416         MachineOperand &MO = MI.getOperand(Idx);
2417         if (!MO.isFI() || !MFI.isSpillSlotObjectIndex(MO.getIndex()))
2418           continue;
2419         if (Idx >= NonZeroCostRange.first && Idx < NonZeroCostRange.second)
2420           FoldedReloads.insert(MO.getIndex());
2421         else
2422           ZeroCostFoldedReloads.insert(MO.getIndex());
2423       }
2424       // If stack slot is used in folded reload it is not zero cost then.
2425       for (unsigned Slot : FoldedReloads)
2426         ZeroCostFoldedReloads.erase(Slot);
2427       Stats.FoldedReloads += FoldedReloads.size();
2428       Stats.ZeroCostFoldedReloads += ZeroCostFoldedReloads.size();
2429       continue;
2430     }
2431     Accesses.clear();
2432     if (TII->hasStoreToStackSlot(MI, Accesses) &&
2433         llvm::any_of(Accesses, isSpillSlotAccess)) {
2434       Stats.FoldedSpills += Accesses.size();
2435     }
2436   }
2437   // Set cost of collected statistic by multiplication to relative frequency of
2438   // this basic block.
2439   float RelFreq = MBFI->getBlockFreqRelativeToEntryBlock(&MBB);
2440   Stats.ReloadsCost = RelFreq * Stats.Reloads;
2441   Stats.FoldedReloadsCost = RelFreq * Stats.FoldedReloads;
2442   Stats.SpillsCost = RelFreq * Stats.Spills;
2443   Stats.FoldedSpillsCost = RelFreq * Stats.FoldedSpills;
2444   Stats.CopiesCost = RelFreq * Stats.Copies;
2445   return Stats;
2446 }
2447 
2448 RAGreedy::RAGreedyStats RAGreedy::reportStats(MachineLoop *L) {
2449   RAGreedyStats Stats;
2450 
2451   // Sum up the spill and reloads in subloops.
2452   for (MachineLoop *SubLoop : *L)
2453     Stats.add(reportStats(SubLoop));
2454 
2455   for (MachineBasicBlock *MBB : L->getBlocks())
2456     // Handle blocks that were not included in subloops.
2457     if (Loops->getLoopFor(MBB) == L)
2458       Stats.add(computeStats(*MBB));
2459 
2460   if (!Stats.isEmpty()) {
2461     using namespace ore;
2462 
2463     ORE->emit([&]() {
2464       MachineOptimizationRemarkMissed R(DEBUG_TYPE, "LoopSpillReloadCopies",
2465                                         L->getStartLoc(), L->getHeader());
2466       Stats.report(R);
2467       R << "generated in loop";
2468       return R;
2469     });
2470   }
2471   return Stats;
2472 }
2473 
2474 void RAGreedy::reportStats() {
2475   if (!ORE->allowExtraAnalysis(DEBUG_TYPE))
2476     return;
2477   RAGreedyStats Stats;
2478   for (MachineLoop *L : *Loops)
2479     Stats.add(reportStats(L));
2480   // Process non-loop blocks.
2481   for (MachineBasicBlock &MBB : *MF)
2482     if (!Loops->getLoopFor(&MBB))
2483       Stats.add(computeStats(MBB));
2484   if (!Stats.isEmpty()) {
2485     using namespace ore;
2486 
2487     ORE->emit([&]() {
2488       DebugLoc Loc;
2489       if (auto *SP = MF->getFunction().getSubprogram())
2490         Loc = DILocation::get(SP->getContext(), SP->getLine(), 1, SP);
2491       MachineOptimizationRemarkMissed R(DEBUG_TYPE, "SpillReloadCopies", Loc,
2492                                         &MF->front());
2493       Stats.report(R);
2494       R << "generated in function";
2495       return R;
2496     });
2497   }
2498 }
2499 
2500 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
2501   LLVM_DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
2502                     << "********** Function: " << mf.getName() << '\n');
2503 
2504   MF = &mf;
2505   TII = MF->getSubtarget().getInstrInfo();
2506 
2507   if (VerifyEnabled)
2508     MF->verify(this, "Before greedy register allocator");
2509 
2510   RegAllocBase::init(getAnalysis<VirtRegMap>(),
2511                      getAnalysis<LiveIntervals>(),
2512                      getAnalysis<LiveRegMatrix>());
2513   Indexes = &getAnalysis<SlotIndexes>();
2514   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
2515   DomTree = &getAnalysis<MachineDominatorTree>();
2516   ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
2517   Loops = &getAnalysis<MachineLoopInfo>();
2518   Bundles = &getAnalysis<EdgeBundles>();
2519   SpillPlacer = &getAnalysis<SpillPlacement>();
2520   DebugVars = &getAnalysis<LiveDebugVariables>();
2521   AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2522 
2523   initializeCSRCost();
2524 
2525   RegCosts = TRI->getRegisterCosts(*MF);
2526   RegClassPriorityTrumpsGlobalness =
2527       GreedyRegClassPriorityTrumpsGlobalness.getNumOccurrences()
2528           ? GreedyRegClassPriorityTrumpsGlobalness
2529           : TRI->regClassPriorityTrumpsGlobalness(*MF);
2530 
2531   ExtraInfo.emplace();
2532   EvictAdvisor =
2533       getAnalysis<RegAllocEvictionAdvisorAnalysis>().getAdvisor(*MF, *this);
2534 
2535   VRAI = std::make_unique<VirtRegAuxInfo>(*MF, *LIS, *VRM, *Loops, *MBFI);
2536   SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM, *VRAI));
2537 
2538   VRAI->calculateSpillWeightsAndHints();
2539 
2540   LLVM_DEBUG(LIS->dump());
2541 
2542   SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
2543   SE.reset(new SplitEditor(*SA, *AA, *LIS, *VRM, *DomTree, *MBFI, *VRAI));
2544 
2545   IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
2546   GlobalCand.resize(32);  // This will grow as needed.
2547   SetOfBrokenHints.clear();
2548   LastEvicted.clear();
2549 
2550   allocatePhysRegs();
2551   tryHintsRecoloring();
2552 
2553   if (VerifyEnabled)
2554     MF->verify(this, "Before post optimization");
2555   postOptimization();
2556   reportStats();
2557 
2558   releaseMemory();
2559   return true;
2560 }
2561