GraphWriter.h revision c500566d9fb70472a17f62b4cf1689062c52e095
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
33namespace llvm {
34
35namespace DOT {  // Private functions...
36  std::string EscapeString(const std::string &Label);
37}
38
39namespace GraphProgram {
40   enum Name {
41      DOT,
42      FDP,
43      NEATO,
44      TWOPI,
45      CIRCO
46   };
47}
48
49void DisplayGraph(const sys::Path& Filename, bool wait=true, GraphProgram::Name program = GraphProgram::DOT);
50
51template<typename GraphType>
52class 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
90public:
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) {
251      if (DOTTraits::hasEdgeDestLabels())
252        O << ":d" << DestNodePort;
253      else
254        O << ":s" << DestNodePort;
255    }
256
257    if (!Attrs.empty())
258      O << "[" << Attrs << "]";
259    O << ";\n";
260  }
261};
262
263template<typename GraphType>
264raw_ostream &WriteGraph(raw_ostream &O, const GraphType &G,
265                        bool ShortNames = false,
266                        const std::string &Name = "",
267                        const std::string &Title = "") {
268  // Start the graph emission process...
269  GraphWriter<GraphType> W(O, G, ShortNames);
270
271  // Output the header for the graph...
272  W.writeHeader(Title);
273
274  // Emit all of the nodes in the graph...
275  W.writeNodes();
276
277  // Output any customizations on the graph
278  DOTGraphTraits<GraphType>::addCustomGraphFeatures(G, W);
279
280  // Output the end of the graph
281  W.writeFooter();
282  return O;
283}
284
285template<typename GraphType>
286sys::Path WriteGraph(const GraphType &G, const std::string &Name,
287                     bool ShortNames = false, const std::string &Title = "") {
288  std::string ErrMsg;
289  sys::Path Filename = sys::Path::GetTemporaryDirectory(&ErrMsg);
290  if (Filename.isEmpty()) {
291    errs() << "Error: " << ErrMsg << "\n";
292    return Filename;
293  }
294  Filename.appendComponent(Name + ".dot");
295  if (Filename.makeUnique(true,&ErrMsg)) {
296    errs() << "Error: " << ErrMsg << "\n";
297    return sys::Path();
298  }
299
300  errs() << "Writing '" << Filename.str() << "'... ";
301
302  std::string ErrorInfo;
303  raw_fd_ostream O(Filename.c_str(), ErrorInfo);
304
305  if (ErrorInfo.empty()) {
306    WriteGraph(O, G, ShortNames, Name, Title);
307    errs() << " done. \n";
308  } else {
309    errs() << "error opening file '" << Filename.str() << "' for writing!\n";
310    Filename.clear();
311  }
312
313  return Filename;
314}
315
316/// ViewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
317/// then cleanup.  For use from the debugger.
318///
319template<typename GraphType>
320void ViewGraph(const GraphType &G, const std::string &Name,
321               bool ShortNames = false, const std::string &Title = "",
322               GraphProgram::Name Program = GraphProgram::DOT) {
323  sys::Path Filename = WriteGraph(G, Name, ShortNames, Title);
324
325  if (Filename.isEmpty())
326    return;
327
328  DisplayGraph(Filename, true, Program);
329}
330
331} // End llvm namespace
332
333#endif
334