14#ifndef LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
15#define LLVM_ANALYSIS_BLOCKFREQUENCYINFOIMPL_H
54#define DEBUG_TYPE "block-freq"
63class BranchProbabilityInfo;
66class MachineBasicBlock;
67class MachineBranchProbabilityInfo;
68class MachineCycleInfo;
99 return BlockMass(std::numeric_limits<uint64_t>::max());
104 bool isFull()
const {
return Mass == std::numeric_limits<uint64_t>::max(); }
114 Mass = Sum < Mass ? std::numeric_limits<uint64_t>::max() : Sum;
124 Mass = Diff > Mass ? 0 : Diff;
129 Mass =
P.scale(Mass);
207 return std::numeric_limits<uint32_t>::max() - 1;
249 template <
class It1,
class It2>
254 Nodes.insert(
Nodes.end(), FirstOther, LastOther);
302 while (L && L->isHeader(
Node))
322 return L ? L->getHeader() :
Node;
333 while (L->Parent && L->Parent->IsPackaged)
470 std::list<LoopData>::iterator Insert);
517 Scaled64 getFloatingBlockFreq(
const BlockNode &
Node)
const;
520 std::optional<uint64_t> getBlockProfileCount(
const Function &
F,
521 const BlockNode &
Node)
const;
522 std::optional<uint64_t> getProfileCountFromFreq(
const Function &
F,
524 bool isIrrLoopHeader(
const BlockNode &
Node);
534namespace bfi_detail {
558 assert(BB &&
"Unexpected nullptr");
559 auto MachineName =
"BB" +
Twine(BB->getNumber());
560 if (BB->getBasicBlock())
561 return (MachineName +
"[" + BB->getName() +
"]").str();
562 return MachineName.str();
566 assert(BB &&
"Unexpected nullptr");
618 template <
class BlockEdgesAdder>
620 BlockEdgesAdder addBlockEdges) :
BFI(
BFI) {
624 template <
class BlockEdgesAdder>
625 void initialize(
const BFIBase::LoopData *OuterLoop,
626 BlockEdgesAdder addBlockEdges);
633 "mass distributed before the region was packaged");
637 template <
class BlockEdgesAdder>
639 BlockEdgesAdder addBlockEdges);
641 const BFIBase::LoopData *OuterLoop);
644template <
class BlockEdgesAdder>
646 BlockEdgesAdder addBlockEdges) {
649 for (
auto N : OuterLoop->
Nodes)
653 for (
uint32_t Index = 0; Index <
BFI.Working.size(); ++Index)
654 addEdges(Index, OuterLoop, addBlockEdges);
659template <
class BlockEdgesAdder>
662 BlockEdgesAdder addBlockEdges) {
667 const auto &Working =
BFI.Working[
Node.Index];
669 if (Working.isAPackage())
670 for (
const auto &
I : Working.Loop->Exits)
673 addBlockEdges(*
this, Irr, OuterLoop);
832 using BranchProbabilityInfoT =
838 const BranchProbabilityInfoT *BPI =
nullptr;
839 const CycleInfoT *CI =
nullptr;
840 const FunctionT *F =
nullptr;
843 std::vector<const BlockT *> RPOT;
846 unsigned BlockNumberEpoch;
848 BlockNode getNode(
const BlockT *BB)
const {
849 assert(BlockNumberEpoch ==
852 return BlockNumber < Nodes.size() ? Nodes[BlockNumber] :
BlockNode();
857 return RPOT[
Node.Index];
861 void initializeRPOT();
870 void initializeLoops();
903 void computeIrreducibleMass(
LoopData *OuterLoop,
904 std::list<LoopData>::iterator Insert);
911 void computeMassInLoops();
920 void computeMassInFunction();
922 std::string getBlockName(
const BlockNode &
Node)
const override {
936 bool needIterativeInference()
const;
939 void applyIterativeInference();
941 using ProbMatrixType = std::vector<std::vector<std::pair<size_t, Scaled64>>>;
944 void iterativeInference(
const ProbMatrixType &ProbMatrix,
946 std::vector<Scaled64> &Freq)
const;
950 void findReachableBlocks(
BitVector &Blocks)
const;
954 void initTransitionProbabilities(
const BitVector &Blocks,
955 ProbMatrixType &ProbMatrix)
const;
960 Scaled64 discrepancy(
const ProbMatrixType &ProbMatrix,
961 const std::vector<Scaled64> &Freq)
const;
969 void calculate(
const FunctionT &F,
const BranchProbabilityInfoT &BPI,
970 const CycleInfoT &CI);
979 const BlockT *BB)
const {
998 const BranchProbabilityInfoT &
getBPI()
const {
return *BPI; }
1020 const BranchProbabilityInfoT &BPI,
1021 const CycleInfoT &CI) {
1033 <<
"\n================="
1034 << std::string(F.getName().size(),
'=') <<
"\n");
1045 computeMassInLoops();
1046 computeMassInFunction();
1051 if (needIterativeInference())
1052 applyIterativeInference();
1059 for (
const BlockT &BB : F)
1072 if (Nodes.size() <= BlockNumber)
1075 if (!
Node.isValid()) {
1080 Freqs.emplace_back();
1085template <
class BT>
void BlockFrequencyInfoImpl<BT>::initializeRPOT() {
1086 const BlockT *Entry = &
F->front();
1087 RPOT.reserve(
F->size());
1089 RPOT.emplace_back(BB);
1090 std::reverse(RPOT.begin(), RPOT.end());
1092 assert(RPOT.size() - 1 <= BlockNode::getMaxIndex() &&
1093 "More nodes in function than Block Frequency Info supports");
1099 BlockNode
Node = BlockNode(Idx);
1104 Working.reserve(RPOT.size());
1105 for (
size_t Index = 0; Index < RPOT.size(); ++Index)
1106 Working.emplace_back(Index);
1107 Freqs.resize(RPOT.size());
1110template <
class BT>
void BlockFrequencyInfoImpl<BT>::initializeLoops() {
1121 if (!CI->isReducible(
C))
1123 for (
CycleRef A = CI->getParentCycle(
C);
A;
A = CI->getParentCycle(
A))
1124 if (!CI->isReducible(
A) && CI->isEntry(
A, CI->getHeader(
C)))
1130 std::deque<std::pair<CycleRef, LoopData *>> Q;
1131 for (
CycleRef C : CI->toplevel_cycles())
1132 Q.emplace_back(
C,
nullptr);
1135 while (!Q.empty()) {
1137 LoopData *Parent = Q.front().second;
1140 if (hasLoop(Cycle)) {
1141 BlockNode Header =
getNode(CI->getHeader(Cycle));
1142 Loops.emplace_back(Parent, Header);
1144 Working[Header.Index].Loop = &
Loops.back();
1146 Parent = &
Loops.back();
1147 }
else if (!CI->isReducible(Cycle)) {
1151 Parent->ContainsIrreducible =
true;
1153 TopContainsIrreducible =
true;
1157 Q.emplace_back(
C, Parent);
1162 for (
size_t Index = 0;
Index < RPOT.size(); ++
Index) {
1164 if (Working[Index].isLoopHeader()) {
1165 LoopData *ContainingLoop = Working[
Index].getContainingLoop();
1167 ContainingLoop->Nodes.push_back(Index);
1171 CycleRef Cycle = CI->getCycle(RPOT[Index]);
1172 while (Cycle && !hasLoop(Cycle))
1173 Cycle = CI->getParentCycle(Cycle);
1178 BlockNode Header =
getNode(CI->getHeader(Cycle));
1179 assert(Header.isValid());
1180 const auto &HeaderData = Working[Header.Index];
1181 assert(HeaderData.isLoopHeader());
1183 Working[
Index].Loop = HeaderData.Loop;
1184 HeaderData.Loop->Nodes.push_back(Index);
1190template <
class BT>
void BlockFrequencyInfoImpl<BT>::computeMassInLoops() {
1193 for (
auto L =
Loops.end(),
B =
Loops.begin(); L !=
B;) {
1195 if (
L->ContainsIrreducible)
1196 computeIrreducibleMass(&*L, std::next(L));
1197 computeMassInLoop(*L);
1202void BlockFrequencyInfoImpl<BT>::computeMassInLoop(LoopData &
Loop) {
1205 if (
Loop.isIrreducible()) {
1207 computeMassInIrreducibleLoop(
Loop);
1209 Working[
Loop.
getHeader().Index].getMass() = BlockMass::getFull();
1211 for (
const BlockNode &M :
Loop.members())
1212 propagateMassToSuccessors(&
Loop, M);
1215 computeLoopScale(
Loop);
1220void BlockFrequencyInfoImpl<BT>::computeMassInIrreducibleLoop(LoopData &
Loop) {
1222 unsigned NumHeadersWithWeight = 0;
1223 std::optional<uint64_t> MinHeaderWeight;
1226 for (uint32_t
H = 0;
H <
Loop.NumHeaders; ++
H) {
1227 auto &HeaderNode =
Loop.Nodes[
H];
1228 const BlockT *
Block = getBlock(HeaderNode);
1229 IsIrrLoopHeader.set(
Loop.Nodes[
H].Index);
1230 std::optional<uint64_t> HeaderWeight =
Block->getIrrLoopHeaderWeight();
1231 if (!HeaderWeight) {
1234 HeadersWithoutWeight.insert(
H);
1238 <<
" has irr loop header weight " << *HeaderWeight
1240 NumHeadersWithWeight++;
1241 uint64_t HeaderWeightValue = *HeaderWeight;
1242 if (!MinHeaderWeight || HeaderWeightValue < MinHeaderWeight)
1243 MinHeaderWeight = HeaderWeightValue;
1244 if (HeaderWeightValue) {
1245 Dist.addLocal(HeaderNode, HeaderWeightValue);
1254 if (!MinHeaderWeight)
1255 MinHeaderWeight = 1;
1256 for (uint32_t
H : HeadersWithoutWeight) {
1257 auto &HeaderNode =
Loop.Nodes[
H];
1258 assert(!getBlock(HeaderNode)->getIrrLoopHeaderWeight() &&
1259 "Shouldn't have a weight metadata");
1260 uint64_t MinWeight = *MinHeaderWeight;
1264 Dist.addLocal(HeaderNode, MinWeight);
1266 distributeIrrLoopHeaderMass(Dist);
1269 for (
const BlockNode &M :
Loop.Nodes)
1270 propagateMassToSuccessors(&
Loop, M);
1271 if (NumHeadersWithWeight == 0)
1273 adjustLoopHeaderMass(
Loop);
1276template <
class BT>
void BlockFrequencyInfoImpl<BT>::computeMassInFunction() {
1277 if (TopContainsIrreducible)
1278 computeIrreducibleMass(
nullptr,
Loops.begin());
1281 assert(!Working.empty() &&
"no blocks in function");
1282 assert(!Working[0].isLoopHeader() &&
"entry block is a loop header");
1284 Working[0].getMass() = BlockMass::getFull();
1285 for (
size_t i = 0, n = RPOT.size(); i != n; ++i) {
1287 if (Working[i].isPackaged())
1290 propagateMassToSuccessors(
nullptr, BlockNode(i));
1295bool BlockFrequencyInfoImpl<BT>::needIterativeInference()
const {
1298 if (!
F->getFunction().hasProfileData())
1302 for (
auto L =
Loops.rbegin(),
E =
Loops.rend(); L !=
E; ++L) {
1303 if (
L->isIrreducible())
1309template <
class BT>
void BlockFrequencyInfoImpl<BT>::applyIterativeInference() {
1315 findReachableBlocks(ReachableBlocks);
1316 if (ReachableBlocks.none())
1320 auto Freq = std::vector<Scaled64>(ReachableBlocks.size());
1322 for (
const BlockT &BB : *
F) {
1324 if (!ReachableBlocks[
Number])
1326 Freq[
Number] = getFloatingBlockFreq(&BB);
1329 assert(!SumFreq.isZero() &&
"empty initial block frequencies");
1331 LLVM_DEBUG(
dbgs() <<
"Applying iterative inference for " <<
F->getName()
1332 <<
" with " << ReachableBlocks.count() <<
" blocks\n");
1335 for (
auto &
Value : Freq) {
1341 ProbMatrixType ProbMatrix;
1342 initTransitionProbabilities(ReachableBlocks, ProbMatrix);
1345 iterativeInference(ProbMatrix, ReachableBlocks, Freq);
1348 for (
const BlockT &BB : *
F) {
1350 if (!
Node.isValid())
1353 Freqs[
Node.Index].Scaled =
1354 ReachableBlocks[
Number] ? Freq[
Number] : Scaled64::getZero();
1359void BlockFrequencyInfoImpl<BT>::iterativeInference(
1360 const ProbMatrixType &ProbMatrix,
const BitVector &Blocks,
1361 std::vector<Scaled64> &Freq)
const {
1363 "incorrectly specified precision");
1365 const auto Precision =
1367 const size_t MaxIterations =
1372 << discrepancy(ProbMatrix, Freq).
toString() <<
"\n");
1376 auto Successors = std::vector<std::vector<size_t>>(Freq.size());
1377 for (
size_t I = 0;
I < Freq.size();
I++) {
1378 for (
const auto &Jump : ProbMatrix[
I]) {
1379 Successors[Jump.first].push_back(
I);
1387 auto IsActive =
BitVector(Freq.size(),
false);
1388 std::queue<size_t> ActiveSet;
1389 for (
unsigned I : Blocks.set_bits()) {
1398 while (It++ < MaxIterations && !ActiveSet.empty()) {
1399 size_t I = ActiveSet.front();
1401 IsActive[
I] =
false;
1407 Scaled64 OneMinusSelfProb = Scaled64::getOne();
1408 for (
const auto &Jump : ProbMatrix[
I]) {
1409 if (Jump.first ==
I) {
1410 OneMinusSelfProb -= Jump.second;
1412 NewFreq += Freq[Jump.first] * Jump.second;
1415 if (OneMinusSelfProb != Scaled64::getOne())
1416 NewFreq /= OneMinusSelfProb;
1420 auto Change = Freq[
I] >= NewFreq ? Freq[
I] - NewFreq : NewFreq - Freq[
I];
1421 if (Change > Precision) {
1424 for (
size_t Succ : Successors[
I]) {
1425 if (!IsActive[Succ]) {
1426 ActiveSet.push(Succ);
1427 IsActive[Succ] =
true;
1436 LLVM_DEBUG(
dbgs() <<
" Completed " << It <<
" inference iterations"
1437 <<
format(
" (%0.0f per block)",
double(It) / Freq.size())
1441 << discrepancy(ProbMatrix, Freq).
toString() <<
"\n");
1446void BlockFrequencyInfoImpl<BT>::findReachableBlocks(
BitVector &Blocks)
const {
1448 auto number = [](
const BlockT *BB) {
1454 std::queue<const BlockT *>
Queue;
1456 const BlockT *
Entry = &
F->front();
1458 Reachable.set(
number(Entry));
1459 while (!
Queue.empty()) {
1460 const BlockT *SrcBB =
Queue.front();
1463 auto EP = BPI->getEdgeProbability(SrcBB, It.index());
1467 if (!Reachable.test(
Number)) {
1469 Queue.push(It.value());
1477 for (
const BlockT &BB : *
F) {
1480 if (!HasSucc && Reachable.test(
number(&BB))) {
1482 InverseReachable.set(
number(&BB));
1485 while (!
Queue.empty()) {
1486 const BlockT *SrcBB =
Queue.front();
1489 auto EP = BPI->getEdgeProbability(DstBB, SrcBB);
1493 if (!InverseReachable.test(
Number)) {
1494 InverseReachable.set(
Number);
1501 Reachable &= InverseReachable;
1502 Blocks = std::move(Reachable);
1506void BlockFrequencyInfoImpl<BT>::initTransitionProbabilities(
1507 const BitVector &Blocks, ProbMatrixType &ProbMatrix)
const {
1508 const size_t NumBlocks = Blocks.size();
1509 auto Succs = std::vector<std::vector<std::pair<size_t, Scaled64>>>(NumBlocks);
1510 auto SumProb = std::vector<Scaled64>(NumBlocks);
1513 for (
const BlockT &BB : *
F) {
1519 const BlockT *
SI = It.value();
1525 if (!UniqueSuccs.insert(
SI).second)
1528 auto EP = BPI->getEdgeProbability(&BB, It.index());
1533 Scaled64::getFraction(EP.getNumerator(), EP.getDenominator());
1534 Succs[Src].push_back(std::make_pair(Dst, EdgeProb));
1535 SumProb[Src] += EdgeProb;
1540 ProbMatrix = ProbMatrixType(NumBlocks);
1541 for (
size_t Src = 0; Src < NumBlocks; Src++) {
1543 if (Succs[Src].
empty())
1546 assert(!SumProb[Src].
isZero() &&
"Zero sum probability of non-exit block");
1547 for (
auto &Jump : Succs[Src]) {
1548 size_t Dst = Jump.first;
1549 Scaled64 Prob = Jump.second;
1550 ProbMatrix[Dst].push_back(std::make_pair(Src, Prob / SumProb[Src]));
1556 for (
size_t Src = 0; Src < NumBlocks; Src++) {
1557 if (Blocks[Src] && Succs[Src].
empty()) {
1558 ProbMatrix[EntryIdx].push_back(std::make_pair(Src, Scaled64::getOne()));
1566 const ProbMatrixType &ProbMatrix,
const std::vector<Scaled64> &Freq)
const {
1568 assert(Freq[EntryIdx] > 0 &&
1569 "Incorrectly computed frequency of the entry block");
1570 Scaled64 Discrepancy;
1571 for (
size_t I = 0;
I < ProbMatrix.size();
I++) {
1573 for (
const auto &Jump : ProbMatrix[
I]) {
1574 Sum += Freq[Jump.first] * Jump.second;
1576 Discrepancy += Freq[
I] >= Sum ? Freq[
I] - Sum : Sum - Freq[
I];
1579 return Discrepancy / Freq[EntryIdx];
1584void BlockFrequencyInfoImpl<BT>::computeIrreducibleMass(
1585 LoopData *OuterLoop, std::list<LoopData>::iterator Insert) {
1587 if (OuterLoop)
dbgs()
1588 <<
"loop: " << getLoopName(*OuterLoop) <<
"\n";
1589 else dbgs() <<
"function\n");
1593 auto addBlockEdges = [&](IrreducibleGraph &
G, IrreducibleGraph::IrrNode &Irr,
1594 const LoopData *OuterLoop) {
1595 const BlockT *BB = RPOT[Irr.Node.Index];
1597 G.addEdge(Irr,
getNode(Succ), OuterLoop);
1599 IrreducibleGraph
G(*
this, OuterLoop, addBlockEdges);
1601 for (
auto &L : analyzeIrreducible(
G, OuterLoop, Insert))
1602 computeMassInLoop(L);
1608 assert(OuterLoop->Exits.empty() &&
"unexpected exits before distribution");
1610 [](BlockMass M) { return M.isEmpty(); }) &&
1611 "unexpected backedge mass before distribution");
1612 auto O = OuterLoop->Nodes.begin() + 1;
1613 for (
auto I = O,
E = OuterLoop->Nodes.end();
I !=
E; ++
I)
1614 if (!Working[
I->Index].isPackaged())
1616 OuterLoop->Nodes.erase(O, OuterLoop->Nodes.end());
1625void BlockFrequencyInfoImpl<BT>::propagateMassToSuccessors(
1626 LoopData *OuterLoop,
const BlockNode &
Node) {
1630 if (
auto *Loop = Working[
Node.Index].getPackagedLoop()) {
1631 assert(Loop != OuterLoop &&
"Cannot propagate mass in a packaged loop");
1632 addLoopSuccessorsToDist(OuterLoop, *Loop, Dist);
1634 const BlockT *BB = getBlock(Node);
1637 Dist, OuterLoop, Node,
getNode(It.value()),
1643 distributeMass(Node, OuterLoop, Dist);
1650 OS <<
"block-frequency-info: " << F->getName() <<
"\n";
1651 for (
const BlockT &BB : *F) {
1655 if (std::optional<uint64_t> ProfileCount =
1657 F->getFunction(), getNode(&BB)))
1658 OS <<
", count = " << *ProfileCount;
1659 if (std::optional<uint64_t> IrrLoopHeaderWeight =
1660 BB.getIrrLoopHeaderWeight())
1661 OS <<
", irr_loop_header_weight = " << *IrrLoopHeaderWeight;
1678 for (
const auto &BB : *F)
1681 size_t MinSize = std::min(Nodes.size(),
Other.Nodes.size());
1682 for (
size_t i = 0; i < MinSize; ++i) {
1688 <<
" existence mismatch.\n";
1689 }
else if (Nodes[i].
isValid()) {
1690 const auto &Freq =
Freqs[Nodes[i].Index];
1691 const auto &OtherFreq =
Other.Freqs[
Other.Nodes[i].Index];
1692 if (Freq.Integer != OtherFreq.Integer) {
1695 <<
" " << Freq.Integer <<
" vs " << OtherFreq.Integer <<
"\n";
1700 for (
size_t i = MinSize; i < Nodes.size(); ++i) {
1704 <<
" existence mismatch.\n";
1707 for (
size_t i = MinSize; i <
Other.Nodes.size(); ++i) {
1708 if (
Other.Nodes[i].isValid()) {
1711 <<
" existence mismatch.\n";
1718 dbgs() <<
"Other\n";
1721 assert(Match &&
"BFI mismatch");
1729template <
class BlockFrequencyInfoT,
class BranchProbabilityInfoT>
1742 return G->getFunction()->getName();
1746 unsigned HotPercentThreshold = 0) {
1748 if (!HotPercentThreshold)
1758 std::max(
MaxFrequency, Graph->getBlockFreq(
N).getFrequency());
1774 GVDAGType GType,
int layout_order = -1) {
1778 if (layout_order != -1)
1779 OS <<
Node->getName() <<
"[" << layout_order <<
"] : ";
1781 OS <<
Node->getName() <<
" : ";
1787 OS << Graph->getBlockFreq(
Node).getFrequency();
1790 auto Count = Graph->getBlockProfileCount(
Node);
1799 "never reach this point.");
1805 const BlockFrequencyInfoT *BFI,
1806 const BranchProbabilityInfoT *BPI,
1807 unsigned HotPercentThreshold = 0) {
1820 if (HotPercentThreshold) {
1825 if (EFreq >= HotFreq)
1826 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 constexpr std::size_t number(BlockVerifier::State S)
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.
void addToDist(Distribution &Dist, const LoopData *OuterLoop, const BlockNode &Pred, const BlockNode &Succ, uint64_t Weight)
Add an edge 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 TopContainsIrreducible
Has an irreducible SCC outside every loop.
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 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.
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.
void addLoopSuccessorsToDist(const LoopData *OuterLoop, LoopData &Loop, Distribution &Dist)
Add all edges out of a packaged loop to the distribution.
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.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
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).
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