1 //===- Printer.cpp - Code for printing data structure graphs nicely -------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements the 'dot' graph printer.
12 //===----------------------------------------------------------------------===//
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/System/Path.h"
23 #include "llvm/System/Program.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Config/config.h"
30 // OnlyPrintMain - The DataStructure printer exposes this option to allow
31 // printing of only the graph for "main".
34 cl::opt<bool> OnlyPrintMain("only-print-main-ds", cl::ReallyHidden);
35 cl::opt<bool> DontPrintAnything("dont-print-ds", cl::ReallyHidden);
36 Statistic<> MaxGraphSize ("dsa", "Maximum graph size");
37 Statistic<> NumFoldedNodes ("dsa", "Number of folded nodes (in final graph)");
40 void DSNode::dump() const { print(std::cerr, 0); }
42 static std::string getCaption(const DSNode *N, const DSGraph *G) {
46 if (!G) G = N->getParentGraph();
48 // Get the module from ONE of the functions in the graph it is available.
49 if (G && G->retnodes_begin() != G->retnodes_end())
50 M = G->retnodes_begin()->first->getParent();
52 // If there is a global in the graph, we can use it to find the module.
53 const DSScalarMap &SM = G->getScalarMap();
54 if (SM.global_begin() != SM.global_end())
55 M = (*SM.global_begin())->getParent();
58 if (N->isNodeCompletelyFolded())
61 WriteTypeSymbolic(OS, N->getType(), M);
65 if (unsigned NodeType = N->getNodeFlags()) {
67 if (NodeType & DSNode::AllocaNode ) OS << "S";
68 if (NodeType & DSNode::HeapNode ) OS << "H";
69 if (NodeType & DSNode::GlobalNode ) OS << "G";
70 if (NodeType & DSNode::UnknownNode) OS << "U";
71 if (NodeType & DSNode::Incomplete ) OS << "I";
72 if (NodeType & DSNode::Modified ) OS << "M";
73 if (NodeType & DSNode::Read ) OS << "R";
75 if (NodeType & DSNode::DEAD ) OS << "<dead>";
80 EquivalenceClasses<GlobalValue*> *GlobalECs = 0;
81 if (G) GlobalECs = &G->getGlobalECs();
83 for (unsigned i = 0, e = N->getGlobalsList().size(); i != e; ++i) {
84 WriteAsOperand(OS, N->getGlobalsList()[i], false, true, M);
86 // Figure out how many globals are equivalent to this one.
88 EquivalenceClasses<GlobalValue*>::iterator I =
89 GlobalECs->findValue(N->getGlobalsList()[i]);
90 if (I != GlobalECs->end()) {
92 std::distance(GlobalECs->member_begin(I), GlobalECs->member_end());
93 if (NumMembers != 1) OS << " + " << (NumMembers-1) << " EC";
104 struct DOTGraphTraits<const DSGraph*> : public DefaultDOTGraphTraits {
105 static std::string getGraphName(const DSGraph *G) {
106 switch (G->getReturnNodes().size()) {
107 case 0: return G->getFunctionNames();
108 case 1: return "Function " + G->getFunctionNames();
109 default: return "Functions: " + G->getFunctionNames();
113 static std::string getNodeLabel(const DSNode *Node, const DSGraph *Graph) {
114 return getCaption(Node, Graph);
117 static std::string getNodeAttributes(const DSNode *N) {
118 return "shape=Mrecord";
121 static bool edgeTargetsEdgeSource(const void *Node,
122 DSNode::const_iterator I) {
123 unsigned O = I.getNode()->getLink(I.getOffset()).getOffset();
124 return (O >> DS::PointerShift) != 0;
127 static DSNode::const_iterator getEdgeTarget(const DSNode *Node,
128 DSNode::const_iterator I) {
129 unsigned O = I.getNode()->getLink(I.getOffset()).getOffset();
130 unsigned LinkNo = O >> DS::PointerShift;
131 const DSNode *N = *I;
132 DSNode::const_iterator R = N->begin();
133 for (; LinkNo; --LinkNo)
139 /// addCustomGraphFeatures - Use this graph writing hook to emit call nodes
140 /// and the return node.
142 static void addCustomGraphFeatures(const DSGraph *G,
143 GraphWriter<const DSGraph*> &GW) {
145 if (G->retnodes_begin() != G->retnodes_end())
146 CurMod = G->retnodes_begin()->first->getParent();
148 // If there is a global in the graph, we can use it to find the module.
149 const DSScalarMap &SM = G->getScalarMap();
150 if (SM.global_begin() != SM.global_end())
151 CurMod = (*SM.global_begin())->getParent();
155 // Add scalar nodes to the graph...
156 const DSGraph::ScalarMapTy &VM = G->getScalarMap();
157 for (DSGraph::ScalarMapTy::const_iterator I = VM.begin(); I != VM.end();++I)
158 if (!isa<GlobalValue>(I->first)) {
159 std::stringstream OS;
160 WriteAsOperand(OS, I->first, false, true, CurMod);
161 GW.emitSimpleNode(I->first, "", OS.str());
163 // Add edge from return node to real destination
164 DSNode *DestNode = I->second.getNode();
165 int EdgeDest = I->second.getOffset() >> DS::PointerShift;
166 if (EdgeDest == 0) EdgeDest = -1;
167 GW.emitEdge(I->first, -1, DestNode,
168 EdgeDest, "arrowtail=tee,color=gray63");
172 // Output the returned value pointer...
173 for (DSGraph::retnodes_iterator I = G->retnodes_begin(),
174 E = G->retnodes_end(); I != E; ++I)
175 if (I->second.getNode()) {
177 if (G->getReturnNodes().size() == 1)
180 Label = I->first->getName() + " ret node";
181 // Output the return node...
182 GW.emitSimpleNode((void*)I->first, "plaintext=circle", Label);
184 // Add edge from return node to real destination
185 DSNode *RetNode = I->second.getNode();
186 int RetEdgeDest = I->second.getOffset() >> DS::PointerShift;;
187 if (RetEdgeDest == 0) RetEdgeDest = -1;
188 GW.emitEdge((void*)I->first, -1, RetNode,
189 RetEdgeDest, "arrowtail=tee,color=gray63");
192 // Output all of the call nodes...
193 const std::list<DSCallSite> &FCs =
194 G->shouldPrintAuxCalls() ? G->getAuxFunctionCalls()
195 : G->getFunctionCalls();
196 for (std::list<DSCallSite>::const_iterator I = FCs.begin(), E = FCs.end();
198 const DSCallSite &Call = *I;
199 std::vector<std::string> EdgeSourceCaptions(Call.getNumPtrArgs()+2);
200 EdgeSourceCaptions[0] = "r";
201 if (Call.isDirectCall())
202 EdgeSourceCaptions[1] = Call.getCalleeFunc()->getName();
204 EdgeSourceCaptions[1] = "f";
206 GW.emitSimpleNode(&Call, "shape=record", "call", Call.getNumPtrArgs()+2,
207 &EdgeSourceCaptions);
209 if (DSNode *N = Call.getRetVal().getNode()) {
210 int EdgeDest = Call.getRetVal().getOffset() >> DS::PointerShift;
211 if (EdgeDest == 0) EdgeDest = -1;
212 GW.emitEdge(&Call, 0, N, EdgeDest, "color=gray63,tailclip=false");
215 // Print out the callee...
216 if (Call.isIndirectCall()) {
217 DSNode *N = Call.getCalleeNode();
218 assert(N && "Null call site callee node!");
219 GW.emitEdge(&Call, 1, N, -1, "color=gray63,tailclip=false");
222 for (unsigned j = 0, e = Call.getNumPtrArgs(); j != e; ++j)
223 if (DSNode *N = Call.getPtrArg(j).getNode()) {
224 int EdgeDest = Call.getPtrArg(j).getOffset() >> DS::PointerShift;
225 if (EdgeDest == 0) EdgeDest = -1;
226 GW.emitEdge(&Call, j+2, N, EdgeDest, "color=gray63,tailclip=false");
231 } // end namespace llvm
233 void DSNode::print(std::ostream &O, const DSGraph *G) const {
234 GraphWriter<const DSGraph *> W(O, G);
238 void DSGraph::print(std::ostream &O) const {
239 WriteGraph(O, this, "DataStructures");
242 void DSGraph::writeGraphToFile(std::ostream &O,
243 const std::string &GraphName) const {
244 std::string Filename = GraphName + ".dot";
245 O << "Writing '" << Filename << "'...";
246 std::ofstream F(Filename.c_str());
250 unsigned NumCalls = shouldPrintAuxCalls() ?
251 getAuxFunctionCalls().size() : getFunctionCalls().size();
252 O << " [" << getGraphSize() << "+" << NumCalls << "]\n";
254 O << " error opening file for writing!\n";
258 /// viewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
259 /// then cleanup. For use from the debugger.
261 void DSGraph::viewGraph() const {
264 sprintf(pathsuff, "%06u", unsigned(rand()));
266 sys::Path TempDir = sys::Path::GetTemporaryDirectory();
267 sys::Path Filename = TempDir;
268 Filename.appendComponent("ds.tempgraph." + std::string(pathsuff) + ".dot");
269 std::cerr << "Writing '" << Filename << "'... ";
270 std::ofstream F(Filename.c_str());
273 std::cerr << " error opening file for writing!\n";
282 sys::Path Graphviz(LLVM_PATH_GRAPHVIZ);
283 std::vector<const char*> args;
284 args.push_back(Graphviz.c_str());
285 args.push_back(Filename.c_str());
288 std::cerr << "Running 'Graphviz' program... " << std::flush;
289 if (sys::Program::ExecuteAndWait(Graphviz, &args[0])) {
290 std::cerr << "Error viewing graph: 'Graphviz' not in path?\n";
292 Filename.eraseFromDisk();
295 #elif (HAVE_GV && HAVE_DOT)
296 sys::Path PSFilename = TempDir;
297 PSFilename.appendComponent(std::string("ds.tempgraph") + "." + pathsuff + ".ps");
299 sys::Path dot(LLVM_PATH_DOT);
300 std::vector<const char*> args;
301 args.push_back(dot.c_str());
302 args.push_back("-Tps");
303 args.push_back("-Nfontname=Courier");
304 args.push_back("-Gsize=7.5,10");
305 args.push_back(Filename.c_str());
306 args.push_back("-o");
307 args.push_back(PSFilename.c_str());
310 std::cerr << "Running 'dot' program... " << std::flush;
311 if (sys::Program::ExecuteAndWait(dot, &args[0])) {
312 std::cerr << "Error viewing graph: 'dot' not in path?\n";
316 sys::Path gv(LLVM_PATH_GV);
318 args.push_back(gv.c_str());
319 args.push_back(PSFilename.c_str());
322 sys::Program::ExecuteAndWait(gv, &args[0]);
324 Filename.eraseFromDisk();
325 PSFilename.eraseFromDisk();
328 sys::Path dotty(LLVM_PATH_DOTTY);
329 std::vector<const char*> args;
330 args.push_back(Filename.c_str());
333 std::cerr << "Running 'dotty' program... " << std::flush;
334 if (sys::Program::ExecuteAndWait(dotty, &args[0])) {
335 std::cerr << "Error viewing graph: 'dotty' not in path?\n";
337 #ifndef __MINGW32__ // Dotty spawns another app and doesn't wait until it returns
338 Filename.eraseFromDisk();
344 Filename.eraseFromDisk();
345 TempDir.eraseFromDisk(true);
349 template <typename Collection>
350 static void printCollection(const Collection &C, std::ostream &O,
351 const Module *M, const std::string &Prefix) {
353 O << "Null Module pointer, cannot continue!\n";
357 unsigned TotalNumNodes = 0, TotalCallNodes = 0;
358 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
359 if (C.hasGraph(*I)) {
360 DSGraph &Gr = C.getDSGraph((Function&)*I);
361 unsigned NumCalls = Gr.shouldPrintAuxCalls() ?
362 Gr.getAuxFunctionCalls().size() : Gr.getFunctionCalls().size();
363 bool IsDuplicateGraph = false;
365 if (I->getName() == "main" || !OnlyPrintMain) {
366 Function *SCCFn = Gr.retnodes_begin()->first;
368 Gr.writeGraphToFile(O, Prefix+I->getName());
370 IsDuplicateGraph = true; // Don't double count node/call nodes.
371 O << "Didn't write '" << Prefix+I->getName()
372 << ".dot' - Graph already emitted to '" << Prefix+SCCFn->getName()
376 Function *SCCFn = Gr.retnodes_begin()->first;
378 O << "Skipped Writing '" << Prefix+I->getName() << ".dot'... ["
379 << Gr.getGraphSize() << "+" << NumCalls << "]\n";
381 IsDuplicateGraph = true; // Don't double count node/call nodes.
385 if (!IsDuplicateGraph) {
386 unsigned GraphSize = Gr.getGraphSize();
387 if (MaxGraphSize < GraphSize) MaxGraphSize = GraphSize;
389 TotalNumNodes += Gr.getGraphSize();
390 TotalCallNodes += NumCalls;
391 for (DSGraph::node_iterator NI = Gr.node_begin(), E = Gr.node_end();
393 if (NI->isNodeCompletelyFolded())
398 DSGraph &GG = C.getGlobalsGraph();
399 TotalNumNodes += GG.getGraphSize();
400 TotalCallNodes += GG.getFunctionCalls().size();
401 if (!OnlyPrintMain) {
402 GG.writeGraphToFile(O, Prefix+"GlobalsGraph");
404 O << "Skipped Writing '" << Prefix << "GlobalsGraph.dot'... ["
405 << GG.getGraphSize() << "+" << GG.getFunctionCalls().size() << "]\n";
408 O << "\nGraphs contain [" << TotalNumNodes << "+" << TotalCallNodes
409 << "] nodes total" << std::endl;
413 // print - Print out the analysis results...
414 void LocalDataStructures::print(std::ostream &O, const Module *M) const {
415 if (DontPrintAnything) return;
416 printCollection(*this, O, M, "ds.");
419 void BUDataStructures::print(std::ostream &O, const Module *M) const {
420 if (DontPrintAnything) return;
421 printCollection(*this, O, M, "bu.");
424 void TDDataStructures::print(std::ostream &O, const Module *M) const {
425 if (DontPrintAnything) return;
426 printCollection(*this, O, M, "td.");
429 void CompleteBUDataStructures::print(std::ostream &O, const Module *M) const {
430 if (DontPrintAnything) return;
431 printCollection(*this, O, M, "cbu.");
435 void EquivClassGraphs::print(std::ostream &O, const Module *M) const {
436 if (DontPrintAnything) return;
437 printCollection(*this, O, M, "eq.");