cf1a53ebe1ca2c86cddff90b252b361284dddbf7
[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/DataStructure.h"
15 #include "llvm/Analysis/DataStructure/EquivClassGraphs.h"
16 #include "llvm/Analysis/DataStructure/DSGraph.h"
17 #include "llvm/Analysis/DataStructure/DSGraphTraits.h"
18 #include "llvm/Module.h"
19 #include "llvm/Constants.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/GraphWriter.h"
23 #include "llvm/ADT/Statistic.h"
24 #include <fstream>
25 #include <sstream>
26 using 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   cl::opt<bool> DontPrintAnything("dont-print-ds", cl::ReallyHidden);
34   Statistic<> MaxGraphSize   ("dsa", "Maximum graph size");
35   Statistic<> NumFoldedNodes ("dsa", "Number of folded nodes (in final graph)");
36 }
37
38 void DSNode::dump() const { print(std::cerr, 0); }
39
40 static std::string getCaption(const DSNode *N, const DSGraph *G) {
41   std::stringstream OS;
42   Module *M = 0;
43
44   if (!G) G = N->getParentGraph();
45
46   // Get the module from ONE of the functions in the graph it is available.
47   if (G && G->retnodes_begin() != G->retnodes_end())
48     M = G->retnodes_begin()->first->getParent();
49   if (M == 0 && G) {
50     // If there is a global in the graph, we can use it to find the module.
51     const DSScalarMap &SM = G->getScalarMap();
52     if (SM.global_begin() != SM.global_end())
53       M = (*SM.global_begin())->getParent();
54   }
55
56   if (N->isNodeCompletelyFolded())
57     OS << "COLLAPSED";
58   else {
59     WriteTypeSymbolic(OS, N->getType(), M);
60     if (N->isArray())
61       OS << " array";
62   }
63   if (unsigned NodeType = N->getNodeFlags()) {
64     OS << ": ";
65     if (NodeType & DSNode::AllocaNode ) OS << "S";
66     if (NodeType & DSNode::HeapNode   ) OS << "H";
67     if (NodeType & DSNode::GlobalNode ) OS << "G";
68     if (NodeType & DSNode::UnknownNode) OS << "U";
69     if (NodeType & DSNode::Incomplete ) OS << "I";
70     if (NodeType & DSNode::Modified   ) OS << "M";
71     if (NodeType & DSNode::Read       ) OS << "R";
72 #ifndef NDEBUG
73     if (NodeType & DSNode::DEAD       ) OS << "<dead>";
74 #endif
75     OS << "\n";
76   }
77
78   for (unsigned i = 0, e = N->getGlobals().size(); i != e; ++i) {
79     WriteAsOperand(OS, N->getGlobals()[i], false, true, M);
80     OS << "\n";
81   }
82
83   return OS.str();
84 }
85
86 namespace llvm {
87 template<>
88 struct DOTGraphTraits<const DSGraph*> : public DefaultDOTGraphTraits {
89   static std::string getGraphName(const DSGraph *G) {
90     switch (G->getReturnNodes().size()) {
91     case 0: return G->getFunctionNames();
92     case 1: return "Function " + G->getFunctionNames();
93     default: return "Functions: " + G->getFunctionNames();
94     }
95   }
96
97   static std::string getNodeLabel(const DSNode *Node, const DSGraph *Graph) {
98     return getCaption(Node, Graph);
99   }
100
101   static std::string getNodeAttributes(const DSNode *N) {
102     return "shape=Mrecord";
103   }
104
105   static bool edgeTargetsEdgeSource(const void *Node,
106                                     DSNode::const_iterator I) {
107     unsigned O = I.getNode()->getLink(I.getOffset()).getOffset();
108     return (O >> DS::PointerShift) != 0;
109   }
110
111   static DSNode::const_iterator getEdgeTarget(const DSNode *Node,
112                                               DSNode::const_iterator I) {
113     unsigned O = I.getNode()->getLink(I.getOffset()).getOffset();
114     unsigned LinkNo = O >> DS::PointerShift;
115     const DSNode *N = *I;
116     DSNode::const_iterator R = N->begin();
117     for (; LinkNo; --LinkNo)
118       ++R;
119     return R;
120   }
121
122   
123   /// addCustomGraphFeatures - Use this graph writing hook to emit call nodes
124   /// and the return node.
125   ///
126   static void addCustomGraphFeatures(const DSGraph *G,
127                                      GraphWriter<const DSGraph*> &GW) {
128     Module *CurMod = 0;
129     if (G->retnodes_begin() != G->retnodes_end())
130       CurMod = G->retnodes_begin()->first->getParent();
131     else {
132       // If there is a global in the graph, we can use it to find the module.
133       const DSScalarMap &SM = G->getScalarMap();
134       if (SM.global_begin() != SM.global_end())
135         CurMod = (*SM.global_begin())->getParent();
136     }
137
138
139     // Add scalar nodes to the graph...
140     const DSGraph::ScalarMapTy &VM = G->getScalarMap();
141     for (DSGraph::ScalarMapTy::const_iterator I = VM.begin(); I != VM.end();++I)
142       if (!isa<GlobalValue>(I->first)) {
143         std::stringstream OS;
144         WriteAsOperand(OS, I->first, false, true, CurMod);
145         GW.emitSimpleNode(I->first, "", OS.str());
146         
147         // Add edge from return node to real destination
148         DSNode *DestNode = I->second.getNode();
149         int EdgeDest = I->second.getOffset() >> DS::PointerShift;
150         if (EdgeDest == 0) EdgeDest = -1;
151         GW.emitEdge(I->first, -1, DestNode,
152                     EdgeDest, "arrowtail=tee,color=gray63");
153       }
154
155
156     // Output the returned value pointer...
157     for (DSGraph::retnodes_iterator I = G->retnodes_begin(),
158            E = G->retnodes_end(); I != E; ++I)
159       if (I->second.getNode()) {
160         std::string Label;
161         if (G->getReturnNodes().size() == 1)
162           Label = "returning";
163         else
164           Label = I->first->getName() + " ret node";
165         // Output the return node...
166         GW.emitSimpleNode((void*)I->first, "plaintext=circle", Label);
167
168         // Add edge from return node to real destination
169         DSNode *RetNode = I->second.getNode();
170         int RetEdgeDest = I->second.getOffset() >> DS::PointerShift;;
171         if (RetEdgeDest == 0) RetEdgeDest = -1;
172         GW.emitEdge((void*)I->first, -1, RetNode,
173                     RetEdgeDest, "arrowtail=tee,color=gray63");
174       }
175
176     // Output all of the call nodes...
177     const std::list<DSCallSite> &FCs =
178       G->shouldPrintAuxCalls() ? G->getAuxFunctionCalls()
179       : G->getFunctionCalls();
180     for (std::list<DSCallSite>::const_iterator I = FCs.begin(), E = FCs.end();
181          I != E; ++I) {
182       const DSCallSite &Call = *I;
183       std::vector<std::string> EdgeSourceCaptions(Call.getNumPtrArgs()+2);
184       EdgeSourceCaptions[0] = "r";
185       if (Call.isDirectCall())
186         EdgeSourceCaptions[1] = Call.getCalleeFunc()->getName();
187       else
188         EdgeSourceCaptions[1] = "f";
189
190       GW.emitSimpleNode(&Call, "shape=record", "call", Call.getNumPtrArgs()+2,
191                         &EdgeSourceCaptions);
192
193       if (DSNode *N = Call.getRetVal().getNode()) {
194         int EdgeDest = Call.getRetVal().getOffset() >> DS::PointerShift;
195         if (EdgeDest == 0) EdgeDest = -1;
196         GW.emitEdge(&Call, 0, N, EdgeDest, "color=gray63,tailclip=false");
197       }
198
199       // Print out the callee...
200       if (Call.isIndirectCall()) {
201         DSNode *N = Call.getCalleeNode();
202         assert(N && "Null call site callee node!");
203         GW.emitEdge(&Call, 1, N, -1, "color=gray63,tailclip=false");
204       }
205
206       for (unsigned j = 0, e = Call.getNumPtrArgs(); j != e; ++j)
207         if (DSNode *N = Call.getPtrArg(j).getNode()) {
208           int EdgeDest = Call.getPtrArg(j).getOffset() >> DS::PointerShift;
209           if (EdgeDest == 0) EdgeDest = -1;
210           GW.emitEdge(&Call, j+2, N, EdgeDest, "color=gray63,tailclip=false");
211         }
212     }
213   }
214 };
215 }   // end namespace llvm
216
217 void DSNode::print(std::ostream &O, const DSGraph *G) const {
218   GraphWriter<const DSGraph *> W(O, G);
219   W.writeNode(this);
220 }
221
222 void DSGraph::print(std::ostream &O) const {
223   WriteGraph(O, this, "DataStructures");
224 }
225
226 void DSGraph::writeGraphToFile(std::ostream &O,
227                                const std::string &GraphName) const {
228   std::string Filename = GraphName + ".dot";
229   O << "Writing '" << Filename << "'...";
230   std::ofstream F(Filename.c_str());
231   
232   if (F.good()) {
233     print(F);
234     unsigned NumCalls = shouldPrintAuxCalls() ?
235       getAuxFunctionCalls().size() : getFunctionCalls().size();
236     O << " [" << getGraphSize() << "+" << NumCalls << "]\n";
237   } else {
238     O << "  error opening file for writing!\n";
239   }
240 }
241
242 /// viewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
243 /// then cleanup.  For use from the debugger.
244 ///
245 void DSGraph::viewGraph() const {
246   std::ofstream F("/tmp/tempgraph.dot");
247   if (!F.good()) {
248     std::cerr << "Error opening '/tmp/tempgraph.dot' for temporary graph!\n";
249     return;
250   }
251   print(F);
252   F.close();
253   if (system("dot -Tps -Gsize=10,7.5 -Grotate=90 /tmp/tempgraph.dot > /tmp/tempgraph.ps"))
254     std::cerr << "Error running dot: 'dot' not in path?\n";
255   system("gv /tmp/tempgraph.ps");
256   system("rm /tmp/tempgraph.dot /tmp/tempgraph.ps");
257 }
258
259
260 template <typename Collection>
261 static void printCollection(const Collection &C, std::ostream &O,
262                             const Module *M, const std::string &Prefix) {
263   if (M == 0) {
264     O << "Null Module pointer, cannot continue!\n";
265     return;
266   }
267
268   unsigned TotalNumNodes = 0, TotalCallNodes = 0;
269   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
270     if (C.hasGraph(*I)) {
271       DSGraph &Gr = C.getDSGraph((Function&)*I);
272       TotalNumNodes += Gr.getGraphSize();
273       unsigned NumCalls = Gr.shouldPrintAuxCalls() ?
274         Gr.getAuxFunctionCalls().size() : Gr.getFunctionCalls().size();
275
276       TotalCallNodes += NumCalls;
277       if (I->getName() == "main" || !OnlyPrintMain) {
278         Function *SCCFn = Gr.retnodes_begin()->first;
279         if (&*I == SCCFn)
280           Gr.writeGraphToFile(O, Prefix+I->getName());
281         else
282           O << "Didn't write '" << Prefix+I->getName()
283             << ".dot' - Graph already emitted to '" << Prefix+SCCFn->getName()
284             << "\n";
285       } else {
286         O << "Skipped Writing '" << Prefix+I->getName() << ".dot'... ["
287           << Gr.getGraphSize() << "+" << NumCalls << "]\n";
288       }
289
290       unsigned GraphSize = Gr.getGraphSize();
291       if (MaxGraphSize < GraphSize) MaxGraphSize = GraphSize;
292
293       for (DSGraph::node_iterator NI = Gr.node_begin(), E = Gr.node_end();
294            NI != E; ++NI)
295         if (NI->isNodeCompletelyFolded())
296           ++NumFoldedNodes;
297     }
298
299   DSGraph &GG = C.getGlobalsGraph();
300   TotalNumNodes  += GG.getGraphSize();
301   TotalCallNodes += GG.getFunctionCalls().size();
302   if (!OnlyPrintMain) {
303     GG.writeGraphToFile(O, Prefix+"GlobalsGraph");
304   } else {
305     O << "Skipped Writing '" << Prefix << "GlobalsGraph.dot'... ["
306       << GG.getGraphSize() << "+" << GG.getFunctionCalls().size() << "]\n";
307   }
308
309   O << "\nGraphs contain [" << TotalNumNodes << "+" << TotalCallNodes 
310     << "] nodes total" << std::endl;
311 }
312
313
314 // print - Print out the analysis results...
315 void LocalDataStructures::print(std::ostream &O, const Module *M) const {
316   if (DontPrintAnything) return;
317   printCollection(*this, O, M, "ds.");
318 }
319
320 void BUDataStructures::print(std::ostream &O, const Module *M) const {
321   if (DontPrintAnything) return;
322   printCollection(*this, O, M, "bu.");
323 }
324
325 void TDDataStructures::print(std::ostream &O, const Module *M) const {
326   if (DontPrintAnything) return;
327   printCollection(*this, O, M, "td.");
328 }
329
330 void CompleteBUDataStructures::print(std::ostream &O, const Module *M) const {
331   if (DontPrintAnything) return;
332   printCollection(*this, O, M, "cbu.");
333 }
334
335
336 void EquivClassGraphs::print(std::ostream &O, const Module *M) const {
337   if (DontPrintAnything) return;
338   printCollection(*this, O, M, "eq.");
339 }
340