Support/GraphWriter: Replace all internal uses of PathV1 with PathV2. The external...
[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/FileSystem.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/ADT/GraphTraits.h"
30 #include "llvm/Support/Path.h"
31 #include <vector>
32 #include <cassert>
33
34 namespace llvm {
35
36 namespace DOT {  // Private functions...
37   std::string EscapeString(const std::string &Label);
38 }
39
40 namespace GraphProgram {
41    enum Name {
42       DOT,
43       FDP,
44       NEATO,
45       TWOPI,
46       CIRCO
47    };
48 }
49
50 void DisplayGraph(const sys::Path& Filename, bool wait=true, GraphProgram::Name program = GraphProgram::DOT);
51
52 template<typename GraphType>
53 class GraphWriter {
54   raw_ostream &O;
55   const GraphType &G;
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   DOTTraits DTraits;
63
64   // Writes the edge labels of the node to O and returns true if there are any
65   // edge labels not equal to the empty string "".
66   bool getEdgeSourceLabels(raw_ostream &O, NodeType *Node) {
67     child_iterator EI = GTraits::child_begin(Node);
68     child_iterator EE = GTraits::child_end(Node);
69     bool hasEdgeSourceLabels = false;
70
71     for (unsigned i = 0; EI != EE && i != 64; ++EI, ++i) {
72       std::string label = DTraits.getEdgeSourceLabel(Node, EI);
73
74       if (label == "")
75         continue;
76
77       hasEdgeSourceLabels = true;
78
79       if (i)
80         O << "|";
81
82       O << "<s" << i << ">" << DTraits.getEdgeSourceLabel(Node, EI);
83     }
84
85     if (EI != EE && hasEdgeSourceLabels)
86       O << "|<s64>truncated...";
87
88     return hasEdgeSourceLabels;
89   }
90
91 public:
92   GraphWriter(raw_ostream &o, const GraphType &g, bool SN) : O(o), G(g) {
93     DTraits = DOTTraits(SN);
94   }
95
96   void writeGraph(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(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   SmallString<128> FilePath;
314
315   int FileFD;
316   if (error_code ec = sys::fs::unique_file("graph-" + Name + "-%%-%%-%%-%%.dot",
317                                            FileFD, FilePath)) {
318     errs() << "Error creating output file: " << ec.message() << '\n';
319     return sys::Path();
320   }
321
322   errs() << "Writing '" << FilePath << "'... ";
323   raw_fd_ostream O(FileFD, true);
324   llvm::WriteGraph(O, G, ShortNames, Title);
325   errs() << " done. \n";
326
327   return sys::Path(FilePath.str());
328 }
329
330 /// ViewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
331 /// then cleanup.  For use from the debugger.
332 ///
333 template<typename GraphType>
334 void ViewGraph(const GraphType &G, const std::string &Name,
335                bool ShortNames = false, const std::string &Title = "",
336                GraphProgram::Name Program = GraphProgram::DOT) {
337   sys::Path Filename = llvm::WriteGraph(G, Name, ShortNames, Title);
338
339   if (Filename.isEmpty())
340     return;
341
342   DisplayGraph(Filename, true, Program);
343 }
344
345 } // End llvm namespace
346
347 #endif