1 //===- llvm/Support/GraphWriter.h - Write graph to a .dot file --*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file defines a simple interface that can be used to print out generic
10 // LLVM graphs to ".dot" files. "dot" is a tool that is part of the AT&T
11 // graphviz package (http://www.research.att.com/sw/tools/graphviz/) which can
12 // be used to turn the files output by this interface into a variety of
13 // different graphics formats.
15 // Graphs do not need to implement any interface past what is already required
16 // by the GraphTraits template, but they can choose to implement specializations
17 // of the DOTGraphTraits template if they want to customize the graphs output in
20 //===----------------------------------------------------------------------===//
22 #ifndef LLVM_SUPPORT_GRAPHWRITER_H
23 #define LLVM_SUPPORT_GRAPHWRITER_H
25 #include "llvm/ADT/GraphTraits.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Twine.h"
28 #include "llvm/Support/DOTGraphTraits.h"
29 #include "llvm/Support/FileSystem.h"
30 #include "llvm/Support/raw_ostream.h"
33 #include <type_traits>
38 namespace DOT { // Private functions...
40 std::string EscapeString(const std::string &Label);
42 /// Get a color string for this node number. Simply round-robin selects
43 /// from a reasonable number of colors.
44 StringRef getColorString(unsigned NodeNumber);
46 } // end namespace DOT
48 namespace GraphProgram {
58 } // end namespace GraphProgram
60 bool DisplayGraph(StringRef Filename, bool wait = true,
61 GraphProgram::Name program = GraphProgram::DOT);
63 template<typename GraphType>
67 bool RenderUsingHTML = false;
69 using DOTTraits = DOTGraphTraits<GraphType>;
70 using GTraits = GraphTraits<GraphType>;
71 using NodeRef = typename GTraits::NodeRef;
72 using node_iterator = typename GTraits::nodes_iterator;
73 using child_iterator = typename GTraits::ChildIteratorType;
76 static_assert(std::is_pointer<NodeRef>::value,
77 "FIXME: Currently GraphWriter requires the NodeRef type to be "
78 "a pointer.\nThe pointer usage should be moved to "
79 "DOTGraphTraits, and removed from GraphWriter itself.");
81 // Writes the edge labels of the node to O and returns true if there are any
82 // edge labels not equal to the empty string "".
83 bool getEdgeSourceLabels(raw_ostream &O, NodeRef Node) {
84 child_iterator EI = GTraits::child_begin(Node);
85 child_iterator EE = GTraits::child_end(Node);
86 bool hasEdgeSourceLabels = false;
91 for (unsigned i = 0; EI != EE && i != 64; ++EI, ++i) {
92 std::string label = DTraits.getEdgeSourceLabel(Node, EI);
97 hasEdgeSourceLabels = true;
100 O << "<td colspan=\"1\" port=\"s" << i << "\">" << label << "</td>";
105 O << "<s" << i << ">" << DOT::EscapeString(label);
109 if (EI != EE && hasEdgeSourceLabels) {
111 O << "<td colspan=\"1\" port=\"s64\">truncated...</td>";
113 O << "|<s64>truncated...";
116 return hasEdgeSourceLabels;
120 GraphWriter(raw_ostream &o, const GraphType &g, bool SN) : O(o), G(g) {
121 DTraits = DOTTraits(SN);
122 RenderUsingHTML = DTraits.renderNodesUsingHTML();
125 void writeGraph(const std::string &Title = "") {
126 // Output the header for the graph...
129 // Emit all of the nodes in the graph...
132 // Output any customizations on the graph
133 DOTGraphTraits<GraphType>::addCustomGraphFeatures(G, *this);
135 // Output the end of the graph
139 void writeHeader(const std::string &Title) {
140 std::string GraphName(DTraits.getGraphName(G));
143 O << "digraph \"" << DOT::EscapeString(Title) << "\" {\n";
144 else if (!GraphName.empty())
145 O << "digraph \"" << DOT::EscapeString(GraphName) << "\" {\n";
147 O << "digraph unnamed {\n";
149 if (DTraits.renderGraphFromBottomUp())
150 O << "\trankdir=\"BT\";\n";
153 O << "\tlabel=\"" << DOT::EscapeString(Title) << "\";\n";
154 else if (!GraphName.empty())
155 O << "\tlabel=\"" << DOT::EscapeString(GraphName) << "\";\n";
156 O << DTraits.getGraphProperties(G);
161 // Finish off the graph
166 // Loop over the graph, printing it out...
167 for (const auto Node : nodes<GraphType>(G))
168 if (!isNodeHidden(Node))
172 bool isNodeHidden(NodeRef Node) { return DTraits.isNodeHidden(Node, G); }
174 void writeNode(NodeRef Node) {
175 std::string NodeAttributes = DTraits.getNodeAttributes(Node, G);
177 O << "\tNode" << static_cast<const void *>(Node) << " [shape=";
183 if (!NodeAttributes.empty()) O << NodeAttributes << ",";
186 if (RenderUsingHTML) {
187 // Count the numbewr of edges out of the node to determine how
188 // many columns to span (max 64)
189 unsigned ColSpan = 0;
190 child_iterator EI = GTraits::child_begin(Node);
191 child_iterator EE = GTraits::child_end(Node);
192 for (; EI != EE && ColSpan != 64; ++EI, ++ColSpan)
196 // Include truncated messages when counting.
199 O << "<<table border=\"0\" cellborder=\"1\" cellspacing=\"0\""
200 << " cellpadding=\"0\"><tr><td align=\"text\" colspan=\"" << ColSpan
205 if (!DTraits.renderGraphFromBottomUp()) {
207 O << DTraits.getNodeLabel(Node, G) << "</td>";
209 O << DOT::EscapeString(DTraits.getNodeLabel(Node, G));
211 // If we should include the address of the node in the label, do so now.
212 std::string Id = DTraits.getNodeIdentifierLabel(Node, G);
214 O << "|" << DOT::EscapeString(Id);
216 std::string NodeDesc = DTraits.getNodeDescription(Node, G);
217 if (!NodeDesc.empty())
218 O << "|" << DOT::EscapeString(NodeDesc);
221 std::string edgeSourceLabels;
222 raw_string_ostream EdgeSourceLabels(edgeSourceLabels);
223 bool hasEdgeSourceLabels = getEdgeSourceLabels(EdgeSourceLabels, Node);
225 if (hasEdgeSourceLabels) {
226 if (!DTraits.renderGraphFromBottomUp())
227 if (!RenderUsingHTML)
231 O << EdgeSourceLabels.str();
233 O << "{" << EdgeSourceLabels.str() << "}";
235 if (DTraits.renderGraphFromBottomUp())
236 if (!RenderUsingHTML)
240 if (DTraits.renderGraphFromBottomUp()) {
242 O << DTraits.getNodeLabel(Node, G);
244 O << DOT::EscapeString(DTraits.getNodeLabel(Node, G));
246 // If we should include the address of the node in the label, do so now.
247 std::string Id = DTraits.getNodeIdentifierLabel(Node, G);
249 O << "|" << DOT::EscapeString(Id);
251 std::string NodeDesc = DTraits.getNodeDescription(Node, G);
252 if (!NodeDesc.empty())
253 O << "|" << DOT::EscapeString(NodeDesc);
256 if (DTraits.hasEdgeDestLabels()) {
259 unsigned i = 0, e = DTraits.numEdgeDestLabels(Node);
260 for (; i != e && i != 64; ++i) {
262 O << "<d" << i << ">"
263 << DOT::EscapeString(DTraits.getEdgeDestLabel(Node, i));
267 O << "|<d64>truncated...";
272 O << "</tr></table>>";
275 O << "];\n"; // Finish printing the "node" line
277 // Output all of the edges now
278 child_iterator EI = GTraits::child_begin(Node);
279 child_iterator EE = GTraits::child_end(Node);
280 for (unsigned i = 0; EI != EE && i != 64; ++EI, ++i)
281 if (!DTraits.isNodeHidden(*EI, G))
282 writeEdge(Node, i, EI);
283 for (; EI != EE; ++EI)
284 if (!DTraits.isNodeHidden(*EI, G))
285 writeEdge(Node, 64, EI);
288 void writeEdge(NodeRef Node, unsigned edgeidx, child_iterator EI) {
289 if (NodeRef TargetNode = *EI) {
291 if (DTraits.edgeTargetsEdgeSource(Node, EI)) {
292 child_iterator TargetIt = DTraits.getEdgeTarget(Node, EI);
294 // Figure out which edge this targets...
296 (unsigned)std::distance(GTraits::child_begin(TargetNode), TargetIt);
297 DestPort = static_cast<int>(Offset);
300 if (DTraits.getEdgeSourceLabel(Node, EI).empty())
303 emitEdge(static_cast<const void*>(Node), edgeidx,
304 static_cast<const void*>(TargetNode), DestPort,
305 DTraits.getEdgeAttributes(Node, EI, G));
309 /// emitSimpleNode - Outputs a simple (non-record) node
310 void emitSimpleNode(const void *ID, const std::string &Attr,
311 const std::string &Label, unsigned NumEdgeSources = 0,
312 const std::vector<std::string> *EdgeSourceLabels = nullptr) {
313 O << "\tNode" << ID << "[ ";
317 if (NumEdgeSources) O << "{";
318 O << DOT::EscapeString(Label);
319 if (NumEdgeSources) {
322 for (unsigned i = 0; i != NumEdgeSources; ++i) {
324 O << "<s" << i << ">";
325 if (EdgeSourceLabels) O << DOT::EscapeString((*EdgeSourceLabels)[i]);
332 /// emitEdge - Output an edge from a simple node into the graph...
333 void emitEdge(const void *SrcNodeID, int SrcNodePort,
334 const void *DestNodeID, int DestNodePort,
335 const std::string &Attrs) {
336 if (SrcNodePort > 64) return; // Eminating from truncated part?
337 if (DestNodePort > 64) DestNodePort = 64; // Targeting the truncated part?
339 O << "\tNode" << SrcNodeID;
340 if (SrcNodePort >= 0)
341 O << ":s" << SrcNodePort;
342 O << " -> Node" << DestNodeID;
343 if (DestNodePort >= 0 && DTraits.hasEdgeDestLabels())
344 O << ":d" << DestNodePort;
347 O << "[" << Attrs << "]";
351 /// getOStream - Get the raw output stream into the graph file. Useful to
352 /// write fancy things using addCustomGraphFeatures().
353 raw_ostream &getOStream() {
358 template<typename GraphType>
359 raw_ostream &WriteGraph(raw_ostream &O, const GraphType &G,
360 bool ShortNames = false,
361 const Twine &Title = "") {
362 // Start the graph emission process...
363 GraphWriter<GraphType> W(O, G, ShortNames);
366 W.writeGraph(Title.str());
371 std::string createGraphFilename(const Twine &Name, int &FD);
373 /// Writes graph into a provided @c Filename.
374 /// If @c Filename is empty, generates a random one.
375 /// \return The resulting filename, or an empty string if writing
377 template <typename GraphType>
378 std::string WriteGraph(const GraphType &G, const Twine &Name,
379 bool ShortNames = false,
380 const Twine &Title = "",
381 std::string Filename = "") {
383 if (Filename.empty()) {
384 Filename = createGraphFilename(Name.str(), FD);
386 std::error_code EC = sys::fs::openFileForWrite(
387 Filename, FD, sys::fs::CD_CreateAlways, sys::fs::OF_Text);
389 // Writing over an existing file is not considered an error.
390 if (EC == std::errc::file_exists) {
391 errs() << "file exists, overwriting" << "\n";
393 errs() << "error writing into file" << "\n";
396 errs() << "writing to the newly created file " << Filename << "\n";
399 raw_fd_ostream O(FD, /*shouldClose=*/ true);
402 errs() << "error opening file '" << Filename << "' for writing!\n";
406 llvm::WriteGraph(O, G, ShortNames, Title);
407 errs() << " done. \n";
412 /// DumpDotGraph - Just dump a dot graph to the user-provided file name.
413 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
414 template <typename GraphType>
415 LLVM_DUMP_METHOD void
416 dumpDotGraphToFile(const GraphType &G, const Twine &FileName,
417 const Twine &Title, bool ShortNames = false,
418 const Twine &Name = "") {
419 llvm::WriteGraph(G, Name, ShortNames, Title, FileName.str());
423 /// ViewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
424 /// then cleanup. For use from the debugger.
426 template<typename GraphType>
427 void ViewGraph(const GraphType &G, const Twine &Name,
428 bool ShortNames = false, const Twine &Title = "",
429 GraphProgram::Name Program = GraphProgram::DOT) {
430 std::string Filename = llvm::WriteGraph(G, Name, ShortNames, Title);
432 if (Filename.empty())
435 DisplayGraph(Filename, false, Program);
438 } // end namespace llvm
440 #endif // LLVM_SUPPORT_GRAPHWRITER_H