Move the getAnalysisUsage method from the header file
[oota-llvm.git] / lib / Analysis / DataStructure / Printer.cpp
1 //===- Printer.cpp - Code for printing data structure graphs nicely -------===//
2 //
3 // This file implements the 'dot' graph printer.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "llvm/Analysis/DataStructure.h"
8 #include "llvm/Analysis/DSGraph.h"
9 #include "llvm/Analysis/DSGraphTraits.h"
10 #include "llvm/Module.h"
11 #include "llvm/Constants.h"
12 #include "llvm/Assembly/Writer.h"
13 #include "Support/CommandLine.h"
14 #include "Support/GraphWriter.h"
15 #include "Support/Statistic.h"
16 #include <fstream>
17 #include <sstream>
18
19 // OnlyPrintMain - The DataStructure printer exposes this option to allow
20 // printing of only the graph for "main".
21 //
22 namespace {
23   cl::opt<bool> OnlyPrintMain("only-print-main-ds", cl::ReallyHidden);
24   Statistic<> MaxGraphSize   ("dsnode", "Maximum graph size");
25   Statistic<> NumFoldedNodes ("dsnode", "Number of folded nodes (in final graph)");
26 }
27
28
29 void DSNode::dump() const { print(std::cerr, 0); }
30
31 static std::string getCaption(const DSNode *N, const DSGraph *G) {
32   std::stringstream OS;
33   Module *M = 0;
34   // Get the module from ONE of the functions in the graph it is available.
35   if (G && !G->getReturnNodes().empty())
36     M = G->getReturnNodes().begin()->first->getParent();
37
38   if (N->isNodeCompletelyFolded())
39     OS << "COLLAPSED";
40   else {
41     WriteTypeSymbolic(OS, N->getType(), M);
42     if (N->isArray())
43       OS << " array";
44   }
45   if (unsigned NodeType = N->getNodeFlags()) {
46     OS << ": ";
47     if (NodeType & DSNode::AllocaNode ) OS << "S";
48     if (NodeType & DSNode::HeapNode   ) OS << "H";
49     if (NodeType & DSNode::GlobalNode ) OS << "G";
50     if (NodeType & DSNode::UnknownNode) OS << "U";
51     if (NodeType & DSNode::Incomplete ) OS << "I";
52     if (NodeType & DSNode::Modified   ) OS << "M";
53     if (NodeType & DSNode::Read       ) OS << "R";
54 #ifndef NDEBUG
55     if (NodeType & DSNode::DEAD       ) OS << "<dead>";
56 #endif
57     OS << "\n";
58   }
59
60   for (unsigned i = 0, e = N->getGlobals().size(); i != e; ++i) {
61     WriteAsOperand(OS, N->getGlobals()[i], false, true, M);
62     OS << "\n";
63   }
64
65   return OS.str();
66 }
67
68 template<>
69 struct DOTGraphTraits<const DSGraph*> : public DefaultDOTGraphTraits {
70   static std::string getGraphName(const DSGraph *G) {
71     switch (G->getReturnNodes().size()) {
72     case 0: return G->getFunctionNames();
73     case 1: return "Function " + G->getFunctionNames();
74     default: return "Functions: " + G->getFunctionNames();
75     }
76   }
77
78   static const char *getGraphProperties(const DSGraph *G) {
79     return "\tsize=\"10,7.5\";\n"
80            "\trotate=\"90\";\n";
81   }
82
83   static std::string getNodeLabel(const DSNode *Node, const DSGraph *Graph) {
84     return getCaption(Node, Graph);
85   }
86
87   static std::string getNodeAttributes(const DSNode *N) {
88     return "shape=Mrecord";//fontname=Courier";
89   }
90   
91   /// addCustomGraphFeatures - Use this graph writing hook to emit call nodes
92   /// and the return node.
93   ///
94   static void addCustomGraphFeatures(const DSGraph *G,
95                                      GraphWriter<const DSGraph*> &GW) {
96     Module *CurMod = 0;
97     if (!G->getReturnNodes().empty())
98       CurMod = G->getReturnNodes().begin()->first->getParent();
99
100     // Add scalar nodes to the graph...
101     const DSGraph::ScalarMapTy &VM = G->getScalarMap();
102     for (DSGraph::ScalarMapTy::const_iterator I = VM.begin(); I != VM.end();++I)
103       if (!isa<GlobalValue>(I->first) && !isa<ConstantPointerRef>(I->first)) {
104         std::stringstream OS;
105         WriteAsOperand(OS, I->first, false, true, CurMod);
106         GW.emitSimpleNode(I->first, "", OS.str());
107         
108         // Add edge from return node to real destination
109         int EdgeDest = I->second.getOffset() >> DS::PointerShift;
110         if (EdgeDest == 0) EdgeDest = -1;
111         GW.emitEdge(I->first, -1, I->second.getNode(),
112                     EdgeDest, "arrowtail=tee,color=gray63");
113       }
114
115
116     // Output the returned value pointer...
117     const DSGraph::ReturnNodesTy &RetNodes = G->getReturnNodes();
118     for (DSGraph::ReturnNodesTy::const_iterator I = RetNodes.begin(),
119            E = RetNodes.end(); I != E; ++I)
120       if (I->second.getNode()) {
121         std::string Label;
122         if (RetNodes.size() == 1)
123           Label = "returning";
124         else
125           Label = I->first->getName() + " ret node";
126         // Output the return node...
127         GW.emitSimpleNode((void*)1, "plaintext=circle", Label);
128
129         // Add edge from return node to real destination
130         int RetEdgeDest = I->second.getOffset() >> DS::PointerShift;;
131         if (RetEdgeDest == 0) RetEdgeDest = -1;
132         GW.emitEdge((void*)1, -1, I->second.getNode(),
133                     RetEdgeDest, "arrowtail=tee,color=gray63");
134       }
135
136     // Output all of the call nodes...
137     const std::vector<DSCallSite> &FCs =
138       G->shouldPrintAuxCalls() ? G->getAuxFunctionCalls()
139       : G->getFunctionCalls();
140     for (unsigned i = 0, e = FCs.size(); i != e; ++i) {
141       const DSCallSite &Call = FCs[i];
142       std::vector<std::string> EdgeSourceCaptions(Call.getNumPtrArgs()+2);
143       EdgeSourceCaptions[0] = "r";
144       if (Call.isDirectCall())
145         EdgeSourceCaptions[1] = Call.getCalleeFunc()->getName();
146       else
147         EdgeSourceCaptions[1] = "f";
148
149       GW.emitSimpleNode(&Call, "shape=record", "call", Call.getNumPtrArgs()+2,
150                         &EdgeSourceCaptions);
151
152       if (DSNode *N = Call.getRetVal().getNode()) {
153         int EdgeDest = Call.getRetVal().getOffset() >> DS::PointerShift;
154         if (EdgeDest == 0) EdgeDest = -1;
155         GW.emitEdge(&Call, 0, N, EdgeDest, "color=gray63,tailclip=false");
156       }
157
158       // Print out the callee...
159       if (Call.isIndirectCall()) {
160         DSNode *N = Call.getCalleeNode();
161         assert(N && "Null call site callee node!");
162         GW.emitEdge(&Call, 1, N, -1, "color=gray63,tailclip=false");
163       }
164
165       for (unsigned j = 0, e = Call.getNumPtrArgs(); j != e; ++j)
166         if (DSNode *N = Call.getPtrArg(j).getNode()) {
167           int EdgeDest = Call.getPtrArg(j).getOffset() >> DS::PointerShift;
168           if (EdgeDest == 0) EdgeDest = -1;
169           GW.emitEdge(&Call, j+2, N, EdgeDest, "color=gray63,tailclip=false");
170         }
171     }
172   }
173 };
174
175 void DSNode::print(std::ostream &O, const DSGraph *G) const {
176   GraphWriter<const DSGraph *> W(O, G);
177   W.writeNode(this);
178 }
179
180 void DSGraph::print(std::ostream &O) const {
181   WriteGraph(O, this, "DataStructures");
182 }
183
184 void DSGraph::writeGraphToFile(std::ostream &O,
185                                const std::string &GraphName) const {
186   std::string Filename = GraphName + ".dot";
187   O << "Writing '" << Filename << "'...";
188   std::ofstream F(Filename.c_str());
189   
190   if (F.good()) {
191     print(F);
192     unsigned NumCalls = shouldPrintAuxCalls() ?
193       getAuxFunctionCalls().size() : getFunctionCalls().size();
194     O << " [" << getGraphSize() << "+" << NumCalls << "]\n";
195   } else {
196     O << "  error opening file for writing!\n";
197   }
198 }
199
200 /// viewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
201 /// then cleanup.  For use from the debugger.
202 ///
203 void DSGraph::viewGraph() const {
204   std::ofstream F("/tmp/tempgraph.dot");
205   if (!F.good()) {
206     std::cerr << "Error opening '/tmp/tempgraph.dot' for temporary graph!\n";
207     return;
208   }
209   print(F);
210   F.close();
211   if (system("dot -Tps /tmp/tempgraph.dot > /tmp/tempgraph.ps"))
212     std::cerr << "Error running dot: 'dot' not in path?\n";
213   system("gv /tmp/tempgraph.ps");
214   system("rm /tmp/tempgraph.dot /tmp/tempgraph.ps");
215 }
216
217
218 template <typename Collection>
219 static void printCollection(const Collection &C, std::ostream &O,
220                             const Module *M, const std::string &Prefix) {
221   if (M == 0) {
222     O << "Null Module pointer, cannot continue!\n";
223     return;
224   }
225
226   unsigned TotalNumNodes = 0, TotalCallNodes = 0;
227   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
228     if (C.hasGraph(*I)) {
229       DSGraph &Gr = C.getDSGraph((Function&)*I);
230       TotalNumNodes += Gr.getGraphSize();
231       unsigned NumCalls = Gr.shouldPrintAuxCalls() ?
232         Gr.getAuxFunctionCalls().size() : Gr.getFunctionCalls().size();
233
234       TotalCallNodes += NumCalls;
235       if (I->getName() == "main" || !OnlyPrintMain)
236         Gr.writeGraphToFile(O, Prefix+I->getName());
237       else {
238         O << "Skipped Writing '" << Prefix+I->getName() << ".dot'... ["
239           << Gr.getGraphSize() << "+" << NumCalls << "]\n";
240       }
241
242       if (MaxGraphSize < Gr.getNodes().size())
243         MaxGraphSize = Gr.getNodes().size();
244       for (unsigned i = 0, e = Gr.getNodes().size(); i != e; ++i)
245         if (Gr.getNodes()[i]->isNodeCompletelyFolded())
246           ++NumFoldedNodes;
247     }
248
249   DSGraph &GG = C.getGlobalsGraph();
250   TotalNumNodes  += GG.getGraphSize();
251   TotalCallNodes += GG.getFunctionCalls().size();
252   if (!OnlyPrintMain) {
253     GG.writeGraphToFile(O, Prefix+"GlobalsGraph");
254   } else {
255     O << "Skipped Writing '" << Prefix << "GlobalsGraph.dot'... ["
256       << GG.getGraphSize() << "+" << GG.getFunctionCalls().size() << "]\n";
257   }
258
259   O << "\nGraphs contain [" << TotalNumNodes << "+" << TotalCallNodes 
260     << "] nodes total" << std::endl;
261 }
262
263
264 // print - Print out the analysis results...
265 void LocalDataStructures::print(std::ostream &O, const Module *M) const {
266   printCollection(*this, O, M, "ds.");
267 }
268
269 void BUDataStructures::print(std::ostream &O, const Module *M) const {
270   printCollection(*this, O, M, "bu.");
271 }
272
273 void TDDataStructures::print(std::ostream &O, const Module *M) const {
274   printCollection(*this, O, M, "td.");
275 }