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/ADT/Statistic.h"
27 // OnlyPrintMain - The DataStructure printer exposes this option to allow
28 // printing of only the graph for "main".
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)");
37 void DSNode::dump() const { print(std::cerr, 0); }
39 static std::string getCaption(const DSNode *N, const DSGraph *G) {
43 if (!G) G = N->getParentGraph();
45 // Get the module from ONE of the functions in the graph it is available.
46 if (G && G->retnodes_begin() != G->retnodes_end())
47 M = G->retnodes_begin()->first->getParent();
49 // If there is a global in the graph, we can use it to find the module.
50 const DSScalarMap &SM = G->getScalarMap();
51 if (SM.global_begin() != SM.global_end())
52 M = (*SM.global_begin())->getParent();
55 if (N->isNodeCompletelyFolded())
58 WriteTypeSymbolic(OS, N->getType(), M);
62 if (unsigned NodeType = N->getNodeFlags()) {
64 if (NodeType & DSNode::AllocaNode ) OS << "S";
65 if (NodeType & DSNode::HeapNode ) OS << "H";
66 if (NodeType & DSNode::GlobalNode ) OS << "G";
67 if (NodeType & DSNode::UnknownNode) OS << "U";
68 if (NodeType & DSNode::Incomplete ) OS << "I";
69 if (NodeType & DSNode::Modified ) OS << "M";
70 if (NodeType & DSNode::Read ) OS << "R";
72 if (NodeType & DSNode::DEAD ) OS << "<dead>";
77 EquivalenceClasses<GlobalValue*> *GlobalECs = 0;
78 if (G) GlobalECs = &G->getGlobalECs();
80 for (unsigned i = 0, e = N->getGlobalsList().size(); i != e; ++i) {
81 WriteAsOperand(OS, N->getGlobalsList()[i], false, true, M);
83 // Figure out how many globals are equivalent to this one.
85 EquivalenceClasses<GlobalValue*>::iterator I =
86 GlobalECs->findValue(N->getGlobalsList()[i]);
87 if (I != GlobalECs->end()) {
89 std::distance(GlobalECs->member_begin(I), GlobalECs->member_end());
90 if (NumMembers != 1) OS << " + " << (NumMembers-1) << " EC";
101 struct DOTGraphTraits<const DSGraph*> : public DefaultDOTGraphTraits {
102 static std::string getGraphName(const DSGraph *G) {
103 switch (G->getReturnNodes().size()) {
104 case 0: return G->getFunctionNames();
105 case 1: return "Function " + G->getFunctionNames();
106 default: return "Functions: " + G->getFunctionNames();
110 static std::string getNodeLabel(const DSNode *Node, const DSGraph *Graph) {
111 return getCaption(Node, Graph);
114 static std::string getNodeAttributes(const DSNode *N) {
115 return "shape=Mrecord";
118 static bool edgeTargetsEdgeSource(const void *Node,
119 DSNode::const_iterator I) {
120 unsigned O = I.getNode()->getLink(I.getOffset()).getOffset();
121 return (O >> DS::PointerShift) != 0;
124 static DSNode::const_iterator getEdgeTarget(const DSNode *Node,
125 DSNode::const_iterator I) {
126 unsigned O = I.getNode()->getLink(I.getOffset()).getOffset();
127 unsigned LinkNo = O >> DS::PointerShift;
128 const DSNode *N = *I;
129 DSNode::const_iterator R = N->begin();
130 for (; LinkNo; --LinkNo)
136 /// addCustomGraphFeatures - Use this graph writing hook to emit call nodes
137 /// and the return node.
139 static void addCustomGraphFeatures(const DSGraph *G,
140 GraphWriter<const DSGraph*> &GW) {
142 if (G->retnodes_begin() != G->retnodes_end())
143 CurMod = G->retnodes_begin()->first->getParent();
145 // If there is a global in the graph, we can use it to find the module.
146 const DSScalarMap &SM = G->getScalarMap();
147 if (SM.global_begin() != SM.global_end())
148 CurMod = (*SM.global_begin())->getParent();
152 // Add scalar nodes to the graph...
153 const DSGraph::ScalarMapTy &VM = G->getScalarMap();
154 for (DSGraph::ScalarMapTy::const_iterator I = VM.begin(); I != VM.end();++I)
155 if (!isa<GlobalValue>(I->first)) {
156 std::stringstream OS;
157 WriteAsOperand(OS, I->first, false, true, CurMod);
158 GW.emitSimpleNode(I->first, "", OS.str());
160 // Add edge from return node to real destination
161 DSNode *DestNode = I->second.getNode();
162 int EdgeDest = I->second.getOffset() >> DS::PointerShift;
163 if (EdgeDest == 0) EdgeDest = -1;
164 GW.emitEdge(I->first, -1, DestNode,
165 EdgeDest, "arrowtail=tee,color=gray63");
169 // Output the returned value pointer...
170 for (DSGraph::retnodes_iterator I = G->retnodes_begin(),
171 E = G->retnodes_end(); I != E; ++I)
172 if (I->second.getNode()) {
174 if (G->getReturnNodes().size() == 1)
177 Label = I->first->getName() + " ret node";
178 // Output the return node...
179 GW.emitSimpleNode((void*)I->first, "plaintext=circle", Label);
181 // Add edge from return node to real destination
182 DSNode *RetNode = I->second.getNode();
183 int RetEdgeDest = I->second.getOffset() >> DS::PointerShift;;
184 if (RetEdgeDest == 0) RetEdgeDest = -1;
185 GW.emitEdge((void*)I->first, -1, RetNode,
186 RetEdgeDest, "arrowtail=tee,color=gray63");
189 // Output all of the call nodes...
190 const std::list<DSCallSite> &FCs =
191 G->shouldPrintAuxCalls() ? G->getAuxFunctionCalls()
192 : G->getFunctionCalls();
193 for (std::list<DSCallSite>::const_iterator I = FCs.begin(), E = FCs.end();
195 const DSCallSite &Call = *I;
196 std::vector<std::string> EdgeSourceCaptions(Call.getNumPtrArgs()+2);
197 EdgeSourceCaptions[0] = "r";
198 if (Call.isDirectCall())
199 EdgeSourceCaptions[1] = Call.getCalleeFunc()->getName();
201 EdgeSourceCaptions[1] = "f";
203 GW.emitSimpleNode(&Call, "shape=record", "call", Call.getNumPtrArgs()+2,
204 &EdgeSourceCaptions);
206 if (DSNode *N = Call.getRetVal().getNode()) {
207 int EdgeDest = Call.getRetVal().getOffset() >> DS::PointerShift;
208 if (EdgeDest == 0) EdgeDest = -1;
209 GW.emitEdge(&Call, 0, N, EdgeDest, "color=gray63,tailclip=false");
212 // Print out the callee...
213 if (Call.isIndirectCall()) {
214 DSNode *N = Call.getCalleeNode();
215 assert(N && "Null call site callee node!");
216 GW.emitEdge(&Call, 1, N, -1, "color=gray63,tailclip=false");
219 for (unsigned j = 0, e = Call.getNumPtrArgs(); j != e; ++j)
220 if (DSNode *N = Call.getPtrArg(j).getNode()) {
221 int EdgeDest = Call.getPtrArg(j).getOffset() >> DS::PointerShift;
222 if (EdgeDest == 0) EdgeDest = -1;
223 GW.emitEdge(&Call, j+2, N, EdgeDest, "color=gray63,tailclip=false");
228 } // end namespace llvm
230 void DSNode::print(std::ostream &O, const DSGraph *G) const {
231 GraphWriter<const DSGraph *> W(O, G);
235 void DSGraph::print(std::ostream &O) const {
236 WriteGraph(O, this, "DataStructures");
239 void DSGraph::writeGraphToFile(std::ostream &O,
240 const std::string &GraphName) const {
241 std::string Filename = GraphName + ".dot";
242 O << "Writing '" << Filename << "'...";
243 std::ofstream F(Filename.c_str());
247 unsigned NumCalls = shouldPrintAuxCalls() ?
248 getAuxFunctionCalls().size() : getFunctionCalls().size();
249 O << " [" << getGraphSize() << "+" << NumCalls << "]\n";
251 O << " error opening file for writing!\n";
255 /// viewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
256 /// then cleanup. For use from the debugger.
258 void DSGraph::viewGraph() const {
259 std::ofstream F("/tmp/tempgraph.dot");
261 std::cerr << "Error opening '/tmp/tempgraph.dot' for temporary graph!\n";
266 if (system("dot -Tps -Gsize=10,7.5 -Grotate=90 /tmp/tempgraph.dot > /tmp/tempgraph.ps"))
267 std::cerr << "Error running dot: 'dot' not in path?\n";
268 system("gv /tmp/tempgraph.ps");
269 system("rm /tmp/tempgraph.dot /tmp/tempgraph.ps");
273 template <typename Collection>
274 static void printCollection(const Collection &C, std::ostream &O,
275 const Module *M, const std::string &Prefix) {
277 O << "Null Module pointer, cannot continue!\n";
281 unsigned TotalNumNodes = 0, TotalCallNodes = 0;
282 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
283 if (C.hasGraph(*I)) {
284 DSGraph &Gr = C.getDSGraph((Function&)*I);
285 unsigned NumCalls = Gr.shouldPrintAuxCalls() ?
286 Gr.getAuxFunctionCalls().size() : Gr.getFunctionCalls().size();
287 bool IsDuplicateGraph = false;
289 if (I->getName() == "main" || !OnlyPrintMain) {
290 Function *SCCFn = Gr.retnodes_begin()->first;
292 Gr.writeGraphToFile(O, Prefix+I->getName());
294 IsDuplicateGraph = true; // Don't double count node/call nodes.
295 O << "Didn't write '" << Prefix+I->getName()
296 << ".dot' - Graph already emitted to '" << Prefix+SCCFn->getName()
300 Function *SCCFn = Gr.retnodes_begin()->first;
302 O << "Skipped Writing '" << Prefix+I->getName() << ".dot'... ["
303 << Gr.getGraphSize() << "+" << NumCalls << "]\n";
305 IsDuplicateGraph = true; // Don't double count node/call nodes.
309 if (!IsDuplicateGraph) {
310 unsigned GraphSize = Gr.getGraphSize();
311 if (MaxGraphSize < GraphSize) MaxGraphSize = GraphSize;
313 TotalNumNodes += Gr.getGraphSize();
314 TotalCallNodes += NumCalls;
315 for (DSGraph::node_iterator NI = Gr.node_begin(), E = Gr.node_end();
317 if (NI->isNodeCompletelyFolded())
322 DSGraph &GG = C.getGlobalsGraph();
323 TotalNumNodes += GG.getGraphSize();
324 TotalCallNodes += GG.getFunctionCalls().size();
325 if (!OnlyPrintMain) {
326 GG.writeGraphToFile(O, Prefix+"GlobalsGraph");
328 O << "Skipped Writing '" << Prefix << "GlobalsGraph.dot'... ["
329 << GG.getGraphSize() << "+" << GG.getFunctionCalls().size() << "]\n";
332 O << "\nGraphs contain [" << TotalNumNodes << "+" << TotalCallNodes
333 << "] nodes total" << std::endl;
337 // print - Print out the analysis results...
338 void LocalDataStructures::print(std::ostream &O, const Module *M) const {
339 if (DontPrintAnything) return;
340 printCollection(*this, O, M, "ds.");
343 void BUDataStructures::print(std::ostream &O, const Module *M) const {
344 if (DontPrintAnything) return;
345 printCollection(*this, O, M, "bu.");
348 void TDDataStructures::print(std::ostream &O, const Module *M) const {
349 if (DontPrintAnything) return;
350 printCollection(*this, O, M, "td.");
353 void CompleteBUDataStructures::print(std::ostream &O, const Module *M) const {
354 if (DontPrintAnything) return;
355 printCollection(*this, O, M, "cbu.");
359 void EquivClassGraphs::print(std::ostream &O, const Module *M) const {
360 if (DontPrintAnything) return;
361 printCollection(*this, O, M, "eq.");