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