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