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