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