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