Add support for 'rename'
[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 using namespace llvm;
26
27 // OnlyPrintMain - The DataStructure printer exposes this option to allow
28 // printing of only the graph for "main".
29 //
30 namespace {
31   cl::opt<bool> OnlyPrintMain("only-print-main-ds", cl::ReallyHidden);
32   cl::opt<bool> DontPrintAnything("dont-print-ds", cl::ReallyHidden);
33   Statistic<> MaxGraphSize   ("dsa", "Maximum graph size");
34   Statistic<> NumFoldedNodes ("dsa", "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 namespace llvm {
77 template<>
78 struct DOTGraphTraits<const DSGraph*> : public DefaultDOTGraphTraits {
79   static std::string getGraphName(const DSGraph *G) {
80     switch (G->getReturnNodes().size()) {
81     case 0: return G->getFunctionNames();
82     case 1: return "Function " + G->getFunctionNames();
83     default: return "Functions: " + G->getFunctionNames();
84     }
85   }
86
87   static const char *getGraphProperties(const DSGraph *G) {
88     return "\tsize=\"10,7.5\";\n"
89            "\trotate=\"90\";\n";
90   }
91
92   static std::string getNodeLabel(const DSNode *Node, const DSGraph *Graph) {
93     return getCaption(Node, Graph);
94   }
95
96   static std::string getNodeAttributes(const DSNode *N) {
97     return "shape=Mrecord";//fontname=Courier";
98   }
99   
100   /// addCustomGraphFeatures - Use this graph writing hook to emit call nodes
101   /// and the return node.
102   ///
103   static void addCustomGraphFeatures(const DSGraph *G,
104                                      GraphWriter<const DSGraph*> &GW) {
105     Module *CurMod = 0;
106     if (!G->getReturnNodes().empty())
107       CurMod = G->getReturnNodes().begin()->first->getParent();
108
109     // Add scalar nodes to the graph...
110     const DSGraph::ScalarMapTy &VM = G->getScalarMap();
111     for (DSGraph::ScalarMapTy::const_iterator I = VM.begin(); I != VM.end();++I)
112       if (!isa<GlobalValue>(I->first) && !isa<ConstantPointerRef>(I->first)) {
113         std::stringstream OS;
114         WriteAsOperand(OS, I->first, false, true, CurMod);
115         GW.emitSimpleNode(I->first, "", OS.str());
116         
117         // Add edge from return node to real destination
118         int EdgeDest = I->second.getOffset() >> DS::PointerShift;
119         if (EdgeDest == 0) EdgeDest = -1;
120         GW.emitEdge(I->first, -1, I->second.getNode(),
121                     EdgeDest, "arrowtail=tee,color=gray63");
122       }
123
124
125     // Output the returned value pointer...
126     const DSGraph::ReturnNodesTy &RetNodes = G->getReturnNodes();
127     for (DSGraph::ReturnNodesTy::const_iterator I = RetNodes.begin(),
128            E = RetNodes.end(); I != E; ++I)
129       if (I->second.getNode()) {
130         std::string Label;
131         if (RetNodes.size() == 1)
132           Label = "returning";
133         else
134           Label = I->first->getName() + " ret node";
135         // Output the return node...
136         GW.emitSimpleNode((void*)I->first, "plaintext=circle", Label);
137
138         // Add edge from return node to real destination
139         int RetEdgeDest = I->second.getOffset() >> DS::PointerShift;;
140         if (RetEdgeDest == 0) RetEdgeDest = -1;
141         GW.emitEdge((void*)I->first, -1, I->second.getNode(),
142                     RetEdgeDest, "arrowtail=tee,color=gray63");
143       }
144
145     // Output all of the call nodes...
146     const std::vector<DSCallSite> &FCs =
147       G->shouldPrintAuxCalls() ? G->getAuxFunctionCalls()
148       : G->getFunctionCalls();
149     for (unsigned i = 0, e = FCs.size(); i != e; ++i) {
150       const DSCallSite &Call = FCs[i];
151       std::vector<std::string> EdgeSourceCaptions(Call.getNumPtrArgs()+2);
152       EdgeSourceCaptions[0] = "r";
153       if (Call.isDirectCall())
154         EdgeSourceCaptions[1] = Call.getCalleeFunc()->getName();
155       else
156         EdgeSourceCaptions[1] = "f";
157
158       GW.emitSimpleNode(&Call, "shape=record", "call", Call.getNumPtrArgs()+2,
159                         &EdgeSourceCaptions);
160
161       if (DSNode *N = Call.getRetVal().getNode()) {
162         int EdgeDest = Call.getRetVal().getOffset() >> DS::PointerShift;
163         if (EdgeDest == 0) EdgeDest = -1;
164         GW.emitEdge(&Call, 0, N, EdgeDest, "color=gray63,tailclip=false");
165       }
166
167       // Print out the callee...
168       if (Call.isIndirectCall()) {
169         DSNode *N = Call.getCalleeNode();
170         assert(N && "Null call site callee node!");
171         GW.emitEdge(&Call, 1, N, -1, "color=gray63,tailclip=false");
172       }
173
174       for (unsigned j = 0, e = Call.getNumPtrArgs(); j != e; ++j)
175         if (DSNode *N = Call.getPtrArg(j).getNode()) {
176           int EdgeDest = Call.getPtrArg(j).getOffset() >> DS::PointerShift;
177           if (EdgeDest == 0) EdgeDest = -1;
178           GW.emitEdge(&Call, j+2, N, EdgeDest, "color=gray63,tailclip=false");
179         }
180     }
181   }
182 };
183 }   // end namespace llvm
184
185 void DSNode::print(std::ostream &O, const DSGraph *G) const {
186   GraphWriter<const DSGraph *> W(O, G);
187   W.writeNode(this);
188 }
189
190 void DSGraph::print(std::ostream &O) const {
191   WriteGraph(O, this, "DataStructures");
192 }
193
194 void DSGraph::writeGraphToFile(std::ostream &O,
195                                const std::string &GraphName) const {
196   std::string Filename = GraphName + ".dot";
197   O << "Writing '" << Filename << "'...";
198   std::ofstream F(Filename.c_str());
199   
200   if (F.good()) {
201     print(F);
202     unsigned NumCalls = shouldPrintAuxCalls() ?
203       getAuxFunctionCalls().size() : getFunctionCalls().size();
204     O << " [" << getGraphSize() << "+" << NumCalls << "]\n";
205   } else {
206     O << "  error opening file for writing!\n";
207   }
208 }
209
210 /// viewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
211 /// then cleanup.  For use from the debugger.
212 ///
213 void DSGraph::viewGraph() const {
214   std::ofstream F("/tmp/tempgraph.dot");
215   if (!F.good()) {
216     std::cerr << "Error opening '/tmp/tempgraph.dot' for temporary graph!\n";
217     return;
218   }
219   print(F);
220   F.close();
221   if (system("dot -Tps /tmp/tempgraph.dot > /tmp/tempgraph.ps"))
222     std::cerr << "Error running dot: 'dot' not in path?\n";
223   system("gv /tmp/tempgraph.ps");
224   system("rm /tmp/tempgraph.dot /tmp/tempgraph.ps");
225 }
226
227
228 template <typename Collection>
229 static void printCollection(const Collection &C, std::ostream &O,
230                             const Module *M, const std::string &Prefix) {
231   if (M == 0) {
232     O << "Null Module pointer, cannot continue!\n";
233     return;
234   }
235
236   unsigned TotalNumNodes = 0, TotalCallNodes = 0;
237   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
238     if (C.hasGraph(*I)) {
239       DSGraph &Gr = C.getDSGraph((Function&)*I);
240       TotalNumNodes += Gr.getGraphSize();
241       unsigned NumCalls = Gr.shouldPrintAuxCalls() ?
242         Gr.getAuxFunctionCalls().size() : Gr.getFunctionCalls().size();
243
244       TotalCallNodes += NumCalls;
245       if (I->getName() == "main" || !OnlyPrintMain)
246         Gr.writeGraphToFile(O, Prefix+I->getName());
247       else {
248         O << "Skipped Writing '" << Prefix+I->getName() << ".dot'... ["
249           << Gr.getGraphSize() << "+" << NumCalls << "]\n";
250       }
251
252       unsigned GraphSize = Gr.getGraphSize();
253       if (MaxGraphSize < GraphSize) MaxGraphSize = GraphSize;
254
255       for (DSGraph::node_iterator NI = Gr.node_begin(), E = Gr.node_end();
256            NI != E; ++NI)
257         if ((*NI)->isNodeCompletelyFolded())
258           ++NumFoldedNodes;
259     }
260
261   DSGraph &GG = C.getGlobalsGraph();
262   TotalNumNodes  += GG.getGraphSize();
263   TotalCallNodes += GG.getFunctionCalls().size();
264   if (!OnlyPrintMain) {
265     GG.writeGraphToFile(O, Prefix+"GlobalsGraph");
266   } else {
267     O << "Skipped Writing '" << Prefix << "GlobalsGraph.dot'... ["
268       << GG.getGraphSize() << "+" << GG.getFunctionCalls().size() << "]\n";
269   }
270
271   O << "\nGraphs contain [" << TotalNumNodes << "+" << TotalCallNodes 
272     << "] nodes total" << std::endl;
273 }
274
275
276 // print - Print out the analysis results...
277 void LocalDataStructures::print(std::ostream &O, const Module *M) const {
278   if (DontPrintAnything) return;
279   printCollection(*this, O, M, "ds.");
280 }
281
282 void BUDataStructures::print(std::ostream &O, const Module *M) const {
283   if (DontPrintAnything) return;
284   printCollection(*this, O, M, "bu.");
285 }
286
287 void TDDataStructures::print(std::ostream &O, const Module *M) const {
288   if (DontPrintAnything) return;
289   printCollection(*this, O, M, "td.");
290 }
291
292 void CompleteBUDataStructures::print(std::ostream &O, const Module *M) const {
293   if (DontPrintAnything) return;
294   printCollection(*this, O, M, "cbu.");
295 }
296
297