Thanks to visit codestin.com
Credit goes to llvm.org

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