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