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