82 #define DEBUG_TYPE "regalloc" 84 STATISTIC(NumGlobalSplits,
"Number of split global live ranges");
85 STATISTIC(NumLocalSplits,
"Number of split local live ranges");
86 STATISTIC(NumEvicted,
"Number of interferences evicted");
90 cl::desc(
"Spill mode for splitting live ranges"),
98 cl::desc(
"Last chance recoloring max depth"),
103 cl::desc(
"Last chance recoloring maximum number of considered" 104 " interference at a time"),
109 cl::desc(
"Exhaustive Search for registers bypassing the depth " 110 "and interference cutoffs of last chance recoloring"),
115 cl::desc(
"Local reassignment can yield better allocation decisions, but " 116 "may be compile time intensive"),
121 cl::desc(
"Instead of spilling a variable right away, defer the actual " 122 "code insertion to the end of the allocation. That way the " 123 "allocator might still find a suitable coloring for this " 124 "variable because of other evicted variables."),
129 cl::desc(
"A threshold of live range size which may cause " 130 "high compile time cost in global splitting."),
136 cl::desc(
"Cost for first time use of callee-saved register."),
141 cl::desc(
"Consider the cost of local intervals created by a split " 142 "candidate when choosing the best split candidate."),
154 using PQueue = std::priority_queue<std::pair<unsigned, unsigned>>;
178 std::unique_ptr<Spiller> SpillerInstance;
180 unsigned NextCascade;
195 enum LiveRangeStage {
240 static const char *
const StageName[];
245 LiveRangeStage Stage = RS_New;
248 unsigned Cascade = 0;
255 LiveRangeStage getStage(
const LiveInterval &VirtReg)
const {
256 return ExtraRegInfo[VirtReg.
reg].Stage;
259 void setStage(
const LiveInterval &VirtReg, LiveRangeStage Stage) {
260 ExtraRegInfo.
resize(
MRI->getNumVirtRegs());
261 ExtraRegInfo[VirtReg.
reg].Stage = Stage;
264 template<
typename Iterator>
265 void setStage(Iterator Begin, Iterator End, LiveRangeStage NewStage) {
266 ExtraRegInfo.
resize(
MRI->getNumVirtRegs());
267 for (;Begin != End; ++Begin) {
268 unsigned Reg = *Begin;
269 if (ExtraRegInfo[Reg].Stage == RS_New)
270 ExtraRegInfo[
Reg].Stage = NewStage;
275 struct EvictionCost {
276 unsigned BrokenHints = 0;
279 EvictionCost() =
default;
281 bool isMax()
const {
return BrokenHints == ~0u; }
283 void setMax() { BrokenHints = ~0u; }
285 void setBrokenHints(
unsigned NHints) { BrokenHints = NHints; }
288 return std::tie(BrokenHints, MaxWeight) <
289 std::tie(O.BrokenHints, O.MaxWeight);
295 class EvictionTrack {
299 std::pair<
unsigned ,
unsigned >;
305 EvicteeInfo Evictees;
309 void clear() { Evictees.clear(); }
316 void clearEvicteeInfo(
unsigned Evictee) { Evictees.erase(Evictee); }
323 void addEviction(
unsigned PhysReg,
unsigned Evictor,
unsigned Evictee) {
324 Evictees[Evictee].first = Evictor;
325 Evictees[Evictee].second = PhysReg;
332 EvictorInfo getEvictor(
unsigned Evictee) {
333 if (Evictees.count(Evictee)) {
334 return Evictees[Evictee];
337 return EvictorInfo(0, 0);
342 EvictionTrack LastEvicted;
345 std::unique_ptr<SplitAnalysis> SA;
346 std::unique_ptr<SplitEditor> SE;
355 struct GlobalSplitCandidate {
374 ActiveBlocks.
clear();
380 for (
unsigned i : LiveBundles.
set_bits())
394 enum :
unsigned {
NoCand = ~0u };
405 bool EnableLocalReassign;
409 bool EnableAdvancedRASplitCost;
418 StringRef getPassName()
const override {
return "Greedy Register Allocator"; }
422 void releaseMemory()
override;
423 Spiller &spiller()
override {
return *SpillerInstance; }
441 SmallVirtRegSet &,
unsigned = 0);
443 bool LRE_CanEraseVirtReg(
unsigned)
override;
444 void LRE_WillShrinkVirtReg(
unsigned)
override;
445 void LRE_DidCloneVirtReg(
unsigned,
unsigned)
override;
452 bool growRegion(GlobalSplitCandidate &Cand);
453 bool splitCanCauseEvictionChain(
unsigned Evictee, GlobalSplitCandidate &Cand,
456 bool splitCanCauseLocalSpill(
unsigned VirtRegToSplit,
457 GlobalSplitCandidate &Cand,
unsigned BBNumber,
461 bool *CanCauseEvictionChain);
462 bool calcCompactRegion(GlobalSplitCandidate&);
465 unsigned canReassign(
LiveInterval &VirtReg,
unsigned PrevReg);
467 bool canEvictInterference(
LiveInterval&,
unsigned,
bool, EvictionCost&,
468 const SmallVirtRegSet&);
469 bool canEvictInterferenceInRange(
LiveInterval &VirtReg,
unsigned PhysReg,
471 EvictionCost &MaxCost);
477 bool mayRecolorAllInterferences(
unsigned PhysReg,
LiveInterval &VirtReg,
478 SmallLISet &RecoloringCandidates,
479 const SmallVirtRegSet &FixedRegisters);
483 const SmallVirtRegSet&);
486 const SmallVirtRegSet&);
489 unsigned isSplitBenefitWorthCost(
LiveInterval &VirtReg);
491 unsigned calculateRegionSplitCost(
LiveInterval &VirtReg,
494 unsigned &NumCands,
bool IgnoreCSR,
495 bool *CanCauseEvictionChain =
nullptr);
497 unsigned doRegionSplit(
LiveInterval &VirtReg,
unsigned BestCand,
503 unsigned PhysReg,
unsigned &CostPerUseLimit,
505 void initializeCSRCost();
514 const SmallVirtRegSet&);
517 SmallVirtRegSet &,
unsigned);
519 SmallVirtRegSet &,
unsigned);
521 void tryHintsRecoloring();
534 : Freq(Freq), Reg(Reg), PhysReg(PhysReg) {}
539 void collectHintInfo(
unsigned, HintsInfo &);
541 bool isUnusedCalleeSavedReg(
unsigned PhysReg)
const;
544 void reportNumberOfSplillsReloads(
MachineLoop *L,
unsigned &Reloads,
545 unsigned &FoldedReloads,
unsigned &Spills,
546 unsigned &FoldedSpills);
549 void reportNumberOfSplillsReloads() {
551 unsigned Reloads, FoldedReloads, Spills, FoldedSpills;
552 reportNumberOfSplillsReloads(L, Reloads, FoldedReloads, Spills,
564 "Greedy Register Allocator",
false,
false)
582 const char *
const RAGreedy::StageName[] = {
598 return new RAGreedy();
636 bool RAGreedy::LRE_CanEraseVirtReg(
unsigned VirtReg) {
638 if (VRM->hasPhys(VirtReg)) {
640 aboutToRemoveInterval(LI);
651 void RAGreedy::LRE_WillShrinkVirtReg(
unsigned VirtReg) {
652 if (!VRM->hasPhys(VirtReg))
661 void RAGreedy::LRE_DidCloneVirtReg(
unsigned New,
unsigned Old) {
670 ExtraRegInfo[Old].Stage = RS_Assign;
671 ExtraRegInfo.
grow(New);
672 ExtraRegInfo[New] = ExtraRegInfo[Old];
675 void RAGreedy::releaseMemory() {
676 SpillerInstance.reset();
677 ExtraRegInfo.
clear();
681 void RAGreedy::enqueue(
LiveInterval *LI) { enqueue(Queue, LI); }
683 void RAGreedy::enqueue(PQueue &CurQueue,
LiveInterval *LI) {
687 const unsigned Reg = LI->
reg;
689 "Can only enqueue virtual registers");
692 ExtraRegInfo.
grow(Reg);
693 if (ExtraRegInfo[Reg].Stage == RS_New)
694 ExtraRegInfo[
Reg].Stage = RS_Assign;
696 if (ExtraRegInfo[Reg].Stage == RS_Split) {
700 }
else if (ExtraRegInfo[Reg].Stage == RS_Memory) {
705 static unsigned MemOp = 0;
712 bool ForceGlobal = !ReverseLocal &&
715 if (ExtraRegInfo[Reg].Stage == RS_Assign && !ForceGlobal && !LI->
empty() &&
716 LIS->intervalIsInOneMBB(*LI)) {
733 Prio = (1u << 29) + Size;
739 if (VRM->hasKnownPreference(Reg))
744 CurQueue.push(std::make_pair(Prio, ~Reg));
747 LiveInterval *RAGreedy::dequeue() {
return dequeue(Queue); }
750 if (CurQueue.empty())
752 LiveInterval *LI = &LIS->getInterval(~CurQueue.top().second);
765 const SmallVirtRegSet &FixedRegisters) {
768 while ((PhysReg = Order.
next()))
769 if (!
Matrix->checkInterference(VirtReg, PhysReg))
771 if (!PhysReg || Order.
isHint())
778 if (
unsigned Hint =
MRI->getSimpleHint(VirtReg.
reg))
781 EvictionCost MaxCost;
782 MaxCost.setBrokenHints(1);
783 if (canEvictInterference(VirtReg, Hint,
true, MaxCost, FixedRegisters)) {
784 evictInterference(VirtReg, Hint, NewVRegs);
789 SetOfBrokenHints.
insert(&VirtReg);
801 unsigned CheapReg = tryEvict(VirtReg, Order, NewVRegs, Cost, FixedRegisters);
802 return CheapReg ? CheapReg : PhysReg;
809 unsigned RAGreedy::canReassign(
LiveInterval &VirtReg,
unsigned PrevReg) {
812 while ((PhysReg = Order.
next())) {
813 if (PhysReg == PrevReg)
817 for (; Units.
isValid(); ++Units) {
820 if (subQ.checkInterference())
847 bool RAGreedy::shouldEvict(
LiveInterval &A,
bool IsHint,
849 bool CanSplit = getStage(B) < RS_Spill;
853 if (CanSplit && IsHint && !BreaksHint)
872 bool RAGreedy::canEvictInterference(
LiveInterval &VirtReg,
unsigned PhysReg,
873 bool IsHint, EvictionCost &MaxCost,
874 const SmallVirtRegSet &FixedRegisters) {
879 bool IsLocal = LIS->intervalIsInOneMBB(VirtReg);
888 unsigned Cascade = ExtraRegInfo[VirtReg.
reg].Cascade;
890 Cascade = NextCascade;
903 "Only expecting virtual register interference from query");
908 if (FixedRegisters.count(Intf->
reg))
912 if (getStage(*Intf) == RS_Done)
922 RegClassInfo.getNumAllocatableRegs(
MRI->getRegClass(VirtReg.
reg)) <
923 RegClassInfo.getNumAllocatableRegs(
MRI->getRegClass(Intf->
reg)));
925 unsigned IntfCascade = ExtraRegInfo[Intf->
reg].Cascade;
926 if (Cascade <= IntfCascade) {
931 Cost.BrokenHints += 10;
934 bool BreaksHint = VRM->hasPreferredPhys(Intf->
reg);
936 Cost.BrokenHints += BreaksHint;
939 if (!(Cost < MaxCost))
944 if (!shouldEvict(VirtReg, IsHint, *Intf, BreaksHint))
949 if (!MaxCost.isMax() && IsLocal && LIS->intervalIsInOneMBB(*Intf) &&
950 (!EnableLocalReassign || !canReassign(*Intf, PhysReg))) {
969 bool RAGreedy::canEvictInterferenceInRange(
LiveInterval &VirtReg,
972 EvictionCost &MaxCost) {
990 if (getStage(*Intf) == RS_Done)
994 bool BreaksHint = VRM->hasPreferredPhys(Intf->
reg);
996 Cost.BrokenHints += BreaksHint;
999 if (!(Cost < MaxCost))
1004 if (Cost.MaxWeight == 0)
1022 unsigned RAGreedy::getCheapestEvicteeWeight(
const AllocationOrder &Order,
1025 float *BestEvictweight) {
1026 EvictionCost BestEvictCost;
1027 BestEvictCost.setMax();
1028 BestEvictCost.MaxWeight = VirtReg.
weight;
1029 unsigned BestEvicteePhys = 0;
1032 for (
auto PhysReg : Order.
getOrder()) {
1034 if (!canEvictInterferenceInRange(VirtReg, PhysReg, Start, End,
1039 BestEvicteePhys = PhysReg;
1041 *BestEvictweight = BestEvictCost.MaxWeight;
1042 return BestEvicteePhys;
1048 void RAGreedy::evictInterference(
LiveInterval &VirtReg,
unsigned PhysReg,
1053 unsigned Cascade = ExtraRegInfo[VirtReg.
reg].Cascade;
1055 Cascade = ExtraRegInfo[VirtReg.
reg].Cascade = NextCascade++;
1058 <<
" interference: Cascade " << Cascade <<
'\n');
1074 for (
unsigned i = 0,
e = Intfs.
size(); i !=
e; ++i) {
1077 if (!VRM->hasPhys(Intf->
reg))
1080 LastEvicted.addEviction(PhysReg, VirtReg.
reg, Intf->
reg);
1083 assert((ExtraRegInfo[Intf->
reg].Cascade < Cascade ||
1085 "Cannot decrease cascade number, illegal eviction");
1086 ExtraRegInfo[Intf->
reg].Cascade = Cascade;
1094 bool RAGreedy::isUnusedCalleeSavedReg(
unsigned PhysReg)
const {
1095 unsigned CSR = RegClassInfo.getLastCalleeSavedAlias(PhysReg);
1099 return !
Matrix->isPhysRegUsed(PhysReg);
1109 unsigned CostPerUseLimit,
1110 const SmallVirtRegSet &FixedRegisters) {
1115 EvictionCost BestCost;
1117 unsigned BestPhys = 0;
1118 unsigned OrderLimit = Order.
getOrder().size();
1122 if (CostPerUseLimit < ~0u) {
1123 BestCost.BrokenHints = 0;
1124 BestCost.MaxWeight = VirtReg.
weight;
1128 unsigned MinCost = RegClassInfo.getMinCost(RC);
1129 if (MinCost >= CostPerUseLimit) {
1131 << MinCost <<
", no cheaper registers to be found.\n");
1138 OrderLimit = RegClassInfo.getLastCostChange(RC);
1145 while (
unsigned PhysReg = Order.
next(OrderLimit)) {
1150 if (CostPerUseLimit == 1 && isUnusedCalleeSavedReg(PhysReg)) {
1152 dbgs() <<
printReg(PhysReg, TRI) <<
" would clobber CSR " 1153 <<
printReg(RegClassInfo.getLastCalleeSavedAlias(PhysReg),
TRI)
1158 if (!canEvictInterference(VirtReg, PhysReg,
false, BestCost,
1173 evictInterference(VirtReg, BestPhys, NewVRegs);
1193 for (
unsigned i = 0; i != UseBlocks.
size(); ++i) {
1201 !LIS->getInstructionFromIndex(BI.
LastInstr)->isImplicitDef())
1228 SA->getFirstSplitPoint(BC.
Number)))
1234 if (Intf.
last() >= SA->getLastSplitPoint(BC.
Number)) {
1261 const unsigned GroupSize = 8;
1263 unsigned TBS[GroupSize];
1264 unsigned B = 0,
T = 0;
1266 for (
unsigned i = 0; i != Blocks.
size(); ++i) {
1267 unsigned Number = Blocks[i];
1271 assert(
T < GroupSize &&
"Array overflow");
1273 if (++
T == GroupSize) {
1280 assert(B < GroupSize &&
"Array overflow");
1285 if (!MBB->
empty() &&
1287 SA->getFirstSplitPoint(Number)))
1296 if (Intf.
last() >= SA->getLastSplitPoint(Number))
1301 if (++B == GroupSize) {
1312 bool RAGreedy::growRegion(GlobalSplitCandidate &Cand) {
1314 BitVector Todo = SA->getThroughBlocks();
1316 unsigned AddedTo = 0;
1318 unsigned Visited = 0;
1324 for (
int i = 0,
e = NewBundles.
size(); i !=
e; ++i) {
1325 unsigned Bundle = NewBundles[i];
1330 unsigned Block = *
I;
1331 if (!Todo.
test(Block))
1342 if (ActiveBlocks.
size() == AddedTo)
1347 auto NewBlocks =
makeArrayRef(ActiveBlocks).slice(AddedTo);
1349 if (!addThroughConstraints(Cand.Intf, NewBlocks))
1355 AddedTo = ActiveBlocks.
size();
1371 bool RAGreedy::calcCompactRegion(GlobalSplitCandidate &Cand) {
1373 if (!SA->getNumThroughBlocks())
1377 Cand.reset(IntfCache, 0);
1383 SpillPlacer->
prepare(Cand.LiveBundles);
1387 if (!addSplitConstraints(Cand.Intf, Cost)) {
1392 if (!growRegion(Cand)) {
1399 if (!Cand.LiveBundles.any()) {
1405 for (
int i : Cand.LiveBundles.set_bits())
1406 dbgs() <<
" EB#" << i;
1417 for (
unsigned i = 0; i != UseBlocks.
size(); ++i) {
1483 bool RAGreedy::splitCanCauseEvictionChain(
unsigned Evictee,
1484 GlobalSplitCandidate &Cand,
1487 EvictionTrack::EvictorInfo VregEvictorInfo = LastEvicted.getEvictor(Evictee);
1488 unsigned Evictor = VregEvictorInfo.first;
1489 unsigned PhysReg = VregEvictorInfo.second;
1492 if (!Evictor || !PhysReg)
1495 float MaxWeight = 0;
1496 unsigned FutureEvictedPhysReg =
1497 getCheapestEvicteeWeight(Order, LIS->getInterval(Evictee),
1498 Cand.Intf.first(), Cand.Intf.last(), &MaxWeight);
1502 if ((PhysReg != Cand.PhysReg) && (PhysReg != FutureEvictedPhysReg))
1505 Cand.Intf.moveToBlock(BBNumber);
1512 if (!LIS->hasInterval(Evictor))
1521 VirtRegAuxInfo VRAI(*MF, *LIS, VRM, getAnalysis<MachineLoopInfo>(), *MBFI);
1522 float splitArtifactWeight =
1524 Cand.Intf.first().getPrevIndex(), Cand.Intf.last());
1525 if (splitArtifactWeight >= 0 && splitArtifactWeight < MaxWeight)
1543 bool RAGreedy::splitCanCauseLocalSpill(
unsigned VirtRegToSplit,
1544 GlobalSplitCandidate &Cand,
1547 Cand.Intf.moveToBlock(BBNumber);
1550 for (
auto PhysReg : Order.
getOrder()) {
1551 if (!
Matrix->checkInterference(Cand.Intf.first().getPrevIndex(),
1552 Cand.Intf.last(), PhysReg))
1557 float CheapestEvictWeight = 0;
1558 unsigned FutureEvictedPhysReg = getCheapestEvicteeWeight(
1559 Order, LIS->getInterval(VirtRegToSplit), Cand.Intf.first(),
1560 Cand.Intf.last(), &CheapestEvictWeight);
1563 if (FutureEvictedPhysReg) {
1564 VirtRegAuxInfo VRAI(*MF, *LIS, VRM, getAnalysis<MachineLoopInfo>(), *MBFI);
1565 float splitArtifactWeight =
1567 Cand.Intf.first().getPrevIndex(), Cand.Intf.last());
1570 if (splitArtifactWeight >= 0 && splitArtifactWeight > CheapestEvictWeight)
1583 BlockFrequency RAGreedy::calcGlobalSplitCost(GlobalSplitCandidate &Cand,
1585 bool *CanCauseEvictionChain) {
1587 const BitVector &LiveBundles = Cand.LiveBundles;
1588 unsigned VirtRegToSplit = SA->getParent().reg;
1590 for (
unsigned i = 0; i != UseBlocks.
size(); ++i) {
1597 Cand.Intf.moveToBlock(BC.
Number);
1601 if (EnableAdvancedRASplitCost && Cand.Intf.hasInterference() && BI.
LiveIn &&
1602 BI.
LiveOut && RegIn && RegOut) {
1604 if (CanCauseEvictionChain &&
1605 splitCanCauseEvictionChain(VirtRegToSplit, Cand, BC.
Number, Order)) {
1612 *CanCauseEvictionChain =
true;
1614 }
else if (splitCanCauseLocalSpill(VirtRegToSplit, Cand, BC.
Number,
1630 for (
unsigned i = 0,
e = Cand.ActiveBlocks.size(); i !=
e; ++i) {
1631 unsigned Number = Cand.ActiveBlocks[i];
1632 bool RegIn = LiveBundles[Bundles->
getBundle(Number,
false)];
1633 bool RegOut = LiveBundles[Bundles->
getBundle(Number,
true)];
1634 if (!RegIn && !RegOut)
1636 if (RegIn && RegOut) {
1638 Cand.Intf.moveToBlock(Number);
1639 if (Cand.Intf.hasInterference()) {
1645 if (EnableAdvancedRASplitCost && CanCauseEvictionChain &&
1646 splitCanCauseEvictionChain(VirtRegToSplit, Cand, Number, Order)) {
1654 *CanCauseEvictionChain =
true;
1681 const unsigned NumGlobalIntvs = LREdit.
size();
1684 assert(NumGlobalIntvs &&
"No global intervals configured");
1689 unsigned Reg = SA->getParent().reg;
1690 bool SingleInstrs = RegClassInfo.isProperSubClass(
MRI->getRegClass(Reg));
1694 for (
unsigned i = 0; i != UseBlocks.
size(); ++i) {
1697 unsigned IntvIn = 0, IntvOut = 0;
1700 unsigned CandIn = BundleCand[Bundles->
getBundle(Number,
false)];
1702 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1703 IntvIn = Cand.IntvIdx;
1704 Cand.Intf.moveToBlock(Number);
1705 IntfIn = Cand.Intf.first();
1709 unsigned CandOut = BundleCand[Bundles->
getBundle(Number,
true)];
1711 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1712 IntvOut = Cand.IntvIdx;
1713 Cand.Intf.moveToBlock(Number);
1714 IntfOut = Cand.Intf.last();
1719 if (!IntvIn && !IntvOut) {
1721 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
1722 SE->splitSingleBlock(BI);
1726 if (IntvIn && IntvOut)
1727 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1729 SE->splitRegInBlock(BI, IntvIn, IntfIn);
1731 SE->splitRegOutBlock(BI, IntvOut, IntfOut);
1737 BitVector Todo = SA->getThroughBlocks();
1738 for (
unsigned c = 0; c != UsedCands.
size(); ++c) {
1740 for (
unsigned i = 0,
e = Blocks.
size(); i !=
e; ++i) {
1741 unsigned Number = Blocks[i];
1742 if (!Todo.
test(Number))
1746 unsigned IntvIn = 0, IntvOut = 0;
1749 unsigned CandIn = BundleCand[Bundles->
getBundle(Number,
false)];
1751 GlobalSplitCandidate &Cand = GlobalCand[CandIn];
1752 IntvIn = Cand.IntvIdx;
1753 Cand.Intf.moveToBlock(Number);
1754 IntfIn = Cand.Intf.first();
1757 unsigned CandOut = BundleCand[Bundles->
getBundle(Number,
true)];
1759 GlobalSplitCandidate &Cand = GlobalCand[CandOut];
1760 IntvOut = Cand.IntvIdx;
1761 Cand.Intf.moveToBlock(Number);
1762 IntfOut = Cand.Intf.last();
1764 if (!IntvIn && !IntvOut)
1766 SE->splitLiveThroughBlock(Number, IntvIn, IntfIn, IntvOut, IntfOut);
1773 SE->finish(&IntvMap);
1776 ExtraRegInfo.
resize(
MRI->getNumVirtRegs());
1777 unsigned OrigBlocks = SA->getNumLiveBlocks();
1784 for (
unsigned i = 0,
e = LREdit.
size(); i !=
e; ++i) {
1788 if (getStage(Reg) != RS_New)
1793 if (IntvMap[i] == 0) {
1794 setStage(Reg, RS_Spill);
1800 if (IntvMap[i] < NumGlobalIntvs) {
1801 if (SA->countLiveBlocks(&Reg) >= OrigBlocks) {
1802 LLVM_DEBUG(
dbgs() <<
"Main interval covers the same " << OrigBlocks
1803 <<
" blocks as original.\n");
1805 setStage(Reg, RS_Split2);
1815 MF->
verify(
this,
"After splitting live range around region");
1821 unsigned RAGreedy::isSplitBenefitWorthCost(
LiveInterval &VirtReg) {
1831 if (!isSplitBenefitWorthCost(VirtReg))
1833 unsigned NumCands = 0;
1838 bool HasCompact = calcCompactRegion(GlobalCand.
front());
1846 BestCost = SpillCost;
1851 bool CanCauseEvictionChain =
false;
1853 calculateRegionSplitCost(VirtReg, Order, BestCost, NumCands,
1854 false , &CanCauseEvictionChain);
1860 if (HasCompact && (BestCost > SpillCost) && (BestCand !=
NoCand) &&
1861 CanCauseEvictionChain) {
1866 if (!HasCompact && BestCand ==
NoCand)
1869 return doRegionSplit(VirtReg, BestCand, HasCompact, NewVRegs);
1872 unsigned RAGreedy::calculateRegionSplitCost(
LiveInterval &VirtReg,
1875 unsigned &NumCands,
bool IgnoreCSR,
1876 bool *CanCauseEvictionChain) {
1877 unsigned BestCand =
NoCand;
1879 while (
unsigned PhysReg = Order.
next()) {
1880 if (IgnoreCSR && isUnusedCalleeSavedReg(PhysReg))
1886 unsigned WorstCount = ~0u;
1888 for (
unsigned i = 0; i != NumCands; ++i) {
1889 if (i == BestCand || !GlobalCand[i].PhysReg)
1891 unsigned Count = GlobalCand[i].LiveBundles.count();
1892 if (Count < WorstCount) {
1898 GlobalCand[Worst] = GlobalCand[NumCands];
1899 if (BestCand == NumCands)
1903 if (GlobalCand.
size() <= NumCands)
1904 GlobalCand.
resize(NumCands+1);
1905 GlobalSplitCandidate &Cand = GlobalCand[NumCands];
1906 Cand.reset(IntfCache, PhysReg);
1908 SpillPlacer->
prepare(Cand.LiveBundles);
1910 if (!addSplitConstraints(Cand.Intf, Cost)) {
1916 if (Cost >= BestCost) {
1919 dbgs() <<
" worse than no bundles\n";
1921 dbgs() <<
" worse than " 1922 <<
printReg(GlobalCand[BestCand].PhysReg, TRI) <<
'\n';
1926 if (!growRegion(Cand)) {
1934 if (!Cand.LiveBundles.any()) {
1939 bool HasEvictionChain =
false;
1940 Cost += calcGlobalSplitCost(Cand, Order, &HasEvictionChain);
1942 dbgs() <<
", total = ";
1944 for (
int i : Cand.LiveBundles.set_bits())
1945 dbgs() <<
" EB#" << i;
1948 if (Cost < BestCost) {
1949 BestCand = NumCands;
1953 if (CanCauseEvictionChain)
1954 *CanCauseEvictionChain = HasEvictionChain;
1959 if (CanCauseEvictionChain && BestCand !=
NoCand) {
1964 if (!(*CanCauseEvictionChain))
1972 unsigned RAGreedy::doRegionSplit(
LiveInterval &VirtReg,
unsigned BestCand,
1977 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM,
this, &DeadRemats);
1984 if (BestCand !=
NoCand) {
1985 GlobalSplitCandidate &Cand = GlobalCand[BestCand];
1986 if (
unsigned B = Cand.getBundles(BundleCand, BestCand)) {
1988 Cand.IntvIdx = SE->openIntv();
1990 << B <<
" bundles, intv " << Cand.IntvIdx <<
".\n");
1997 GlobalSplitCandidate &Cand = GlobalCand.
front();
1998 assert(!Cand.PhysReg &&
"Compact region has no physreg");
1999 if (
unsigned B = Cand.getBundles(BundleCand, 0)) {
2001 Cand.IntvIdx = SE->openIntv();
2003 <<
" bundles, intv " << Cand.IntvIdx <<
".\n");
2008 splitAroundRegion(LREdit, UsedCands);
2021 assert(&SA->getParent() == &VirtReg &&
"Live range wasn't analyzed");
2022 unsigned Reg = VirtReg.
reg;
2023 bool SingleInstrs = RegClassInfo.isProperSubClass(
MRI->getRegClass(Reg));
2024 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM,
this, &DeadRemats);
2027 for (
unsigned i = 0; i != UseBlocks.
size(); ++i) {
2029 if (SA->shouldSplitSingleBlock(BI, SingleInstrs))
2030 SE->splitSingleBlock(BI);
2038 SE->finish(&IntvMap);
2043 ExtraRegInfo.
resize(
MRI->getNumVirtRegs());
2047 for (
unsigned i = 0,
e = LREdit.
size(); i !=
e; ++i) {
2049 if (getStage(LI) == RS_New && IntvMap[i] == 0)
2050 setStage(LI, RS_Spill);
2054 MF->
verify(
this,
"After splitting live range around basic blocks");
2068 assert(SuperRC &&
"Invalid register class");
2090 if (!RegClassInfo.isProperSubClass(CurRC))
2095 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM,
this, &DeadRemats);
2099 if (Uses.
size() <= 1)
2103 <<
" individual instrs.\n");
2112 for (
unsigned i = 0; i != Uses.
size(); ++i) {
2114 if (
MI->isFullCopy() ||
2115 SuperRCNumAllocatableRegs ==
2122 SlotIndex SegStart = SE->enterIntvBefore(Uses[i]);
2123 SlotIndex SegStop = SE->leaveIntvAfter(Uses[i]);
2124 SE->useIntv(SegStart, SegStop);
2127 if (LREdit.
empty()) {
2133 SE->finish(&IntvMap);
2135 ExtraRegInfo.
resize(
MRI->getNumVirtRegs());
2138 setStage(LREdit.
begin(), LREdit.
end(), RS_Spill);
2151 void RAGreedy::calcGapWeights(
unsigned PhysReg,
2153 assert(SA->getUseBlocks().size() == 1 &&
"Not a local interval");
2156 const unsigned NumGaps = Uses.
size()-1;
2160 BI.LiveIn ? BI.FirstInstr.
getBaseIndex() : BI.FirstInstr;
2164 GapWeight.
assign(NumGaps, 0.0f);
2168 if (!
Matrix->query(const_cast<LiveInterval&>(SA->getParent()), *Units)
2169 .checkInterference())
2180 Matrix->getLiveUnions()[*Units] .find(StartIdx);
2181 for (
unsigned Gap = 0; IntI.
valid() && IntI.
start() < StopIdx; ++IntI) {
2183 while (Uses[Gap+1].getBoundaryIndex() < IntI.
start())
2184 if (++Gap == NumGaps)
2190 const float weight = IntI.
value()->weight;
2191 for (; Gap != NumGaps; ++Gap) {
2192 GapWeight[Gap] =
std::max(GapWeight[Gap], weight);
2193 if (Uses[Gap+1].getBaseIndex() >= IntI.
stop())
2203 const LiveRange &LR = LIS->getRegUnit(*Units);
2208 for (
unsigned Gap = 0; I != E && I->start < StopIdx; ++
I) {
2209 while (Uses[Gap+1].getBoundaryIndex() < I->start)
2210 if (++Gap == NumGaps)
2215 for (; Gap != NumGaps; ++Gap) {
2217 if (Uses[Gap+1].getBaseIndex() >= I->
end)
2233 if (SA->getUseBlocks().size() != 1)
2246 if (Uses.
size() <= 2)
2248 const unsigned NumGaps = Uses.
size()-1;
2251 dbgs() <<
"tryLocalSplit: ";
2252 for (
unsigned i = 0,
e = Uses.
size(); i !=
e; ++i)
2253 dbgs() <<
' ' << Uses[i];
2260 if (
Matrix->checkRegMaskInterference(VirtReg)) {
2267 unsigned re = RMS.
size();
2268 for (
unsigned i = 0; i != NumGaps && ri != re; ++i) {
2279 RegMaskGaps.push_back(i);
2306 bool ProgressRequired = getStage(VirtReg) >= RS_Split2;
2309 unsigned BestBefore = NumGaps;
2310 unsigned BestAfter = 0;
2313 const float blockFreq =
2319 while (
unsigned PhysReg = Order.
next()) {
2322 calcGapWeights(PhysReg, GapWeight);
2325 if (
Matrix->checkRegMaskInterference(VirtReg, PhysReg))
2326 for (
unsigned i = 0,
e = RegMaskGaps.size(); i !=
e; ++i)
2333 unsigned SplitBefore = 0, SplitAfter = 1;
2337 float MaxGap = GapWeight[0];
2341 const bool LiveBefore = SplitBefore != 0 || BI.
LiveIn;
2342 const bool LiveAfter = SplitAfter != NumGaps || BI.
LiveOut;
2345 <<
'-' << Uses[SplitAfter] <<
" i=" << MaxGap);
2348 if (!LiveBefore && !LiveAfter) {
2356 unsigned NewGaps = LiveBefore + SplitAfter - SplitBefore + LiveAfter;
2359 bool Legal = !ProgressRequired || NewGaps < NumGaps;
2368 blockFreq * (NewGaps + 1),
2369 Uses[SplitBefore].distance(Uses[SplitAfter]) +
2375 if (EstWeight * Hysteresis >= MaxGap) {
2377 float Diff = EstWeight - MaxGap;
2378 if (Diff > BestDiff) {
2380 BestDiff = Hysteresis * Diff;
2381 BestBefore = SplitBefore;
2382 BestAfter = SplitAfter;
2389 if (++SplitBefore < SplitAfter) {
2392 if (GapWeight[SplitBefore - 1] >= MaxGap) {
2393 MaxGap = GapWeight[SplitBefore];
2394 for (
unsigned i = SplitBefore + 1; i != SplitAfter; ++i)
2395 MaxGap =
std::max(MaxGap, GapWeight[i]);
2403 if (SplitAfter >= NumGaps) {
2409 MaxGap =
std::max(MaxGap, GapWeight[SplitAfter++]);
2414 if (BestBefore == NumGaps)
2417 LLVM_DEBUG(
dbgs() <<
"Best local split range: " << Uses[BestBefore] <<
'-' 2418 << Uses[BestAfter] <<
", " << BestDiff <<
", " 2419 << (BestAfter - BestBefore + 1) <<
" instrs\n");
2421 LiveRangeEdit LREdit(&VirtReg, NewVRegs, *MF, *LIS, VRM,
this, &DeadRemats);
2425 SlotIndex SegStart = SE->enterIntvBefore(Uses[BestBefore]);
2426 SlotIndex SegStop = SE->leaveIntvAfter(Uses[BestAfter]);
2427 SE->useIntv(SegStart, SegStop);
2429 SE->finish(&IntvMap);
2435 bool LiveBefore = BestBefore != 0 || BI.
LiveIn;
2436 bool LiveAfter = BestAfter != NumGaps || BI.
LiveOut;
2437 unsigned NewGaps = LiveBefore + BestAfter - BestBefore + LiveAfter;
2438 if (NewGaps >= NumGaps) {
2440 assert(!ProgressRequired &&
"Didn't make progress when it was required.");
2441 for (
unsigned i = 0,
e = IntvMap.
size(); i !=
e; ++i)
2442 if (IntvMap[i] == 1) {
2443 setStage(LIS->getInterval(LREdit.
get(i)), RS_Split2);
2462 const SmallVirtRegSet &FixedRegisters) {
2464 if (getStage(VirtReg) >= RS_Spill)
2468 if (LIS->intervalIsInOneMBB(VirtReg)) {
2471 SA->analyze(&VirtReg);
2472 unsigned PhysReg = tryLocalSplit(VirtReg, Order, NewVRegs);
2473 if (PhysReg || !NewVRegs.
empty())
2475 return tryInstructionSplit(VirtReg, Order, NewVRegs);
2481 SA->analyze(&VirtReg);
2487 if (SA->didRepairRange()) {
2489 Matrix->invalidateVirtRegs();
2490 if (
unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs, FixedRegisters))
2497 if (getStage(VirtReg) < RS_Split2) {
2498 unsigned PhysReg = tryRegionSplit(VirtReg, Order, NewVRegs);
2499 if (PhysReg || !NewVRegs.
empty())
2504 return tryBlockSplit(VirtReg, Order, NewVRegs);
2529 RAGreedy::mayRecolorAllInterferences(
unsigned PhysReg,
LiveInterval &VirtReg,
2530 SmallLISet &RecoloringCandidates,
2531 const SmallVirtRegSet &FixedRegisters) {
2541 CutOffInfo |= CO_Interf;
2550 if (((getStage(*Intf) == RS_Done &&
2551 MRI->getRegClass(Intf->
reg) == CurRC) &&
2553 FixedRegisters.count(Intf->
reg)) {
2555 dbgs() <<
"Early abort: the interference is not recolorable.\n");
2558 RecoloringCandidates.insert(Intf);
2603 unsigned RAGreedy::tryLastChanceRecoloring(
LiveInterval &VirtReg,
2606 SmallVirtRegSet &FixedRegisters,
2608 LLVM_DEBUG(
dbgs() <<
"Try last chance recoloring for " << VirtReg <<
'\n');
2611 "Last chance recoloring should really be last chance");
2617 LLVM_DEBUG(
dbgs() <<
"Abort because max depth has been reached.\n");
2618 CutOffInfo |= CO_Depth;
2623 SmallLISet RecoloringCandidates;
2629 assert(!FixedRegisters.count(VirtReg.
reg));
2630 FixedRegisters.insert(VirtReg.
reg);
2634 while (
unsigned PhysReg = Order.
next()) {
2636 <<
printReg(PhysReg, TRI) <<
'\n');
2637 RecoloringCandidates.clear();
2638 VirtRegToPhysReg.
clear();
2639 CurrentNewVRegs.
clear();
2642 if (
Matrix->checkInterference(VirtReg, PhysReg) >
2645 dbgs() <<
"Some interferences are not with virtual registers.\n");
2652 if (!mayRecolorAllInterferences(PhysReg, VirtReg, RecoloringCandidates,
2654 LLVM_DEBUG(
dbgs() <<
"Some interferences cannot be recolored.\n");
2661 PQueue RecoloringQueue;
2662 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2663 EndIt = RecoloringCandidates.end();
2664 It != EndIt; ++It) {
2665 unsigned ItVirtReg = (*It)->reg;
2666 enqueue(RecoloringQueue, *It);
2667 assert(VRM->hasPhys(ItVirtReg) &&
2668 "Interferences are supposed to be with allocated variables");
2671 VirtRegToPhysReg[ItVirtReg] = VRM->getPhys(ItVirtReg);
2679 Matrix->assign(VirtReg, PhysReg);
2684 SmallVirtRegSet SaveFixedRegisters(FixedRegisters);
2685 if (tryRecoloringCandidates(RecoloringQueue, CurrentNewVRegs,
2686 FixedRegisters, Depth)) {
2688 for (
unsigned NewVReg : CurrentNewVRegs)
2692 Matrix->unassign(VirtReg);
2697 <<
printReg(PhysReg, TRI) <<
'\n');
2700 FixedRegisters = SaveFixedRegisters;
2701 Matrix->unassign(VirtReg);
2708 End = CurrentNewVRegs.
end();
2709 Next != End; ++Next) {
2710 if (RecoloringCandidates.count(&LIS->getInterval(*Next)))
2715 for (SmallLISet::iterator It = RecoloringCandidates.begin(),
2716 EndIt = RecoloringCandidates.end();
2717 It != EndIt; ++It) {
2718 unsigned ItVirtReg = (*It)->reg;
2719 if (VRM->hasPhys(ItVirtReg))
2721 unsigned ItPhysReg = VirtRegToPhysReg[ItVirtReg];
2722 Matrix->assign(**It, ItPhysReg);
2738 bool RAGreedy::tryRecoloringCandidates(PQueue &RecoloringQueue,
2740 SmallVirtRegSet &FixedRegisters,
2742 while (!RecoloringQueue.empty()) {
2746 PhysReg = selectOrSplitImpl(*LI, NewVRegs, FixedRegisters, Depth + 1);
2751 if (PhysReg == ~0u || (!PhysReg && !LI->
empty()))
2755 assert(LI->
empty() &&
"Only empty live-range do not require a register");
2757 <<
" succeeded. Empty LI.\n");
2761 <<
" succeeded with: " <<
printReg(PhysReg, TRI) <<
'\n');
2763 Matrix->assign(*LI, PhysReg);
2764 FixedRegisters.insert(LI->
reg);
2773 unsigned RAGreedy::selectOrSplit(
LiveInterval &VirtReg,
2775 CutOffInfo = CO_None;
2777 SmallVirtRegSet FixedRegisters;
2778 unsigned Reg = selectOrSplitImpl(VirtReg, NewVRegs, FixedRegisters);
2779 if (Reg == ~0U && (CutOffInfo != CO_None)) {
2780 uint8_t CutOffEncountered = CutOffInfo & (CO_Depth | CO_Interf);
2781 if (CutOffEncountered == CO_Depth)
2782 Ctx.
emitError(
"register allocation failed: maximum depth for recoloring " 2783 "reached. Use -fexhaustive-register-search to skip " 2785 else if (CutOffEncountered == CO_Interf)
2786 Ctx.
emitError(
"register allocation failed: maximum interference for " 2787 "recoloring reached. Use -fexhaustive-register-search " 2789 else if (CutOffEncountered == (CO_Depth | CO_Interf))
2790 Ctx.
emitError(
"register allocation failed: maximum interference and " 2791 "depth for recoloring reached. Use " 2792 "-fexhaustive-register-search to skip cutoffs");
2803 unsigned RAGreedy::tryAssignCSRFirstTime(
LiveInterval &VirtReg,
2806 unsigned &CostPerUseLimit,
2808 if (getStage(VirtReg) == RS_Spill && VirtReg.
isSpillable()) {
2811 SA->analyze(&VirtReg);
2812 if (calcSpillCost() >= CSRCost)
2817 CostPerUseLimit = 1;
2820 if (getStage(VirtReg) < RS_Split) {
2823 SA->analyze(&VirtReg);
2824 unsigned NumCands = 0;
2826 unsigned BestCand = calculateRegionSplitCost(VirtReg, Order, BestCost,
2833 doRegionSplit(VirtReg, BestCand,
false, NewVRegs);
2839 void RAGreedy::aboutToRemoveInterval(
LiveInterval &LI) {
2841 SetOfBrokenHints.
remove(&LI);
2844 void RAGreedy::initializeCSRCost() {
2858 uint64_t FixedEntry = 1 << 14;
2859 if (ActualEntry < FixedEntry)
2861 else if (ActualEntry <= UINT32_MAX)
2866 CSRCost = CSRCost.
getFrequency() * (ActualEntry / FixedEntry);
2872 void RAGreedy::collectHintInfo(
unsigned Reg, HintsInfo &Out) {
2874 if (!Instr.isFullCopy())
2877 Register OtherReg = Instr.getOperand(0).getReg();
2878 if (OtherReg == Reg) {
2879 OtherReg = Instr.getOperand(1).getReg();
2880 if (OtherReg == Reg)
2886 : VRM->getPhys(OtherReg);
2888 Out.push_back(HintInfo(MBFI->
getBlockFreq(Instr.getParent()), OtherReg,
2899 for (
const HintInfo &
Info : List) {
2900 if (
Info.PhysReg != PhysReg)
2914 void RAGreedy::tryHintRecoloring(
LiveInterval &VirtReg) {
2921 unsigned Reg = VirtReg.
reg;
2922 Register PhysReg = VRM->getPhys(Reg);
2929 <<
'(' <<
printReg(PhysReg, TRI) <<
")\n");
2938 assert(VRM->hasPhys(Reg) &&
"We have unallocated variable!!");
2943 Register CurrPhys = VRM->getPhys(Reg);
2946 if (CurrPhys != PhysReg && (!
MRI->getRegClass(Reg)->contains(PhysReg) ||
2947 Matrix->checkInterference(LI, PhysReg)))
2951 <<
") is recolorable.\n");
2955 collectHintInfo(Reg, Info);
2958 if (CurrPhys != PhysReg) {
2960 BlockFrequency OldCopiesCost = getBrokenHintFreq(Info, CurrPhys);
2965 if (OldCopiesCost < NewCopiesCost) {
2975 Matrix->assign(LI, PhysReg);
2979 for (
const HintInfo &
HI : Info) {
2983 }
while (!RecoloringCandidates.
empty());
3022 void RAGreedy::tryHintsRecoloring() {
3025 "Recoloring is possible only for virtual registers");
3028 if (!VRM->hasPhys(LI->
reg))
3030 tryHintRecoloring(*LI);
3034 unsigned RAGreedy::selectOrSplitImpl(
LiveInterval &VirtReg,
3036 SmallVirtRegSet &FixedRegisters,
3038 unsigned CostPerUseLimit = ~0u;
3041 if (
unsigned PhysReg = tryAssign(VirtReg, Order, NewVRegs, FixedRegisters)) {
3043 LastEvicted.clearEvicteeInfo(VirtReg.
reg);
3047 if (CSRCost.
getFrequency() && isUnusedCalleeSavedReg(PhysReg) &&
3049 unsigned CSRReg = tryAssignCSRFirstTime(VirtReg, Order, PhysReg,
3050 CostPerUseLimit, NewVRegs);
3051 if (CSRReg || !NewVRegs.
empty())
3059 LiveRangeStage Stage = getStage(VirtReg);
3061 << ExtraRegInfo[VirtReg.
reg].Cascade <<
'\n');
3066 if (Stage != RS_Split)
3067 if (
unsigned PhysReg =
3068 tryEvict(VirtReg, Order, NewVRegs, CostPerUseLimit,
3070 unsigned Hint =
MRI->getSimpleHint(VirtReg.
reg);
3076 if (Hint && Hint != PhysReg)
3077 SetOfBrokenHints.
insert(&VirtReg);
3080 LastEvicted.clearEvicteeInfo(VirtReg.
reg);
3084 assert((NewVRegs.
empty() ||
Depth) &&
"Cannot append to existing NewVRegs");
3089 if (Stage < RS_Split) {
3090 setStage(VirtReg, RS_Split);
3096 if (Stage < RS_Spill) {
3098 unsigned NewVRegSizeBefore = NewVRegs.
size();
3099 unsigned PhysReg = trySplit(VirtReg, Order, NewVRegs, FixedRegisters);
3100 if (PhysReg || (NewVRegs.
size() - NewVRegSizeBefore)) {
3102 LastEvicted.clearEvicteeInfo(VirtReg.
reg);
3110 return tryLastChanceRecoloring(VirtReg, Order, NewVRegs, FixedRegisters,
3119 setStage(VirtReg, RS_Memory);
3125 LiveRangeEdit LRE(&VirtReg, NewVRegs, *MF, *LIS, VRM,
this, &DeadRemats);
3126 spiller().spill(LRE);
3127 setStage(NewVRegs.
begin(), NewVRegs.
end(), RS_Done);
3135 MF->
verify(
this,
"After spilling");
3143 void RAGreedy::reportNumberOfSplillsReloads(
MachineLoop *L,
unsigned &Reloads,
3144 unsigned &FoldedReloads,
3146 unsigned &FoldedSpills) {
3154 unsigned SubReloads;
3155 unsigned SubFoldedReloads;
3157 unsigned SubFoldedSpills;
3159 reportNumberOfSplillsReloads(SubLoop, SubReloads, SubFoldedReloads,
3160 SubSpills, SubFoldedSpills);
3161 Reloads += SubReloads;
3162 FoldedReloads += SubFoldedReloads;
3163 Spills += SubSpills;
3164 FoldedSpills += SubFoldedSpills;
3178 cast<FixedStackPseudoSourceValue>(A->getPseudoValue())
3195 if (Reloads || FoldedReloads || Spills || FoldedSpills) {
3196 using namespace ore;
3200 L->getStartLoc(), L->getHeader());
3202 R <<
NV(
"NumSpills", Spills) <<
" spills ";
3204 R <<
NV(
"NumFoldedSpills", FoldedSpills) <<
" folded spills ";
3206 R <<
NV(
"NumReloads", Reloads) <<
" reloads ";
3208 R <<
NV(
"NumFoldedReloads", FoldedReloads) <<
" folded reloads ";
3209 R <<
"generated in loop";
3216 LLVM_DEBUG(
dbgs() <<
"********** GREEDY REGISTER ALLOCATION **********\n" 3217 <<
"********** Function: " << mf.
getName() <<
'\n');
3220 TRI = MF->getSubtarget().getRegisterInfo();
3221 TII = MF->getSubtarget().getInstrInfo();
3225 MF->getSubtarget().enableRALocalReassignment(
3226 MF->getTarget().getOptLevel());
3228 EnableAdvancedRASplitCost =
3231 : MF->getSubtarget().enableAdvancedRASplitCost();
3234 MF->verify(
this,
"Before greedy register allocator");
3237 getAnalysis<LiveIntervals>(),
3238 getAnalysis<LiveRegMatrix>());
3239 Indexes = &getAnalysis<SlotIndexes>();
3240 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
3241 DomTree = &getAnalysis<MachineDominatorTree>();
3242 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
3244 Loops = &getAnalysis<MachineLoopInfo>();
3245 Bundles = &getAnalysis<EdgeBundles>();
3246 SpillPlacer = &getAnalysis<SpillPlacement>();
3247 DebugVars = &getAnalysis<LiveDebugVariables>();
3248 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3250 initializeCSRCost();
3257 SE.reset(
new SplitEditor(*SA, *AA, *LIS, *VRM, *DomTree, *MBFI));
3258 ExtraRegInfo.
clear();
3259 ExtraRegInfo.
resize(
MRI->getNumVirtRegs());
3261 IntfCache.
init(MF,
Matrix->getLiveUnions(), Indexes, LIS,
TRI);
3263 SetOfBrokenHints.
clear();
3264 LastEvicted.clear();
3267 tryHintsRecoloring();
3269 reportNumberOfSplillsReloads();
bool isHint() const
Return true if the last register returned from next() was a preferred register.
auto lower_bound(R &&Range, T &&Value) -> decltype(adl_begin(Range))
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
const T & front() const
front - Get the first element.
The default distance between instructions as returned by distance().
void setPhysReg(InterferenceCache &Cache, unsigned PhysReg)
setPhysReg - Point this cursor to PhysReg's interference.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Calculate auxiliary information for a virtual register such as its spill weight and allocation hint...
DiagnosticInfoOptimizationBase::Argument NV
unsigned getBundle(unsigned N, bool Out) const
getBundle - Return the ingoing (Out = false) or outgoing (Out = true) bundle number for basic block N...
SlotIndex getBaseIndex() const
Returns the base index for associated with this index.
void rewind()
Start over from the beginning.
This class represents lattice values for constants.
unsigned getNumRegs() const
Return the number of registers in this class.
MachineInstr & instr_front()
A register is impossible, variable must be spilled.
void push_back(const T &Elt)
static cl::opt< bool > ConsiderLocalIntervalCost("consider-local-interval-cost", cl::Hidden, cl::desc("Consider the cost of local intervals created by a split " "candidate when choosing the best split candidate."), cl::init(false))
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
LiveInterval - This class represents the liveness of a register, or stack slot.
SM_Speed - Overlap intervals to minimize the expected execution frequency of the inserted copies...
unsigned getCostPerUse(unsigned RegNo) const
Return the additional cost of using this register instead of other registers in its class...
bool test(unsigned Idx) const
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
SlotIndex FirstDef
First non-phi valno->def, or SlotIndex().
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
virtual bool reverseLocalAssignment() const
Allow the target to reverse allocation order of local live ranges.
unsigned next(unsigned Limit=0)
Return the next physical register in the allocation order, or 0.
bool isValid() const
Returns true if this is a valid index.
STATISTIC(NumFunctions, "Total number of functions")
ArrayRef< unsigned > regs() const
unsigned const TargetRegisterInfo * TRI
bool valid() const
valid - Return true if the current position is valid, false for end().
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.
char & RAGreedyID
Greedy register allocator.
Callback methods for LiveRangeEdit owners.
static cl::opt< bool > EnableDeferredSpilling("enable-deferred-spilling", cl::Hidden, cl::desc("Instead of spilling a variable right away, defer the actual " "code insertion to the end of the allocation. That way the " "allocator might still find a suitable coloring for this " "variable because of other evicted variables."), cl::init(false))
This class represents the liveness of a register, stack slot, etc.
ArrayRef< unsigned > getBlocks(unsigned Bundle) const
getBlocks - Return an array of blocks that are connected to Bundle.
static bool isEarlierInstr(SlotIndex A, SlotIndex B)
isEarlierInstr - Return true if A refers to an instruction earlier than B.
const char * getRegClassName(const TargetRegisterClass *Class) const
Returns the name of the register class.
SlotIndex getLastIndex()
Returns the base index of the last slot in this analysis.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
A description of a memory reference used in the backend.
void clear()
clear - Removes all bits from the bitvector. Does not change capacity.
Query interferences between a single live virtual register and a live interval union.
void addPrefSpill(ArrayRef< unsigned > Blocks, bool Strong)
addPrefSpill - Add PrefSpill constraints to all blocks listed.
static cl::opt< unsigned > HugeSizeForSplit("huge-size-for-split", cl::Hidden, cl::desc("A threshold of live range size which may cause " "high compile time cost in global splitting."), cl::init(5000))
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
static cl::opt< unsigned > LastChanceRecoloringMaxDepth("lcr-max-depth", cl::Hidden, cl::desc("Last chance recoloring max depth"), cl::init(5))
Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
bool scanActiveBundles()
scanActiveBundles - Perform an initial scan of all bundles activated by addConstraints and addLinks...
void init(MachineFunction *mf, LiveIntervalUnion *liuarray, SlotIndexes *indexes, LiveIntervals *lis, const TargetRegisterInfo *tri)
init - Prepare cache for a new function.
This class is basically a combination of TimeRegion and Timer.
ArrayRef< unsigned > getRecentPositive()
getRecentPositive - Return an array of bundles that became positive during the previous call to scanA...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted...
static cl::opt< bool > EnableLocalReassignment("enable-local-reassign", cl::Hidden, cl::desc("Local reassignment can yield better allocation decisions, but " "may be compile time intensive"), cl::init(false))
void iterate()
iterate - Update the network iteratively until convergence, or new bundles are found.
bool remove(const value_type &X)
Remove an item from the set vector.
RegAllocBase provides the register allocation driver and interface that can be extended to add intere...
BorderConstraint Exit
Constraint on block exit.
void assign(size_type NumElts, const T &Elt)
void emitError(unsigned LocCookie, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
const TargetRegisterClass * getRegClassConstraintEffectForVReg(Register Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI, bool ExploreBundle=false) const
Applies the constraints (def/use) implied by this MI on Reg to the given CurRC.
bool insert(const value_type &X)
Insert a new element into the SetVector.
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def...
const SmallVectorImpl< LiveInterval * > & interferingVRegs() const
SplitEditor - Edit machine code and LiveIntervals for live range splitting.
iterator_range< def_iterator > def_operands(unsigned Reg) const
INITIALIZE_PASS_BEGIN(RAGreedy, "greedy", "Greedy Register Allocator", false, false) INITIALIZE_PASS_END(RAGreedy
virtual unsigned isStoreToStackSlot(const MachineInstr &MI, int &FrameIndex) const
If the specified machine instruction is a direct store to a stack slot, return the virtual or physica...
const float huge_valf
Use this rather than HUGE_VALF; the latter causes warnings on MSVC.
virtual const TargetRegisterClass * getLargestLegalSuperClass(const TargetRegisterClass *RC, const MachineFunction &) const
Returns the largest super class of RC that is legal to use in the current sub-target and has the same...
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
virtual const TargetInstrInfo * getInstrInfo() const
BlockConstraint - Entry and exit constraints for a basic block.
bool inBounds(IndexT n) const
Analysis containing CSE Info
SlotIndex LastInstr
Last instr accessing current reg.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
float futureWeight(LiveInterval &li, SlotIndex start, SlotIndex end)
Compute future expected spill weight of a split artifact of li that will span between start and end s...
TargetInstrInfo - Interface to description of machine instruction set.
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)
void addLinks(ArrayRef< unsigned > Links)
addLinks - Add transparent blocks with the given numbers.
unsigned collectInterferingVRegs(unsigned MaxInterferingRegs=std::numeric_limits< unsigned >::max())
SlotIndex last()
last - Return the ending index of the last interfering range in the current block.
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction for the given index, or null if the given index has no instruction associated...
initializer< Ty > init(const Ty &Val)
SlotIndex endIndex() const
endNumber - return the maximum point of the range of the whole, exclusive.
const uint8_t AllocationPriority
Classes with a higher priority value are assigned first by register allocators using a greedy heurist...
MachineBasicBlock * getBlockNumbered(unsigned N) const
getBlockNumbered - MachineBasicBlocks are automatically numbered when they are inserted into the mach...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
unsigned const MachineRegisterInfo * MRI
Block doesn't care / variable not live.
BlockFrequency getBlockFrequency(unsigned Number) const
getBlockFrequency - Return the estimated block execution frequency per function invocation.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
This is an important class for using LLVM in a threaded context.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
Cursor - The primary query interface for the block interference cache.
size_t size() const
size - Get the array size.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
SM_Partition(Default) - Try to create the complement interval so it doesn't overlap any other interva...
ArrayRef< MCPhysReg > getOrder() const
Get the allocation order without reordered hints.
const KeyT & start() const
start - Return the beginning of the current interval.
SM_Size - Overlap intervals to minimize the number of inserted COPY instructions. ...
BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const
getblockFreq - Return block frequency.
raw_ostream & printBlockFreq(raw_ostream &OS, const BlockFrequency Freq) const
SlotIndex getMBBStartIdx(unsigned Num) const
Returns the first index in the given basic block number.
Represent the analysis usage information of a pass.
Greedy Register Allocator
static unsigned getNumAllocatableRegsForConstraints(const MachineInstr *MI, unsigned 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 ...
int getInstrDistance(SlotIndex other) const
Return the scaled distance from this index to the given one, where all slots on the same instruction ...
unsigned Number
Basic block number (from MBB::getNumber()).
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
SlotIndex getZeroIndex()
Returns the zero index for this analysis.
void resize(typename StorageT::size_type s)
FunctionPass class - This class is used to implement most global optimizations.
unsigned getNumAllocatableRegs(const TargetRegisterClass *RC) const
getNumAllocatableRegs - Returns the number of actually allocatable registers in RC in the current fun...
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))
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
void runOnMachineFunction(const MachineFunction &MF)
runOnFunction - Prepare to answer questions about MF.
void init(VirtRegMap &vrm, LiveIntervals &lis, LiveRegMatrix &mat)
virtual unsigned getCSRFirstUseCost() const
Allow the target to override the cost of using a callee-saved register for the first time...
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
BorderConstraint Entry
Constraint on block entry.
bool finish()
finish - Compute the optimal spill code placement given the constraints.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
Block entry/exit prefers a register.
void addConstraints(ArrayRef< BlockConstraint > LiveBlocks)
addConstraints - Add constraints and biases.
iterator find(SlotIndex Pos)
find - Return an iterator pointing to the first segment that ends after Pos, or end().
static bool hasTiedDef(MachineRegisterInfo *MRI, unsigned reg)
Return true if reg has any tied def operand.
virtual bool hasLoadFromStackSlot(const MachineInstr &MI, SmallVectorImpl< const MachineMemOperand *> &Accesses) const
If the specified machine instruction has a load from a stack slot, return true along with the FrameIn...
A SetVector that performs no allocations if smaller than a certain size.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Align max(MaybeAlign Lhs, Align Rhs)
void calculateSpillWeightsAndHints(LiveIntervals &LIS, MachineFunction &MF, VirtRegMap *VRM, const MachineLoopInfo &MLI, const MachineBlockFrequencyInfo &MBFI, VirtRegAuxInfo::NormalizingFn norm=normalizeSpillWeight)
Compute spill weights and allocation hints for all virtual register live intervals.
static bool isSameInstr(SlotIndex A, SlotIndex B)
isSameInstr - Return true if A and B refer to the same instruction.
void splitRegister(unsigned OldReg, ArrayRef< unsigned > NewRegs, LiveIntervals &LIS)
splitRegister - Move any user variables in OldReg to the live ranges in NewRegs where they are live...
Segments::const_iterator const_iterator
Block entry/exit prefers a stack slot.
SlotIndex FirstInstr
First instr accessing current reg.
MachineOperand class - Representation of each machine instruction operand.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Additional information about basic blocks where the current variable is live.
SplitAnalysis - Analyze a LiveInterval, looking for live range splitting opportunities.
LLVM_NODISCARD T pop_back_val()
void prepare(BitVector &RegBundles)
prepare - Reset state and prepare for a new spill placement computation.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
bool hasInterference()
hasInterference - Return true if the current block has any interference.
const Function & getFunction() const
Return the LLVM function that this machine code represents.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
unsigned getSize() const
getSize - Returns the sum of sizes of all the LiveRange's.
void clear()
Completely clear the SetVector.
const ValT & value() const
value - Return the mapped value at the current interval.
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
bool LiveOut
Current reg is live out.
static void clear(coro::Shape &Shape)
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
unsigned getNumBundles() const
getNumBundles - Return the total number of bundles in the CFG.
void moveToBlock(unsigned MBBNum)
moveTo - Move cursor to basic block MBBNum.
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
const KeyT & stop() const
stop - Return the end of the current interval.
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))
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
MachineFunctionProperties & set(Property P)
Spiller * createInlineSpiller(MachineFunctionPass &pass, MachineFunction &mf, VirtRegMap &vrm)
Create and return a spiller that will insert spill code directly instead of deferring though VirtRegM...
Representation of each machine instruction.
virtual bool hasStoreToStackSlot(const MachineInstr &MI, SmallVectorImpl< const MachineMemOperand *> &Accesses) const
If the specified machine instruction has a store to a stack slot, return true along with the FrameInd...
static uint64_t getMaxFrequency()
Returns the maximum possible frequency, the saturation value.
bool overlaps(const LiveRange &other) const
overlaps - Return true if the intersection of the two live ranges is not empty.
LLVM_NODISCARD bool empty() const
bool verify(Pass *p=nullptr, const char *Banner=nullptr, bool AbortOnError=true) const
Run the current MachineFunction through the machine code verifier, useful for debugger use...
virtual unsigned isLoadFromStackSlot(const MachineInstr &MI, int &FrameIndex) const
If the specified machine instruction is a direct load from a stack slot, return the virtual or physic...
FunctionPass * createGreedyRegisterAllocator()
Greedy register allocation pass - This pass implements a global register allocator for optimized buil...
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)
static RegisterRegAlloc greedyRegAlloc("greedy", "greedy register allocator", createGreedyRegisterAllocator)
uint64_t getEntryFreq() const
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static float normalizeSpillWeight(float UseDefFreq, unsigned Size, unsigned NumInstr)
Normalize the spill weight of a live interval.
bool operator<(int64_t V1, const APSInt &V2)
bool isSpillable() const
isSpillable - Can this interval be spilled?
SlotIndex beginIndex() const
beginIndex - Return the lowest numbered slot covered.
iterator_range< const_set_bits_iterator > set_bits() const
MachineLoop * getLoopFor(const MachineBasicBlock *BB) const
Return the innermost loop that BB lives in.
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
bool isTriviallyReMaterializable(const MachineInstr &MI, AAResults *AA=nullptr) const
Return true if the instruction is trivially rematerializable, meaning it has no side effects and requ...
StringRef - Represent a constant reference to a string, i.e.
iterator FindSegmentContaining(SlotIndex Idx)
Return an iterator to the segment that contains the specified index, or end() if there is none...
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
bool TimePassesIsEnabled
If the user specifies the -time-passes argument on an LLVM tool command line then the value of this b...
bool LiveIn
Current reg is live in.
unsigned getMaxCursors() const
getMaxCursors - Return the maximum number of concurrent cursors that can be supported.
SlotIndex - An opaque wrapper around machine indexes.
Virtual register interference.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
The operation is expected to be selectable directly by the target, and no transformation is necessary...
SlotIndex first()
first - Return the starting index of the first interfering range in the current block.
unsigned get(unsigned idx) const
SlotIndex getBoundaryIndex() const
Returns the boundary index for associated with this index.
bool isSpillSlotObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a spill slot.
Properties which a MachineFunction may have at a given point in time.
Wrapper class representing virtual and physical registers.
bool ChangesValue
True when this block changes the value of the live range.