LLVM 24.0.0git
CFGPrinter.cpp
Go to the documentation of this file.
1//===- CFGPrinter.cpp - DOT printer for the control flow graph ------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines a `-dot-cfg` analysis pass, which emits the
10// `<prefix>.<fnname>.dot` file for each function in the program, with a graph
11// of the CFG for that function. The default value for `<prefix>` is `cfg` but
12// can be customized as needed.
13//
14// The other main feature of this file is that it implements the
15// Function::viewCFG method, which is useful for debugging passes which operate
16// on the CFG.
17//
18//===----------------------------------------------------------------------===//
19
21#include "AnalysisOptions.h"
26
27using namespace llvm;
28
29static void writeCFGToDotFile(const AnalysisOptions &Opts, Function &F,
31 BranchProbabilityInfo *BPI, uint64_t MaxFreq,
32 bool CFGOnly = false) {
33 std::string Filename =
34 (Opts.cfg_dot_filename_prefix + "." + F.getName() + ".dot").str();
35 errs() << "Writing '" << Filename << "'...";
36
37 std::error_code EC;
39
40 DOTFuncInfo CFGInfo(&F, BFI, BPI, MaxFreq);
41 CFGInfo.setHeatColors(Opts.cfg_heat_colors);
42 CFGInfo.setEdgeWeights(Opts.cfg_weights);
43 CFGInfo.setRawEdgeWeights(Opts.cfg_raw_weights);
44
45 if (!EC)
46 WriteGraph(File, &CFGInfo, CFGOnly);
47 else
48 errs() << " error opening file for writing!";
49 errs() << "\n";
50}
51
52static void viewCFG(const AnalysisOptions &Opts, Function &F,
53 const BlockFrequencyInfo *BFI,
54 const BranchProbabilityInfo *BPI, uint64_t MaxFreq,
55 bool CFGOnly = false) {
56 DOTFuncInfo CFGInfo(&F, BFI, BPI, MaxFreq);
57 CFGInfo.setHeatColors(Opts.cfg_heat_colors);
58 CFGInfo.setEdgeWeights(Opts.cfg_weights);
59 CFGInfo.setRawEdgeWeights(Opts.cfg_raw_weights);
60
61 ViewGraph(&CFGInfo, "cfg." + F.getName(), CFGOnly);
62}
63
65 const BranchProbabilityInfo *BPI, uint64_t MaxFreq,
66 std::optional<NodeIdFormatterTy> NodeIdFormatter)
67 : F(F), BFI(BFI), BPI(BPI), MaxFreq(MaxFreq),
68 NodeIdFormatter(NodeIdFormatter) {
69 ShowHeat = false;
70 EdgeWeights = !!BPI; // Print EdgeWeights when BPI is available.
71 RawWeights = !!BFI; // Print RawWeights when BFI is available.
72}
73
75
77 if (!MSTStorage)
78 MSTStorage = std::make_unique<ModuleSlotTracker>(F->getParent());
79 return &*MSTStorage;
80}
81
83 const AnalysisOptions &Opts = getAnalysisOptions(F);
84 if (!Opts.cfg_func_name.empty() && !F.getName().contains(Opts.cfg_func_name))
86 auto *BFI = &AM.getResult<BlockFrequencyAnalysis>(F);
87 auto *BPI = &AM.getResult<BranchProbabilityAnalysis>(F);
88 viewCFG(Opts, F, BFI, BPI, getMaxFreq(F, BFI));
90}
91
94 const AnalysisOptions &Opts = getAnalysisOptions(F);
95 if (!Opts.cfg_func_name.empty() && !F.getName().contains(Opts.cfg_func_name))
97 auto *BFI = &AM.getResult<BlockFrequencyAnalysis>(F);
98 auto *BPI = &AM.getResult<BranchProbabilityAnalysis>(F);
99 viewCFG(Opts, F, BFI, BPI, getMaxFreq(F, BFI), /*CFGOnly=*/true);
100 return PreservedAnalyses::all();
101}
102
105 const AnalysisOptions &Opts = getAnalysisOptions(F);
106 if (!Opts.cfg_func_name.empty() && !F.getName().contains(Opts.cfg_func_name))
107 return PreservedAnalyses::all();
108 auto *BFI = &AM.getResult<BlockFrequencyAnalysis>(F);
109 auto *BPI = &AM.getResult<BranchProbabilityAnalysis>(F);
110 writeCFGToDotFile(Opts, F, BFI, BPI, getMaxFreq(F, BFI));
111 return PreservedAnalyses::all();
112}
113
116 const AnalysisOptions &Opts = getAnalysisOptions(F);
117 if (!Opts.cfg_func_name.empty() && !F.getName().contains(Opts.cfg_func_name))
118 return PreservedAnalyses::all();
119 auto *BFI = &AM.getResult<BlockFrequencyAnalysis>(F);
120 auto *BPI = &AM.getResult<BranchProbabilityAnalysis>(F);
121 writeCFGToDotFile(Opts, F, BFI, BPI, getMaxFreq(F, BFI), /*CFGOnly=*/true);
122 return PreservedAnalyses::all();
123}
124
125/// viewCFG - This function is meant for use from the debugger. You can just
126/// say 'call F->viewCFG()' and a ghostview window should pop up from the
127/// program, displaying the CFG of the current function. This depends on there
128/// being a 'dot' and 'gv' program in your path.
129///
130void Function::viewCFG() const { viewCFG(false, nullptr, nullptr); }
131
132void Function::viewCFG(const char *OutputFileName) const {
133 viewCFG(false, nullptr, nullptr, OutputFileName);
134}
135
136void Function::viewCFG(bool ViewCFGOnly, const BlockFrequencyInfo *BFI,
137 const BranchProbabilityInfo *BPI,
138 const char *OutputFileName) const {
139 StringRef CFGFuncName = getAnalysisOptions(*this).cfg_func_name;
140 if (!CFGFuncName.empty() && !getName().contains(CFGFuncName))
141 return;
142 DOTFuncInfo CFGInfo(this, BFI, BPI, BFI ? getMaxFreq(*this, BFI) : 0);
143 ViewGraph(&CFGInfo, OutputFileName ? OutputFileName : "cfg" + getName(),
144 ViewCFGOnly);
145}
146
147/// viewCFGOnly - This function is meant for use from the debugger. It works
148/// just like viewCFG, but it does not include the contents of basic blocks
149/// into the nodes, just the label. If you are only interested in the CFG
150/// this can make the graph smaller.
151///
152void Function::viewCFGOnly() const { viewCFGOnly(nullptr, nullptr); }
153
154void Function::viewCFGOnly(const char *OutputFileName) const {
155 viewCFG(true, nullptr, nullptr, OutputFileName);
156}
157
159 const BranchProbabilityInfo *BPI) const {
160 viewCFG(true, BFI, BPI);
161}
162
163/// Find all blocks on the paths which terminate with a deoptimize or
164/// unreachable (i.e. all blocks which are post-dominated by a deoptimize
165/// or unreachable). These paths are hidden if the corresponding cl::opts
166/// are enabled.
168 const Function *F) {
169 const AnalysisOptions &Opts = getAnalysisOptions(*F);
170 auto evaluateBB = [&](const BasicBlock *Node) {
171 if (succ_empty(Node)) {
172 const Instruction *TI = Node->getTerminator();
173 isOnDeoptOrUnreachablePath[Node] =
174 (Opts.cfg_hide_unreachable_paths && isa<UnreachableInst>(TI)) ||
175 (Opts.cfg_hide_deoptimize_paths &&
176 Node->getTerminatingDeoptimizeCall());
177 return;
178 }
179 isOnDeoptOrUnreachablePath[Node] =
180 llvm::all_of(successors(Node), [this](const BasicBlock *BB) {
181 return isOnDeoptOrUnreachablePath[BB];
182 });
183 };
184 /// The post order traversal iteration is done to know the status of
185 /// isOnDeoptOrUnreachablePath for all the successors on the current BB.
186 llvm::for_each(post_order(&F->getEntryBlock()), evaluateBB);
187}
188
190 const DOTFuncInfo *CFGInfo) {
191 const AnalysisOptions &Opts = getAnalysisOptions(*CFGInfo->getFunction());
192 if (Opts.cfg_hide_cold_paths)
193 if (auto *BFI = CFGInfo->getBFI()) {
194 BlockFrequency NodeFreq = BFI->getBlockFreq(Node);
195 BlockFrequency EntryFreq = BFI->getEntryFreq();
196 // Hide blocks with relative frequency below -cfg-hide-cold-paths.
197 if ((double)NodeFreq.getFrequency() / EntryFreq.getFrequency() <
198 *Opts.cfg_hide_cold_paths)
199 return true;
200 }
201 if (Opts.cfg_hide_unreachable_paths || Opts.cfg_hide_deoptimize_paths) {
202 if (!isOnDeoptOrUnreachablePath.contains(Node))
203 computeDeoptOrUnreachablePaths(Node->getParent());
204 return isOnDeoptOrUnreachablePath[Node];
205 }
206 return false;
207}
208
210 const BasicBlock *Node, DOTFuncInfo *CFGInfo,
212 HandleBasicBlock,
213 function_ref<void(std::string &, unsigned &, unsigned)> HandleComment) {
214 if (HandleBasicBlock)
215 return CompleteNodeLabelString(Node, HandleBasicBlock, HandleComment);
216
217 // Default basic block printing
218 std::optional<ModuleSlotTracker> MSTStorage;
219 ModuleSlotTracker *MST = nullptr;
220
221 if (CFGInfo) {
222 MST = CFGInfo->getModuleSlotTracker();
223 } else {
224 MSTStorage.emplace(Node->getModule());
225 MST = &*MSTStorage;
226 }
227
229 Node,
231 [MST](raw_string_ostream &OS, const BasicBlock &Node) -> void {
232 // Prepend label name
233 Node.printAsOperand(OS, false, *MST);
234 OS << ":\n";
235
236 for (const Instruction &Inst : Node) {
237 Inst.print(OS, *MST, /* IsForDebug */ false);
238 OS << '\n';
239 }
240 }),
241 HandleComment);
242}
uint64_t uint64_t
static void viewCFG(const AnalysisOptions &Opts, Function &F, const BlockFrequencyInfo *BFI, const BranchProbabilityInfo *BPI, uint64_t MaxFreq, bool CFGOnly=false)
static void writeCFGToDotFile(const AnalysisOptions &Opts, Function &F, BlockFrequencyInfo *BFI, BranchProbabilityInfo *BPI, uint64_t MaxFreq, bool CFGOnly=false)
#define F(x, y, z)
Definition MD5.cpp:54
static cl::opt< bool > CFGOnly("dot-mcfg-only", cl::init(false), cl::Hidden, cl::desc("Print only the CFG without blocks body"))
static constexpr StringLiteral Filename
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
static StringRef getName(Value *V)
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:480
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
Analysis pass which computes BranchProbabilityInfo.
Analysis providing branch probability information.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
void setRawEdgeWeights(bool RawWeights)
Definition CFGPrinter.h:102
LLVM_ABI ~DOTFuncInfo()
void setEdgeWeights(bool EdgeWeights)
Definition CFGPrinter.h:106
DOTFuncInfo(const Function *F)
Definition CFGPrinter.h:76
LLVM_ABI ModuleSlotTracker * getModuleSlotTracker()
const Function * getFunction() const
Definition CFGPrinter.h:88
const BlockFrequencyInfo * getBFI() const
Definition CFGPrinter.h:84
void setHeatColors(bool ShowHeat)
Definition CFGPrinter.h:98
void viewCFG() const
viewCFG - This function is meant for use from the debugger.
void viewCFGOnly() const
viewCFGOnly - This function is meant for use from the debugger.
Manage lifetime of a slot tracker for printing IR.
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
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
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
An efficient, type-erasing, non-owning reference to a callable.
A raw_ostream that writes to a file descriptor.
A raw_ostream that writes to an std::string.
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
Definition FileSystem.h:793
This is an optimization pass for GlobalISel generic memory operations.
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1748
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
bool succ_empty(const Instruction *I)
Definition CFG.h:141
auto successors(const MachineBasicBlock *BB)
raw_ostream & WriteGraph(raw_ostream &O, const GraphType &G, bool ShortNames=false, const Twine &Title="")
const AnalysisOptions & getAnalysisOptions(const LLVMContext &C)
auto post_order(const T &G)
Post-order traversal of a graph.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
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.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
std::string CompleteNodeLabelString(const BasicBlockT *Node, function_ref< void(raw_string_ostream &, const BasicBlockT &)> HandleBasicBlock, function_ref< void(std::string &, unsigned &, unsigned)> HandleComment)
Definition CFGPrinter.h:150
LLVM_ABI uint64_t getMaxFreq(const Function &F, const BlockFrequencyInfo *BFI)
Definition HeatUtils.cpp:49
DOTGraphTraits - Template class that can be specialized to customize how graphs are converted to 'dot...
static bool isNodeHidden(const void *, const GraphType &)
isNodeHidden - If the function returns true, the given node is not displayed in the graph.