LLVM 22.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
26
27using namespace llvm;
28
30 CFGFuncName("cfg-func-name", cl::Hidden,
31 cl::desc("The name of a function (or its substring)"
32 " whose CFG is viewed/printed."));
33
35 "cfg-dot-filename-prefix", cl::Hidden,
36 cl::desc("The prefix used for the CFG dot file names."));
37
38static cl::opt<bool> HideUnreachablePaths("cfg-hide-unreachable-paths",
39 cl::init(false));
40
41static cl::opt<bool> HideDeoptimizePaths("cfg-hide-deoptimize-paths",
42 cl::init(false));
43
45 "cfg-hide-cold-paths", cl::init(0.0),
46 cl::desc("Hide blocks with relative frequency below the given value"));
47
48static cl::opt<bool> ShowHeatColors("cfg-heat-colors", cl::init(true),
50 cl::desc("Show heat colors in CFG"));
51
52static cl::opt<bool> UseRawEdgeWeight("cfg-raw-weights", cl::init(false),
54 cl::desc("Use raw weights for labels. "
55 "Use percentages as default."));
56
57static cl::opt<bool>
58 ShowEdgeWeight("cfg-weights", cl::init(false), cl::Hidden,
59 cl::desc("Show edges labeled with weights"));
60
62 BranchProbabilityInfo *BPI, uint64_t MaxFreq,
63 bool CFGOnly = false) {
64 std::string Filename =
65 (CFGDotFilenamePrefix + "." + F.getName() + ".dot").str();
66 errs() << "Writing '" << Filename << "'...";
67
68 std::error_code EC;
69 raw_fd_ostream File(Filename, EC, sys::fs::OF_Text);
70
71 DOTFuncInfo CFGInfo(&F, BFI, BPI, MaxFreq);
75
76 if (!EC)
77 WriteGraph(File, &CFGInfo, CFGOnly);
78 else
79 errs() << " error opening file for writing!";
80 errs() << "\n";
81}
82
83static void viewCFG(Function &F, const BlockFrequencyInfo *BFI,
84 const BranchProbabilityInfo *BPI, uint64_t MaxFreq,
85 bool CFGOnly = false) {
86 DOTFuncInfo CFGInfo(&F, BFI, BPI, MaxFreq);
90
91 ViewGraph(&CFGInfo, "cfg." + F.getName(), CFGOnly);
92}
93
95 const BranchProbabilityInfo *BPI, uint64_t MaxFreq,
96 std::optional<NodeIdFormatterTy> NodeIdFormatter)
97 : F(F), BFI(BFI), BPI(BPI), MaxFreq(MaxFreq),
98 NodeIdFormatter(NodeIdFormatter) {
99 ShowHeat = false;
100 EdgeWeights = !!BPI; // Print EdgeWeights when BPI is available.
101 RawWeights = !!BFI; // Print RawWeights when BFI is available.
102}
103
104DOTFuncInfo::~DOTFuncInfo() = default;
105
107 if (!MSTStorage)
108 MSTStorage = std::make_unique<ModuleSlotTracker>(F->getParent());
109 return &*MSTStorage;
110}
111
113 if (!CFGFuncName.empty() && !F.getName().contains(CFGFuncName))
114 return PreservedAnalyses::all();
115 auto *BFI = &AM.getResult<BlockFrequencyAnalysis>(F);
116 auto *BPI = &AM.getResult<BranchProbabilityAnalysis>(F);
117 viewCFG(F, BFI, BPI, getMaxFreq(F, BFI));
118 return PreservedAnalyses::all();
119}
120
123 if (!CFGFuncName.empty() && !F.getName().contains(CFGFuncName))
124 return PreservedAnalyses::all();
125 auto *BFI = &AM.getResult<BlockFrequencyAnalysis>(F);
126 auto *BPI = &AM.getResult<BranchProbabilityAnalysis>(F);
127 viewCFG(F, BFI, BPI, getMaxFreq(F, BFI), /*CFGOnly=*/true);
128 return PreservedAnalyses::all();
129}
130
133 if (!CFGFuncName.empty() && !F.getName().contains(CFGFuncName))
134 return PreservedAnalyses::all();
135 auto *BFI = &AM.getResult<BlockFrequencyAnalysis>(F);
136 auto *BPI = &AM.getResult<BranchProbabilityAnalysis>(F);
137 writeCFGToDotFile(F, BFI, BPI, getMaxFreq(F, BFI));
138 return PreservedAnalyses::all();
139}
140
143 if (!CFGFuncName.empty() && !F.getName().contains(CFGFuncName))
144 return PreservedAnalyses::all();
145 auto *BFI = &AM.getResult<BlockFrequencyAnalysis>(F);
146 auto *BPI = &AM.getResult<BranchProbabilityAnalysis>(F);
147 writeCFGToDotFile(F, BFI, BPI, getMaxFreq(F, BFI), /*CFGOnly=*/true);
148 return PreservedAnalyses::all();
149}
150
151/// viewCFG - This function is meant for use from the debugger. You can just
152/// say 'call F->viewCFG()' and a ghostview window should pop up from the
153/// program, displaying the CFG of the current function. This depends on there
154/// being a 'dot' and 'gv' program in your path.
155///
156void Function::viewCFG() const { viewCFG(false, nullptr, nullptr); }
157
158void Function::viewCFG(const char *OutputFileName) const {
159 viewCFG(false, nullptr, nullptr, OutputFileName);
160}
161
162void Function::viewCFG(bool ViewCFGOnly, const BlockFrequencyInfo *BFI,
163 const BranchProbabilityInfo *BPI,
164 const char *OutputFileName) const {
165 if (!CFGFuncName.empty() && !getName().contains(CFGFuncName))
166 return;
167 DOTFuncInfo CFGInfo(this, BFI, BPI, BFI ? getMaxFreq(*this, BFI) : 0);
168 ViewGraph(&CFGInfo, OutputFileName ? OutputFileName : "cfg" + getName(),
169 ViewCFGOnly);
170}
171
172/// viewCFGOnly - This function is meant for use from the debugger. It works
173/// just like viewCFG, but it does not include the contents of basic blocks
174/// into the nodes, just the label. If you are only interested in the CFG
175/// this can make the graph smaller.
176///
177void Function::viewCFGOnly() const { viewCFGOnly(nullptr, nullptr); }
178
179void Function::viewCFGOnly(const char *OutputFileName) const {
180 viewCFG(true, nullptr, nullptr, OutputFileName);
181}
182
184 const BranchProbabilityInfo *BPI) const {
185 viewCFG(true, BFI, BPI);
186}
187
188/// Find all blocks on the paths which terminate with a deoptimize or
189/// unreachable (i.e. all blocks which are post-dominated by a deoptimize
190/// or unreachable). These paths are hidden if the corresponding cl::opts
191/// are enabled.
193 const Function *F) {
194 auto evaluateBB = [&](const BasicBlock *Node) {
195 if (succ_empty(Node)) {
196 const Instruction *TI = Node->getTerminator();
197 isOnDeoptOrUnreachablePath[Node] =
199 (HideDeoptimizePaths && Node->getTerminatingDeoptimizeCall());
200 return;
201 }
202 isOnDeoptOrUnreachablePath[Node] =
203 llvm::all_of(successors(Node), [this](const BasicBlock *BB) {
204 return isOnDeoptOrUnreachablePath[BB];
205 });
206 };
207 /// The post order traversal iteration is done to know the status of
208 /// isOnDeoptOrUnreachablePath for all the successors on the current BB.
209 llvm::for_each(post_order(&F->getEntryBlock()), evaluateBB);
210}
211
213 const DOTFuncInfo *CFGInfo) {
214 if (HideColdPaths.getNumOccurrences() > 0)
215 if (auto *BFI = CFGInfo->getBFI()) {
216 BlockFrequency NodeFreq = BFI->getBlockFreq(Node);
217 BlockFrequency EntryFreq = BFI->getEntryFreq();
218 // Hide blocks with relative frequency below HideColdPaths threshold.
219 if ((double)NodeFreq.getFrequency() / EntryFreq.getFrequency() <
221 return true;
222 }
224 if (!isOnDeoptOrUnreachablePath.contains(Node))
225 computeDeoptOrUnreachablePaths(Node->getParent());
226 return isOnDeoptOrUnreachablePath[Node];
227 }
228 return false;
229}
230
232 const BasicBlock *Node, DOTFuncInfo *CFGInfo,
234 HandleBasicBlock,
235 function_ref<void(std::string &, unsigned &, unsigned)> HandleComment) {
236 if (HandleBasicBlock)
237 return CompleteNodeLabelString(Node, HandleBasicBlock, HandleComment);
238
239 // Default basic block printing
240 std::optional<ModuleSlotTracker> MSTStorage;
241 ModuleSlotTracker *MST = nullptr;
242
243 if (CFGInfo) {
244 MST = CFGInfo->getModuleSlotTracker();
245 } else {
246 MSTStorage.emplace(Node->getModule());
247 MST = &*MSTStorage;
248 }
249
251 Node,
253 [MST](raw_string_ostream &OS, const BasicBlock &Node) -> void {
254 // Prepend label name
255 Node.printAsOperand(OS, false, *MST);
256 OS << ":\n";
257
258 for (const Instruction &Inst : Node) {
259 Inst.print(OS, *MST, /* IsForDebug */ false);
260 OS << '\n';
261 }
262 }),
263 HandleComment);
264}
static cl::opt< bool > UseRawEdgeWeight("cfg-raw-weights", cl::init(false), cl::Hidden, cl::desc("Use raw weights for labels. " "Use percentages as default."))
static cl::opt< bool > HideUnreachablePaths("cfg-hide-unreachable-paths", cl::init(false))
static void writeCFGToDotFile(Function &F, BlockFrequencyInfo *BFI, BranchProbabilityInfo *BPI, uint64_t MaxFreq, bool CFGOnly=false)
static cl::opt< bool > ShowHeatColors("cfg-heat-colors", cl::init(true), cl::Hidden, cl::desc("Show heat colors in CFG"))
static cl::opt< std::string > CFGDotFilenamePrefix("cfg-dot-filename-prefix", cl::Hidden, cl::desc("The prefix used for the CFG dot file names."))
static void viewCFG(Function &F, const BlockFrequencyInfo *BFI, const BranchProbabilityInfo *BPI, uint64_t MaxFreq, bool CFGOnly=false)
static cl::opt< double > HideColdPaths("cfg-hide-cold-paths", cl::init(0.0), cl::desc("Hide blocks with relative frequency below the given value"))
static cl::opt< bool > HideDeoptimizePaths("cfg-hide-deoptimize-paths", cl::init(false))
static cl::opt< std::string > CFGFuncName("cfg-func-name", cl::Hidden, cl::desc("The name of a function (or its substring)" " whose CFG is viewed/printed."))
static cl::opt< bool > ShowEdgeWeight("cfg-weights", cl::init(false), cl::Hidden, cl::desc("Show edges labeled with weights"))
static cl::opt< bool > ShowHeatColors("callgraph-heat-colors", cl::init(false), cl::Hidden, cl::desc("Show heat colors in call-graph"))
static cl::opt< bool > ShowEdgeWeight("callgraph-show-weights", cl::init(false), cl::Hidden, cl::desc("Show edges labeled with weights"))
#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"))
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:106
LLVM_ABI ~DOTFuncInfo()
void setEdgeWeights(bool EdgeWeights)
Definition CFGPrinter.h:110
DOTFuncInfo(const Function *F)
Definition CFGPrinter.h:80
LLVM_ABI ModuleSlotTracker * getModuleSlotTracker()
const BlockFrequencyInfo * getBFI() const
Definition CFGPrinter.h:88
void setHeatColors(bool ShowHeat)
Definition CFGPrinter.h:102
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
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
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.
initializer< Ty > init(const Ty &Val)
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:755
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:1718
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:1725
bool succ_empty(const Instruction *I)
Definition CFG.h:257
auto successors(const MachineBasicBlock *BB)
iterator_range< po_iterator< T > > post_order(const T &G)
raw_ostream & WriteGraph(raw_ostream &O, const GraphType &G, bool ShortNames=false, const Twine &Title="")
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:154
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.