3ff3fa8ffe1cba5f7f856f547d7c7132b242b2e1
[oota-llvm.git] / include / llvm / Support / GraphWriter.h
1 //===-- llvm/Support/GraphWriter.h - Write graph to a .dot file -*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a simple interface that can be used to print out generic
11 // LLVM graphs to ".dot" files.  "dot" is a tool that is part of the AT&T
12 // graphviz package (http://www.research.att.com/sw/tools/graphviz/) which can
13 // be used to turn the files output by this interface into a variety of
14 // different graphics formats.
15 //
16 // Graphs do not need to implement any interface past what is already required
17 // by the GraphTraits template, but they can choose to implement specializations
18 // of the DOTGraphTraits template if they want to customize the graphs output in
19 // any way.
20 //
21 //===----------------------------------------------------------------------===//
22
23 #ifndef LLVM_SUPPORT_GRAPHWRITER_H
24 #define LLVM_SUPPORT_GRAPHWRITER_H
25
26 #include "llvm/Support/DOTGraphTraits.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/ADT/GraphTraits.h"
29 #include "llvm/System/Path.h"
30 #include <vector>
31 #include <cassert>
32
33 namespace llvm {
34
35 namespace DOT {  // Private functions...
36   std::string EscapeString(const std::string &Label);
37 }
38
39 namespace GraphProgram {
40    enum Name {
41       DOT,
42       FDP,
43       NEATO,
44       TWOPI,
45       CIRCO
46    };
47 }
48
49 void DisplayGraph(const sys::Path& Filename, bool wait=true, GraphProgram::Name program = GraphProgram::DOT);
50
51 template<typename GraphType>
52 class GraphWriter {
53   raw_ostream &O;
54   const GraphType &G;
55
56   typedef DOTGraphTraits<GraphType>           DOTTraits;
57   typedef GraphTraits<GraphType>              GTraits;
58   typedef typename GTraits::NodeType          NodeType;
59   typedef typename GTraits::nodes_iterator    node_iterator;
60   typedef typename GTraits::ChildIteratorType child_iterator;
61   DOTTraits DTraits;
62
63   // Writes the edge labels of the node to O and returns true if there are any
64   // edge labels not equal to the empty string "".
65   bool getEdgeSourceLabels(raw_ostream &O, NodeType *Node) {
66     child_iterator EI = GTraits::child_begin(Node);
67     child_iterator EE = GTraits::child_end(Node);
68     bool hasEdgeSourceLabels = false;
69
70     for (unsigned i = 0; EI != EE && i != 64; ++EI, ++i) {
71       std::string label = DTraits.getEdgeSourceLabel(Node, EI);
72
73       if (label == "")
74         continue;
75
76       hasEdgeSourceLabels = true;
77
78       if (i)
79         O << "|";
80
81       O << "<s" << i << ">" << DTraits.getEdgeSourceLabel(Node, EI);
82     }
83
84     if (EI != EE && hasEdgeSourceLabels)
85       O << "|<s64>truncated...";
86
87     return hasEdgeSourceLabels;
88   }
89
90 public:
91   GraphWriter(raw_ostream &o, const GraphType &g, bool SN) : O(o), G(g) {
92     DTraits = DOTTraits(SN);
93   }
94
95   void writeGraph(bool ShortNames = false,
96                   const std::string &Title = "") {
97     // Output the header for the graph...
98     writeHeader(Title);
99
100     // Emit all of the nodes in the graph...
101     writeNodes();
102
103     // Output any customizations on the graph
104     DOTGraphTraits<GraphType>::addCustomGraphFeatures(G, *this);
105
106     // Output the end of the graph
107     writeFooter();
108   }
109
110   void writeHeader(const std::string &Title) {
111     std::string GraphName = DTraits.getGraphName(G);
112
113     if (!Title.empty())
114       O << "digraph \"" << DOT::EscapeString(Title) << "\" {\n";
115     else if (!GraphName.empty())
116       O << "digraph \"" << DOT::EscapeString(GraphName) << "\" {\n";
117     else
118       O << "digraph unnamed {\n";
119
120     if (DTraits.renderGraphFromBottomUp())
121       O << "\trankdir=\"BT\";\n";
122
123     if (!Title.empty())
124       O << "\tlabel=\"" << DOT::EscapeString(Title) << "\";\n";
125     else if (!GraphName.empty())
126       O << "\tlabel=\"" << DOT::EscapeString(GraphName) << "\";\n";
127     O << DTraits.getGraphProperties(G);
128     O << "\n";
129   }
130
131   void writeFooter() {
132     // Finish off the graph
133     O << "}\n";
134   }
135
136   void writeNodes() {
137     // Loop over the graph, printing it out...
138     for (node_iterator I = GTraits::nodes_begin(G), E = GTraits::nodes_end(G);
139          I != E; ++I)
140       if (!isNodeHidden(*I))
141         writeNode(*I);
142   }
143
144   bool isNodeHidden(NodeType &Node) {
145     return isNodeHidden(&Node);
146   }
147
148   bool isNodeHidden(NodeType *const *Node) {
149     return isNodeHidden(*Node);
150   }
151
152   bool isNodeHidden(NodeType *Node) {
153     return DTraits.isNodeHidden(Node);
154   }
155
156   void writeNode(NodeType& Node) {
157     writeNode(&Node);
158   }
159
160   void writeNode(NodeType *const *Node) {
161     writeNode(*Node);
162   }
163
164   void writeNode(NodeType *Node) {
165     std::string NodeAttributes = DTraits.getNodeAttributes(Node, G);
166
167     O << "\tNode" << static_cast<const void*>(Node) << " [shape=record,";
168     if (!NodeAttributes.empty()) O << NodeAttributes << ",";
169     O << "label=\"{";
170
171     if (!DTraits.renderGraphFromBottomUp()) {
172       O << DOT::EscapeString(DTraits.getNodeLabel(Node, G));
173
174       // If we should include the address of the node in the label, do so now.
175       if (DTraits.hasNodeAddressLabel(Node, G))
176         O << "|" << (void*)Node;
177     }
178
179     std::string edgeSourceLabels;
180     raw_string_ostream EdgeSourceLabels(edgeSourceLabels);
181     bool hasEdgeSourceLabels = getEdgeSourceLabels(EdgeSourceLabels, Node);
182
183     if (hasEdgeSourceLabels) {
184       if (!DTraits.renderGraphFromBottomUp()) O << "|";
185
186       O << "{" << EdgeSourceLabels.str() << "}";
187
188       if (DTraits.renderGraphFromBottomUp()) O << "|";
189     }
190
191     if (DTraits.renderGraphFromBottomUp()) {
192       O << DOT::EscapeString(DTraits.getNodeLabel(Node, G));
193
194       // If we should include the address of the node in the label, do so now.
195       if (DTraits.hasNodeAddressLabel(Node, G))
196         O << "|" << (void*)Node;
197     }
198
199     if (DTraits.hasEdgeDestLabels()) {
200       O << "|{";
201
202       unsigned i = 0, e = DTraits.numEdgeDestLabels(Node);
203       for (; i != e && i != 64; ++i) {
204         if (i) O << "|";
205         O << "<d" << i << ">"
206           << DOT::EscapeString(DTraits.getEdgeDestLabel(Node, i));
207       }
208
209       if (i != e)
210         O << "|<d64>truncated...";
211       O << "}";
212     }
213
214     O << "}\"];\n";   // Finish printing the "node" line
215
216     // Output all of the edges now
217     child_iterator EI = GTraits::child_begin(Node);
218     child_iterator EE = GTraits::child_end(Node);
219     for (unsigned i = 0; EI != EE && i != 64; ++EI, ++i)
220       if (!DTraits.isNodeHidden(*EI))
221         writeEdge(Node, i, EI);
222     for (; EI != EE; ++EI)
223       if (!DTraits.isNodeHidden(*EI))
224         writeEdge(Node, 64, EI);
225   }
226
227   void writeEdge(NodeType *Node, unsigned edgeidx, child_iterator EI) {
228     if (NodeType *TargetNode = *EI) {
229       int DestPort = -1;
230       if (DTraits.edgeTargetsEdgeSource(Node, EI)) {
231         child_iterator TargetIt = DTraits.getEdgeTarget(Node, EI);
232
233         // Figure out which edge this targets...
234         unsigned Offset =
235           (unsigned)std::distance(GTraits::child_begin(TargetNode), TargetIt);
236         DestPort = static_cast<int>(Offset);
237       }
238
239       if (DTraits.getEdgeSourceLabel(Node, EI) == "")
240         edgeidx = -1;
241
242       emitEdge(static_cast<const void*>(Node), edgeidx,
243                static_cast<const void*>(TargetNode), DestPort,
244                DTraits.getEdgeAttributes(Node, EI));
245     }
246   }
247
248   /// emitSimpleNode - Outputs a simple (non-record) node
249   void emitSimpleNode(const void *ID, const std::string &Attr,
250                       const std::string &Label, unsigned NumEdgeSources = 0,
251                       const std::vector<std::string> *EdgeSourceLabels = 0) {
252     O << "\tNode" << ID << "[ ";
253     if (!Attr.empty())
254       O << Attr << ",";
255     O << " label =\"";
256     if (NumEdgeSources) O << "{";
257     O << DOT::EscapeString(Label);
258     if (NumEdgeSources) {
259       O << "|{";
260
261       for (unsigned i = 0; i != NumEdgeSources; ++i) {
262         if (i) O << "|";
263         O << "<s" << i << ">";
264         if (EdgeSourceLabels) O << DOT::EscapeString((*EdgeSourceLabels)[i]);
265       }
266       O << "}}";
267     }
268     O << "\"];\n";
269   }
270
271   /// emitEdge - Output an edge from a simple node into the graph...
272   void emitEdge(const void *SrcNodeID, int SrcNodePort,
273                 const void *DestNodeID, int DestNodePort,
274                 const std::string &Attrs) {
275     if (SrcNodePort  > 64) return;             // Eminating from truncated part?
276     if (DestNodePort > 64) DestNodePort = 64;  // Targetting the truncated part?
277
278     O << "\tNode" << SrcNodeID;
279     if (SrcNodePort >= 0)
280       O << ":s" << SrcNodePort;
281     O << " -> Node" << DestNodeID;
282     if (DestNodePort >= 0 && DTraits.hasEdgeDestLabels())
283       O << ":d" << DestNodePort;
284
285     if (!Attrs.empty())
286       O << "[" << Attrs << "]";
287     O << ";\n";
288   }
289
290   /// getOStream - Get the raw output stream into the graph file. Useful to
291   /// write fancy things using addCustomGraphFeatures().
292   raw_ostream &getOStream() {
293     return O;
294   }
295 };
296
297 template<typename GraphType>
298 raw_ostream &WriteGraph(raw_ostream &O, const GraphType &G,
299                         bool ShortNames = false,
300                         const std::string &Title = "") {
301   // Start the graph emission process...
302   GraphWriter<GraphType> W(O, G, ShortNames);
303
304   // Emit the graph.
305   W.writeGraph(ShortNames, Title);
306
307   return O;
308 }
309
310 template<typename GraphType>
311 sys::Path WriteGraph(const GraphType &G, const std::string &Name,
312                      bool ShortNames = false, const std::string &Title = "") {
313   std::string ErrMsg;
314   sys::Path Filename = sys::Path::GetTemporaryDirectory(&ErrMsg);
315   if (Filename.isEmpty()) {
316     errs() << "Error: " << ErrMsg << "\n";
317     return Filename;
318   }
319   Filename.appendComponent(Name + ".dot");
320   if (Filename.makeUnique(true,&ErrMsg)) {
321     errs() << "Error: " << ErrMsg << "\n";
322     return sys::Path();
323   }
324
325   errs() << "Writing '" << Filename.str() << "'... ";
326
327   std::string ErrorInfo;
328   raw_fd_ostream O(Filename.c_str(), ErrorInfo);
329
330   if (ErrorInfo.empty()) {
331     llvm::WriteGraph(O, G, ShortNames, Title);
332     errs() << " done. \n";
333   } else {
334     errs() << "error opening file '" << Filename.str() << "' for writing!\n";
335     Filename.clear();
336   }
337
338   return Filename;
339 }
340
341 /// ViewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
342 /// then cleanup.  For use from the debugger.
343 ///
344 template<typename GraphType>
345 void ViewGraph(const GraphType &G, const std::string &Name,
346                bool ShortNames = false, const std::string &Title = "",
347                GraphProgram::Name Program = GraphProgram::DOT) {
348   sys::Path Filename = llvm::WriteGraph(G, Name, ShortNames, Title);
349
350   if (Filename.isEmpty())
351     return;
352
353   DisplayGraph(Filename, true, Program);
354 }
355
356 } // End llvm namespace
357
358 #endif