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