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