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