c89eb55c98f0fb7ddbf8383dfda2bfb8900e5818
[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   bool ShortNames;
56
57   typedef DOTGraphTraits<GraphType>           DOTTraits;
58   typedef GraphTraits<GraphType>              GTraits;
59   typedef typename GTraits::NodeType          NodeType;
60   typedef typename GTraits::nodes_iterator    node_iterator;
61   typedef typename GTraits::ChildIteratorType child_iterator;
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 = DOTTraits::getEdgeSourceLabel(Node, EI);
72
73       if (label == "")
74         continue;
75
76       hasEdgeSourceLabels = true;
77
78       if (i)
79         O << "|";
80
81       O << "<s" << i << ">" << DOTTraits::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) :
92     O(o), G(g), ShortNames(SN) {}
93
94   void writeHeader(const std::string &Name) {
95     std::string GraphName = DOTTraits::getGraphName(G);
96
97     if (!Name.empty())
98       O << "digraph \"" << DOT::EscapeString(Name) << "\" {\n";
99     else if (!GraphName.empty())
100       O << "digraph \"" << DOT::EscapeString(GraphName) << "\" {\n";
101     else
102       O << "digraph unnamed {\n";
103
104     if (DOTTraits::renderGraphFromBottomUp())
105       O << "\trankdir=\"BT\";\n";
106
107     if (!Name.empty())
108       O << "\tlabel=\"" << DOT::EscapeString(Name) << "\";\n";
109     else if (!GraphName.empty())
110       O << "\tlabel=\"" << DOT::EscapeString(GraphName) << "\";\n";
111     O << DOTTraits::getGraphProperties(G);
112     O << "\n";
113   }
114
115   void writeFooter() {
116     // Finish off the graph
117     O << "}\n";
118   }
119
120   void writeNodes() {
121     // Loop over the graph, printing it out...
122     for (node_iterator I = GTraits::nodes_begin(G), E = GTraits::nodes_end(G);
123          I != E; ++I)
124       writeNode(*I);
125   }
126
127   void writeNode(NodeType& Node) {
128     writeNode(&Node);
129   }
130
131   void writeNode(NodeType *const *Node) {
132     writeNode(*Node);
133   }
134
135   void writeNode(NodeType *Node) {
136     std::string NodeAttributes = DOTTraits::getNodeAttributes(Node, G);
137
138     O << "\tNode" << static_cast<const void*>(Node) << " [shape=record,";
139     if (!NodeAttributes.empty()) O << NodeAttributes << ",";
140     O << "label=\"{";
141
142     if (!DOTTraits::renderGraphFromBottomUp()) {
143       O << DOT::EscapeString(DOTTraits::getNodeLabel(Node, G, ShortNames));
144
145       // If we should include the address of the node in the label, do so now.
146       if (DOTTraits::hasNodeAddressLabel(Node, G))
147         O << "|" << (void*)Node;
148     }
149
150     std::string edgeSourceLabels;
151     raw_string_ostream::raw_string_ostream EdgeSourceLabels(edgeSourceLabels);
152     bool hasEdgeSourceLabels = getEdgeSourceLabels(EdgeSourceLabels, Node);
153
154     if (hasEdgeSourceLabels) {
155       if (!DOTTraits::renderGraphFromBottomUp()) O << "|";
156
157       O << "{" << EdgeSourceLabels.str() << "}";
158
159       if (DOTTraits::renderGraphFromBottomUp()) O << "|";
160     }
161
162     if (DOTTraits::renderGraphFromBottomUp()) {
163       O << DOT::EscapeString(DOTTraits::getNodeLabel(Node, G, ShortNames));
164
165       // If we should include the address of the node in the label, do so now.
166       if (DOTTraits::hasNodeAddressLabel(Node, G))
167         O << "|" << (void*)Node;
168     }
169
170     if (DOTTraits::hasEdgeDestLabels()) {
171       O << "|{";
172
173       unsigned i = 0, e = DOTTraits::numEdgeDestLabels(Node);
174       for (; i != e && i != 64; ++i) {
175         if (i) O << "|";
176         O << "<d" << i << ">" << DOTTraits::getEdgeDestLabel(Node, i);
177       }
178
179       if (i != e)
180         O << "|<d64>truncated...";
181       O << "}";
182     }
183
184     O << "}\"];\n";   // Finish printing the "node" line
185
186     // Output all of the edges now
187     child_iterator EI = GTraits::child_begin(Node);
188     child_iterator EE = GTraits::child_end(Node);
189     for (unsigned i = 0; EI != EE && i != 64; ++EI, ++i)
190       writeEdge(Node, i, EI);
191     for (; EI != EE; ++EI)
192       writeEdge(Node, 64, EI);
193   }
194
195   void writeEdge(NodeType *Node, unsigned edgeidx, child_iterator EI) {
196     if (NodeType *TargetNode = *EI) {
197       int DestPort = -1;
198       if (DOTTraits::edgeTargetsEdgeSource(Node, EI)) {
199         child_iterator TargetIt = DOTTraits::getEdgeTarget(Node, EI);
200
201         // Figure out which edge this targets...
202         unsigned Offset =
203           (unsigned)std::distance(GTraits::child_begin(TargetNode), TargetIt);
204         DestPort = static_cast<int>(Offset);
205       }
206
207       if (DOTTraits::getEdgeSourceLabel(Node, EI) == "")
208         edgeidx = -1;
209
210       emitEdge(static_cast<const void*>(Node), edgeidx,
211                static_cast<const void*>(TargetNode), DestPort,
212                DOTTraits::getEdgeAttributes(Node, EI));
213     }
214   }
215
216   /// emitSimpleNode - Outputs a simple (non-record) node
217   void emitSimpleNode(const void *ID, const std::string &Attr,
218                       const std::string &Label, unsigned NumEdgeSources = 0,
219                       const std::vector<std::string> *EdgeSourceLabels = 0) {
220     O << "\tNode" << ID << "[ ";
221     if (!Attr.empty())
222       O << Attr << ",";
223     O << " label =\"";
224     if (NumEdgeSources) O << "{";
225     O << DOT::EscapeString(Label);
226     if (NumEdgeSources) {
227       O << "|{";
228
229       for (unsigned i = 0; i != NumEdgeSources; ++i) {
230         if (i) O << "|";
231         O << "<s" << i << ">";
232         if (EdgeSourceLabels) O << (*EdgeSourceLabels)[i];
233       }
234       O << "}}";
235     }
236     O << "\"];\n";
237   }
238
239   /// emitEdge - Output an edge from a simple node into the graph...
240   void emitEdge(const void *SrcNodeID, int SrcNodePort,
241                 const void *DestNodeID, int DestNodePort,
242                 const std::string &Attrs) {
243     if (SrcNodePort  > 64) return;             // Eminating from truncated part?
244     if (DestNodePort > 64) DestNodePort = 64;  // Targetting the truncated part?
245
246     O << "\tNode" << SrcNodeID;
247     if (SrcNodePort >= 0)
248       O << ":s" << SrcNodePort;
249     O << " -> Node" << DestNodeID;
250     if (DestNodePort >= 0 && DOTTraits::hasEdgeDestLabels())
251       O << ":d" << DestNodePort;
252
253     if (!Attrs.empty())
254       O << "[" << Attrs << "]";
255     O << ";\n";
256   }
257 };
258
259 template<typename GraphType>
260 raw_ostream &WriteGraph(raw_ostream &O, const GraphType &G,
261                         bool ShortNames = false,
262                         const std::string &Name = "",
263                         const std::string &Title = "") {
264   // Start the graph emission process...
265   GraphWriter<GraphType> W(O, G, ShortNames);
266
267   // Output the header for the graph...
268   W.writeHeader(Title);
269
270   // Emit all of the nodes in the graph...
271   W.writeNodes();
272
273   // Output any customizations on the graph
274   DOTGraphTraits<GraphType>::addCustomGraphFeatures(G, W);
275
276   // Output the end of the graph
277   W.writeFooter();
278   return O;
279 }
280
281 template<typename GraphType>
282 sys::Path WriteGraph(const GraphType &G, const std::string &Name,
283                      bool ShortNames = false, const std::string &Title = "") {
284   std::string ErrMsg;
285   sys::Path Filename = sys::Path::GetTemporaryDirectory(&ErrMsg);
286   if (Filename.isEmpty()) {
287     errs() << "Error: " << ErrMsg << "\n";
288     return Filename;
289   }
290   Filename.appendComponent(Name + ".dot");
291   if (Filename.makeUnique(true,&ErrMsg)) {
292     errs() << "Error: " << ErrMsg << "\n";
293     return sys::Path();
294   }
295
296   errs() << "Writing '" << Filename.str() << "'... ";
297
298   std::string ErrorInfo;
299   raw_fd_ostream O(Filename.c_str(), ErrorInfo);
300
301   if (ErrorInfo.empty()) {
302     WriteGraph(O, G, ShortNames, Name, Title);
303     errs() << " done. \n";
304   } else {
305     errs() << "error opening file '" << Filename.str() << "' for writing!\n";
306     Filename.clear();
307   }
308
309   return Filename;
310 }
311
312 /// ViewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
313 /// then cleanup.  For use from the debugger.
314 ///
315 template<typename GraphType>
316 void ViewGraph(const GraphType &G, const std::string &Name,
317                bool ShortNames = false, const std::string &Title = "",
318                GraphProgram::Name Program = GraphProgram::DOT) {
319   sys::Path Filename = WriteGraph(G, Name, ShortNames, Title);
320
321   if (Filename.isEmpty())
322     return;
323
324   DisplayGraph(Filename, true, Program);
325 }
326
327 } // End llvm namespace
328
329 #endif