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 : F(F), BFI(BFI), BPI(BPI), MaxFreq(MaxFreq) {
97 ShowHeat = false;
98 EdgeWeights = !!BPI; // Print EdgeWeights when BPI is available.
99 RawWeights = !!BFI; // Print RawWeights when BFI is available.
100}
101
102DOTFuncInfo::~DOTFuncInfo() = default;
103
105 if (!MSTStorage)
106 MSTStorage = std::make_unique<ModuleSlotTracker>(F->getParent());
107 return &*MSTStorage;
108}
109
111 if (!CFGFuncName.empty() && !F.getName().contains(CFGFuncName))
112 return PreservedAnalyses::all();
113 auto *BFI = &AM.getResult<BlockFrequencyAnalysis>(F);
114 auto *BPI = &AM.getResult<BranchProbabilityAnalysis>(F);
115 viewCFG(F, BFI, BPI, getMaxFreq(F, BFI));
116 return PreservedAnalyses::all();
117}
118
121 if (!CFGFuncName.empty() && !F.getName().contains(CFGFuncName))
122 return PreservedAnalyses::all();
123 auto *BFI = &AM.getResult<BlockFrequencyAnalysis>(F);
124 auto *BPI = &AM.getResult<BranchProbabilityAnalysis>(F);
125 viewCFG(F, BFI, BPI, getMaxFreq(F, BFI), /*CFGOnly=*/true);
126 return PreservedAnalyses::all();
127}
128
131 if (!CFGFuncName.empty() && !F.getName().contains(CFGFuncName))
132 return PreservedAnalyses::all();
133 auto *BFI = &AM.getResult<BlockFrequencyAnalysis>(F);
134 auto *BPI = &AM.getResult<BranchProbabilityAnalysis>(F);
135 writeCFGToDotFile(F, BFI, BPI, getMaxFreq(F, BFI));
136 return PreservedAnalyses::all();
137}
138
141 if (!CFGFuncName.empty() && !F.getName().contains(CFGFuncName))
142 return PreservedAnalyses::all();
143 auto *BFI = &AM.getResult<BlockFrequencyAnalysis>(F);
144 auto *BPI = &AM.getResult<BranchProbabilityAnalysis>(F);
145 writeCFGToDotFile(F, BFI, BPI, getMaxFreq(F, BFI), /*CFGOnly=*/true);
146 return PreservedAnalyses::all();
147}
148
149/// viewCFG - This function is meant for use from the debugger. You can just
150/// say 'call F->viewCFG()' and a ghostview window should pop up from the
151/// program, displaying the CFG of the current function. This depends on there
152/// being a 'dot' and 'gv' program in your path.
153///
154void Function::viewCFG() const { viewCFG(false, nullptr, nullptr); }
155
156void Function::viewCFG(const char *OutputFileName) const {
157 viewCFG(false, nullptr, nullptr, OutputFileName);
158}
159
160void Function::viewCFG(bool ViewCFGOnly, const BlockFrequencyInfo *BFI,
161 const BranchProbabilityInfo *BPI,
162 const char *OutputFileName) const {
163 if (!CFGFuncName.empty() && !getName().contains(CFGFuncName))
164 return;
165 DOTFuncInfo CFGInfo(this, BFI, BPI, BFI ? getMaxFreq(*this, BFI) : 0);
166 ViewGraph(&CFGInfo, OutputFileName ? OutputFileName : "cfg" + getName(),
167 ViewCFGOnly);
168}
169
170/// viewCFGOnly - This function is meant for use from the debugger. It works
171/// just like viewCFG, but it does not include the contents of basic blocks
172/// into the nodes, just the label. If you are only interested in the CFG
173/// this can make the graph smaller.
174///
175void Function::viewCFGOnly() const { viewCFGOnly(nullptr, nullptr); }
176
177void Function::viewCFGOnly(const char *OutputFileName) const {
178 viewCFG(true, nullptr, nullptr, OutputFileName);
179}
180
182 const BranchProbabilityInfo *BPI) const {
183 viewCFG(true, BFI, BPI);
184}
185
186/// Find all blocks on the paths which terminate with a deoptimize or
187/// unreachable (i.e. all blocks which are post-dominated by a deoptimize
188/// or unreachable). These paths are hidden if the corresponding cl::opts
189/// are enabled.
191 const Function *F) {
192 auto evaluateBB = [&](const BasicBlock *Node) {
193 if (succ_empty(Node)) {
194 const Instruction *TI = Node->getTerminator();
195 isOnDeoptOrUnreachablePath[Node] =
196 (HideUnreachablePaths && isa<UnreachableInst>(TI)) ||
197 (HideDeoptimizePaths && Node->getTerminatingDeoptimizeCall());
198 return;
199 }
200 isOnDeoptOrUnreachablePath[Node] =
201 llvm::all_of(successors(Node), [this](const BasicBlock *BB) {
202 return isOnDeoptOrUnreachablePath[BB];
203 });
204 };
205 /// The post order traversal iteration is done to know the status of
206 /// isOnDeoptOrUnreachablePath for all the successors on the current BB.
207 llvm::for_each(post_order(&F->getEntryBlock()), evaluateBB);
208}
209
211 const DOTFuncInfo *CFGInfo) {
212 if (HideColdPaths.getNumOccurrences() > 0)
213 if (auto *BFI = CFGInfo->getBFI()) {
214 BlockFrequency NodeFreq = BFI->getBlockFreq(Node);
215 BlockFrequency EntryFreq = BFI->getEntryFreq();
216 // Hide blocks with relative frequency below HideColdPaths threshold.
217 if ((double)NodeFreq.getFrequency() / EntryFreq.getFrequency() <
219 return true;
220 }
222 if (!isOnDeoptOrUnreachablePath.contains(Node))
223 computeDeoptOrUnreachablePaths(Node->getParent());
224 return isOnDeoptOrUnreachablePath[Node];
225 }
226 return false;
227}
228
230 const BasicBlock *Node, DOTFuncInfo *CFGInfo,
232 HandleBasicBlock,
233 function_ref<void(std::string &, unsigned &, unsigned)> HandleComment) {
234 if (HandleBasicBlock)
235 return CompleteNodeLabelString(Node, HandleBasicBlock, HandleComment);
236
237 // Default basic block printing
238 std::optional<ModuleSlotTracker> MSTStorage;
239 ModuleSlotTracker *MST = nullptr;
240
241 if (CFGInfo) {
242 MST = CFGInfo->getModuleSlotTracker();
243 } else {
244 MSTStorage.emplace(Node->getModule());
245 MST = &*MSTStorage;
246 }
247
249 Node,
251 [MST](raw_string_ostream &OS, const BasicBlock &Node) -> void {
252 // Prepend label name
253 Node.printAsOperand(OS, false, *MST);
254 OS << ":\n";
255
256 for (const Instruction &Inst : Node) {
257 Inst.print(OS, *MST, /* IsForDebug */ false);
258 OS << '\n';
259 }
260 }),
261 HandleComment);
262}
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:61
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:83
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.
raw_pwrite_stream & OS
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition: Value.cpp:480
void printAsOperand(OutputBuffer &OB, Prec P=Prec::Default, bool StrictlyWorse=false) const
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:255
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:412
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)
Definition: CFGPrinter.cpp:139
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition: CFGPrinter.cpp:119
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition: CFGPrinter.cpp:129
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition: CFGPrinter.cpp:110
void setRawEdgeWeights(bool RawWeights)
Definition: CFGPrinter.h:98
LLVM_ABI ~DOTFuncInfo()
void setEdgeWeights(bool EdgeWeights)
Definition: CFGPrinter.h:102
DOTFuncInfo(const Function *F)
Definition: CFGPrinter.h:74
LLVM_ABI ModuleSlotTracker * getModuleSlotTracker()
Definition: CFGPrinter.cpp:104
const BlockFrequencyInfo * getBFI() const
Definition: CFGPrinter.h:80
void setHeatColors(bool ShowHeat)
Definition: CFGPrinter.h:94
void viewCFG() const
viewCFG - This function is meant for use from the debugger.
Definition: CFGPrinter.cpp:154
void viewCFGOnly() const
viewCFGOnly - This function is meant for use from the debugger.
Definition: CFGPrinter.cpp:175
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:663
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.
Definition: raw_ostream.h:461
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:662
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:444
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
Definition: FileSystem.h:762
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:1737
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:1744
bool succ_empty(const Instruction *I)
Definition: CFG.h:256
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:376
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.
Definition: GraphWriter.h:443
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:142
LLVM_ABI 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.