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