1 //===-- RegAllocGreedy.cpp - greedy register allocator --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the RAGreedy function pass for register allocation in
13 //===----------------------------------------------------------------------===//
15 #include "AllocationOrder.h"
16 #include "InterferenceCache.h"
17 #include "LiveDebugVariables.h"
18 #include "RegAllocBase.h"
19 #include "SpillPlacement.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/CalcSpillWeights.h"
25 #include "llvm/CodeGen/EdgeBundles.h"
26 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
27 #include "llvm/CodeGen/LiveRangeEdit.h"
28 #include "llvm/CodeGen/LiveRegMatrix.h"
29 #include "llvm/CodeGen/LiveStackAnalysis.h"
30 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
31 #include "llvm/CodeGen/MachineDominators.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunctionPass.h"
34 #include "llvm/CodeGen/MachineLoopInfo.h"
35 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/Passes.h"
38 #include "llvm/CodeGen/RegAllocRegistry.h"
39 #include "llvm/CodeGen/RegisterClassInfo.h"
40 #include "llvm/CodeGen/VirtRegMap.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/PassAnalysisSupport.h"
43 #include "llvm/Support/BranchProbability.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/Timer.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/Target/TargetInstrInfo.h"
50 #include "llvm/Target/TargetSubtargetInfo.h"
55 #define DEBUG_TYPE "regalloc"
57 STATISTIC(NumGlobalSplits, "Number of split global live ranges");
58 STATISTIC(NumLocalSplits, "Number of split local live ranges");
59 STATISTIC(NumEvicted, "Number of interferences evicted");
61 static cl::opt<SplitEditor::ComplementSpillMode> SplitSpillMode(
62 "split-spill-mode", cl::Hidden,
63 cl::desc("Spill mode for splitting live ranges"),
64 cl::values(clEnumValN(SplitEditor::SM_Partition, "default", "Default"),
65 clEnumValN(SplitEditor::SM_Size, "size", "Optimize for size"),
66 clEnumValN(SplitEditor::SM_Speed, "speed", "Optimize for speed")),
67 cl::init(SplitEditor::SM_Speed));
69 static cl::opt<unsigned>
70 LastChanceRecoloringMaxDepth("lcr-max-depth", cl::Hidden,
71 cl::desc("Last chance recoloring max depth"),
74 static cl::opt<unsigned> LastChanceRecoloringMaxInterference(
75 "lcr-max-interf", cl::Hidden,
76 cl::desc("Last chance recoloring maximum number of considered"
77 " interference at a time"),
81 ExhaustiveSearch("exhaustive-register-search", cl::NotHidden,
82 cl::desc("Exhaustive Search for registers bypassing the depth "
83 "and interference cutoffs of last chance recoloring"));
85 static cl::opt<bool> EnableLocalReassignment(
86 "enable-local-reassign", cl::Hidden,
87 cl::desc("Local reassignment can yield better allocation decisions, but "
88 "may be compile time intensive"),
91 static cl::opt<bool> EnableDeferredSpilling(
92 "enable-deferred-spilling", cl::Hidden,
93 cl::desc("Instead of spilling a variable right away, defer the actual "
94 "code insertion to the end of the allocation. That way the "
95 "allocator might still find a suitable coloring for this "
96 "variable because of other evicted variables."),
99 // FIXME: Find a good default for this flag and remove the flag.
100 static cl::opt<unsigned>
101 CSRFirstTimeCost("regalloc-csr-first-time-cost",
102 cl::desc("Cost for first time use of callee-saved register."),
103 cl::init(0), cl::Hidden);
105 static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator",
106 createGreedyRegisterAllocator);
109 class RAGreedy : public MachineFunctionPass,
111 private LiveRangeEdit::Delegate {
112 // Convenient shortcuts.
113 typedef std::priority_queue<std::pair<unsigned, unsigned> > PQueue;
114 typedef SmallPtrSet<LiveInterval *, 4> SmallLISet;
115 typedef SmallSet<unsigned, 16> SmallVirtRegSet;
120 // Shortcuts to some useful interface.
121 const TargetInstrInfo *TII;
122 const TargetRegisterInfo *TRI;
123 RegisterClassInfo RCI;
126 SlotIndexes *Indexes;
127 MachineBlockFrequencyInfo *MBFI;
128 MachineDominatorTree *DomTree;
129 MachineLoopInfo *Loops;
130 MachineOptimizationRemarkEmitter *ORE;
131 EdgeBundles *Bundles;
132 SpillPlacement *SpillPlacer;
133 LiveDebugVariables *DebugVars;
137 std::unique_ptr<Spiller> SpillerInstance;
139 unsigned NextCascade;
141 // Live ranges pass through a number of stages as we try to allocate them.
142 // Some of the stages may also create new live ranges:
144 // - Region splitting.
145 // - Per-block splitting.
146 // - Local splitting.
149 // Ranges produced by one of the stages skip the previous stages when they are
150 // dequeued. This improves performance because we can skip interference checks
151 // that are unlikely to give any results. It also guarantees that the live
152 // range splitting algorithm terminates, something that is otherwise hard to
154 enum LiveRangeStage {
155 /// Newly created live range that has never been queued.
158 /// Only attempt assignment and eviction. Then requeue as RS_Split.
161 /// Attempt live range splitting if assignment is impossible.
164 /// Attempt more aggressive live range splitting that is guaranteed to make
165 /// progress. This is used for split products that may not be making
169 /// Live range will be spilled. No more splitting will be attempted.
173 /// Live range is in memory. Because of other evictions, it might get moved
174 /// in a register in the end.
177 /// There is nothing more we can do to this live range. Abort compilation
178 /// if it can't be assigned.
182 // Enum CutOffStage to keep a track whether the register allocation failed
183 // because of the cutoffs encountered in last chance recoloring.
184 // Note: This is used as bitmask. New value should be next power of 2.
186 // No cutoffs encountered
189 // lcr-max-depth cutoff encountered
192 // lcr-max-interf cutoff encountered
199 static const char *const StageName[];
202 // RegInfo - Keep additional information about each live range.
204 LiveRangeStage Stage;
206 // Cascade - Eviction loop prevention. See canEvictInterference().
209 RegInfo() : Stage(RS_New), Cascade(0) {}
212 IndexedMap<RegInfo, VirtReg2IndexFunctor> ExtraRegInfo;
214 LiveRangeStage getStage(const LiveInterval &VirtReg) const {
215 return ExtraRegInfo[VirtReg.reg].Stage;
218 void setStage(const LiveInterval &VirtReg, LiveRangeStage Stage) {
219 ExtraRegInfo.resize(MRI->getNumVirtRegs());
220 ExtraRegInfo[VirtReg.reg].Stage = Stage;
223 template<typename Iterator>
224 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
225 ExtraRegInfo.resize(MRI->getNumVirtRegs());
226 for (;Begin != End; ++Begin) {
227 unsigned Reg = *Begin;
228 if (ExtraRegInfo[Reg].Stage == RS_New)
229 ExtraRegInfo[Reg].Stage = NewStage;
233 /// Cost of evicting interference.
234 struct EvictionCost {
235 unsigned BrokenHints; ///< Total number of broken hints.
236 float MaxWeight; ///< Maximum spill weight evicted.
238 EvictionCost(): BrokenHints(0), MaxWeight(0) {}
240 bool isMax() const { return BrokenHints == ~0u; }
242 void setMax() { BrokenHints = ~0u; }
244 void setBrokenHints(unsigned NHints) { BrokenHints = NHints; }
246 bool operator<(const EvictionCost &O) const {
247 return std::tie(BrokenHints, MaxWeight) <
248 std::tie(O.BrokenHints, O.MaxWeight);
253 std::unique_ptr<SplitAnalysis> SA;
254 std::unique_ptr<SplitEditor> SE;
256 /// Cached per-block interference maps
257 InterferenceCache IntfCache;
259 /// All basic blocks where the current register has uses.
260 SmallVector<SpillPlacement::BlockConstraint, 8> SplitConstraints;
262 /// Global live range splitting candidate info.
263 struct GlobalSplitCandidate {
264 // Register intended for assignment, or 0.
267 // SplitKit interval index for this candidate.
270 // Interference for PhysReg.
271 InterferenceCache::Cursor Intf;
273 // Bundles where this candidate should be live.
274 BitVector LiveBundles;
275 SmallVector<unsigned, 8> ActiveBlocks;
277 void reset(InterferenceCache &Cache, unsigned Reg) {
280 Intf.setPhysReg(Cache, Reg);
282 ActiveBlocks.clear();
285 // Set B[i] = C for every live bundle where B[i] was NoCand.
286 unsigned getBundles(SmallVectorImpl<unsigned> &B, unsigned C) {
288 for (unsigned i : LiveBundles.set_bits())
289 if (B[i] == NoCand) {
297 /// Candidate info for each PhysReg in AllocationOrder.
298 /// This vector never shrinks, but grows to the size of the largest register
300 SmallVector<GlobalSplitCandidate, 32> GlobalCand;
302 enum : unsigned { NoCand = ~0u };
304 /// Candidate map. Each edge bundle is assigned to a GlobalCand entry, or to
305 /// NoCand which indicates the stack interval.
306 SmallVector<unsigned, 32> BundleCand;
308 /// Callee-save register cost, calculated once per machine function.
309 BlockFrequency CSRCost;
311 /// Run or not the local reassignment heuristic. This information is
312 /// obtained from the TargetSubtargetInfo.
313 bool EnableLocalReassign;
315 /// Set of broken hints that may be reconciled later because of eviction.
316 SmallSetVector<LiveInterval *, 8> SetOfBrokenHints;
321 /// Return the pass name.
322 StringRef getPassName() const override { return "Greedy Register Allocator"; }
324 /// RAGreedy analysis usage.
325 void getAnalysisUsage(AnalysisUsage &AU) const override;
326 void releaseMemory() override;
327 Spiller &spiller() override { return *SpillerInstance; }
328 void enqueue(LiveInterval *LI) override;
329 LiveInterval *dequeue() override;
330 unsigned selectOrSplit(LiveInterval&, SmallVectorImpl<unsigned>&) override;
331 void aboutToRemoveInterval(LiveInterval &) override;
333 /// Perform register allocation.
334 bool runOnMachineFunction(MachineFunction &mf) override;
336 MachineFunctionProperties getRequiredProperties() const override {
337 return MachineFunctionProperties().set(
338 MachineFunctionProperties::Property::NoPHIs);
344 unsigned selectOrSplitImpl(LiveInterval &, SmallVectorImpl<unsigned> &,
345 SmallVirtRegSet &, unsigned = 0);
347 bool LRE_CanEraseVirtReg(unsigned) override;
348 void LRE_WillShrinkVirtReg(unsigned) override;
349 void LRE_DidCloneVirtReg(unsigned, unsigned) override;
350 void enqueue(PQueue &CurQueue, LiveInterval *LI);
351 LiveInterval *dequeue(PQueue &CurQueue);
353 BlockFrequency calcSpillCost();
354 bool addSplitConstraints(InterferenceCache::Cursor, BlockFrequency&);
355 void addThroughConstraints(InterferenceCache::Cursor, ArrayRef<unsigned>);
356 void growRegion(GlobalSplitCandidate &Cand);
357 BlockFrequency calcGlobalSplitCost(GlobalSplitCandidate&);
358 bool calcCompactRegion(GlobalSplitCandidate&);
359 void splitAroundRegion(LiveRangeEdit&, ArrayRef<unsigned>);
360 void calcGapWeights(unsigned, SmallVectorImpl<float>&);
361 unsigned canReassign(LiveInterval &VirtReg, unsigned PhysReg);
362 bool shouldEvict(LiveInterval &A, bool, LiveInterval &B, bool);
363 bool canEvictInterference(LiveInterval&, unsigned, bool, EvictionCost&);
364 void evictInterference(LiveInterval&, unsigned,
365 SmallVectorImpl<unsigned>&);
366 bool mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
367 SmallLISet &RecoloringCandidates,
368 const SmallVirtRegSet &FixedRegisters);
370 unsigned tryAssign(LiveInterval&, AllocationOrder&,
371 SmallVectorImpl<unsigned>&);
372 unsigned tryEvict(LiveInterval&, AllocationOrder&,
373 SmallVectorImpl<unsigned>&, unsigned = ~0u);
374 unsigned tryRegionSplit(LiveInterval&, AllocationOrder&,
375 SmallVectorImpl<unsigned>&);
376 /// Calculate cost of region splitting.
377 unsigned calculateRegionSplitCost(LiveInterval &VirtReg,
378 AllocationOrder &Order,
379 BlockFrequency &BestCost,
380 unsigned &NumCands, bool IgnoreCSR);
381 /// Perform region splitting.
382 unsigned doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
384 SmallVectorImpl<unsigned> &NewVRegs);
385 /// Check other options before using a callee-saved register for the first
387 unsigned tryAssignCSRFirstTime(LiveInterval &VirtReg, AllocationOrder &Order,
388 unsigned PhysReg, unsigned &CostPerUseLimit,
389 SmallVectorImpl<unsigned> &NewVRegs);
390 void initializeCSRCost();
391 unsigned tryBlockSplit(LiveInterval&, AllocationOrder&,
392 SmallVectorImpl<unsigned>&);
393 unsigned tryInstructionSplit(LiveInterval&, AllocationOrder&,
394 SmallVectorImpl<unsigned>&);
395 unsigned tryLocalSplit(LiveInterval&, AllocationOrder&,
396 SmallVectorImpl<unsigned>&);
397 unsigned trySplit(LiveInterval&, AllocationOrder&,
398 SmallVectorImpl<unsigned>&);
399 unsigned tryLastChanceRecoloring(LiveInterval &, AllocationOrder &,
400 SmallVectorImpl<unsigned> &,
401 SmallVirtRegSet &, unsigned);
402 bool tryRecoloringCandidates(PQueue &, SmallVectorImpl<unsigned> &,
403 SmallVirtRegSet &, unsigned);
404 void tryHintRecoloring(LiveInterval &);
405 void tryHintsRecoloring();
407 /// Model the information carried by one end of a copy.
409 /// The frequency of the copy.
411 /// The virtual register or physical register.
413 /// Its currently assigned register.
414 /// In case of a physical register Reg == PhysReg.
416 HintInfo(BlockFrequency Freq, unsigned Reg, unsigned PhysReg)
417 : Freq(Freq), Reg(Reg), PhysReg(PhysReg) {}
419 typedef SmallVector<HintInfo, 4> HintsInfo;
420 BlockFrequency getBrokenHintFreq(const HintsInfo &, unsigned);
421 void collectHintInfo(unsigned, HintsInfo &);
423 bool isUnusedCalleeSavedReg(unsigned PhysReg) const;
425 /// Compute and report the number of spills and reloads for a loop.
426 void reportNumberOfSplillsReloads(MachineLoop *L, unsigned &Reloads,
427 unsigned &FoldedReloads, unsigned &Spills,
428 unsigned &FoldedSpills);
430 /// Report the number of spills and reloads for each loop.
431 void reportNumberOfSplillsReloads() {
432 for (MachineLoop *L : *Loops) {
433 unsigned Reloads, FoldedReloads, Spills, FoldedSpills;
434 reportNumberOfSplillsReloads(L, Reloads, FoldedReloads, Spills,
439 } // end anonymous namespace
441 char RAGreedy::ID = 0;
442 char &llvm::RAGreedyID = RAGreedy::ID;
444 INITIALIZE_PASS_BEGIN(RAGreedy, "greedy",
445 "Greedy Register Allocator", false, false)
446 INITIALIZE_PASS_DEPENDENCY(LiveDebugVariables)
447 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
448 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
449 INITIALIZE_PASS_DEPENDENCY(RegisterCoalescer)
450 INITIALIZE_PASS_DEPENDENCY(MachineScheduler)
451 INITIALIZE_PASS_DEPENDENCY(LiveStacks)
452 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
453 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
454 INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
455 INITIALIZE_PASS_DEPENDENCY(LiveRegMatrix)
456 INITIALIZE_PASS_DEPENDENCY(EdgeBundles)
457 INITIALIZE_PASS_DEPENDENCY(SpillPlacement)
458 INITIALIZE_PASS_DEPENDENCY(MachineOptimizationRemarkEmitterPass)
459 INITIALIZE_PASS_END(RAGreedy, "greedy",
460 "Greedy Register Allocator", false, false)
463 const char *const RAGreedy::StageName[] = {
474 // Hysteresis to use when comparing floats.
475 // This helps stabilize decisions based on float comparisons.
476 const float Hysteresis = (2007 / 2048.0f); // 0.97998046875
479 FunctionPass* llvm::createGreedyRegisterAllocator() {
480 return new RAGreedy();
483 RAGreedy::RAGreedy(): MachineFunctionPass(ID) {
486 void RAGreedy::getAnalysisUsage(AnalysisUsage &AU) const {
487 AU.setPreservesCFG();
488 AU.addRequired<MachineBlockFrequencyInfo>();
489 AU.addPreserved<MachineBlockFrequencyInfo>();
490 AU.addRequired<AAResultsWrapperPass>();
491 AU.addPreserved<AAResultsWrapperPass>();
492 AU.addRequired<LiveIntervals>();
493 AU.addPreserved<LiveIntervals>();
494 AU.addRequired<SlotIndexes>();
495 AU.addPreserved<SlotIndexes>();
496 AU.addRequired<LiveDebugVariables>();
497 AU.addPreserved<LiveDebugVariables>();
498 AU.addRequired<LiveStacks>();
499 AU.addPreserved<LiveStacks>();
500 AU.addRequired<MachineDominatorTree>();
501 AU.addPreserved<MachineDominatorTree>();
502 AU.addRequired<MachineLoopInfo>();
503 AU.addPreserved<MachineLoopInfo>();
504 AU.addRequired<VirtRegMap>();
505 AU.addPreserved<VirtRegMap>();
506 AU.addRequired<LiveRegMatrix>();
507 AU.addPreserved<LiveRegMatrix>();
508 AU.addRequired<EdgeBundles>();
509 AU.addRequired<SpillPlacement>();
510 AU.addRequired<MachineOptimizationRemarkEmitterPass>();
511 MachineFunctionPass::getAnalysisUsage(AU);
515 //===----------------------------------------------------------------------===//
516 // LiveRangeEdit delegate methods
517 //===----------------------------------------------------------------------===//
519 bool RAGreedy::LRE_CanEraseVirtReg(unsigned VirtReg) {
520 if (VRM->hasPhys(VirtReg)) {
521 LiveInterval &LI = LIS->getInterval(VirtReg);
522 Matrix->unassign(LI);
523 aboutToRemoveInterval(LI);
526 // Unassigned virtreg is probably in the priority queue.
527 // RegAllocBase will erase it after dequeueing.
531 void RAGreedy::LRE_WillShrinkVirtReg(unsigned VirtReg) {
532 if (!VRM->hasPhys(VirtReg))
535 // Register is assigned, put it back on the queue for reassignment.
536 LiveInterval &LI = LIS->getInterval(VirtReg);
537 Matrix->unassign(LI);
541 void RAGreedy::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
542 // Cloning a register we haven't even heard about yet? Just ignore it.
543 if (!ExtraRegInfo.inBounds(Old))
546 // LRE may clone a virtual register because dead code elimination causes it to
547 // be split into connected components. The new components are much smaller
548 // than the original, so they should get a new chance at being assigned.
549 // same stage as the parent.
550 ExtraRegInfo[Old].Stage = RS_Assign;
551 ExtraRegInfo.grow(New);
552 ExtraRegInfo[New] = ExtraRegInfo[Old];
555 void RAGreedy::releaseMemory() {
556 SpillerInstance.reset();
557 ExtraRegInfo.clear();
561 void RAGreedy::enqueue(LiveInterval *LI) { enqueue(Queue, LI); }
563 void RAGreedy::enqueue(PQueue &CurQueue, LiveInterval *LI) {
564 // Prioritize live ranges by size, assigning larger ranges first.
565 // The queue holds (size, reg) pairs.
566 const unsigned Size = LI->getSize();
567 const unsigned Reg = LI->reg;
568 assert(TargetRegisterInfo::isVirtualRegister(Reg) &&
569 "Can only enqueue virtual registers");
572 ExtraRegInfo.grow(Reg);
573 if (ExtraRegInfo[Reg].Stage == RS_New)
574 ExtraRegInfo[Reg].Stage = RS_Assign;
576 if (ExtraRegInfo[Reg].Stage == RS_Split) {
577 // Unsplit ranges that couldn't be allocated immediately are deferred until
578 // everything else has been allocated.
580 } else if (ExtraRegInfo[Reg].Stage == RS_Memory) {
581 // Memory operand should be considered last.
582 // Change the priority such that Memory operand are assigned in
583 // the reverse order that they came in.
584 // TODO: Make this a member variable and probably do something about hints.
585 static unsigned MemOp = 0;
588 // Giant live ranges fall back to the global assignment heuristic, which
589 // prevents excessive spilling in pathological cases.
590 bool ReverseLocal = TRI->reverseLocalAssignment();
591 const TargetRegisterClass &RC = *MRI->getRegClass(Reg);
592 bool ForceGlobal = !ReverseLocal &&
593 (Size / SlotIndex::InstrDist) > (2 * RC.getNumRegs());
595 if (ExtraRegInfo[Reg].Stage == RS_Assign && !ForceGlobal && !LI->empty() &&
596 LIS->intervalIsInOneMBB(*LI)) {
597 // Allocate original local ranges in linear instruction order. Since they
598 // are singly defined, this produces optimal coloring in the absence of
599 // global interference and other constraints.
601 Prio = LI->beginIndex().getInstrDistance(Indexes->getLastIndex());
603 // Allocating bottom up may allow many short LRGs to be assigned first
604 // to one of the cheap registers. This could be much faster for very
605 // large blocks on targets with many physical registers.
606 Prio = Indexes->getZeroIndex().getInstrDistance(LI->endIndex());
608 Prio |= RC.AllocationPriority << 24;
610 // Allocate global and split ranges in long->short order. Long ranges that
611 // don't fit should be spilled (or split) ASAP so they don't create
612 // interference. Mark a bit to prioritize global above local ranges.
613 Prio = (1u << 29) + Size;
615 // Mark a higher bit to prioritize global and local above RS_Split.
618 // Boost ranges that have a physical register hint.
619 if (VRM->hasKnownPreference(Reg))
622 // The virtual register number is a tie breaker for same-sized ranges.
623 // Give lower vreg numbers higher priority to assign them first.
624 CurQueue.push(std::make_pair(Prio, ~Reg));
627 LiveInterval *RAGreedy::dequeue() { return dequeue(Queue); }
629 LiveInterval *RAGreedy::dequeue(PQueue &CurQueue) {
630 if (CurQueue.empty())
632 LiveInterval *LI = &LIS->getInterval(~CurQueue.top().second);
638 //===----------------------------------------------------------------------===//
640 //===----------------------------------------------------------------------===//
642 /// tryAssign - Try to assign VirtReg to an available register.
643 unsigned RAGreedy::tryAssign(LiveInterval &VirtReg,
644 AllocationOrder &Order,
645 SmallVectorImpl<unsigned> &NewVRegs) {
648 while ((PhysReg = Order.next()))
649 if (!Matrix->checkInterference(VirtReg, PhysReg))
651 if (!PhysReg || Order.isHint())
654 // PhysReg is available, but there may be a better choice.
656 // If we missed a simple hint, try to cheaply evict interference from the
657 // preferred register.
658 if (unsigned Hint = MRI->getSimpleHint(VirtReg.reg))
659 if (Order.isHint(Hint)) {
660 DEBUG(dbgs() << "missed hint " << PrintReg(Hint, TRI) << '\n');
661 EvictionCost MaxCost;
662 MaxCost.setBrokenHints(1);
663 if (canEvictInterference(VirtReg, Hint, true, MaxCost)) {
664 evictInterference(VirtReg, Hint, NewVRegs);
667 // Record the missed hint, we may be able to recover
668 // at the end if the surrounding allocation changed.
669 SetOfBrokenHints.insert(&VirtReg);
672 // Try to evict interference from a cheaper alternative.
673 unsigned Cost = TRI->getCostPerUse(PhysReg);
675 // Most registers have 0 additional cost.
679 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is available at cost " << Cost
681 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost);
682 return CheapReg ? CheapReg : PhysReg;
686 //===----------------------------------------------------------------------===//
687 // Interference eviction
688 //===----------------------------------------------------------------------===//
690 unsigned RAGreedy::canReassign(LiveInterval &VirtReg, unsigned PrevReg) {
691 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo, Matrix);
693 while ((PhysReg = Order.next())) {
694 if (PhysReg == PrevReg)
697 MCRegUnitIterator Units(PhysReg, TRI);
698 for (; Units.isValid(); ++Units) {
699 // Instantiate a "subquery", not to be confused with the Queries array.
700 LiveIntervalUnion::Query subQ(VirtReg, Matrix->getLiveUnions()[*Units]);
701 if (subQ.checkInterference())
704 // If no units have interference, break out with the current PhysReg.
705 if (!Units.isValid())
709 DEBUG(dbgs() << "can reassign: " << VirtReg << " from "
710 << PrintReg(PrevReg, TRI) << " to " << PrintReg(PhysReg, TRI)
715 /// shouldEvict - determine if A should evict the assigned live range B. The
716 /// eviction policy defined by this function together with the allocation order
717 /// defined by enqueue() decides which registers ultimately end up being split
720 /// Cascade numbers are used to prevent infinite loops if this function is a
723 /// @param A The live range to be assigned.
724 /// @param IsHint True when A is about to be assigned to its preferred
726 /// @param B The live range to be evicted.
727 /// @param BreaksHint True when B is already assigned to its preferred register.
728 bool RAGreedy::shouldEvict(LiveInterval &A, bool IsHint,
729 LiveInterval &B, bool BreaksHint) {
730 bool CanSplit = getStage(B) < RS_Spill;
732 // Be fairly aggressive about following hints as long as the evictee can be
734 if (CanSplit && IsHint && !BreaksHint)
737 if (A.weight > B.weight) {
738 DEBUG(dbgs() << "should evict: " << B << " w= " << B.weight << '\n');
744 /// canEvictInterference - Return true if all interferences between VirtReg and
745 /// PhysReg can be evicted.
747 /// @param VirtReg Live range that is about to be assigned.
748 /// @param PhysReg Desired register for assignment.
749 /// @param IsHint True when PhysReg is VirtReg's preferred register.
750 /// @param MaxCost Only look for cheaper candidates and update with new cost
751 /// when returning true.
752 /// @returns True when interference can be evicted cheaper than MaxCost.
753 bool RAGreedy::canEvictInterference(LiveInterval &VirtReg, unsigned PhysReg,
754 bool IsHint, EvictionCost &MaxCost) {
755 // It is only possible to evict virtual register interference.
756 if (Matrix->checkInterference(VirtReg, PhysReg) > LiveRegMatrix::IK_VirtReg)
759 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
761 // Find VirtReg's cascade number. This will be unassigned if VirtReg was never
762 // involved in an eviction before. If a cascade number was assigned, deny
763 // evicting anything with the same or a newer cascade number. This prevents
764 // infinite eviction loops.
766 // This works out so a register without a cascade number is allowed to evict
767 // anything, and it can be evicted by anything.
768 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
770 Cascade = NextCascade;
773 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
774 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
775 // If there is 10 or more interferences, chances are one is heavier.
776 if (Q.collectInterferingVRegs(10) >= 10)
779 // Check if any interfering live range is heavier than MaxWeight.
780 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
781 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
782 assert(TargetRegisterInfo::isVirtualRegister(Intf->reg) &&
783 "Only expecting virtual register interference from query");
784 // Never evict spill products. They cannot split or spill.
785 if (getStage(*Intf) == RS_Done)
787 // Once a live range becomes small enough, it is urgent that we find a
788 // register for it. This is indicated by an infinite spill weight. These
789 // urgent live ranges get to evict almost anything.
791 // Also allow urgent evictions of unspillable ranges from a strictly
792 // larger allocation order.
793 bool Urgent = !VirtReg.isSpillable() &&
794 (Intf->isSpillable() ||
795 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(VirtReg.reg)) <
796 RegClassInfo.getNumAllocatableRegs(MRI->getRegClass(Intf->reg)));
797 // Only evict older cascades or live ranges without a cascade.
798 unsigned IntfCascade = ExtraRegInfo[Intf->reg].Cascade;
799 if (Cascade <= IntfCascade) {
802 // We permit breaking cascades for urgent evictions. It should be the
803 // last resort, though, so make it really expensive.
804 Cost.BrokenHints += 10;
806 // Would this break a satisfied hint?
807 bool BreaksHint = VRM->hasPreferredPhys(Intf->reg);
808 // Update eviction cost.
809 Cost.BrokenHints += BreaksHint;
810 Cost.MaxWeight = std::max(Cost.MaxWeight, Intf->weight);
811 // Abort if this would be too expensive.
812 if (!(Cost < MaxCost))
816 // Apply the eviction policy for non-urgent evictions.
817 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
819 // If !MaxCost.isMax(), then we're just looking for a cheap register.
820 // Evicting another local live range in this case could lead to suboptimal
822 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
823 (!EnableLocalReassign || !canReassign(*Intf, PhysReg))) {
832 /// evictInterference - Evict any interferring registers that prevent VirtReg
833 /// from being assigned to Physreg. This assumes that canEvictInterference
835 void RAGreedy::evictInterference(LiveInterval &VirtReg, unsigned PhysReg,
836 SmallVectorImpl<unsigned> &NewVRegs) {
837 // Make sure that VirtReg has a cascade number, and assign that cascade
838 // number to every evicted register. These live ranges than then only be
839 // evicted by a newer cascade, preventing infinite loops.
840 unsigned Cascade = ExtraRegInfo[VirtReg.reg].Cascade;
842 Cascade = ExtraRegInfo[VirtReg.reg].Cascade = NextCascade++;
844 DEBUG(dbgs() << "evicting " << PrintReg(PhysReg, TRI)
845 << " interference: Cascade " << Cascade << '\n');
847 // Collect all interfering virtregs first.
848 SmallVector<LiveInterval*, 8> Intfs;
849 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
850 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
851 // We usually have the interfering VRegs cached so collectInterferingVRegs()
852 // should be fast, we may need to recalculate if when different physregs
853 // overlap the same register unit so we had different SubRanges queried
855 Q.collectInterferingVRegs();
856 ArrayRef<LiveInterval*> IVR = Q.interferingVRegs();
857 Intfs.append(IVR.begin(), IVR.end());
860 // Evict them second. This will invalidate the queries.
861 for (unsigned i = 0, e = Intfs.size(); i != e; ++i) {
862 LiveInterval *Intf = Intfs[i];
863 // The same VirtReg may be present in multiple RegUnits. Skip duplicates.
864 if (!VRM->hasPhys(Intf->reg))
866 Matrix->unassign(*Intf);
867 assert((ExtraRegInfo[Intf->reg].Cascade < Cascade ||
868 VirtReg.isSpillable() < Intf->isSpillable()) &&
869 "Cannot decrease cascade number, illegal eviction");
870 ExtraRegInfo[Intf->reg].Cascade = Cascade;
872 NewVRegs.push_back(Intf->reg);
876 /// Returns true if the given \p PhysReg is a callee saved register and has not
877 /// been used for allocation yet.
878 bool RAGreedy::isUnusedCalleeSavedReg(unsigned PhysReg) const {
879 unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg);
883 return !Matrix->isPhysRegUsed(PhysReg);
886 /// tryEvict - Try to evict all interferences for a physreg.
887 /// @param VirtReg Currently unassigned virtual register.
888 /// @param Order Physregs to try.
889 /// @return Physreg to assign VirtReg, or 0.
890 unsigned RAGreedy::tryEvict(LiveInterval &VirtReg,
891 AllocationOrder &Order,
892 SmallVectorImpl<unsigned> &NewVRegs,
893 unsigned CostPerUseLimit) {
894 NamedRegionTimer T("evict", "Evict", TimerGroupName, TimerGroupDescription,
895 TimePassesIsEnabled);
897 // Keep track of the cheapest interference seen so far.
898 EvictionCost BestCost;
900 unsigned BestPhys = 0;
901 unsigned OrderLimit = Order.getOrder().size();
903 // When we are just looking for a reduced cost per use, don't break any
904 // hints, and only evict smaller spill weights.
905 if (CostPerUseLimit < ~0u) {
906 BestCost.BrokenHints = 0;
907 BestCost.MaxWeight = VirtReg.weight;
909 // Check of any registers in RC are below CostPerUseLimit.
910 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg.reg);
911 unsigned MinCost = RegClassInfo.getMinCost(RC);
912 if (MinCost >= CostPerUseLimit) {
913 DEBUG(dbgs() << TRI->getRegClassName(RC) << " minimum cost = " << MinCost
914 << ", no cheaper registers to be found.\n");
918 // It is normal for register classes to have a long tail of registers with
919 // the same cost. We don't need to look at them if they're too expensive.
920 if (TRI->getCostPerUse(Order.getOrder().back()) >= CostPerUseLimit) {
921 OrderLimit = RegClassInfo.getLastCostChange(RC);
922 DEBUG(dbgs() << "Only trying the first " << OrderLimit << " regs.\n");
927 while (unsigned PhysReg = Order.next(OrderLimit)) {
928 if (TRI->getCostPerUse(PhysReg) >= CostPerUseLimit)
930 // The first use of a callee-saved register in a function has cost 1.
931 // Don't start using a CSR when the CostPerUseLimit is low.
932 if (CostPerUseLimit == 1 && isUnusedCalleeSavedReg(PhysReg)) {
933 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " would clobber CSR "
934 << PrintReg(RegClassInfo.getLastCalleeSavedAlias(PhysReg), TRI)
939 if (!canEvictInterference(VirtReg, PhysReg, false, BestCost))
945 // Stop if the hint can be used.
953 evictInterference(VirtReg, BestPhys, NewVRegs);
958 //===----------------------------------------------------------------------===//
960 //===----------------------------------------------------------------------===//
962 /// addSplitConstraints - Fill out the SplitConstraints vector based on the
963 /// interference pattern in Physreg and its aliases. Add the constraints to
964 /// SpillPlacement and return the static cost of this split in Cost, assuming
965 /// that all preferences in SplitConstraints are met.
966 /// Return false if there are no bundles with positive bias.
967 bool RAGreedy::addSplitConstraints(InterferenceCache::Cursor Intf,
968 BlockFrequency &Cost) {
969 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
971 // Reset interference dependent info.
972 SplitConstraints.resize(UseBlocks.size());
973 BlockFrequency StaticCost = 0;
974 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
975 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
976 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
978 BC.Number = BI.MBB->getNumber();
979 Intf.moveToBlock(BC.Number);
980 BC.Entry = BI.LiveIn ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
981 BC.Exit = BI.LiveOut ? SpillPlacement::PrefReg : SpillPlacement::DontCare;
982 BC.ChangesValue = BI.FirstDef.isValid();
984 if (!Intf.hasInterference())
987 // Number of spill code instructions to insert.
990 // Interference for the live-in value.
992 if (Intf.first() <= Indexes->getMBBStartIdx(BC.Number)) {
993 BC.Entry = SpillPlacement::MustSpill;
995 } else if (Intf.first() < BI.FirstInstr) {
996 BC.Entry = SpillPlacement::PrefSpill;
998 } else if (Intf.first() < BI.LastInstr) {
1003 // Interference for the live-out value.
1005 if (Intf.last() >= SA->getLastSplitPoint(BC.Number)) {
1006 BC.Exit = SpillPlacement::MustSpill;
1008 } else if (Intf.last() > BI.LastInstr) {
1009 BC.Exit = SpillPlacement::PrefSpill;
1011 } else if (Intf.last() > BI.FirstInstr) {
1016 // Accumulate the total frequency of inserted spill code.
1018 StaticCost += SpillPlacer->getBlockFrequency(BC.Number);
1022 // Add constraints for use-blocks. Note that these are the only constraints
1023 // that may add a positive bias, it is downhill from here.
1024 SpillPlacer->addConstraints(SplitConstraints);
1025 return SpillPlacer->scanActiveBundles();
1029 /// addThroughConstraints - Add constraints and links to SpillPlacer from the
1030 /// live-through blocks in Blocks.
1031 void RAGreedy::addThroughConstraints(InterferenceCache::Cursor Intf,
1032 ArrayRef<unsigned> Blocks) {
1033 const unsigned GroupSize = 8;
1034 SpillPlacement::BlockConstraint BCS[GroupSize];
1035 unsigned TBS[GroupSize];
1036 unsigned B = 0, T = 0;
1038 for (unsigned i = 0; i != Blocks.size(); ++i) {
1039 unsigned Number = Blocks[i];
1040 Intf.moveToBlock(Number);
1042 if (!Intf.hasInterference()) {
1043 assert(T < GroupSize && "Array overflow");
1045 if (++T == GroupSize) {
1046 SpillPlacer->addLinks(makeArrayRef(TBS, T));
1052 assert(B < GroupSize && "Array overflow");
1053 BCS[B].Number = Number;
1055 // Interference for the live-in value.
1056 if (Intf.first() <= Indexes->getMBBStartIdx(Number))
1057 BCS[B].Entry = SpillPlacement::MustSpill;
1059 BCS[B].Entry = SpillPlacement::PrefSpill;
1061 // Interference for the live-out value.
1062 if (Intf.last() >= SA->getLastSplitPoint(Number))
1063 BCS[B].Exit = SpillPlacement::MustSpill;
1065 BCS[B].Exit = SpillPlacement::PrefSpill;
1067 if (++B == GroupSize) {
1068 SpillPlacer->addConstraints(makeArrayRef(BCS, B));
1073 SpillPlacer->addConstraints(makeArrayRef(BCS, B));
1074 SpillPlacer->addLinks(makeArrayRef(TBS, T));
1077 void RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
1078 // Keep track of through blocks that have not been added to SpillPlacer.
1079 BitVector Todo = SA->getThroughBlocks();
1080 SmallVectorImpl<unsigned> &ActiveBlocks = Cand.ActiveBlocks;
1081 unsigned AddedTo = 0;
1083 unsigned Visited = 0;
1087 ArrayRef<unsigned> NewBundles = SpillPlacer->getRecentPositive();
1088 // Find new through blocks in the periphery of PrefRegBundles.
1089 for (int i = 0, e = NewBundles.size(); i != e; ++i) {
1090 unsigned Bundle = NewBundles[i];
1091 // Look at all blocks connected to Bundle in the full graph.
1092 ArrayRef<unsigned> Blocks = Bundles->getBlocks(Bundle);
1093 for (ArrayRef<unsigned>::iterator I = Blocks.begin(), E = Blocks.end();
1095 unsigned Block = *I;
1096 if (!Todo.test(Block))
1099 // This is a new through block. Add it to SpillPlacer later.
1100 ActiveBlocks.push_back(Block);
1106 // Any new blocks to add?
1107 if (ActiveBlocks.size() == AddedTo)
1110 // Compute through constraints from the interference, or assume that all
1111 // through blocks prefer spilling when forming compact regions.
1112 auto NewBlocks = makeArrayRef(ActiveBlocks).slice(AddedTo);
1114 addThroughConstraints(Cand.Intf, NewBlocks);
1116 // Provide a strong negative bias on through blocks to prevent unwanted
1117 // liveness on loop backedges.
1118 SpillPlacer->addPrefSpill(NewBlocks, /* Strong= */ true);
1119 AddedTo = ActiveBlocks.size();
1121 // Perhaps iterating can enable more bundles?
1122 SpillPlacer->iterate();
1124 DEBUG(dbgs() << ", v=" << Visited);
1127 /// calcCompactRegion - Compute the set of edge bundles that should be live
1128 /// when splitting the current live range into compact regions. Compact
1129 /// regions can be computed without looking at interference. They are the
1130 /// regions formed by removing all the live-through blocks from the live range.
1132 /// Returns false if the current live range is already compact, or if the
1133 /// compact regions would form single block regions anyway.
1134 bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
1135 // Without any through blocks, the live range is already compact.
1136 if (!SA->getNumThroughBlocks())
1139 // Compact regions don't correspond to any physreg.
1140 Cand.reset(IntfCache, 0);
1142 DEBUG(dbgs() << "Compact region bundles");
1144 // Use the spill placer to determine the live bundles. GrowRegion pretends
1145 // that all the through blocks have interference when PhysReg is unset.
1146 SpillPlacer->prepare(Cand.LiveBundles);
1148 // The static split cost will be zero since Cand.Intf reports no interference.
1149 BlockFrequency Cost;
1150 if (!addSplitConstraints(Cand.Intf, Cost)) {
1151 DEBUG(dbgs() << ", none.\n");
1156 SpillPlacer->finish();
1158 if (!Cand.LiveBundles.any()) {
1159 DEBUG(dbgs() << ", none.\n");
1164 for (int i : Cand.LiveBundles.set_bits())
1165 dbgs() << " EB#" << i;
1171 /// calcSpillCost - Compute how expensive it would be to split the live range in
1172 /// SA around all use blocks instead of forming bundle regions.
1173 BlockFrequency RAGreedy::calcSpillCost() {
1174 BlockFrequency Cost = 0;
1175 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1176 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1177 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1178 unsigned Number = BI.MBB->getNumber();
1179 // We normally only need one spill instruction - a load or a store.
1180 Cost += SpillPlacer->getBlockFrequency(Number);
1182 // Unless the value is redefined in the block.
1183 if (BI.LiveIn && BI.LiveOut && BI.FirstDef)
1184 Cost += SpillPlacer->getBlockFrequency(Number);
1189 /// calcGlobalSplitCost - Return the global split cost of following the split
1190 /// pattern in LiveBundles. This cost should be added to the local cost of the
1191 /// interference pattern in SplitConstraints.
1193 BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand) {
1194 BlockFrequency GlobalCost = 0;
1195 const BitVector &LiveBundles = Cand.LiveBundles;
1196 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1197 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1198 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1199 SpillPlacement::BlockConstraint &BC = SplitConstraints[i];
1200 bool RegIn = LiveBundles[Bundles->getBundle(BC.Number, 0)];
1201 bool RegOut = LiveBundles[Bundles->getBundle(BC.Number, 1)];
1205 Ins += RegIn != (BC.Entry == SpillPlacement::PrefReg);
1207 Ins += RegOut != (BC.Exit == SpillPlacement::PrefReg);
1209 GlobalCost += SpillPlacer->getBlockFrequency(BC.Number);
1212 for (unsigned i = 0, e = Cand.ActiveBlocks.size(); i != e; ++i) {
1213 unsigned Number = Cand.ActiveBlocks[i];
1214 bool RegIn = LiveBundles[Bundles->getBundle(Number, 0)];
1215 bool RegOut = LiveBundles[Bundles->getBundle(Number, 1)];
1216 if (!RegIn && !RegOut)
1218 if (RegIn && RegOut) {
1219 // We need double spill code if this block has interference.
1220 Cand.Intf.moveToBlock(Number);
1221 if (Cand.Intf.hasInterference()) {
1222 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1223 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1227 // live-in / stack-out or stack-in live-out.
1228 GlobalCost += SpillPlacer->getBlockFrequency(Number);
1233 /// splitAroundRegion - Split the current live range around the regions
1234 /// determined by BundleCand and GlobalCand.
1236 /// Before calling this function, GlobalCand and BundleCand must be initialized
1237 /// so each bundle is assigned to a valid candidate, or NoCand for the
1238 /// stack-bound bundles. The shared SA/SE SplitAnalysis and SplitEditor
1239 /// objects must be initialized for the current live range, and intervals
1240 /// created for the used candidates.
1242 /// @param LREdit The LiveRangeEdit object handling the current split.
1243 /// @param UsedCands List of used GlobalCand entries. Every BundleCand value
1244 /// must appear in this list.
1245 void RAGreedy::splitAroundRegion(LiveRangeEdit &LREdit,
1246 ArrayRef<unsigned> UsedCands) {
1247 // These are the intervals created for new global ranges. We may create more
1248 // intervals for local ranges.
1249 const unsigned NumGlobalIntvs = LREdit.size();
1250 DEBUG(dbgs() << "splitAroundRegion with " << NumGlobalIntvs << " globals.\n");
1251 assert(NumGlobalIntvs && "No global intervals configured");
1253 // Isolate even single instructions when dealing with a proper sub-class.
1254 // That guarantees register class inflation for the stack interval because it
1256 unsigned Reg = SA->getParent().reg;
1257 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1259 // First handle all the blocks with uses.
1260 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1261 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1262 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1263 unsigned Number = BI.MBB->getNumber();
1264 unsigned IntvIn = 0, IntvOut = 0;
1265 SlotIndex IntfIn, IntfOut;
1267 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1268 if (CandIn != NoCand) {
1269 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1270 IntvIn = Cand.IntvIdx;
1271 Cand.Intf.moveToBlock(Number);
1272 IntfIn = Cand.Intf.first();
1276 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1277 if (CandOut != NoCand) {
1278 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1279 IntvOut = Cand.IntvIdx;
1280 Cand.Intf.moveToBlock(Number);
1281 IntfOut = Cand.Intf.last();
1285 // Create separate intervals for isolated blocks with multiple uses.
1286 if (!IntvIn && !IntvOut) {
1287 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " isolated.\n");
1288 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1289 SE->splitSingleBlock(BI);
1293 if (IntvIn && IntvOut)
1294 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1296 SE->splitRegInBlock(BI, IntvIn, IntfIn);
1298 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
1301 // Handle live-through blocks. The relevant live-through blocks are stored in
1302 // the ActiveBlocks list with each candidate. We need to filter out
1304 BitVector Todo = SA->getThroughBlocks();
1305 for (unsigned c = 0; c != UsedCands.size(); ++c) {
1306 ArrayRef<unsigned> Blocks = GlobalCand[UsedCands[c]].ActiveBlocks;
1307 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
1308 unsigned Number = Blocks[i];
1309 if (!Todo.test(Number))
1313 unsigned IntvIn = 0, IntvOut = 0;
1314 SlotIndex IntfIn, IntfOut;
1316 unsigned CandIn = BundleCand[Bundles->getBundle(Number, 0)];
1317 if (CandIn != NoCand) {
1318 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1319 IntvIn = Cand.IntvIdx;
1320 Cand.Intf.moveToBlock(Number);
1321 IntfIn = Cand.Intf.first();
1324 unsigned CandOut = BundleCand[Bundles->getBundle(Number, 1)];
1325 if (CandOut != NoCand) {
1326 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1327 IntvOut = Cand.IntvIdx;
1328 Cand.Intf.moveToBlock(Number);
1329 IntfOut = Cand.Intf.last();
1331 if (!IntvIn && !IntvOut)
1333 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1339 SmallVector<unsigned, 8> IntvMap;
1340 SE->finish(&IntvMap);
1341 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
1343 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1344 unsigned OrigBlocks = SA->getNumLiveBlocks();
1346 // Sort out the new intervals created by splitting. We get four kinds:
1347 // - Remainder intervals should not be split again.
1348 // - Candidate intervals can be assigned to Cand.PhysReg.
1349 // - Block-local splits are candidates for local splitting.
1350 // - DCE leftovers should go back on the queue.
1351 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1352 LiveInterval &Reg = LIS->getInterval(LREdit.get(i));
1354 // Ignore old intervals from DCE.
1355 if (getStage(Reg) != RS_New)
1358 // Remainder interval. Don't try splitting again, spill if it doesn't
1360 if (IntvMap[i] == 0) {
1361 setStage(Reg, RS_Spill);
1365 // Global intervals. Allow repeated splitting as long as the number of live
1366 // blocks is strictly decreasing.
1367 if (IntvMap[i] < NumGlobalIntvs) {
1368 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
1369 DEBUG(dbgs() << "Main interval covers the same " << OrigBlocks
1370 << " blocks as original.\n");
1371 // Don't allow repeated splitting as a safe guard against looping.
1372 setStage(Reg, RS_Split2);
1377 // Other intervals are treated as new. This includes local intervals created
1378 // for blocks with multiple uses, and anything created by DCE.
1382 MF->verify(this, "After splitting live range around region");
1385 unsigned RAGreedy::tryRegionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1386 SmallVectorImpl<unsigned> &NewVRegs) {
1387 unsigned NumCands = 0;
1388 BlockFrequency BestCost;
1390 // Check if we can split this live range around a compact region.
1391 bool HasCompact = calcCompactRegion(GlobalCand.front());
1393 // Yes, keep GlobalCand[0] as the compact region candidate.
1395 BestCost = BlockFrequency::getMaxFrequency();
1397 // No benefit from the compact region, our fallback will be per-block
1398 // splitting. Make sure we find a solution that is cheaper than spilling.
1399 BestCost = calcSpillCost();
1400 DEBUG(dbgs() << "Cost of isolating all blocks = ";
1401 MBFI->printBlockFreq(dbgs(), BestCost) << '\n');
1405 calculateRegionSplitCost(VirtReg, Order, BestCost, NumCands,
1406 false/*IgnoreCSR*/);
1408 // No solutions found, fall back to single block splitting.
1409 if (!HasCompact && BestCand == NoCand)
1412 return doRegionSplit(VirtReg, BestCand, HasCompact, NewVRegs);
1415 unsigned RAGreedy::calculateRegionSplitCost(LiveInterval &VirtReg,
1416 AllocationOrder &Order,
1417 BlockFrequency &BestCost,
1420 unsigned BestCand = NoCand;
1422 while (unsigned PhysReg = Order.next()) {
1423 if (IgnoreCSR && isUnusedCalleeSavedReg(PhysReg))
1426 // Discard bad candidates before we run out of interference cache cursors.
1427 // This will only affect register classes with a lot of registers (>32).
1428 if (NumCands == IntfCache.getMaxCursors()) {
1429 unsigned WorstCount = ~0u;
1431 for (unsigned i = 0; i != NumCands; ++i) {
1432 if (i == BestCand || !GlobalCand[i].PhysReg)
1434 unsigned Count = GlobalCand[i].LiveBundles.count();
1435 if (Count < WorstCount) {
1441 GlobalCand[Worst] = GlobalCand[NumCands];
1442 if (BestCand == NumCands)
1446 if (GlobalCand.size() <= NumCands)
1447 GlobalCand.resize(NumCands+1);
1448 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1449 Cand.reset(IntfCache, PhysReg);
1451 SpillPlacer->prepare(Cand.LiveBundles);
1452 BlockFrequency Cost;
1453 if (!addSplitConstraints(Cand.Intf, Cost)) {
1454 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tno positive bundles\n");
1457 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << "\tstatic = ";
1458 MBFI->printBlockFreq(dbgs(), Cost));
1459 if (Cost >= BestCost) {
1461 if (BestCand == NoCand)
1462 dbgs() << " worse than no bundles\n";
1464 dbgs() << " worse than "
1465 << PrintReg(GlobalCand[BestCand].PhysReg, TRI) << '\n';
1471 SpillPlacer->finish();
1473 // No live bundles, defer to splitSingleBlocks().
1474 if (!Cand.LiveBundles.any()) {
1475 DEBUG(dbgs() << " no bundles.\n");
1479 Cost += calcGlobalSplitCost(Cand);
1481 dbgs() << ", total = "; MBFI->printBlockFreq(dbgs(), Cost)
1483 for (int i : Cand.LiveBundles.set_bits())
1484 dbgs() << " EB#" << i;
1487 if (Cost < BestCost) {
1488 BestCand = NumCands;
1496 unsigned RAGreedy::doRegionSplit(LiveInterval &VirtReg, unsigned BestCand,
1498 SmallVectorImpl<unsigned> &NewVRegs) {
1499 SmallVector<unsigned, 8> UsedCands;
1500 // Prepare split editor.
1501 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
1502 SE->reset(LREdit, SplitSpillMode);
1504 // Assign all edge bundles to the preferred candidate, or NoCand.
1505 BundleCand.assign(Bundles->getNumBundles(), NoCand);
1507 // Assign bundles for the best candidate region.
1508 if (BestCand != NoCand) {
1509 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1510 if (unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1511 UsedCands.push_back(BestCand);
1512 Cand.IntvIdx = SE->openIntv();
1513 DEBUG(dbgs() << "Split for " << PrintReg(Cand.PhysReg, TRI) << " in "
1514 << B << " bundles, intv " << Cand.IntvIdx << ".\n");
1519 // Assign bundles for the compact region.
1521 GlobalSplitCandidate &Cand = GlobalCand.front();
1522 assert(!Cand.PhysReg && "Compact region has no physreg");
1523 if (unsigned B = Cand.getBundles(BundleCand, 0)) {
1524 UsedCands.push_back(0);
1525 Cand.IntvIdx = SE->openIntv();
1526 DEBUG(dbgs() << "Split for compact region in " << B << " bundles, intv "
1527 << Cand.IntvIdx << ".\n");
1532 splitAroundRegion(LREdit, UsedCands);
1537 //===----------------------------------------------------------------------===//
1538 // Per-Block Splitting
1539 //===----------------------------------------------------------------------===//
1541 /// tryBlockSplit - Split a global live range around every block with uses. This
1542 /// creates a lot of local live ranges, that will be split by tryLocalSplit if
1543 /// they don't allocate.
1544 unsigned RAGreedy::tryBlockSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1545 SmallVectorImpl<unsigned> &NewVRegs) {
1546 assert(&SA->getParent() == &VirtReg && "Live range wasn't analyzed");
1547 unsigned Reg = VirtReg.reg;
1548 bool SingleInstrs = RegClassInfo.isProperSubClass(MRI->getRegClass(Reg));
1549 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
1550 SE->reset(LREdit, SplitSpillMode);
1551 ArrayRef<SplitAnalysis::BlockInfo> UseBlocks = SA->getUseBlocks();
1552 for (unsigned i = 0; i != UseBlocks.size(); ++i) {
1553 const SplitAnalysis::BlockInfo &BI = UseBlocks[i];
1554 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1555 SE->splitSingleBlock(BI);
1557 // No blocks were split.
1561 // We did split for some blocks.
1562 SmallVector<unsigned, 8> IntvMap;
1563 SE->finish(&IntvMap);
1565 // Tell LiveDebugVariables about the new ranges.
1566 DebugVars->splitRegister(Reg, LREdit.regs(), *LIS);
1568 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1570 // Sort out the new intervals created by splitting. The remainder interval
1571 // goes straight to spilling, the new local ranges get to stay RS_New.
1572 for (unsigned i = 0, e = LREdit.size(); i != e; ++i) {
1573 LiveInterval &LI = LIS->getInterval(LREdit.get(i));
1574 if (getStage(LI) == RS_New && IntvMap[i] == 0)
1575 setStage(LI, RS_Spill);
1579 MF->verify(this, "After splitting live range around basic blocks");
1584 //===----------------------------------------------------------------------===//
1585 // Per-Instruction Splitting
1586 //===----------------------------------------------------------------------===//
1588 /// Get the number of allocatable registers that match the constraints of \p Reg
1589 /// on \p MI and that are also in \p SuperRC.
1590 static unsigned getNumAllocatableRegsForConstraints(
1591 const MachineInstr *MI, unsigned Reg, const TargetRegisterClass *SuperRC,
1592 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI,
1593 const RegisterClassInfo &RCI) {
1594 assert(SuperRC && "Invalid register class");
1596 const TargetRegisterClass *ConstrainedRC =
1597 MI->getRegClassConstraintEffectForVReg(Reg, SuperRC, TII, TRI,
1598 /* ExploreBundle */ true);
1601 return RCI.getNumAllocatableRegs(ConstrainedRC);
1604 /// tryInstructionSplit - Split a live range around individual instructions.
1605 /// This is normally not worthwhile since the spiller is doing essentially the
1606 /// same thing. However, when the live range is in a constrained register
1607 /// class, it may help to insert copies such that parts of the live range can
1608 /// be moved to a larger register class.
1610 /// This is similar to spilling to a larger register class.
1612 RAGreedy::tryInstructionSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1613 SmallVectorImpl<unsigned> &NewVRegs) {
1614 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
1615 // There is no point to this if there are no larger sub-classes.
1616 if (!RegClassInfo.isProperSubClass(CurRC))
1619 // Always enable split spill mode, since we're effectively spilling to a
1621 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
1622 SE->reset(LREdit, SplitEditor::SM_Size);
1624 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1625 if (Uses.size() <= 1)
1628 DEBUG(dbgs() << "Split around " << Uses.size() << " individual instrs.\n");
1630 const TargetRegisterClass *SuperRC =
1631 TRI->getLargestLegalSuperClass(CurRC, *MF);
1632 unsigned SuperRCNumAllocatableRegs = RCI.getNumAllocatableRegs(SuperRC);
1633 // Split around every non-copy instruction if this split will relax
1634 // the constraints on the virtual register.
1635 // Otherwise, splitting just inserts uncoalescable copies that do not help
1637 for (unsigned i = 0; i != Uses.size(); ++i) {
1638 if (const MachineInstr *MI = Indexes->getInstructionFromIndex(Uses[i]))
1639 if (MI->isFullCopy() ||
1640 SuperRCNumAllocatableRegs ==
1641 getNumAllocatableRegsForConstraints(MI, VirtReg.reg, SuperRC, TII,
1643 DEBUG(dbgs() << " skip:\t" << Uses[i] << '\t' << *MI);
1647 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
1648 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
1649 SE->useIntv(SegStart, SegStop);
1652 if (LREdit.empty()) {
1653 DEBUG(dbgs() << "All uses were copies.\n");
1657 SmallVector<unsigned, 8> IntvMap;
1658 SE->finish(&IntvMap);
1659 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
1660 ExtraRegInfo.resize(MRI->getNumVirtRegs());
1662 // Assign all new registers to RS_Spill. This was the last chance.
1663 setStage(LREdit.begin(), LREdit.end(), RS_Spill);
1668 //===----------------------------------------------------------------------===//
1670 //===----------------------------------------------------------------------===//
1673 /// calcGapWeights - Compute the maximum spill weight that needs to be evicted
1674 /// in order to use PhysReg between two entries in SA->UseSlots.
1676 /// GapWeight[i] represents the gap between UseSlots[i] and UseSlots[i+1].
1678 void RAGreedy::calcGapWeights(unsigned PhysReg,
1679 SmallVectorImpl<float> &GapWeight) {
1680 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1681 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1682 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1683 const unsigned NumGaps = Uses.size()-1;
1685 // Start and end points for the interference check.
1686 SlotIndex StartIdx =
1687 BI.LiveIn ? BI.FirstInstr.getBaseIndex() : BI.FirstInstr;
1689 BI.LiveOut ? BI.LastInstr.getBoundaryIndex() : BI.LastInstr;
1691 GapWeight.assign(NumGaps, 0.0f);
1693 // Add interference from each overlapping register.
1694 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1695 if (!Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
1696 .checkInterference())
1699 // We know that VirtReg is a continuous interval from FirstInstr to
1700 // LastInstr, so we don't need InterferenceQuery.
1702 // Interference that overlaps an instruction is counted in both gaps
1703 // surrounding the instruction. The exception is interference before
1704 // StartIdx and after StopIdx.
1706 LiveIntervalUnion::SegmentIter IntI =
1707 Matrix->getLiveUnions()[*Units] .find(StartIdx);
1708 for (unsigned Gap = 0; IntI.valid() && IntI.start() < StopIdx; ++IntI) {
1709 // Skip the gaps before IntI.
1710 while (Uses[Gap+1].getBoundaryIndex() < IntI.start())
1711 if (++Gap == NumGaps)
1716 // Update the gaps covered by IntI.
1717 const float weight = IntI.value()->weight;
1718 for (; Gap != NumGaps; ++Gap) {
1719 GapWeight[Gap] = std::max(GapWeight[Gap], weight);
1720 if (Uses[Gap+1].getBaseIndex() >= IntI.stop())
1728 // Add fixed interference.
1729 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
1730 const LiveRange &LR = LIS->getRegUnit(*Units);
1731 LiveRange::const_iterator I = LR.find(StartIdx);
1732 LiveRange::const_iterator E = LR.end();
1734 // Same loop as above. Mark any overlapped gaps as HUGE_VALF.
1735 for (unsigned Gap = 0; I != E && I->start < StopIdx; ++I) {
1736 while (Uses[Gap+1].getBoundaryIndex() < I->start)
1737 if (++Gap == NumGaps)
1742 for (; Gap != NumGaps; ++Gap) {
1743 GapWeight[Gap] = llvm::huge_valf;
1744 if (Uses[Gap+1].getBaseIndex() >= I->end)
1753 /// tryLocalSplit - Try to split VirtReg into smaller intervals inside its only
1756 unsigned RAGreedy::tryLocalSplit(LiveInterval &VirtReg, AllocationOrder &Order,
1757 SmallVectorImpl<unsigned> &NewVRegs) {
1758 assert(SA->getUseBlocks().size() == 1 && "Not a local interval");
1759 const SplitAnalysis::BlockInfo &BI = SA->getUseBlocks().front();
1761 // Note that it is possible to have an interval that is live-in or live-out
1762 // while only covering a single block - A phi-def can use undef values from
1763 // predecessors, and the block could be a single-block loop.
1764 // We don't bother doing anything clever about such a case, we simply assume
1765 // that the interval is continuous from FirstInstr to LastInstr. We should
1766 // make sure that we don't do anything illegal to such an interval, though.
1768 ArrayRef<SlotIndex> Uses = SA->getUseSlots();
1769 if (Uses.size() <= 2)
1771 const unsigned NumGaps = Uses.size()-1;
1774 dbgs() << "tryLocalSplit: ";
1775 for (unsigned i = 0, e = Uses.size(); i != e; ++i)
1776 dbgs() << ' ' << Uses[i];
1780 // If VirtReg is live across any register mask operands, compute a list of
1781 // gaps with register masks.
1782 SmallVector<unsigned, 8> RegMaskGaps;
1783 if (Matrix->checkRegMaskInterference(VirtReg)) {
1784 // Get regmask slots for the whole block.
1785 ArrayRef<SlotIndex> RMS = LIS->getRegMaskSlotsInBlock(BI.MBB->getNumber());
1786 DEBUG(dbgs() << RMS.size() << " regmasks in block:");
1787 // Constrain to VirtReg's live range.
1788 unsigned ri = std::lower_bound(RMS.begin(), RMS.end(),
1789 Uses.front().getRegSlot()) - RMS.begin();
1790 unsigned re = RMS.size();
1791 for (unsigned i = 0; i != NumGaps && ri != re; ++i) {
1792 // Look for Uses[i] <= RMS <= Uses[i+1].
1793 assert(!SlotIndex::isEarlierInstr(RMS[ri], Uses[i]));
1794 if (SlotIndex::isEarlierInstr(Uses[i+1], RMS[ri]))
1796 // Skip a regmask on the same instruction as the last use. It doesn't
1797 // overlap the live range.
1798 if (SlotIndex::isSameInstr(Uses[i+1], RMS[ri]) && i+1 == NumGaps)
1800 DEBUG(dbgs() << ' ' << RMS[ri] << ':' << Uses[i] << '-' << Uses[i+1]);
1801 RegMaskGaps.push_back(i);
1802 // Advance ri to the next gap. A regmask on one of the uses counts in
1804 while (ri != re && SlotIndex::isEarlierInstr(RMS[ri], Uses[i+1]))
1807 DEBUG(dbgs() << '\n');
1810 // Since we allow local split results to be split again, there is a risk of
1811 // creating infinite loops. It is tempting to require that the new live
1812 // ranges have less instructions than the original. That would guarantee
1813 // convergence, but it is too strict. A live range with 3 instructions can be
1814 // split 2+3 (including the COPY), and we want to allow that.
1816 // Instead we use these rules:
1818 // 1. Allow any split for ranges with getStage() < RS_Split2. (Except for the
1819 // noop split, of course).
1820 // 2. Require progress be made for ranges with getStage() == RS_Split2. All
1821 // the new ranges must have fewer instructions than before the split.
1822 // 3. New ranges with the same number of instructions are marked RS_Split2,
1823 // smaller ranges are marked RS_New.
1825 // These rules allow a 3 -> 2+3 split once, which we need. They also prevent
1826 // excessive splitting and infinite loops.
1828 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
1830 // Best split candidate.
1831 unsigned BestBefore = NumGaps;
1832 unsigned BestAfter = 0;
1835 const float blockFreq =
1836 SpillPlacer->getBlockFrequency(BI.MBB->getNumber()).getFrequency() *
1837 (1.0f / MBFI->getEntryFreq());
1838 SmallVector<float, 8> GapWeight;
1841 while (unsigned PhysReg = Order.next()) {
1842 // Keep track of the largest spill weight that would need to be evicted in
1843 // order to make use of PhysReg between UseSlots[i] and UseSlots[i+1].
1844 calcGapWeights(PhysReg, GapWeight);
1846 // Remove any gaps with regmask clobbers.
1847 if (Matrix->checkRegMaskInterference(VirtReg, PhysReg))
1848 for (unsigned i = 0, e = RegMaskGaps.size(); i != e; ++i)
1849 GapWeight[RegMaskGaps[i]] = llvm::huge_valf;
1851 // Try to find the best sequence of gaps to close.
1852 // The new spill weight must be larger than any gap interference.
1854 // We will split before Uses[SplitBefore] and after Uses[SplitAfter].
1855 unsigned SplitBefore = 0, SplitAfter = 1;
1857 // MaxGap should always be max(GapWeight[SplitBefore..SplitAfter-1]).
1858 // It is the spill weight that needs to be evicted.
1859 float MaxGap = GapWeight[0];
1862 // Live before/after split?
1863 const bool LiveBefore = SplitBefore != 0 || BI.LiveIn;
1864 const bool LiveAfter = SplitAfter != NumGaps || BI.LiveOut;
1866 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << ' '
1867 << Uses[SplitBefore] << '-' << Uses[SplitAfter]
1868 << " i=" << MaxGap);
1870 // Stop before the interval gets so big we wouldn't be making progress.
1871 if (!LiveBefore && !LiveAfter) {
1872 DEBUG(dbgs() << " all\n");
1875 // Should the interval be extended or shrunk?
1878 // How many gaps would the new range have?
1879 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
1881 // Legally, without causing looping?
1882 bool Legal = !ProgressRequired || NewGaps < NumGaps;
1884 if (Legal && MaxGap < llvm::huge_valf) {
1885 // Estimate the new spill weight. Each instruction reads or writes the
1886 // register. Conservatively assume there are no read-modify-write
1889 // Try to guess the size of the new interval.
1890 const float EstWeight = normalizeSpillWeight(
1891 blockFreq * (NewGaps + 1),
1892 Uses[SplitBefore].distance(Uses[SplitAfter]) +
1893 (LiveBefore + LiveAfter) * SlotIndex::InstrDist,
1895 // Would this split be possible to allocate?
1896 // Never allocate all gaps, we wouldn't be making progress.
1897 DEBUG(dbgs() << " w=" << EstWeight);
1898 if (EstWeight * Hysteresis >= MaxGap) {
1900 float Diff = EstWeight - MaxGap;
1901 if (Diff > BestDiff) {
1902 DEBUG(dbgs() << " (best)");
1903 BestDiff = Hysteresis * Diff;
1904 BestBefore = SplitBefore;
1905 BestAfter = SplitAfter;
1912 if (++SplitBefore < SplitAfter) {
1913 DEBUG(dbgs() << " shrink\n");
1914 // Recompute the max when necessary.
1915 if (GapWeight[SplitBefore - 1] >= MaxGap) {
1916 MaxGap = GapWeight[SplitBefore];
1917 for (unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
1918 MaxGap = std::max(MaxGap, GapWeight[i]);
1925 // Try to extend the interval.
1926 if (SplitAfter >= NumGaps) {
1927 DEBUG(dbgs() << " end\n");
1931 DEBUG(dbgs() << " extend\n");
1932 MaxGap = std::max(MaxGap, GapWeight[SplitAfter++]);
1936 // Didn't find any candidates?
1937 if (BestBefore == NumGaps)
1940 DEBUG(dbgs() << "Best local split range: " << Uses[BestBefore]
1941 << '-' << Uses[BestAfter] << ", " << BestDiff
1942 << ", " << (BestAfter - BestBefore + 1) << " instrs\n");
1944 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
1948 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
1949 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
1950 SE->useIntv(SegStart, SegStop);
1951 SmallVector<unsigned, 8> IntvMap;
1952 SE->finish(&IntvMap);
1953 DebugVars->splitRegister(VirtReg.reg, LREdit.regs(), *LIS);
1955 // If the new range has the same number of instructions as before, mark it as
1956 // RS_Split2 so the next split will be forced to make progress. Otherwise,
1957 // leave the new intervals as RS_New so they can compete.
1958 bool LiveBefore = BestBefore != 0 || BI.LiveIn;
1959 bool LiveAfter = BestAfter != NumGaps || BI.LiveOut;
1960 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
1961 if (NewGaps >= NumGaps) {
1962 DEBUG(dbgs() << "Tagging non-progress ranges: ");
1963 assert(!ProgressRequired && "Didn't make progress when it was required.");
1964 for (unsigned i = 0, e = IntvMap.size(); i != e; ++i)
1965 if (IntvMap[i] == 1) {
1966 setStage(LIS->getInterval(LREdit.get(i)), RS_Split2);
1967 DEBUG(dbgs() << PrintReg(LREdit.get(i)));
1969 DEBUG(dbgs() << '\n');
1976 //===----------------------------------------------------------------------===//
1977 // Live Range Splitting
1978 //===----------------------------------------------------------------------===//
1980 /// trySplit - Try to split VirtReg or one of its interferences, making it
1982 /// @return Physreg when VirtReg may be assigned and/or new NewVRegs.
1983 unsigned RAGreedy::trySplit(LiveInterval &VirtReg, AllocationOrder &Order,
1984 SmallVectorImpl<unsigned>&NewVRegs) {
1985 // Ranges must be Split2 or less.
1986 if (getStage(VirtReg) >= RS_Spill)
1989 // Local intervals are handled separately.
1990 if (LIS->intervalIsInOneMBB(VirtReg)) {
1991 NamedRegionTimer T("local_split", "Local Splitting", TimerGroupName,
1992 TimerGroupDescription, TimePassesIsEnabled);
1993 SA->analyze(&VirtReg);
1994 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
1995 if (PhysReg || !NewVRegs.empty())
1997 return tryInstructionSplit(VirtReg, Order, NewVRegs);
2000 NamedRegionTimer T("global_split", "Global Splitting", TimerGroupName,
2001 TimerGroupDescription, TimePassesIsEnabled);
2003 SA->analyze(&VirtReg);
2005 // FIXME: SplitAnalysis may repair broken live ranges coming from the
2006 // coalescer. That may cause the range to become allocatable which means that
2007 // tryRegionSplit won't be making progress. This check should be replaced with
2008 // an assertion when the coalescer is fixed.
2009 if (SA->didRepairRange()) {
2010 // VirtReg has changed, so all cached queries are invalid.
2011 Matrix->invalidateVirtRegs();
2012 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs))
2016 // First try to split around a region spanning multiple blocks. RS_Split2
2017 // ranges already made dubious progress with region splitting, so they go
2018 // straight to single block splitting.
2019 if (getStage(VirtReg) < RS_Split2) {
2020 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
2021 if (PhysReg || !NewVRegs.empty())
2025 // Then isolate blocks.
2026 return tryBlockSplit(VirtReg, Order, NewVRegs);
2029 //===----------------------------------------------------------------------===//
2030 // Last Chance Recoloring
2031 //===----------------------------------------------------------------------===//
2033 /// mayRecolorAllInterferences - Check if the virtual registers that
2034 /// interfere with \p VirtReg on \p PhysReg (or one of its aliases) may be
2035 /// recolored to free \p PhysReg.
2036 /// When true is returned, \p RecoloringCandidates has been augmented with all
2037 /// the live intervals that need to be recolored in order to free \p PhysReg
2039 /// \p FixedRegisters contains all the virtual registers that cannot be
2042 RAGreedy::mayRecolorAllInterferences(unsigned PhysReg, LiveInterval &VirtReg,
2043 SmallLISet &RecoloringCandidates,
2044 const SmallVirtRegSet &FixedRegisters) {
2045 const TargetRegisterClass *CurRC = MRI->getRegClass(VirtReg.reg);
2047 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
2048 LiveIntervalUnion::Query &Q = Matrix->query(VirtReg, *Units);
2049 // If there is LastChanceRecoloringMaxInterference or more interferences,
2050 // chances are one would not be recolorable.
2051 if (Q.collectInterferingVRegs(LastChanceRecoloringMaxInterference) >=
2052 LastChanceRecoloringMaxInterference && !ExhaustiveSearch) {
2053 DEBUG(dbgs() << "Early abort: too many interferences.\n");
2054 CutOffInfo |= CO_Interf;
2057 for (unsigned i = Q.interferingVRegs().size(); i; --i) {
2058 LiveInterval *Intf = Q.interferingVRegs()[i - 1];
2059 // If Intf is done and sit on the same register class as VirtReg,
2060 // it would not be recolorable as it is in the same state as VirtReg.
2061 if ((getStage(*Intf) == RS_Done &&
2062 MRI->getRegClass(Intf->reg) == CurRC) ||
2063 FixedRegisters.count(Intf->reg)) {
2064 DEBUG(dbgs() << "Early abort: the inteference is not recolorable.\n");
2067 RecoloringCandidates.insert(Intf);
2073 /// tryLastChanceRecoloring - Try to assign a color to \p VirtReg by recoloring
2074 /// its interferences.
2075 /// Last chance recoloring chooses a color for \p VirtReg and recolors every
2076 /// virtual register that was using it. The recoloring process may recursively
2077 /// use the last chance recoloring. Therefore, when a virtual register has been
2078 /// assigned a color by this mechanism, it is marked as Fixed, i.e., it cannot
2079 /// be last-chance-recolored again during this recoloring "session".
2082 /// vA can use {R1, R2 }
2083 /// vB can use { R2, R3}
2084 /// vC can use {R1 }
2085 /// Where vA, vB, and vC cannot be split anymore (they are reloads for
2086 /// instance) and they all interfere.
2088 /// vA is assigned R1
2089 /// vB is assigned R2
2090 /// vC tries to evict vA but vA is already done.
2091 /// Regular register allocation fails.
2093 /// Last chance recoloring kicks in:
2094 /// vC does as if vA was evicted => vC uses R1.
2095 /// vC is marked as fixed.
2096 /// vA needs to find a color.
2097 /// None are available.
2098 /// vA cannot evict vC: vC is a fixed virtual register now.
2099 /// vA does as if vB was evicted => vA uses R2.
2100 /// vB needs to find a color.
2101 /// R3 is available.
2102 /// Recoloring => vC = R1, vA = R2, vB = R3
2104 /// \p Order defines the preferred allocation order for \p VirtReg.
2105 /// \p NewRegs will contain any new virtual register that have been created
2106 /// (split, spill) during the process and that must be assigned.
2107 /// \p FixedRegisters contains all the virtual registers that cannot be
2109 /// \p Depth gives the current depth of the last chance recoloring.
2110 /// \return a physical register that can be used for VirtReg or ~0u if none
2112 unsigned RAGreedy::tryLastChanceRecoloring(LiveInterval &VirtReg,
2113 AllocationOrder &Order,
2114 SmallVectorImpl<unsigned> &NewVRegs,
2115 SmallVirtRegSet &FixedRegisters,
2117 DEBUG(dbgs() << "Try last chance recoloring for " << VirtReg << '\n');
2118 // Ranges must be Done.
2119 assert((getStage(VirtReg) >= RS_Done || !VirtReg.isSpillable()) &&
2120 "Last chance recoloring should really be last chance");
2121 // Set the max depth to LastChanceRecoloringMaxDepth.
2122 // We may want to reconsider that if we end up with a too large search space
2123 // for target with hundreds of registers.
2124 // Indeed, in that case we may want to cut the search space earlier.
2125 if (Depth >= LastChanceRecoloringMaxDepth && !ExhaustiveSearch) {
2126 DEBUG(dbgs() << "Abort because max depth has been reached.\n");
2127 CutOffInfo |= CO_Depth;
2131 // Set of Live intervals that will need to be recolored.
2132 SmallLISet RecoloringCandidates;
2133 // Record the original mapping virtual register to physical register in case
2134 // the recoloring fails.
2135 DenseMap<unsigned, unsigned> VirtRegToPhysReg;
2136 // Mark VirtReg as fixed, i.e., it will not be recolored pass this point in
2137 // this recoloring "session".
2138 FixedRegisters.insert(VirtReg.reg);
2139 SmallVector<unsigned, 4> CurrentNewVRegs;
2142 while (unsigned PhysReg = Order.next()) {
2143 DEBUG(dbgs() << "Try to assign: " << VirtReg << " to "
2144 << PrintReg(PhysReg, TRI) << '\n');
2145 RecoloringCandidates.clear();
2146 VirtRegToPhysReg.clear();
2147 CurrentNewVRegs.clear();
2149 // It is only possible to recolor virtual register interference.
2150 if (Matrix->checkInterference(VirtReg, PhysReg) >
2151 LiveRegMatrix::IK_VirtReg) {
2152 DEBUG(dbgs() << "Some inteferences are not with virtual registers.\n");
2157 // Early give up on this PhysReg if it is obvious we cannot recolor all
2158 // the interferences.
2159 if (!mayRecolorAllInterferences(PhysReg, VirtReg, RecoloringCandidates,
2161 DEBUG(dbgs() << "Some inteferences cannot be recolored.\n");
2165 // RecoloringCandidates contains all the virtual registers that interfer
2166 // with VirtReg on PhysReg (or one of its aliases).
2167 // Enqueue them for recoloring and perform the actual recoloring.
2168 PQueue RecoloringQueue;
2169 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2170 EndIt = RecoloringCandidates.end();
2171 It != EndIt; ++It) {
2172 unsigned ItVirtReg = (*It)->reg;
2173 enqueue(RecoloringQueue, *It);
2174 assert(VRM->hasPhys(ItVirtReg) &&
2175 "Interferences are supposed to be with allocated vairables");
2177 // Record the current allocation.
2178 VirtRegToPhysReg[ItVirtReg] = VRM->getPhys(ItVirtReg);
2179 // unset the related struct.
2180 Matrix->unassign(**It);
2183 // Do as if VirtReg was assigned to PhysReg so that the underlying
2184 // recoloring has the right information about the interferes and
2185 // available colors.
2186 Matrix->assign(VirtReg, PhysReg);
2188 // Save the current recoloring state.
2189 // If we cannot recolor all the interferences, we will have to start again
2190 // at this point for the next physical register.
2191 SmallVirtRegSet SaveFixedRegisters(FixedRegisters);
2192 if (tryRecoloringCandidates(RecoloringQueue, CurrentNewVRegs,
2193 FixedRegisters, Depth)) {
2194 // Push the queued vregs into the main queue.
2195 for (unsigned NewVReg : CurrentNewVRegs)
2196 NewVRegs.push_back(NewVReg);
2197 // Do not mess up with the global assignment process.
2198 // I.e., VirtReg must be unassigned.
2199 Matrix->unassign(VirtReg);
2203 DEBUG(dbgs() << "Fail to assign: " << VirtReg << " to "
2204 << PrintReg(PhysReg, TRI) << '\n');
2206 // The recoloring attempt failed, undo the changes.
2207 FixedRegisters = SaveFixedRegisters;
2208 Matrix->unassign(VirtReg);
2210 // For a newly created vreg which is also in RecoloringCandidates,
2211 // don't add it to NewVRegs because its physical register will be restored
2212 // below. Other vregs in CurrentNewVRegs are created by calling
2213 // selectOrSplit and should be added into NewVRegs.
2214 for (SmallVectorImpl<unsigned>::iterator Next = CurrentNewVRegs.begin(),
2215 End = CurrentNewVRegs.end();
2216 Next != End; ++Next) {
2217 if (RecoloringCandidates.count(&LIS->getInterval(*Next)))
2219 NewVRegs.push_back(*Next);
2222 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2223 EndIt = RecoloringCandidates.end();
2224 It != EndIt; ++It) {
2225 unsigned ItVirtReg = (*It)->reg;
2226 if (VRM->hasPhys(ItVirtReg))
2227 Matrix->unassign(**It);
2228 unsigned ItPhysReg = VirtRegToPhysReg[ItVirtReg];
2229 Matrix->assign(**It, ItPhysReg);
2233 // Last chance recoloring did not worked either, give up.
2237 /// tryRecoloringCandidates - Try to assign a new color to every register
2238 /// in \RecoloringQueue.
2239 /// \p NewRegs will contain any new virtual register created during the
2240 /// recoloring process.
2241 /// \p FixedRegisters[in/out] contains all the registers that have been
2243 /// \return true if all virtual registers in RecoloringQueue were successfully
2244 /// recolored, false otherwise.
2245 bool RAGreedy::tryRecoloringCandidates(PQueue &RecoloringQueue,
2246 SmallVectorImpl<unsigned> &NewVRegs,
2247 SmallVirtRegSet &FixedRegisters,
2249 while (!RecoloringQueue.empty()) {
2250 LiveInterval *LI = dequeue(RecoloringQueue);
2251 DEBUG(dbgs() << "Try to recolor: " << *LI << '\n');
2253 PhysReg = selectOrSplitImpl(*LI, NewVRegs, FixedRegisters, Depth + 1);
2254 // When splitting happens, the live-range may actually be empty.
2255 // In that case, this is okay to continue the recoloring even
2256 // if we did not find an alternative color for it. Indeed,
2257 // there will not be anything to color for LI in the end.
2258 if (PhysReg == ~0u || (!PhysReg && !LI->empty()))
2262 assert(LI->empty() && "Only empty live-range do not require a register");
2263 DEBUG(dbgs() << "Recoloring of " << *LI << " succeeded. Empty LI.\n");
2266 DEBUG(dbgs() << "Recoloring of " << *LI
2267 << " succeeded with: " << PrintReg(PhysReg, TRI) << '\n');
2269 Matrix->assign(*LI, PhysReg);
2270 FixedRegisters.insert(LI->reg);
2275 //===----------------------------------------------------------------------===//
2277 //===----------------------------------------------------------------------===//
2279 unsigned RAGreedy::selectOrSplit(LiveInterval &VirtReg,
2280 SmallVectorImpl<unsigned> &NewVRegs) {
2281 CutOffInfo = CO_None;
2282 LLVMContext &Ctx = MF->getFunction()->getContext();
2283 SmallVirtRegSet FixedRegisters;
2284 unsigned Reg = selectOrSplitImpl(VirtReg, NewVRegs, FixedRegisters);
2285 if (Reg == ~0U && (CutOffInfo != CO_None)) {
2286 uint8_t CutOffEncountered = CutOffInfo & (CO_Depth | CO_Interf);
2287 if (CutOffEncountered == CO_Depth)
2288 Ctx.emitError("register allocation failed: maximum depth for recoloring "
2289 "reached. Use -fexhaustive-register-search to skip "
2291 else if (CutOffEncountered == CO_Interf)
2292 Ctx.emitError("register allocation failed: maximum interference for "
2293 "recoloring reached. Use -fexhaustive-register-search "
2295 else if (CutOffEncountered == (CO_Depth | CO_Interf))
2296 Ctx.emitError("register allocation failed: maximum interference and "
2297 "depth for recoloring reached. Use "
2298 "-fexhaustive-register-search to skip cutoffs");
2303 /// Using a CSR for the first time has a cost because it causes push|pop
2304 /// to be added to prologue|epilogue. Splitting a cold section of the live
2305 /// range can have lower cost than using the CSR for the first time;
2306 /// Spilling a live range in the cold path can have lower cost than using
2307 /// the CSR for the first time. Returns the physical register if we decide
2308 /// to use the CSR; otherwise return 0.
2309 unsigned RAGreedy::tryAssignCSRFirstTime(LiveInterval &VirtReg,
2310 AllocationOrder &Order,
2312 unsigned &CostPerUseLimit,
2313 SmallVectorImpl<unsigned> &NewVRegs) {
2314 if (getStage(VirtReg) == RS_Spill && VirtReg.isSpillable()) {
2315 // We choose spill over using the CSR for the first time if the spill cost
2316 // is lower than CSRCost.
2317 SA->analyze(&VirtReg);
2318 if (calcSpillCost() >= CSRCost)
2321 // We are going to spill, set CostPerUseLimit to 1 to make sure that
2322 // we will not use a callee-saved register in tryEvict.
2323 CostPerUseLimit = 1;
2326 if (getStage(VirtReg) < RS_Split) {
2327 // We choose pre-splitting over using the CSR for the first time if
2328 // the cost of splitting is lower than CSRCost.
2329 SA->analyze(&VirtReg);
2330 unsigned NumCands = 0;
2331 BlockFrequency BestCost = CSRCost; // Don't modify CSRCost.
2332 unsigned BestCand = calculateRegionSplitCost(VirtReg, Order, BestCost,
2333 NumCands, true /*IgnoreCSR*/);
2334 if (BestCand == NoCand)
2335 // Use the CSR if we can't find a region split below CSRCost.
2338 // Perform the actual pre-splitting.
2339 doRegionSplit(VirtReg, BestCand, false/*HasCompact*/, NewVRegs);
2345 void RAGreedy::aboutToRemoveInterval(LiveInterval &LI) {
2346 // Do not keep invalid information around.
2347 SetOfBrokenHints.remove(&LI);
2350 void RAGreedy::initializeCSRCost() {
2351 // We use the larger one out of the command-line option and the value report
2353 CSRCost = BlockFrequency(
2354 std::max((unsigned)CSRFirstTimeCost, TRI->getCSRFirstUseCost()));
2355 if (!CSRCost.getFrequency())
2358 // Raw cost is relative to Entry == 2^14; scale it appropriately.
2359 uint64_t ActualEntry = MBFI->getEntryFreq();
2364 uint64_t FixedEntry = 1 << 14;
2365 if (ActualEntry < FixedEntry)
2366 CSRCost *= BranchProbability(ActualEntry, FixedEntry);
2367 else if (ActualEntry <= UINT32_MAX)
2368 // Invert the fraction and divide.
2369 CSRCost /= BranchProbability(FixedEntry, ActualEntry);
2371 // Can't use BranchProbability in general, since it takes 32-bit numbers.
2372 CSRCost = CSRCost.getFrequency() * (ActualEntry / FixedEntry);
2375 /// \brief Collect the hint info for \p Reg.
2376 /// The results are stored into \p Out.
2377 /// \p Out is not cleared before being populated.
2378 void RAGreedy::collectHintInfo(unsigned Reg, HintsInfo &Out) {
2379 for (const MachineInstr &Instr : MRI->reg_nodbg_instructions(Reg)) {
2380 if (!Instr.isFullCopy())
2382 // Look for the other end of the copy.
2383 unsigned OtherReg = Instr.getOperand(0).getReg();
2384 if (OtherReg == Reg) {
2385 OtherReg = Instr.getOperand(1).getReg();
2386 if (OtherReg == Reg)
2389 // Get the current assignment.
2390 unsigned OtherPhysReg = TargetRegisterInfo::isPhysicalRegister(OtherReg)
2392 : VRM->getPhys(OtherReg);
2393 // Push the collected information.
2394 Out.push_back(HintInfo(MBFI->getBlockFreq(Instr.getParent()), OtherReg,
2399 /// \brief Using the given \p List, compute the cost of the broken hints if
2400 /// \p PhysReg was used.
2401 /// \return The cost of \p List for \p PhysReg.
2402 BlockFrequency RAGreedy::getBrokenHintFreq(const HintsInfo &List,
2404 BlockFrequency Cost = 0;
2405 for (const HintInfo &Info : List) {
2406 if (Info.PhysReg != PhysReg)
2412 /// \brief Using the register assigned to \p VirtReg, try to recolor
2413 /// all the live ranges that are copy-related with \p VirtReg.
2414 /// The recoloring is then propagated to all the live-ranges that have
2415 /// been recolored and so on, until no more copies can be coalesced or
2416 /// it is not profitable.
2417 /// For a given live range, profitability is determined by the sum of the
2418 /// frequencies of the non-identity copies it would introduce with the old
2419 /// and new register.
2420 void RAGreedy::tryHintRecoloring(LiveInterval &VirtReg) {
2421 // We have a broken hint, check if it is possible to fix it by
2422 // reusing PhysReg for the copy-related live-ranges. Indeed, we evicted
2423 // some register and PhysReg may be available for the other live-ranges.
2424 SmallSet<unsigned, 4> Visited;
2425 SmallVector<unsigned, 2> RecoloringCandidates;
2427 unsigned Reg = VirtReg.reg;
2428 unsigned PhysReg = VRM->getPhys(Reg);
2429 // Start the recoloring algorithm from the input live-interval, then
2430 // it will propagate to the ones that are copy-related with it.
2431 Visited.insert(Reg);
2432 RecoloringCandidates.push_back(Reg);
2434 DEBUG(dbgs() << "Trying to reconcile hints for: " << PrintReg(Reg, TRI) << '('
2435 << PrintReg(PhysReg, TRI) << ")\n");
2438 Reg = RecoloringCandidates.pop_back_val();
2440 // We cannot recolor physcal register.
2441 if (TargetRegisterInfo::isPhysicalRegister(Reg))
2444 assert(VRM->hasPhys(Reg) && "We have unallocated variable!!");
2446 // Get the live interval mapped with this virtual register to be able
2447 // to check for the interference with the new color.
2448 LiveInterval &LI = LIS->getInterval(Reg);
2449 unsigned CurrPhys = VRM->getPhys(Reg);
2450 // Check that the new color matches the register class constraints and
2451 // that it is free for this live range.
2452 if (CurrPhys != PhysReg && (!MRI->getRegClass(Reg)->contains(PhysReg) ||
2453 Matrix->checkInterference(LI, PhysReg)))
2456 DEBUG(dbgs() << PrintReg(Reg, TRI) << '(' << PrintReg(CurrPhys, TRI)
2457 << ") is recolorable.\n");
2459 // Gather the hint info.
2461 collectHintInfo(Reg, Info);
2462 // Check if recoloring the live-range will increase the cost of the
2463 // non-identity copies.
2464 if (CurrPhys != PhysReg) {
2465 DEBUG(dbgs() << "Checking profitability:\n");
2466 BlockFrequency OldCopiesCost = getBrokenHintFreq(Info, CurrPhys);
2467 BlockFrequency NewCopiesCost = getBrokenHintFreq(Info, PhysReg);
2468 DEBUG(dbgs() << "Old Cost: " << OldCopiesCost.getFrequency()
2469 << "\nNew Cost: " << NewCopiesCost.getFrequency() << '\n');
2470 if (OldCopiesCost < NewCopiesCost) {
2471 DEBUG(dbgs() << "=> Not profitable.\n");
2474 // At this point, the cost is either cheaper or equal. If it is
2475 // equal, we consider this is profitable because it may expose
2476 // more recoloring opportunities.
2477 DEBUG(dbgs() << "=> Profitable.\n");
2478 // Recolor the live-range.
2479 Matrix->unassign(LI);
2480 Matrix->assign(LI, PhysReg);
2482 // Push all copy-related live-ranges to keep reconciling the broken
2484 for (const HintInfo &HI : Info) {
2485 if (Visited.insert(HI.Reg).second)
2486 RecoloringCandidates.push_back(HI.Reg);
2488 } while (!RecoloringCandidates.empty());
2491 /// \brief Try to recolor broken hints.
2492 /// Broken hints may be repaired by recoloring when an evicted variable
2493 /// freed up a register for a larger live-range.
2494 /// Consider the following example:
2502 /// Let us assume b gets split:
2512 /// Because of how the allocation work, b, c, and d may be assigned different
2513 /// colors. Now, if a gets evicted later:
2523 /// e = ld SpillSlot
2525 /// This is likely that we can assign the same register for b, c, and d,
2526 /// getting rid of 2 copies.
2527 void RAGreedy::tryHintsRecoloring() {
2528 for (LiveInterval *LI : SetOfBrokenHints) {
2529 assert(TargetRegisterInfo::isVirtualRegister(LI->reg) &&
2530 "Recoloring is possible only for virtual registers");
2531 // Some dead defs may be around (e.g., because of debug uses).
2533 if (!VRM->hasPhys(LI->reg))
2535 tryHintRecoloring(*LI);
2539 unsigned RAGreedy::selectOrSplitImpl(LiveInterval &VirtReg,
2540 SmallVectorImpl<unsigned> &NewVRegs,
2541 SmallVirtRegSet &FixedRegisters,
2543 unsigned CostPerUseLimit = ~0u;
2544 // First try assigning a free register.
2545 AllocationOrder Order(VirtReg.reg, *VRM, RegClassInfo, Matrix);
2546 if (unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs)) {
2547 // When NewVRegs is not empty, we may have made decisions such as evicting
2548 // a virtual register, go with the earlier decisions and use the physical
2550 if (CSRCost.getFrequency() && isUnusedCalleeSavedReg(PhysReg) &&
2552 unsigned CSRReg = tryAssignCSRFirstTime(VirtReg, Order, PhysReg,
2553 CostPerUseLimit, NewVRegs);
2554 if (CSRReg || !NewVRegs.empty())
2555 // Return now if we decide to use a CSR or create new vregs due to
2562 LiveRangeStage Stage = getStage(VirtReg);
2563 DEBUG(dbgs() << StageName[Stage]
2564 << " Cascade " << ExtraRegInfo[VirtReg.reg].Cascade << '\n');
2566 // Try to evict a less worthy live range, but only for ranges from the primary
2567 // queue. The RS_Split ranges already failed to do this, and they should not
2568 // get a second chance until they have been split.
2569 if (Stage != RS_Split)
2570 if (unsigned PhysReg =
2571 tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit)) {
2572 unsigned Hint = MRI->getSimpleHint(VirtReg.reg);
2573 // If VirtReg has a hint and that hint is broken record this
2574 // virtual register as a recoloring candidate for broken hint.
2575 // Indeed, since we evicted a variable in its neighborhood it is
2576 // likely we can at least partially recolor some of the
2577 // copy-related live-ranges.
2578 if (Hint && Hint != PhysReg)
2579 SetOfBrokenHints.insert(&VirtReg);
2583 assert((NewVRegs.empty() || Depth) && "Cannot append to existing NewVRegs");
2585 // The first time we see a live range, don't try to split or spill.
2586 // Wait until the second time, when all smaller ranges have been allocated.
2587 // This gives a better picture of the interference to split around.
2588 if (Stage < RS_Split) {
2589 setStage(VirtReg, RS_Split);
2590 DEBUG(dbgs() << "wait for second round\n");
2591 NewVRegs.push_back(VirtReg.reg);
2595 if (Stage < RS_Spill) {
2596 // Try splitting VirtReg or interferences.
2597 unsigned NewVRegSizeBefore = NewVRegs.size();
2598 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs);
2599 if (PhysReg || (NewVRegs.size() - NewVRegSizeBefore))
2603 // If we couldn't allocate a register from spilling, there is probably some
2604 // invalid inline assembly. The base class wil report it.
2605 if (Stage >= RS_Done || !VirtReg.isSpillable())
2606 return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters,
2609 // Finally spill VirtReg itself.
2610 if (EnableDeferredSpilling && getStage(VirtReg) < RS_Memory) {
2611 // TODO: This is experimental and in particular, we do not model
2612 // the live range splitting done by spilling correctly.
2613 // We would need a deep integration with the spiller to do the
2614 // right thing here. Anyway, that is still good for early testing.
2615 setStage(VirtReg, RS_Memory);
2616 DEBUG(dbgs() << "Do as if this register is in memory\n");
2617 NewVRegs.push_back(VirtReg.reg);
2619 NamedRegionTimer T("spill", "Spiller", TimerGroupName,
2620 TimerGroupDescription, TimePassesIsEnabled);
2621 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM, this, &DeadRemats);
2622 spiller().spill(LRE);
2623 setStage(NewVRegs.begin(), NewVRegs.end(), RS_Done);
2626 MF->verify(this, "After spilling");
2629 // The live virtual register requesting allocation was spilled, so tell
2630 // the caller not to allocate anything during this round.
2634 void RAGreedy::reportNumberOfSplillsReloads(MachineLoop *L, unsigned &Reloads,
2635 unsigned &FoldedReloads,
2637 unsigned &FoldedSpills) {
2643 // Sum up the spill and reloads in subloops.
2644 for (MachineLoop *SubLoop : *L) {
2645 unsigned SubReloads;
2646 unsigned SubFoldedReloads;
2648 unsigned SubFoldedSpills;
2650 reportNumberOfSplillsReloads(SubLoop, SubReloads, SubFoldedReloads,
2651 SubSpills, SubFoldedSpills);
2652 Reloads += SubReloads;
2653 FoldedReloads += SubFoldedReloads;
2654 Spills += SubSpills;
2655 FoldedSpills += SubFoldedSpills;
2658 const MachineFrameInfo &MFI = MF->getFrameInfo();
2659 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
2662 for (MachineBasicBlock *MBB : L->getBlocks())
2663 // Handle blocks that were not included in subloops.
2664 if (Loops->getLoopFor(MBB) == L)
2665 for (MachineInstr &MI : *MBB) {
2666 const MachineMemOperand *MMO;
2668 if (TII->isLoadFromStackSlot(MI, FI) && MFI.isSpillSlotObjectIndex(FI))
2670 else if (TII->hasLoadFromStackSlot(MI, MMO, FI) &&
2671 MFI.isSpillSlotObjectIndex(FI))
2673 else if (TII->isStoreToStackSlot(MI, FI) &&
2674 MFI.isSpillSlotObjectIndex(FI))
2676 else if (TII->hasStoreToStackSlot(MI, MMO, FI) &&
2677 MFI.isSpillSlotObjectIndex(FI))
2681 if (Reloads || FoldedReloads || Spills || FoldedSpills) {
2682 using namespace ore;
2683 MachineOptimizationRemarkMissed R(DEBUG_TYPE, "LoopSpillReload",
2684 L->getStartLoc(), L->getHeader());
2686 R << NV("NumSpills", Spills) << " spills ";
2688 R << NV("NumFoldedSpills", FoldedSpills) << " folded spills ";
2690 R << NV("NumReloads", Reloads) << " reloads ";
2692 R << NV("NumFoldedReloads", FoldedReloads) << " folded reloads ";
2693 ORE->emit(R << "generated in loop");
2697 bool RAGreedy::runOnMachineFunction(MachineFunction &mf) {
2698 DEBUG(dbgs() << "********** GREEDY REGISTER ALLOCATION **********\n"
2699 << "********** Function: " << mf.getName() << '\n');
2702 TRI = MF->getSubtarget().getRegisterInfo();
2703 TII = MF->getSubtarget().getInstrInfo();
2704 RCI.runOnMachineFunction(mf);
2706 EnableLocalReassign = EnableLocalReassignment ||
2707 MF->getSubtarget().enableRALocalReassignment(
2708 MF->getTarget().getOptLevel());
2711 MF->verify(this, "Before greedy register allocator");
2713 RegAllocBase::init(getAnalysis<VirtRegMap>(),
2714 getAnalysis<LiveIntervals>(),
2715 getAnalysis<LiveRegMatrix>());
2716 Indexes = &getAnalysis<SlotIndexes>();
2717 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
2718 DomTree = &getAnalysis<MachineDominatorTree>();
2719 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
2720 SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM));
2721 Loops = &getAnalysis<MachineLoopInfo>();
2722 Bundles = &getAnalysis<EdgeBundles>();
2723 SpillPlacer = &getAnalysis<SpillPlacement>();
2724 DebugVars = &getAnalysis<LiveDebugVariables>();
2725 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2727 initializeCSRCost();
2729 calculateSpillWeightsAndHints(*LIS, mf, VRM, *Loops, *MBFI);
2733 SA.reset(new SplitAnalysis(*VRM, *LIS, *Loops));
2734 SE.reset(new SplitEditor(*SA, *AA, *LIS, *VRM, *DomTree, *MBFI));
2735 ExtraRegInfo.clear();
2736 ExtraRegInfo.resize(MRI->getNumVirtRegs());
2738 IntfCache.init(MF, Matrix->getLiveUnions(), Indexes, LIS, TRI);
2739 GlobalCand.resize(32); // This will grow as needed.
2740 SetOfBrokenHints.clear();
2743 tryHintsRecoloring();
2745 reportNumberOfSplillsReloads();