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