LLVM 20.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
25
26using namespace llvm;
27
29 CFGFuncName("cfg-func-name", cl::Hidden,
30 cl::desc("The name of a function (or its substring)"
31 " whose CFG is viewed/printed."));
32
34 "cfg-dot-filename-prefix", cl::Hidden,
35 cl::desc("The prefix used for the CFG dot file names."));
36
37static cl::opt<bool> HideUnreachablePaths("cfg-hide-unreachable-paths",
38 cl::init(false));
39
40static cl::opt<bool> HideDeoptimizePaths("cfg-hide-deoptimize-paths",
41 cl::init(false));
42
44 "cfg-hide-cold-paths", cl::init(0.0),
45 cl::desc("Hide blocks with relative frequency below the given value"));
46
47static cl::opt<bool> ShowHeatColors("cfg-heat-colors", cl::init(true),
49 cl::desc("Show heat colors in CFG"));
50
51static cl::opt<bool> UseRawEdgeWeight("cfg-raw-weights", cl::init(false),
53 cl::desc("Use raw weights for labels. "
54 "Use percentages as default."));
55
56static cl::opt<bool>
57 ShowEdgeWeight("cfg-weights", cl::init(false), cl::Hidden,
58 cl::desc("Show edges labeled with weights"));
59
61 BranchProbabilityInfo *BPI, uint64_t MaxFreq,
62 bool CFGOnly = false) {
63 std::string Filename =
64 (CFGDotFilenamePrefix + "." + F.getName() + ".dot").str();
65 errs() << "Writing '" << Filename << "'...";
66
67 std::error_code EC;
68 raw_fd_ostream File(Filename, EC, sys::fs::OF_Text);
69
70 DOTFuncInfo CFGInfo(&F, BFI, BPI, MaxFreq);
74
75 if (!EC)
76 WriteGraph(File, &CFGInfo, CFGOnly);
77 else
78 errs() << " error opening file for writing!";
79 errs() << "\n";
80}
81
82static void viewCFG(Function &F, const BlockFrequencyInfo *BFI,
83 const BranchProbabilityInfo *BPI, uint64_t MaxFreq,
84 bool CFGOnly = false) {
85 DOTFuncInfo CFGInfo(&F, BFI, BPI, MaxFreq);
89
90 ViewGraph(&CFGInfo, "cfg." + F.getName(), CFGOnly);
91}
92
94 if (!CFGFuncName.empty() && !F.getName().contains(CFGFuncName))
96 auto *BFI = &AM.getResult<BlockFrequencyAnalysis>(F);
97 auto *BPI = &AM.getResult<BranchProbabilityAnalysis>(F);
98 viewCFG(F, BFI, BPI, getMaxFreq(F, BFI));
100}
101
104 if (!CFGFuncName.empty() && !F.getName().contains(CFGFuncName))
105 return PreservedAnalyses::all();
106 auto *BFI = &AM.getResult<BlockFrequencyAnalysis>(F);
107 auto *BPI = &AM.getResult<BranchProbabilityAnalysis>(F);
108 viewCFG(F, BFI, BPI, getMaxFreq(F, BFI), /*CFGOnly=*/true);
109 return PreservedAnalyses::all();
110}
111
114 if (!CFGFuncName.empty() && !F.getName().contains(CFGFuncName))
115 return PreservedAnalyses::all();
116 auto *BFI = &AM.getResult<BlockFrequencyAnalysis>(F);
117 auto *BPI = &AM.getResult<BranchProbabilityAnalysis>(F);
118 writeCFGToDotFile(F, BFI, BPI, getMaxFreq(F, BFI));
119 return PreservedAnalyses::all();
120}
121
124 if (!CFGFuncName.empty() && !F.getName().contains(CFGFuncName))
125 return PreservedAnalyses::all();
126 auto *BFI = &AM.getResult<BlockFrequencyAnalysis>(F);
127 auto *BPI = &AM.getResult<BranchProbabilityAnalysis>(F);
128 writeCFGToDotFile(F, BFI, BPI, getMaxFreq(F, BFI), /*CFGOnly=*/true);
129 return PreservedAnalyses::all();
130}
131
132/// viewCFG - This function is meant for use from the debugger. You can just
133/// say 'call F->viewCFG()' and a ghostview window should pop up from the
134/// program, displaying the CFG of the current function. This depends on there
135/// being a 'dot' and 'gv' program in your path.
136///
137void Function::viewCFG() const { viewCFG(false, nullptr, nullptr); }
138
139void Function::viewCFG(const char *OutputFileName) const {
140 viewCFG(false, nullptr, nullptr, OutputFileName);
141}
142
143void Function::viewCFG(bool ViewCFGOnly, const BlockFrequencyInfo *BFI,
144 const BranchProbabilityInfo *BPI,
145 const char *OutputFileName) const {
146 if (!CFGFuncName.empty() && !getName().contains(CFGFuncName))
147 return;
148 DOTFuncInfo CFGInfo(this, BFI, BPI, BFI ? getMaxFreq(*this, BFI) : 0);
149 ViewGraph(&CFGInfo, OutputFileName ? OutputFileName : "cfg" + getName(),
150 ViewCFGOnly);
151}
152
153/// viewCFGOnly - This function is meant for use from the debugger. It works
154/// just like viewCFG, but it does not include the contents of basic blocks
155/// into the nodes, just the label. If you are only interested in the CFG
156/// this can make the graph smaller.
157///
158void Function::viewCFGOnly() const { viewCFGOnly(nullptr, nullptr); }
159
160void Function::viewCFGOnly(const char *OutputFileName) const {
161 viewCFG(true, nullptr, nullptr, OutputFileName);
162}
163
165 const BranchProbabilityInfo *BPI) const {
166 viewCFG(true, BFI, BPI);
167}
168
169/// Find all blocks on the paths which terminate with a deoptimize or
170/// unreachable (i.e. all blocks which are post-dominated by a deoptimize
171/// or unreachable). These paths are hidden if the corresponding cl::opts
172/// are enabled.
174 const Function *F) {
175 auto evaluateBB = [&](const BasicBlock *Node) {
176 if (succ_empty(Node)) {
177 const Instruction *TI = Node->getTerminator();
178 isOnDeoptOrUnreachablePath[Node] =
179 (HideUnreachablePaths && isa<UnreachableInst>(TI)) ||
180 (HideDeoptimizePaths && Node->getTerminatingDeoptimizeCall());
181 return;
182 }
183 isOnDeoptOrUnreachablePath[Node] =
184 llvm::all_of(successors(Node), [this](const BasicBlock *BB) {
185 return isOnDeoptOrUnreachablePath[BB];
186 });
187 };
188 /// The post order traversal iteration is done to know the status of
189 /// isOnDeoptOrUnreachablePath for all the successors on the current BB.
190 llvm::for_each(post_order(&F->getEntryBlock()), evaluateBB);
191}
192
194 const DOTFuncInfo *CFGInfo) {
195 if (HideColdPaths.getNumOccurrences() > 0)
196 if (auto *BFI = CFGInfo->getBFI()) {
197 BlockFrequency NodeFreq = BFI->getBlockFreq(Node);
198 BlockFrequency EntryFreq = BFI->getEntryFreq();
199 // Hide blocks with relative frequency below HideColdPaths threshold.
200 if ((double)NodeFreq.getFrequency() / EntryFreq.getFrequency() <
202 return true;
203 }
205 if (!isOnDeoptOrUnreachablePath.contains(Node))
206 computeDeoptOrUnreachablePaths(Node->getParent());
207 return isOnDeoptOrUnreachablePath[Node];
208 }
209 return false;
210}
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)
Definition: CFGPrinter.cpp:60
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)
Definition: CFGPrinter.cpp:82
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"))
#define F(x, y, z)
Definition: MD5.cpp:55
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 bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition: Value.cpp:469
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:410
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
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.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition: CFGPrinter.cpp:122
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition: CFGPrinter.cpp:102
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition: CFGPrinter.cpp:112
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition: CFGPrinter.cpp:93
void setRawEdgeWeights(bool RawWeights)
Definition: CFGPrinter.h:96
void setEdgeWeights(bool EdgeWeights)
Definition: CFGPrinter.h:100
const BlockFrequencyInfo * getBFI() const
Definition: CFGPrinter.h:80
void setHeatColors(bool ShowHeat)
Definition: CFGPrinter.h:92
void viewCFG() const
viewCFG - This function is meant for use from the debugger.
Definition: CFGPrinter.cpp:137
void viewCFGOnly() const
viewCFGOnly - This function is meant for use from the debugger.
Definition: CFGPrinter.cpp:158
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:460
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
Definition: FileSystem.h:758
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
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:1732
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:1739
bool succ_empty(const Instruction *I)
Definition: CFG.h:255
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="")
Definition: GraphWriter.h:359
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.
Definition: GraphWriter.h:427
uint64_t getMaxFreq(const Function &F, const BlockFrequencyInfo *BFI)
Definition: HeatUtils.cpp:53
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.