Finegrainify namespacification
[oota-llvm.git] / lib / Analysis / CFGPrinter.cpp
1 //===- CFGPrinter.cpp - DOT printer for the control flow graph ------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a '-print-cfg' analysis pass, which emits the
11 // cfg.<fnname>.dot file for each function in the program, with a graph of the
12 // CFG for that function.
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 "Support/GraphWriter.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Function.h"
23 #include "llvm/iTerminators.h"
24 #include "llvm/Assembly/Writer.h"
25 #include "llvm/Support/CFG.h"
26 #include <sstream>
27 #include <fstream>
28 using namespace llvm;
29
30 /// CFGOnly flag - This is used to control whether or not the CFG graph printer
31 /// prints out the contents of basic blocks or not.  This is acceptable because
32 /// this code is only really used for debugging purposes.
33 ///
34 static bool CFGOnly = false;
35
36 namespace llvm {
37 template<>
38 struct DOTGraphTraits<const Function*> : public DefaultDOTGraphTraits {
39   static std::string getGraphName(const Function *F) {
40     return "CFG for '" + F->getName() + "' function";
41   }
42
43   static std::string getNodeLabel(const BasicBlock *Node,
44                                   const Function *Graph) {
45     if (CFGOnly && !Node->getName().empty())
46       return Node->getName() + ":";
47
48     std::ostringstream Out;
49     if (CFGOnly) {
50       WriteAsOperand(Out, Node, false, true);
51       return Out.str();
52     }
53
54     if (Node->getName().empty()) {
55       WriteAsOperand(Out, Node, false, true);
56       Out << ":";
57     }
58
59     Out << *Node;
60     std::string OutStr = Out.str();
61     if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
62
63     // Process string output to make it nicer...
64     for (unsigned i = 0; i != OutStr.length(); ++i)
65       if (OutStr[i] == '\n') {                            // Left justify
66         OutStr[i] = '\\';
67         OutStr.insert(OutStr.begin()+i+1, 'l');
68       } else if (OutStr[i] == ';') {                      // Delete comments!
69         unsigned Idx = OutStr.find('\n', i+1);            // Find end of line
70         OutStr.erase(OutStr.begin()+i, OutStr.begin()+Idx);
71         --i;
72       }
73
74     return OutStr;
75   }
76
77   static std::string getNodeAttributes(const BasicBlock *N) {
78     return "fontname=Courier";
79   }
80   
81   static std::string getEdgeSourceLabel(const BasicBlock *Node,
82                                         succ_const_iterator I) {
83     // Label source of conditional branches with "T" or "F"
84     if (const BranchInst *BI = dyn_cast<BranchInst>(Node->getTerminator()))
85       if (BI->isConditional())
86         return (I == succ_begin(Node)) ? "T" : "F";
87     return "";
88   }
89 };
90 }
91
92 namespace {
93   struct CFGPrinter : public FunctionPass {
94     virtual bool runOnFunction(Function &F) {
95       std::string Filename = "cfg." + F.getName() + ".dot";
96       std::cerr << "Writing '" << Filename << "'...";
97       std::ofstream File(Filename.c_str());
98       
99       if (File.good())
100         WriteGraph(File, (const Function*)&F);
101       else
102         std::cerr << "  error opening file for writing!";
103       std::cerr << "\n";
104       return false;
105     }
106
107     void print(std::ostream &OS) const {}
108     
109     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
110       AU.setPreservesAll();
111     }
112   };
113
114   RegisterAnalysis<CFGPrinter> P1("print-cfg",
115                                   "Print CFG of function to 'dot' file");
116
117   struct CFGOnlyPrinter : public CFGPrinter {
118     virtual bool runOnFunction(Function &F) {
119       bool OldCFGOnly = CFGOnly;
120       CFGOnly = true;
121       CFGPrinter::runOnFunction(F);
122       CFGOnly = OldCFGOnly;
123       return false;
124     }
125     void print(std::ostream &OS) const {}
126     
127     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
128       AU.setPreservesAll();
129     }
130   };
131
132   RegisterAnalysis<CFGOnlyPrinter>
133   P2("print-cfg-only",
134      "Print CFG of function to 'dot' file (with no function bodies)");
135 }
136
137 /// viewCFG - This function is meant for use from the debugger.  You can just
138 /// say 'call F->viewCFG()' and a ghostview window should pop up from the
139 /// program, displaying the CFG of the current function.  This depends on there
140 /// being a 'dot' and 'gv' program in your path.
141 ///
142 void Function::viewCFG() const {
143   std::string Filename = "/tmp/cfg." + getName() + ".dot";
144   std::cerr << "Writing '" << Filename << "'... ";
145   std::ofstream F(Filename.c_str());
146   
147   if (!F.good()) {
148     std::cerr << "  error opening file for writing!\n";
149     return;
150   }
151
152   WriteGraph(F, this);
153   F.close();
154   std::cerr << "\n";
155
156   std::cerr << "Running 'dot' program... " << std::flush;
157   if (system(("dot -Tps " + Filename + " > /tmp/cfg.tempgraph.ps").c_str())) {
158     std::cerr << "Error running dot: 'dot' not in path?\n";
159   } else {
160     std::cerr << "\n";
161     system("gv /tmp/cfg.tempgraph.ps");
162   }
163   system(("rm " + Filename + " /tmp/cfg.tempgraph.ps").c_str());
164 }
165
166 /// viewCFGOnly - This function is meant for use from the debugger.  It works
167 /// just like viewCFG, but it does not include the contents of basic blocks
168 /// into the nodes, just the label.  If you are only interested in the CFG t
169 /// his can make the graph smaller.
170 ///
171 void Function::viewCFGOnly() const {
172   CFGOnly = true;
173   viewCFG();
174   CFGOnly = false;
175 }