GraphWriter.h revision afbd0737e7593f1b79ed5060e506749558e82ab9
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/Streams.h"
28#include "llvm/ADT/GraphTraits.h"
29#include "llvm/System/Path.h"
30#include <fstream>
31#include <vector>
32
33namespace llvm {
34
35namespace DOT {  // Private functions...
36  inline std::string EscapeString(const std::string &Label) {
37    std::string Str(Label);
38    for (unsigned i = 0; i != Str.length(); ++i)
39      switch (Str[i]) {
40      case '\n':
41        Str.insert(Str.begin()+i, '\\');  // Escape character...
42        ++i;
43        Str[i] = 'n';
44        break;
45      case '\t':
46        Str.insert(Str.begin()+i, ' ');  // Convert to two spaces
47        ++i;
48        Str[i] = ' ';
49        break;
50      case '\\':
51        if (i+1 != Str.length())
52          switch (Str[i+1]) {
53            case 'l': continue; // don't disturb \l
54            case '|': case '{': case '}':
55               Str.erase(Str.begin()+i); continue;
56            default: break;
57          }
58      case '{': case '}':
59      case '<': case '>':
60      case '|': case '"':
61        Str.insert(Str.begin()+i, '\\');  // Escape character...
62        ++i;  // don't infinite loop
63        break;
64      }
65    return Str;
66  }
67}
68
69void DisplayGraph(const sys::Path& Filename);
70
71template<typename GraphType>
72class GraphWriter {
73  std::ostream &O;
74  const GraphType &G;
75
76  typedef DOTGraphTraits<GraphType>           DOTTraits;
77  typedef GraphTraits<GraphType>              GTraits;
78  typedef typename GTraits::NodeType          NodeType;
79  typedef typename GTraits::nodes_iterator    node_iterator;
80  typedef typename GTraits::ChildIteratorType child_iterator;
81public:
82  GraphWriter(std::ostream &o, const GraphType &g) : O(o), G(g) {}
83
84  void writeHeader(const std::string &Name) {
85    std::string GraphName = DOTTraits::getGraphName(G);
86
87    if (!Name.empty())
88      O << "digraph " << Name << " {\n";
89    else if (!GraphName.empty())
90      O << "digraph " << GraphName << " {\n";
91    else
92      O << "digraph unnamed {\n";
93
94    if (DOTTraits::renderGraphFromBottomUp())
95      O << "\trankdir=\"BT\";\n";
96
97    if (!GraphName.empty())
98      O << "\tlabel=\"" << DOT::EscapeString(GraphName) << "\";\n";
99    O << DOTTraits::getGraphProperties(G);
100    O << "\n";
101  }
102
103  void writeFooter() {
104    // Finish off the graph
105    O << "}\n";
106  }
107
108  void writeNodes() {
109    // Loop over the graph, printing it out...
110    for (node_iterator I = GTraits::nodes_begin(G), E = GTraits::nodes_end(G);
111         I != E; ++I)
112      writeNode(*I);
113  }
114
115  void writeNode(NodeType& Node) {
116    writeNode(&Node);
117  }
118
119  void writeNode(NodeType *const *Node) {
120    writeNode(*Node);
121  }
122
123  void writeNode(NodeType *Node) {
124    std::string NodeAttributes = DOTTraits::getNodeAttributes(Node, G);
125
126    O << "\tNode" << reinterpret_cast<const void*>(Node) << " [shape=record,";
127    if (!NodeAttributes.empty()) O << NodeAttributes << ",";
128    O << "label=\"{";
129
130    if (!DOTTraits::renderGraphFromBottomUp()) {
131      O << DOT::EscapeString(DOTTraits::getNodeLabel(Node, G));
132
133      // If we should include the address of the node in the label, do so now.
134      if (DOTTraits::hasNodeAddressLabel(Node, G))
135        O << "|" << (void*)Node;
136    }
137
138    // Print out the fields of the current node...
139    child_iterator EI = GTraits::child_begin(Node);
140    child_iterator EE = GTraits::child_end(Node);
141    if (EI != EE) {
142      if (!DOTTraits::renderGraphFromBottomUp()) O << "|";
143      O << "{";
144
145      for (unsigned i = 0; EI != EE && i != 64; ++EI, ++i) {
146        if (i) O << "|";
147        O << "<g" << i << ">" << DOTTraits::getEdgeSourceLabel(Node, EI);
148      }
149
150      if (EI != EE)
151        O << "|<g64>truncated...";
152      O << "}";
153      if (DOTTraits::renderGraphFromBottomUp()) O << "|";
154    }
155
156    if (DOTTraits::renderGraphFromBottomUp()) {
157      O << DOT::EscapeString(DOTTraits::getNodeLabel(Node, G));
158
159      // If we should include the address of the node in the label, do so now.
160      if (DOTTraits::hasNodeAddressLabel(Node, G))
161        O << "|" << (void*)Node;
162    }
163
164    O << "}\"];\n";   // Finish printing the "node" line
165
166    // Output all of the edges now
167    EI = GTraits::child_begin(Node);
168    for (unsigned i = 0; EI != EE && i != 64; ++EI, ++i)
169      writeEdge(Node, i, EI);
170    for (; EI != EE; ++EI)
171      writeEdge(Node, 64, EI);
172  }
173
174  void writeEdge(NodeType *Node, unsigned edgeidx, child_iterator EI) {
175    if (NodeType *TargetNode = *EI) {
176      int DestPort = -1;
177      if (DOTTraits::edgeTargetsEdgeSource(Node, EI)) {
178        child_iterator TargetIt = DOTTraits::getEdgeTarget(Node, EI);
179
180        // Figure out which edge this targets...
181        unsigned Offset =
182          (unsigned)std::distance(GTraits::child_begin(TargetNode), TargetIt);
183        DestPort = static_cast<int>(Offset);
184      }
185
186      emitEdge(reinterpret_cast<const void*>(Node), edgeidx,
187               reinterpret_cast<const void*>(TargetNode), DestPort,
188               DOTTraits::getEdgeAttributes(Node, EI));
189    }
190  }
191
192  /// emitSimpleNode - Outputs a simple (non-record) node
193  void emitSimpleNode(const void *ID, const std::string &Attr,
194                      const std::string &Label, unsigned NumEdgeSources = 0,
195                      const std::vector<std::string> *EdgeSourceLabels = 0) {
196    O << "\tNode" << ID << "[ ";
197    if (!Attr.empty())
198      O << Attr << ",";
199    O << " label =\"";
200    if (NumEdgeSources) O << "{";
201    O << DOT::EscapeString(Label);
202    if (NumEdgeSources) {
203      O << "|{";
204
205      for (unsigned i = 0; i != NumEdgeSources; ++i) {
206        if (i) O << "|";
207        O << "<g" << i << ">";
208        if (EdgeSourceLabels) O << (*EdgeSourceLabels)[i];
209      }
210      O << "}}";
211    }
212    O << "\"];\n";
213  }
214
215  /// emitEdge - Output an edge from a simple node into the graph...
216  void emitEdge(const void *SrcNodeID, int SrcNodePort,
217                const void *DestNodeID, int DestNodePort,
218                const std::string &Attrs) {
219    if (SrcNodePort  > 64) return;             // Eminating from truncated part?
220    if (DestNodePort > 64) DestNodePort = 64;  // Targetting the truncated part?
221
222    O << "\tNode" << SrcNodeID;
223    if (SrcNodePort >= 0)
224      O << ":g" << SrcNodePort;
225    O << " -> Node" << reinterpret_cast<const void*>(DestNodeID);
226    if (DestNodePort >= 0)
227      O << ":g" << DestNodePort;
228
229    if (!Attrs.empty())
230      O << "[" << Attrs << "]";
231    O << ";\n";
232  }
233};
234
235template<typename GraphType>
236std::ostream &WriteGraph(std::ostream &O, const GraphType &G,
237                         const std::string &Name = "") {
238  // Start the graph emission process...
239  GraphWriter<GraphType> W(O, G);
240
241  // Output the header for the graph...
242  W.writeHeader(Name);
243
244  // Emit all of the nodes in the graph...
245  W.writeNodes();
246
247  // Output any customizations on the graph
248  DOTGraphTraits<GraphType>::addCustomGraphFeatures(G, W);
249
250  // Output the end of the graph
251  W.writeFooter();
252  return O;
253}
254
255template<typename GraphType>
256sys::Path WriteGraph(const GraphType &G,
257                     const std::string& Name,
258                     const std::string& Title = "") {
259  std::string ErrMsg;
260  sys::Path Filename = sys::Path::GetTemporaryDirectory(&ErrMsg);
261  if (Filename.isEmpty()) {
262    cerr << "Error: " << ErrMsg << "\n";
263    return Filename;
264  }
265  Filename.appendComponent(Name + ".dot");
266  if (Filename.makeUnique(true,&ErrMsg)) {
267    cerr << "Error: " << ErrMsg << "\n";
268    return sys::Path();
269  }
270
271  cerr << "Writing '" << Filename << "'... ";
272
273  std::ofstream O(Filename.c_str());
274
275  if (O.good()) {
276    // Start the graph emission process...
277    GraphWriter<GraphType> W(O, G);
278
279    // Output the header for the graph...
280    W.writeHeader(Title);
281
282    // Emit all of the nodes in the graph...
283    W.writeNodes();
284
285    // Output any customizations on the graph
286    DOTGraphTraits<GraphType>::addCustomGraphFeatures(G, W);
287
288    // Output the end of the graph
289    W.writeFooter();
290    cerr << " done. \n";
291
292    O.close();
293
294  } else {
295    cerr << "error opening file for writing!\n";
296    Filename.clear();
297  }
298
299  return Filename;
300}
301
302/// ViewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
303/// then cleanup.  For use from the debugger.
304///
305template<typename GraphType>
306void ViewGraph(const GraphType& G,
307               const std::string& Name,
308               const std::string& Title = "") {
309  sys::Path Filename =  WriteGraph(G, Name, Title);
310
311  if (Filename.isEmpty()) {
312    return;
313  }
314
315  DisplayGraph(Filename);
316}
317
318} // End llvm namespace
319
320#endif
321