LLVM 24.0.0git
MachineBlockFrequencyInfo.cpp
Go to the documentation of this file.
1//===- MachineBlockFrequencyInfo.cpp - MBB Frequency Analysis -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Loops should be simplified before this analysis.
10//
11//===----------------------------------------------------------------------===//
12
14#include "llvm/ADT/DenseMap.h"
15#include "llvm/ADT/iterator.h"
23#include "llvm/Pass.h"
26#include <optional>
27#include <string>
28
29using namespace llvm;
30
31#define DEBUG_TYPE "machine-block-freq"
32
34 "view-machine-block-freq-propagation-dags", cl::Hidden,
35 cl::desc("Pop up a window to show a dag displaying how machine block "
36 "frequencies propagate through the CFG."),
37 cl::values(clEnumValN(GVDT_None, "none", "do not display graphs."),
38 clEnumValN(GVDT_Fraction, "fraction",
39 "display a graph using the "
40 "fractional block frequency representation."),
41 clEnumValN(GVDT_Integer, "integer",
42 "display a graph using the raw "
43 "integer fractional block frequency representation."),
44 clEnumValN(GVDT_Count, "count", "display a graph using the real "
45 "profile count if available.")));
46
47namespace llvm {
48// Similar option above, but used to control BFI display only after MBP pass
50 "view-block-layout-with-bfi", cl::Hidden,
52 "Pop up a window to show a dag displaying MBP layout and associated "
53 "block frequencies of the CFG."),
54 cl::values(clEnumValN(GVDT_None, "none", "do not display graphs."),
55 clEnumValN(GVDT_Fraction, "fraction",
56 "display a graph using the "
57 "fractional block frequency representation."),
58 clEnumValN(GVDT_Integer, "integer",
59 "display a graph using the raw "
60 "integer fractional block frequency representation."),
61 clEnumValN(GVDT_Count, "count",
62 "display a graph using the real "
63 "profile count if available.")));
64
65} // namespace llvm
66
67static cl::opt<bool>
68 PrintMachineBlockFreq("print-machine-bfi", cl::init(false), cl::Hidden,
69 cl::desc("Print the machine block frequency info."));
70
77
79 using NodeRef = const MachineBasicBlock *;
82
84 return &G->getFunction()->front();
85 }
86
88 return N->succ_begin();
89 }
90
91 static ChildIteratorType child_end(const NodeRef N) { return N->succ_end(); }
92
94 return nodes_iterator(G->getFunction()->begin());
95 }
96
98 return nodes_iterator(G->getFunction()->end());
99 }
100};
101
105
106template <>
108 : public MBFIDOTGraphTraitsBase {
109 const MachineFunction *CurFunc = nullptr;
111
112 explicit DOTGraphTraits(bool isSimple = false)
114
117 int layout_order = -1;
118 // Attach additional ordering information if 'isSimple' is false.
119 if (!isSimple()) {
120 const MachineFunction *F = Node->getParent();
121 if (!CurFunc || F != CurFunc) {
122 if (CurFunc)
123 LayoutOrderMap.clear();
124
125 CurFunc = F;
126 int O = 0;
127 for (auto MBI = F->begin(); MBI != F->end(); ++MBI, ++O) {
128 LayoutOrderMap[&*MBI] = O;
129 }
130 }
131 layout_order = LayoutOrderMap[Node];
132 }
134 layout_order);
135 }
136
140 Node, Graph,
141 getViewHotFreqPercent(Node->getParent()->getFunction().getContext()));
142 }
143
145 const MachineBlockFrequencyInfo *MBFI) {
147 Node, EI, MBFI, MBFI->getMBPI(),
148 getViewHotFreqPercent(Node->getParent()->getFunction().getContext()));
149 }
150};
151
152AnalysisKey MachineBlockFrequencyAnalysis::Key;
153
157 auto &MBPI = MFAM.getResult<MachineBranchProbabilityAnalysis>(MF);
158 auto &MCI = MFAM.getResult<MachineCycleAnalysis>(MF);
159 return Result(MF, MBPI, MCI);
160}
161
165 auto &MBFI = MFAM.getResult<MachineBlockFrequencyAnalysis>(MF);
166 OS << "Machine block frequency for machine function: " << MF.getName()
167 << '\n';
168 MBFI.print(OS);
169 return PreservedAnalyses::all();
170}
171
173 "Machine Block Frequency Analysis", true, true)
177 "Machine Block Frequency Analysis", true, true)
178
180
183
185
187 MachineBlockFrequencyInfo &&) = default;
188
194
196
198 MachineFunction &MF, const PreservedAnalyses &PA,
199 MachineFunctionAnalysisManager::Invalidator &) {
200 // Check whether the analysis, all analyses on machine functions, or the
201 // machine function's CFG have been preserved.
203 return !PAC.preserved() &&
204 !PAC.preservedSet<AllAnalysesOn<MachineFunction>>() &&
205 !PAC.preservedSet<CFGAnalyses>();
206}
207
215
218 const MachineCycleInfo &MCI) {
219 if (!MBFI)
220 MBFI.reset(new ImplType);
221 MBFI->calculate(F, MBPI, MCI);
222 const LLVMContext &Ctx = F.getFunction().getContext();
223 StringRef ViewFuncName = getViewBlockFreqFuncName(Ctx);
225 (ViewFuncName.empty() || F.getName() == ViewFuncName)) {
226 view("MachineBlockFrequencyDAGS." + F.getName());
227 }
228 StringRef PrintFuncName = getPrintBFIFuncName(Ctx);
230 (PrintFuncName.empty() || F.getName() == PrintFuncName)) {
231 MBFI->print(dbgs());
232 }
233}
234
244
246
248
249/// Pop up a ghostview window with the current block frequency propagation
250/// rendered using dot.
251void MachineBlockFrequencyInfo::view(const Twine &Name, bool isSimple) const {
252 // This code is only for debugging.
253 ViewGraph(const_cast<MachineBlockFrequencyInfo *>(this), Name, isSimple);
254}
255
258 return MBFI ? MBFI->getBlockFreq(MBB) : BlockFrequency(0);
259}
260
262 const MachineBasicBlock *MBB) const {
263 if (!MBFI)
264 return std::nullopt;
265
266 const Function &F = MBFI->getFunction()->getFunction();
267 return MBFI->getBlockProfileCount(F, MBB);
268}
269
270std::optional<uint64_t>
272 if (!MBFI)
273 return std::nullopt;
274
275 const Function &F = MBFI->getFunction()->getFunction();
276 return MBFI->getProfileCountFromFreq(F, Freq);
277}
278
280 const MachineBasicBlock &NewPredecessor,
281 const MachineBasicBlock &NewSuccessor,
282 const MachineBranchProbabilityInfo &MBPI) {
283 assert(MBFI && "Expected analysis to be available");
284 auto NewSuccFreq = MBFI->getBlockFreq(&NewPredecessor) *
285 MBPI.getEdgeProbability(&NewPredecessor, &NewSuccessor);
286
287 MBFI->setBlockFreq(&NewSuccessor, NewSuccFreq);
288}
289
291 return MBFI ? MBFI->getFunction() : nullptr;
292}
293
295 return MBFI ? &MBFI->getBPI() : nullptr;
296}
297
299 return MBFI ? MBFI->getEntryFreq() : BlockFrequency(0);
300}
301
303 BlockFrequency Freq) {
304 return Printable([&MBFI, Freq](raw_ostream &OS) {
305 printRelativeBlockFreq(OS, MBFI.getEntryFreq(), Freq);
306 });
307}
308
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
This file defines the DenseMap class.
#define DEBUG_TYPE
#define F(x, y, z)
Definition MD5.cpp:54
#define G(x, y, z)
Definition MD5.cpp:55
static GVDAGType getGVDT()
static cl::opt< GVDAGType > ViewMachineBlockFreqPropagationDAG("view-machine-block-freq-propagation-dags", cl::Hidden, cl::desc("Pop up a window to show a dag displaying how machine block " "frequencies propagate through the CFG."), cl::values(clEnumValN(GVDT_None, "none", "do not display graphs."), clEnumValN(GVDT_Fraction, "fraction", "display a graph using the " "fractional block frequency representation."), clEnumValN(GVDT_Integer, "integer", "display a graph using the raw " "integer fractional block frequency representation."), clEnumValN(GVDT_Count, "count", "display a graph using the real " "profile count if available.")))
BFIDOTGraphTraitsBase< MachineBlockFrequencyInfo, MachineBranchProbabilityInfo > MBFIDOTGraphTraitsBase
static cl::opt< bool > PrintMachineBlockFreq("print-machine-bfi", cl::init(false), cl::Hidden, cl::desc("Print the machine block frequency info."))
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
void print(raw_ostream &Out) const
Print the cycle info.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
SmallVectorImpl< MachineBasicBlock * >::const_iterator const_succ_iterator
LLVM_ABI Result run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
bool runOnMachineFunction(MachineFunction &F) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
LLVM_ABI void view(const Twine &Name, bool isSimple=true) const
Pop up a ghostview window with the current block frequency propagation rendered using dot.
LLVM_ABI const MachineBranchProbabilityInfo * getMBPI() const
LLVM_ABI BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const
getblockFreq - Return block frequency.
LLVM_ABI void onEdgeSplit(const MachineBasicBlock &NewPredecessor, const MachineBasicBlock &NewSuccessor, const MachineBranchProbabilityInfo &MBPI)
incrementally calculate block frequencies when we split edges, to avoid full CFG traversal.
LLVM_ABI const MachineFunction * getFunction() const
LLVM_ABI std::optional< uint64_t > getProfileCountFromFreq(BlockFrequency Freq) const
LLVM_ABI bool invalidate(MachineFunction &F, const PreservedAnalyses &PA, MachineFunctionAnalysisManager::Invalidator &)
Handle invalidation explicitly.
LLVM_ABI BlockFrequency getEntryFreq() const
Divide a block's BlockFrequency::getFrequency() value by this value to obtain the entry block - relat...
LLVM_ABI std::optional< uint64_t > getBlockProfileCount(const MachineBasicBlock *MBB) const
LLVM_ABI void calculate(const MachineFunction &F, const MachineBranchProbabilityInfo &MBPI, const MachineCycleInfo &MCI)
calculate - compute block frequency info for the given function.
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LLVM_ABI BranchProbability getEdgeProbability(const MachineBasicBlock *Src, const MachineBasicBlock *Dst) const
Legacy analysis pass which computes a MachineCycleInfo.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
Function & getFunction()
Return the LLVM function that this machine code represents.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
Simple wrapper around std::function<void(raw_ostream&)>.
Definition Printable.h:38
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
cl::opt< GVDAGType > ViewBlockLayoutWithBFI("view-block-layout-with-bfi", cl::Hidden, cl::desc("Pop up a window to show a dag displaying MBP layout and associated " "block frequencies of the CFG."), cl::values(clEnumValN(GVDT_None, "none", "do not display graphs."), clEnumValN(GVDT_Fraction, "fraction", "display a graph using the " "fractional block frequency representation."), clEnumValN(GVDT_Integer, "integer", "display a graph using the raw " "integer fractional block frequency representation."), clEnumValN(GVDT_Count, "count", "display a graph using the real " "profile count if available.")))
void ViewGraph(const GraphType &G, const Twine &Name, bool ShortNames=false, const Twine &Title="", GraphProgram::Name Program=GraphProgram::DOT)
ViewGraph - Emit a dot graph, run 'dot', run gv on the postscript file, then cleanup.
LLVM_ABI void printRelativeBlockFreq(raw_ostream &OS, BlockFrequency EntryFreq, BlockFrequency Freq)
LLVM_ABI Printable printBlockFreq(const BlockFrequencyInfo &BFI, BlockFrequency Freq)
Print the block frequency Freq relative to the current functions entry frequency.
LLVM_ABI StringRef getPrintBFIFuncName(const LLVMContext &C)
Return -print-bfi-func-name.
LLVM_ABI StringRef getViewBlockFreqFuncName(const LLVMContext &C)
Return -view-bfi-func-name.
LLVM_ABI unsigned getViewHotFreqPercent(const LLVMContext &C)
Return -view-hot-freq-percent.
#define N
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
std::string getNodeAttributes(NodeRef Node, const MachineBlockFrequencyInfo *Graph, unsigned HotPercentThreshold=0)
std::string getNodeLabel(NodeRef Node, const MachineBlockFrequencyInfo *Graph, GVDAGType GType, int layout_order=-1)
std::string getEdgeAttributes(NodeRef Node, EdgeIter EI, const MachineBlockFrequencyInfo *BFI, const MachineBranchProbabilityInfo *BPI, unsigned HotPercentThreshold=0)
std::string getEdgeAttributes(const MachineBasicBlock *Node, EdgeIter EI, const MachineBlockFrequencyInfo *MBFI)
std::string getNodeAttributes(const MachineBasicBlock *Node, const MachineBlockFrequencyInfo *Graph)
DenseMap< const MachineBasicBlock *, int > LayoutOrderMap
std::string getNodeLabel(const MachineBasicBlock *Node, const MachineBlockFrequencyInfo *Graph)
DOTGraphTraits - Template class that can be specialized to customize how graphs are converted to 'dot...
static ChildIteratorType child_begin(const NodeRef N)
static ChildIteratorType child_end(const NodeRef N)
static NodeRef getEntryNode(const MachineBlockFrequencyInfo *G)
static nodes_iterator nodes_begin(const MachineBlockFrequencyInfo *G)
MachineBasicBlock::const_succ_iterator ChildIteratorType
pointer_iterator< MachineFunction::const_iterator > nodes_iterator
static nodes_iterator nodes_end(const MachineBlockFrequencyInfo *G)