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