14#ifndef LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
15#define LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
53#define DEBUG_TYPE "block-freq"
62class BranchProbabilityInfo;
65class MachineBasicBlock;
66class MachineBranchProbabilityInfo;
67class MachineCycleInfo;
98 return BlockMass(std::numeric_limits<uint64_t>::max());
103 bool isFull()
const {
return Mass == std::numeric_limits<uint64_t>::max(); }
113 Mass = Sum < Mass ? std::numeric_limits<uint64_t>::max() : Sum;
123 Mass = Diff > Mass ? 0 : Diff;
128 Mass =
P.scale(Mass);
206 return std::numeric_limits<uint32_t>::max() - 1;
244 template <
class It1,
class It2>
249 Nodes.insert(
Nodes.end(), FirstOther, LastOther);
297 while (L && L->isHeader(
Node))
317 return L ? L->getHeader() :
Node;
328 while (L->Parent && L->Parent->IsPackaged)
466 std::list<LoopData>::iterator Insert);
521 Scaled64 getFloatingBlockFreq(
const BlockNode &
Node)
const;
524 std::optional<uint64_t> getBlockProfileCount(
const Function &
F,
525 const BlockNode &
Node)
const;
526 std::optional<uint64_t> getProfileCountFromFreq(
const Function &
F,
528 bool isIrrLoopHeader(
const BlockNode &
Node);
538namespace bfi_detail {
562 assert(BB &&
"Unexpected nullptr");
563 auto MachineName =
"BB" +
Twine(BB->getNumber());
564 if (BB->getBasicBlock())
565 return (MachineName +
"[" + BB->getName() +
"]").str();
566 return MachineName.str();
570 assert(BB &&
"Unexpected nullptr");
622 template <
class BlockEdgesAdder>
624 BlockEdgesAdder addBlockEdges) :
BFI(
BFI) {
628 template <
class BlockEdgesAdder>
629 void initialize(
const BFIBase::LoopData *OuterLoop,
630 BlockEdgesAdder addBlockEdges);
640 template <
class BlockEdgesAdder>
642 BlockEdgesAdder addBlockEdges);
644 const BFIBase::LoopData *OuterLoop);
647template <
class BlockEdgesAdder>
649 BlockEdgesAdder addBlockEdges) {
652 for (
auto N : OuterLoop->
Nodes)
656 for (
uint32_t Index = 0; Index <
BFI.Working.size(); ++Index)
657 addEdges(Index, OuterLoop, addBlockEdges);
662template <
class BlockEdgesAdder>
665 BlockEdgesAdder addBlockEdges) {
670 const auto &Working =
BFI.Working[
Node.Index];
672 if (Working.isAPackage())
673 for (
const auto &
I : Working.Loop->Exits)
676 addBlockEdges(*
this, Irr, OuterLoop);
837 using BranchProbabilityInfoT =
843 const BranchProbabilityInfoT *BPI =
nullptr;
844 const CycleInfoT *CI =
nullptr;
845 const FunctionT *F =
nullptr;
848 std::vector<const BlockT *> RPOT;
851 unsigned BlockNumberEpoch;
853 BlockNode getNode(
const BlockT *BB)
const {
854 assert(BlockNumberEpoch ==
857 return BlockNumber < Nodes.size() ? Nodes[BlockNumber] :
BlockNode();
862 return RPOT[
Node.Index];
868 void initializeRPOT();
877 void initializeLoops();
905 bool tryToComputeMassInFunction();
919 void computeIrreducibleMass(
LoopData *OuterLoop,
920 std::list<LoopData>::iterator Insert);
931 void computeMassInLoops();
939 void computeMassInFunction();
941 std::string getBlockName(
const BlockNode &
Node)
const override {
955 bool needIterativeInference()
const;
958 void applyIterativeInference();
960 using ProbMatrixType = std::vector<std::vector<std::pair<size_t, Scaled64>>>;
963 void iterativeInference(
const ProbMatrixType &ProbMatrix,
964 std::vector<Scaled64> &Freq)
const;
968 void findReachableBlocks(std::vector<const BlockT *> &Blocks)
const;
972 void initTransitionProbabilities(
973 const std::vector<const BlockT *> &Blocks,
975 ProbMatrixType &ProbMatrix)
const;
980 Scaled64 discrepancy(
const ProbMatrixType &ProbMatrix,
981 const std::vector<Scaled64> &Freq)
const;
989 void calculate(
const FunctionT &F,
const BranchProbabilityInfoT &BPI,
990 const CycleInfoT &CI);
999 const BlockT *BB)
const {
1018 const BranchProbabilityInfoT &
getBPI()
const {
return *BPI; }
1040 const BranchProbabilityInfoT &BPI,
1041 const CycleInfoT &CI) {
1054 <<
"\n================="
1055 << std::string(F.getName().size(),
'=') <<
"\n");
1061 computeMassInLoops();
1062 computeMassInFunction();
1066 if (needIterativeInference())
1067 applyIterativeInference();
1074 for (
const BlockT &BB : F)
1087 if (Nodes.size() <= BlockNumber)
1090 if (!
Node.isValid()) {
1095 Freqs.emplace_back();
1100template <
class BT>
void BlockFrequencyInfoImpl<BT>::initializeRPOT() {
1101 const BlockT *Entry = &
F->front();
1102 RPOT.reserve(
F->size());
1104 RPOT.emplace_back(BB);
1105 std::reverse(RPOT.begin(), RPOT.end());
1107 assert(RPOT.size() - 1 <= BlockNode::getMaxIndex() &&
1108 "More nodes in function than Block Frequency Info supports");
1114 BlockNode
Node = BlockNode(Idx);
1119 Working.reserve(RPOT.size());
1120 for (
size_t Index = 0; Index < RPOT.size(); ++Index)
1121 Working.emplace_back(Index);
1122 Freqs.resize(RPOT.size());
1125template <
class BT>
void BlockFrequencyInfoImpl<BT>::initializeLoops() {
1136 if (!CI->isReducible(
C))
1138 for (
CycleRef A = CI->getParentCycle(
C);
A;
A = CI->getParentCycle(
A))
1139 if (!CI->isReducible(
A) && CI->isEntry(
A, CI->getHeader(
C)))
1145 std::deque<std::pair<CycleRef, LoopData *>> Q;
1146 for (
CycleRef C : CI->toplevel_cycles())
1147 Q.emplace_back(
C,
nullptr);
1150 while (!Q.empty()) {
1152 LoopData *Parent = Q.front().second;
1155 if (hasLoop(Cycle)) {
1156 BlockNode Header =
getNode(CI->getHeader(Cycle));
1157 Loops.emplace_back(Parent, Header);
1159 Working[Header.Index].Loop = &
Loops.back();
1161 Parent = &
Loops.back();
1165 Q.emplace_back(
C, Parent);
1170 for (
size_t Index = 0;
Index < RPOT.size(); ++
Index) {
1172 if (Working[Index].isLoopHeader()) {
1173 LoopData *ContainingLoop = Working[
Index].getContainingLoop();
1175 ContainingLoop->Nodes.push_back(Index);
1179 CycleRef Cycle = CI->getCycle(RPOT[Index]);
1180 while (Cycle && !hasLoop(Cycle))
1181 Cycle = CI->getParentCycle(Cycle);
1186 BlockNode Header =
getNode(CI->getHeader(Cycle));
1187 assert(Header.isValid());
1188 const auto &HeaderData = Working[Header.Index];
1189 assert(HeaderData.isLoopHeader());
1191 Working[
Index].Loop = HeaderData.Loop;
1192 HeaderData.Loop->Nodes.push_back(Index);
1198template <
class BT>
void BlockFrequencyInfoImpl<BT>::computeMassInLoops() {
1203 for (
auto L =
Loops.end(),
B =
Loops.begin(); L !=
B;) {
1205 if (computeMassInLoop(*L))
1207 computeIrreducibleMass(&*L, std::next(L));
1208 if (!computeMassInLoop(*L))
1214bool BlockFrequencyInfoImpl<BT>::computeMassInLoop(LoopData &
Loop) {
1218 if (
Loop.isIrreducible()) {
1221 unsigned NumHeadersWithWeight = 0;
1222 std::optional<uint64_t> MinHeaderWeight;
1225 for (uint32_t
H = 0;
H <
Loop.NumHeaders; ++
H) {
1226 auto &HeaderNode =
Loop.Nodes[
H];
1227 const BlockT *
Block = getBlock(HeaderNode);
1228 IsIrrLoopHeader.set(
Loop.Nodes[
H].Index);
1229 std::optional<uint64_t> HeaderWeight =
Block->getIrrLoopHeaderWeight();
1230 if (!HeaderWeight) {
1233 HeadersWithoutWeight.insert(
H);
1237 <<
" has irr loop header weight " << *HeaderWeight
1239 NumHeadersWithWeight++;
1240 uint64_t HeaderWeightValue = *HeaderWeight;
1241 if (!MinHeaderWeight || HeaderWeightValue < MinHeaderWeight)
1242 MinHeaderWeight = HeaderWeightValue;
1243 if (HeaderWeightValue) {
1244 Dist.addLocal(HeaderNode, HeaderWeightValue);
1253 if (!MinHeaderWeight)
1254 MinHeaderWeight = 1;
1255 for (uint32_t
H : HeadersWithoutWeight) {
1256 auto &HeaderNode =
Loop.Nodes[
H];
1257 assert(!getBlock(HeaderNode)->getIrrLoopHeaderWeight() &&
1258 "Shouldn't have a weight metadata");
1259 uint64_t MinWeight = *MinHeaderWeight;
1263 Dist.addLocal(HeaderNode, MinWeight);
1265 distributeIrrLoopHeaderMass(Dist);
1266 for (
const BlockNode &M :
Loop.Nodes)
1267 if (!propagateMassToSuccessors(&
Loop, M))
1269 if (NumHeadersWithWeight == 0)
1271 adjustLoopHeaderMass(
Loop);
1273 Working[
Loop.
getHeader().Index].getMass() = BlockMass::getFull();
1276 for (
const BlockNode &M :
Loop.members())
1277 if (!propagateMassToSuccessors(&
Loop, M))
1282 computeLoopScale(
Loop);
1288bool BlockFrequencyInfoImpl<BT>::tryToComputeMassInFunction() {
1291 assert(!Working.empty() &&
"no blocks in function");
1292 assert(!Working[0].isLoopHeader() &&
"entry block is a loop header");
1294 Working[0].getMass() = BlockMass::getFull();
1295 for (
size_t i = 0, n = RPOT.size(); i != n; ++i) {
1297 if (Working[i].isPackaged())
1300 if (!propagateMassToSuccessors(
nullptr, BlockNode(i)))
1306template <
class BT>
void BlockFrequencyInfoImpl<BT>::computeMassInFunction() {
1307 if (tryToComputeMassInFunction())
1309 computeIrreducibleMass(
nullptr,
Loops.begin());
1310 if (tryToComputeMassInFunction())
1316bool BlockFrequencyInfoImpl<BT>::needIterativeInference()
const {
1319 if (!
F->getFunction().hasProfileData())
1323 for (
auto L =
Loops.rbegin(),
E =
Loops.rend(); L !=
E; ++L) {
1324 if (
L->isIrreducible())
1330template <
class BT>
void BlockFrequencyInfoImpl<BT>::applyIterativeInference() {
1335 std::vector<const BlockT *> ReachableBlocks;
1336 findReachableBlocks(ReachableBlocks);
1337 if (ReachableBlocks.empty())
1344 auto Freq = std::vector<Scaled64>(ReachableBlocks.size());
1346 for (
size_t I = 0;
I < ReachableBlocks.size();
I++) {
1347 const BlockT *BB = ReachableBlocks[
I];
1349 Freq[
I] = getFloatingBlockFreq(BB);
1352 assert(!SumFreq.isZero() &&
"empty initial block frequencies");
1354 LLVM_DEBUG(
dbgs() <<
"Applying iterative inference for " <<
F->getName()
1355 <<
" with " << ReachableBlocks.size() <<
" blocks\n");
1358 for (
auto &
Value : Freq) {
1364 ProbMatrixType ProbMatrix;
1365 initTransitionProbabilities(ReachableBlocks, BlockIndex, ProbMatrix);
1368 iterativeInference(ProbMatrix, Freq);
1371 for (
const BlockT &BB : *
F) {
1373 if (!
Node.isValid())
1375 if (
auto It = BlockIndex.find(&BB); It != BlockIndex.end())
1376 Freqs[
Node.Index].Scaled = Freq[It->second];
1378 Freqs[
Node.Index].Scaled = Scaled64::getZero();
1383void BlockFrequencyInfoImpl<BT>::iterativeInference(
1384 const ProbMatrixType &ProbMatrix, std::vector<Scaled64> &Freq)
const {
1386 "incorrectly specified precision");
1388 const auto Precision =
1394 << discrepancy(ProbMatrix, Freq).
toString() <<
"\n");
1398 auto Successors = std::vector<std::vector<size_t>>(Freq.size());
1399 for (
size_t I = 0;
I < Freq.size();
I++) {
1400 for (
const auto &Jump : ProbMatrix[
I]) {
1401 Successors[Jump.first].push_back(
I);
1409 auto IsActive =
BitVector(Freq.size(),
false);
1410 std::queue<size_t> ActiveSet;
1411 for (
size_t I = 0;
I < Freq.size();
I++) {
1420 while (It++ < MaxIterations && !ActiveSet.empty()) {
1421 size_t I = ActiveSet.front();
1423 IsActive[
I] =
false;
1429 Scaled64 OneMinusSelfProb = Scaled64::getOne();
1430 for (
const auto &Jump : ProbMatrix[
I]) {
1431 if (Jump.first ==
I) {
1432 OneMinusSelfProb -= Jump.second;
1434 NewFreq += Freq[Jump.first] * Jump.second;
1437 if (OneMinusSelfProb != Scaled64::getOne())
1438 NewFreq /= OneMinusSelfProb;
1442 auto Change = Freq[
I] >= NewFreq ? Freq[
I] - NewFreq : NewFreq - Freq[
I];
1443 if (Change > Precision) {
1446 for (
size_t Succ : Successors[
I]) {
1447 if (!IsActive[Succ]) {
1448 ActiveSet.push(Succ);
1449 IsActive[Succ] =
true;
1458 LLVM_DEBUG(
dbgs() <<
" Completed " << It <<
" inference iterations"
1459 <<
format(
" (%0.0f per block)",
double(It) / Freq.size())
1463 << discrepancy(ProbMatrix, Freq).
toString() <<
"\n");
1468void BlockFrequencyInfoImpl<BT>::findReachableBlocks(
1469 std::vector<const BlockT *> &Blocks)
const {
1472 std::queue<const BlockT *>
Queue;
1474 const BlockT *
Entry = &
F->front();
1476 Reachable.insert(Entry);
1477 while (!
Queue.empty()) {
1478 const BlockT *SrcBB =
Queue.front();
1481 auto EP = BPI->getEdgeProbability(SrcBB, It.index());
1484 if (Reachable.insert(It.value()).second)
1485 Queue.push(It.value());
1492 for (
const BlockT &BB : *
F) {
1495 if (!HasSucc && Reachable.count(&BB)) {
1497 InverseReachable.insert(&BB);
1500 while (!
Queue.empty()) {
1501 const BlockT *SrcBB =
Queue.front();
1504 auto EP = BPI->getEdgeProbability(DstBB, SrcBB);
1507 if (InverseReachable.insert(DstBB).second)
1513 Blocks.reserve(
F->size());
1514 for (
const BlockT &BB : *
F) {
1515 if (Reachable.count(&BB) && InverseReachable.count(&BB)) {
1516 Blocks.push_back(&BB);
1522void BlockFrequencyInfoImpl<BT>::initTransitionProbabilities(
1523 const std::vector<const BlockT *> &Blocks,
1525 ProbMatrixType &ProbMatrix)
const {
1526 const size_t NumBlocks = Blocks.size();
1527 auto Succs = std::vector<std::vector<std::pair<size_t, Scaled64>>>(NumBlocks);
1528 auto SumProb = std::vector<Scaled64>(NumBlocks);
1531 for (
size_t Src = 0; Src < NumBlocks; Src++) {
1532 const BlockT *BB = Blocks[Src];
1535 const BlockT *
SI = It.value();
1537 auto BlockIndexIt = BlockIndex.find(
SI);
1538 if (BlockIndexIt == BlockIndex.end())
1541 if (!UniqueSuccs.insert(
SI).second)
1544 auto EP = BPI->getEdgeProbability(BB, It.index());
1549 Scaled64::getFraction(EP.getNumerator(), EP.getDenominator());
1550 size_t Dst = BlockIndexIt->second;
1551 Succs[Src].push_back(std::make_pair(Dst, EdgeProb));
1552 SumProb[Src] += EdgeProb;
1557 ProbMatrix = ProbMatrixType(NumBlocks);
1558 for (
size_t Src = 0; Src < NumBlocks; Src++) {
1560 if (Succs[Src].
empty())
1563 assert(!SumProb[Src].
isZero() &&
"Zero sum probability of non-exit block");
1564 for (
auto &Jump : Succs[Src]) {
1565 size_t Dst = Jump.first;
1566 Scaled64 Prob = Jump.second;
1567 ProbMatrix[Dst].push_back(std::make_pair(Src, Prob / SumProb[Src]));
1572 size_t EntryIdx = BlockIndex.find(&
F->front())->second;
1573 for (
size_t Src = 0; Src < NumBlocks; Src++) {
1574 if (Succs[Src].
empty()) {
1575 ProbMatrix[EntryIdx].push_back(std::make_pair(Src, Scaled64::getOne()));
1583 const ProbMatrixType &ProbMatrix,
const std::vector<Scaled64> &Freq)
const {
1584 assert(Freq[0] > 0 &&
"Incorrectly computed frequency of the entry block");
1585 Scaled64 Discrepancy;
1586 for (
size_t I = 0;
I < ProbMatrix.size();
I++) {
1588 for (
const auto &Jump : ProbMatrix[
I]) {
1589 Sum += Freq[Jump.first] * Jump.second;
1591 Discrepancy += Freq[
I] >= Sum ? Freq[
I] - Sum : Sum - Freq[
I];
1594 return Discrepancy / Freq[0];
1599void BlockFrequencyInfoImpl<BT>::computeIrreducibleMass(
1600 LoopData *OuterLoop, std::list<LoopData>::iterator Insert) {
1602 if (OuterLoop)
dbgs()
1603 <<
"loop: " << getLoopName(*OuterLoop) <<
"\n";
1604 else dbgs() <<
"function\n");
1608 auto addBlockEdges = [&](IrreducibleGraph &
G, IrreducibleGraph::IrrNode &Irr,
1609 const LoopData *OuterLoop) {
1610 const BlockT *BB = RPOT[Irr.Node.Index];
1612 G.addEdge(Irr,
getNode(Succ), OuterLoop);
1614 IrreducibleGraph
G(*
this, OuterLoop, addBlockEdges);
1616 for (
auto &L : analyzeIrreducible(
G, OuterLoop, Insert))
1617 computeMassInLoop(L);
1621 updateLoopWithIrreducible(*OuterLoop);
1631BlockFrequencyInfoImpl<BT>::propagateMassToSuccessors(LoopData *OuterLoop,
1632 const BlockNode &
Node) {
1636 if (
auto *Loop = Working[
Node.Index].getPackagedLoop()) {
1637 assert(Loop != OuterLoop &&
"Cannot propagate mass in a packaged loop");
1638 if (!addLoopSuccessorsToDist(OuterLoop, *Loop, Dist))
1642 const BlockT *BB = getBlock(Node);
1645 Dist, OuterLoop, Node,
getNode(It.value()),
1653 distributeMass(Node, OuterLoop, Dist);
1661 OS <<
"block-frequency-info: " << F->getName() <<
"\n";
1662 for (
const BlockT &BB : *F) {
1666 if (std::optional<uint64_t> ProfileCount =
1668 F->getFunction(), getNode(&BB)))
1669 OS <<
", count = " << *ProfileCount;
1670 if (std::optional<uint64_t> IrrLoopHeaderWeight =
1671 BB.getIrrLoopHeaderWeight())
1672 OS <<
", irr_loop_header_weight = " << *IrrLoopHeaderWeight;
1689 for (
const auto &BB : *F)
1692 size_t MinSize = std::min(Nodes.size(),
Other.Nodes.size());
1693 for (
size_t i = 0; i < MinSize; ++i) {
1699 <<
" existence mismatch.\n";
1700 }
else if (Nodes[i].
isValid()) {
1701 const auto &Freq =
Freqs[Nodes[i].Index];
1702 const auto &OtherFreq =
Other.Freqs[
Other.Nodes[i].Index];
1703 if (Freq.Integer != OtherFreq.Integer) {
1706 <<
" " << Freq.Integer <<
" vs " << OtherFreq.Integer <<
"\n";
1711 for (
size_t i = MinSize; i < Nodes.size(); ++i) {
1715 <<
" existence mismatch.\n";
1718 for (
size_t i = MinSize; i <
Other.Nodes.size(); ++i) {
1719 if (
Other.Nodes[i].isValid()) {
1722 <<
" existence mismatch.\n";
1729 dbgs() <<
"Other\n";
1732 assert(Match &&
"BFI mismatch");
1740template <
class BlockFrequencyInfoT,
class BranchProbabilityInfoT>
1753 return G->getFunction()->getName();
1757 unsigned HotPercentThreshold = 0) {
1759 if (!HotPercentThreshold)
1769 std::max(
MaxFrequency, Graph->getBlockFreq(
N).getFrequency());
1785 GVDAGType GType,
int layout_order = -1) {
1789 if (layout_order != -1)
1790 OS <<
Node->getName() <<
"[" << layout_order <<
"] : ";
1792 OS <<
Node->getName() <<
" : ";
1798 OS << Graph->getBlockFreq(
Node).getFrequency();
1801 auto Count = Graph->getBlockProfileCount(
Node);
1810 "never reach this point.");
1816 const BlockFrequencyInfoT *BFI,
1817 const BranchProbabilityInfoT *BPI,
1818 unsigned HotPercentThreshold = 0) {
1831 if (HotPercentThreshold) {
1836 if (EFreq >= HotFreq)
1837 OS <<
",color=\"red\"";
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
This file implements the BitVector class.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
Find all cycles in a control-flow graph, including irreducible loops.
This file defines the little GraphTraits<X> template class that should be specialized by classes that...
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Branch Probability Basic Block static false std::string getBlockName(const MachineBasicBlock *BB)
Helper to print the name of a MBB.
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the SparseBitVector class.
LLVM Basic Block Representation.
Base class for BlockFrequencyInfoImpl.
std::vector< WorkingData > Working
Loop data: see initializeLoops().
std::optional< uint64_t > getProfileCountFromFreq(const Function &F, BlockFrequency Freq) const
virtual ~BlockFrequencyInfoImplBase()=default
Virtual destructor.
std::list< LoopData > Loops
Indexed information about loops.
bool addLoopSuccessorsToDist(const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist)
Add all edges out of a packaged loop to the distribution.
std::optional< uint64_t > getBlockProfileCount(const Function &F, const BlockNode &Node) const
ScaledNumber< uint64_t > Scaled64
std::string getLoopName(const LoopData &Loop) const
bool isIrrLoopHeader(const BlockNode &Node)
void computeLoopScale(LoopData &Loop)
Compute the loop scale for a loop.
bfi_detail::BlockMass BlockMass
void packageLoop(LoopData &Loop)
Package up a loop.
virtual raw_ostream & print(raw_ostream &OS) const
void finalizeMetrics()
Finalize frequency metrics.
void setBlockFreq(const BlockNode &Node, BlockFrequency Freq)
BlockFrequency getEntryFreq() const
void updateLoopWithIrreducible(LoopData &OuterLoop)
Update a loop after packaging irreducible SCCs inside of it.
void clear()
Clear all memory.
BlockFrequency getBlockFreq(const BlockNode &Node) const
void distributeIrrLoopHeaderMass(Distribution &Dist)
iterator_range< std::list< LoopData >::iterator > analyzeIrreducible(const bfi_detail::IrreducibleGraph &G, LoopData *OuterLoop, std::list< LoopData >::iterator Insert)
Analyze irreducible SCCs.
bool addToDist(Distribution &Dist, const LoopData *OuterLoop, const BlockNode &Pred, const BlockNode &Succ, uint64_t Weight)
Add an edge to the distribution.
void unwrapLoops()
Unwrap loops.
Scaled64 getFloatingBlockFreq(const BlockNode &Node) const
void distributeMass(const BlockNode &Source, LoopData *OuterLoop, Distribution &Dist)
Distribute mass according to a distribution.
SparseBitVector IsIrrLoopHeader
Whether each block is an irreducible loop header.
std::vector< FrequencyData > Freqs
Data about each block. This is used downstream.
void adjustLoopHeaderMass(LoopData &Loop)
Adjust the mass of all headers in an irreducible loop.
bool isIrrLoopHeader(const BlockT *BB)
std::optional< uint64_t > getProfileCountFromFreq(const Function &F, BlockFrequency Freq) const
const BranchProbabilityInfoT & getBPI() const
const FunctionT * getFunction() const
void verifyMatch(BlockFrequencyInfoImpl< BT > &Other) const
std::optional< uint64_t > getBlockProfileCount(const Function &F, const BlockT *BB) const
Scaled64 getFloatingBlockFreq(const BlockT *BB) const
void setBlockFreq(const BlockT *BB, BlockFrequency Freq)
void calculate(const FunctionT &F, const BranchProbabilityInfoT &BPI, const CycleInfoT &CI)
BlockFrequencyInfoImpl()=default
raw_ostream & print(raw_ostream &OS) const override
Print the frequencies for the current function.
BlockFrequency getBlockFreq(const BlockT *BB) const
Analysis providing branch probability information.
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
static uint32_t getDenominator()
uint32_t getNumerator() const
Opaque handle to a cycle within a GenericCycleInfo that wraps the cycle's preorder index.
Implements a dense probed hash-table based set.
BlockT * getHeader() const
Represents a single loop in the control flow graph.
Simple representation of a scaled number.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
typename SuperClass::const_iterator const_iterator
ptrdiff_t difference_type
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
std::string str() const
Get the contents as an std::string.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM Value Representation.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
bool operator<(BlockMass X) const
bool operator>(BlockMass X) const
LLVM_ABI raw_ostream & print(raw_ostream &OS) const
bool operator==(BlockMass X) const
static BlockMass getEmpty()
LLVM_ABI void dump() const
BlockMass & operator-=(BlockMass X)
Subtract another mass.
bool operator<=(BlockMass X) const
BlockMass & operator*=(BranchProbability P)
static BlockMass getFull()
bool operator!=(BlockMass X) const
BlockMass & operator+=(BlockMass X)
Add another mass.
bool operator>=(BlockMass X) const
LLVM_ABI ScaledNumber< uint64_t > toScaled() const
Convert to scaled number.
void reserve(size_t Size)
Grow the DenseSet so that it can contain at least NumEntries items before resizing again.
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
A raw_ostream that writes to an std::string.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
std::string getBlockName(const BlockT *BB)
Get the name of a MachineBasicBlock.
BlockMass operator*(BlockMass L, BranchProbability R)
BlockMass operator+(BlockMass L, BlockMass R)
raw_ostream & operator<<(raw_ostream &OS, BlockMass X)
BlockMass operator-(BlockMass L, BlockMass R)
NodeAddr< NodeBase * > Node
This is an optimization pass for GlobalISel generic memory operations.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
uint32_t getWeightFromBranchProb(const BranchProbability Prob)
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI llvm::cl::opt< unsigned > IterativeBFIMaxIterationsPerBlock
LLVM_ABI llvm::cl::opt< bool > UseIterativeBFIInference
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
auto post_order(const T &G)
Post-order traversal of a graph.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
LLVM_ABI llvm::cl::opt< bool > CheckBFIUnknownBlockQueries
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
constexpr NextUseDistance max(NextUseDistance A, NextUseDistance B)
iterator_range< typename GraphTraits< Inverse< GraphType > >::ChildIteratorType > inverse_children(const typename GraphTraits< GraphType >::NodeRef &G)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
iterator_range< typename GraphTraits< GraphType >::ChildIteratorType > children(const typename GraphTraits< GraphType >::NodeRef &G)
LLVM_ABI Printable printBlockFreq(const BlockFrequencyInfo &BFI, BlockFrequency Freq)
Print the block frequency Freq relative to the current functions entry frequency.
LLVM_ABI llvm::cl::opt< double > IterativeBFIPrecision
Implement std::hash so that hash_code can be used in STL containers.
GraphTraits< BlockFrequencyInfoT * > GTraits
std::string getNodeAttributes(NodeRef Node, const BlockFrequencyInfoT *Graph, unsigned HotPercentThreshold=0)
typename GTraits::nodes_iterator NodeIter
typename GTraits::NodeRef NodeRef
typename GTraits::ChildIteratorType EdgeIter
std::string getNodeLabel(NodeRef Node, const BlockFrequencyInfoT *Graph, GVDAGType GType, int layout_order=-1)
std::string getEdgeAttributes(NodeRef Node, EdgeIter EI, const BlockFrequencyInfoT *BFI, const BranchProbabilityInfoT *BPI, unsigned HotPercentThreshold=0)
BFIDOTGraphTraitsBase(bool isSimple=false)
static StringRef getGraphName(const BlockFrequencyInfoT *G)
Representative of a block.
bool operator==(const BlockNode &X) const
bool operator!=(const BlockNode &X) const
bool operator<(const BlockNode &X) const
bool operator>=(const BlockNode &X) const
BlockNode(IndexType Index)
static size_t getMaxIndex()
bool operator<=(const BlockNode &X) const
bool operator>(const BlockNode &X) const
Distribution of unscaled probability weight.
void addBackedge(const BlockNode &Node, uint64_t Amount)
SmallVector< Weight, 4 > WeightList
WeightList Weights
Individual successor weights.
uint64_t Total
Sum of all weights.
void addExit(const BlockNode &Node, uint64_t Amount)
bool DidOverflow
Whether Total did overflow.
void addLocal(const BlockNode &Node, uint64_t Amount)
Stats about a block itself.
bool isHeader(const BlockNode &Node) const
SmallVector< std::pair< BlockNode, BlockMass >, 4 > ExitMap
LoopData * Parent
The parent loop.
LoopData(LoopData *Parent, It1 FirstHeader, It1 LastHeader, It2 FirstOther, It2 LastOther)
ExitMap Exits
Successor edges (and weights).
uint32_t NumHeaders
Number of headers.
bool IsPackaged
Whether this has been packaged.
LoopData(LoopData *Parent, It FirstHeader, It LastHeader)
LoopData(LoopData *Parent, const BlockNode &Header)
SmallVector< BlockNode, 4 > NodeList
NodeList::const_iterator members_end() const
NodeList::const_iterator members_begin() const
bool isIrreducible() const
BlockNode getHeader() const
SmallVector< BlockMass, 1 > HeaderMassList
NodeList Nodes
Header and the members of the loop.
HeaderMassList BackedgeMass
Mass returned to each loop header.
HeaderMassList::difference_type getHeaderIndex(const BlockNode &B)
iterator_range< NodeList::const_iterator > members() const
Unscaled probability weight.
Weight(DistType Type, BlockNode TargetNode, uint64_t Amount)
bool isPackaged() const
Has ContainingLoop been packaged up?
BlockMass Mass
Mass distribution from the entry block.
BlockMass & getMass()
The mass slot for Node: its own, or that of the outermost packaged loop it heads.
WorkingData(const BlockNode &Node)
bool isAPackage() const
Has Loop been packaged up?
bool isLoopHeader() const
LoopData * Loop
The loop this block is inside.
LoopData * getContainingLoop() const
The innermost loop containing Node that Node does not head.
LoopData * getPackagedLoop() const
The outermost loop containing Node that is currently packaged, if any.
BlockNode getResolvedNode() const
Resolve a node to its representative.
DefaultDOTGraphTraits(bool simple=false)
static nodes_iterator nodes_end(const BlockFrequencyInfo *G)
static nodes_iterator nodes_begin(const BlockFrequencyInfo *G)
typename BlockFrequencyInfoT *::UnknownGraphTypeError NodeRef
IrrNode(const BlockNode &Node)
SmallVectorImpl< const IrrNode * >::const_iterator iterator
SmallVector< const IrrNode *, 4 > Succs
iterator succ_begin() const
iterator succ_end() const
Graph of irreducible control flow.
LLVM_ABI void addNodesInFunction()
IrreducibleGraph(BFIBase &BFI, const BFIBase::LoopData *OuterLoop, BlockEdgesAdder addBlockEdges)
Construct an explicit graph containing irreducible control flow.
LLVM_ABI void indexNodes()
LLVM_ABI void addEdge(IrrNode &Irr, const BlockNode &Succ, const BFIBase::LoopData *OuterLoop)
unsigned getIndex(const IrrNode *N) const
The position of N in Nodes, for indexing side tables.
BlockFrequencyInfoImplBase BFIBase
void addEdges(const BlockNode &Node, const BFIBase::LoopData *OuterLoop, BlockEdgesAdder addBlockEdges)
BFIBase::BlockNode BlockNode
std::vector< IrrNode > Nodes
SmallDenseMap< uint32_t, IrrNode *, 4 > Lookup
void initialize(const BFIBase::LoopData *OuterLoop, BlockEdgesAdder addBlockEdges)
void addNode(const BlockNode &Node)
LLVM_ABI void addNodesInLoop(const BFIBase::LoopData &OuterLoop)
BranchProbabilityInfo BranchProbabilityInfoT
MachineFunction FunctionT
MachineBranchProbabilityInfo BranchProbabilityInfoT
MachineCycleInfo CycleInfoT