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 
20 #include "llvm/Analysis/CFGPrinter.h"
21 #include "llvm/InitializePasses.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/FileSystem.h"
25 using namespace llvm;
26 
27 static cl::opt<std::string> CFGFuncName(
28     "cfg-func-name", cl::Hidden,
29     cl::desc("The name of a function (or its substring)"
30              " whose CFG is viewed/printed."));
31 
32 static cl::opt<std::string> CFGDotFilenamePrefix(
33     "cfg-dot-filename-prefix", cl::Hidden,
34     cl::desc("The prefix used for the CFG dot file names."));
35 
36 namespace {
37   struct CFGViewerLegacyPass : public FunctionPass {
38     static char ID; // Pass identifcation, replacement for typeid
39     CFGViewerLegacyPass() : FunctionPass(ID) {
40       initializeCFGViewerLegacyPassPass(*PassRegistry::getPassRegistry());
41     }
42 
43     bool runOnFunction(Function &F) override {
44       F.viewCFG();
45       return false;
46     }
47 
48     void print(raw_ostream &OS, const Module* = nullptr) const override {}
49 
50     void getAnalysisUsage(AnalysisUsage &AU) const override {
51       AU.setPreservesAll();
52     }
53   };
54 }
55 
56 char CFGViewerLegacyPass::ID = 0;
57 INITIALIZE_PASS(CFGViewerLegacyPass, "view-cfg", "View CFG of function", false, true)
58 
59 PreservedAnalyses CFGViewerPass::run(Function &F,
60                                      FunctionAnalysisManager &AM) {
61   F.viewCFG();
62   return PreservedAnalyses::all();
63 }
64 
65 
66 namespace {
67   struct CFGOnlyViewerLegacyPass : public FunctionPass {
68     static char ID; // Pass identifcation, replacement for typeid
69     CFGOnlyViewerLegacyPass() : FunctionPass(ID) {
70       initializeCFGOnlyViewerLegacyPassPass(*PassRegistry::getPassRegistry());
71     }
72 
73     bool runOnFunction(Function &F) override {
74       F.viewCFGOnly();
75       return false;
76     }
77 
78     void print(raw_ostream &OS, const Module* = nullptr) const override {}
79 
80     void getAnalysisUsage(AnalysisUsage &AU) const override {
81       AU.setPreservesAll();
82     }
83   };
84 }
85 
86 char CFGOnlyViewerLegacyPass::ID = 0;
87 INITIALIZE_PASS(CFGOnlyViewerLegacyPass, "view-cfg-only",
88                 "View CFG of function (with no function bodies)", false, true)
89 
90 PreservedAnalyses CFGOnlyViewerPass::run(Function &F,
91                                          FunctionAnalysisManager &AM) {
92   F.viewCFGOnly();
93   return PreservedAnalyses::all();
94 }
95 
96 static void writeCFGToDotFile(Function &F, bool CFGOnly = false) {
97   if (!CFGFuncName.empty() && !F.getName().contains(CFGFuncName))
98      return;
99   std::string Filename =
100       (CFGDotFilenamePrefix + "." + F.getName() + ".dot").str();
101   errs() << "Writing '" << Filename << "'...";
102 
103   std::error_code EC;
104   raw_fd_ostream File(Filename, EC, sys::fs::OF_Text);
105 
106   if (!EC)
107     WriteGraph(File, (const Function*)&F, CFGOnly);
108   else
109     errs() << "  error opening file for writing!";
110   errs() << "\n";
111 }
112 
113 namespace {
114   struct CFGPrinterLegacyPass : public FunctionPass {
115     static char ID; // Pass identification, replacement for typeid
116     CFGPrinterLegacyPass() : FunctionPass(ID) {
117       initializeCFGPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
118     }
119 
120     bool runOnFunction(Function &F) override {
121       writeCFGToDotFile(F);
122       return false;
123     }
124 
125     void print(raw_ostream &OS, const Module* = nullptr) const override {}
126 
127     void getAnalysisUsage(AnalysisUsage &AU) const override {
128       AU.setPreservesAll();
129     }
130   };
131 }
132 
133 char CFGPrinterLegacyPass::ID = 0;
134 INITIALIZE_PASS(CFGPrinterLegacyPass, "dot-cfg", "Print CFG of function to 'dot' file",
135                 false, true)
136 
137 PreservedAnalyses CFGPrinterPass::run(Function &F,
138                                       FunctionAnalysisManager &AM) {
139   writeCFGToDotFile(F);
140   return PreservedAnalyses::all();
141 }
142 
143 namespace {
144   struct CFGOnlyPrinterLegacyPass : public FunctionPass {
145     static char ID; // Pass identification, replacement for typeid
146     CFGOnlyPrinterLegacyPass() : FunctionPass(ID) {
147       initializeCFGOnlyPrinterLegacyPassPass(*PassRegistry::getPassRegistry());
148     }
149 
150     bool runOnFunction(Function &F) override {
151       writeCFGToDotFile(F, /*CFGOnly=*/true);
152       return false;
153     }
154     void print(raw_ostream &OS, const Module* = nullptr) const override {}
155 
156     void getAnalysisUsage(AnalysisUsage &AU) const override {
157       AU.setPreservesAll();
158     }
159   };
160 }
161 
162 char CFGOnlyPrinterLegacyPass::ID = 0;
163 INITIALIZE_PASS(CFGOnlyPrinterLegacyPass, "dot-cfg-only",
164    "Print CFG of function to 'dot' file (with no function bodies)",
165    false, true)
166 
167 PreservedAnalyses CFGOnlyPrinterPass::run(Function &F,
168                                           FunctionAnalysisManager &AM) {
169   writeCFGToDotFile(F, /*CFGOnly=*/true);
170   return PreservedAnalyses::all();
171 }
172 
173 /// viewCFG - This function is meant for use from the debugger.  You can just
174 /// say 'call F->viewCFG()' and a ghostview window should pop up from the
175 /// program, displaying the CFG of the current function.  This depends on there
176 /// being a 'dot' and 'gv' program in your path.
177 ///
178 void Function::viewCFG() const {
179   if (!CFGFuncName.empty() && !getName().contains(CFGFuncName))
180      return;
181   ViewGraph(this, "cfg" + getName());
182 }
183 
184 /// viewCFGOnly - This function is meant for use from the debugger.  It works
185 /// just like viewCFG, but it does not include the contents of basic blocks
186 /// into the nodes, just the label.  If you are only interested in the CFG
187 /// this can make the graph smaller.
188 ///
189 void Function::viewCFGOnly() const {
190   if (!CFGFuncName.empty() && !getName().contains(CFGFuncName))
191      return;
192   ViewGraph(this, "cfg" + getName(), true);
193 }
194 
195 FunctionPass *llvm::createCFGPrinterLegacyPassPass () {
196   return new CFGPrinterLegacyPass();
197 }
198 
199 FunctionPass *llvm::createCFGOnlyPrinterLegacyPassPass () {
200   return new CFGOnlyPrinterLegacyPass();
201 }
202 
203