1 //===- ViewOpGraph.cpp - View/write op graphviz graphs --------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "mlir/Transforms/ViewOpGraph.h"
10 #include "PassDetail.h"
11 #include "mlir/IR/Block.h"
12 #include "mlir/IR/Operation.h"
13 #include "mlir/Support/IndentedOstream.h"
14 #include "llvm/Support/Format.h"
15 
16 using namespace mlir;
17 
18 static const StringRef kLineStyleDataFlow = "solid";
19 static const StringRef kShapeNode = "ellipse";
20 static const StringRef kShapeNone = "plain";
21 
22 /// Return the size limits for eliding large attributes.
23 static int64_t getLargeAttributeSizeLimit() {
24   // Use the default from the printer flags if possible.
25   if (Optional<int64_t> limit = OpPrintingFlags().getLargeElementsAttrLimit())
26     return *limit;
27   return 16;
28 }
29 
30 /// Return all values printed onto a stream as a string.
31 static std::string strFromOs(function_ref<void(raw_ostream &)> func) {
32   std::string buf;
33   llvm::raw_string_ostream os(buf);
34   func(os);
35   return os.str();
36 }
37 
38 /// Escape special characters such as '\n' and quotation marks.
39 static std::string escapeString(std::string str) {
40   return strFromOs([&](raw_ostream &os) { os.write_escaped(str); });
41 }
42 
43 /// Put quotation marks around a given string.
44 static std::string quoteString(std::string str) { return "\"" + str + "\""; }
45 
46 using AttributeMap = llvm::StringMap<std::string>;
47 
48 namespace {
49 
50 /// This struct represents a node in the DOT language. Each node has an
51 /// identifier and an optional identifier for the cluster (subgraph) that
52 /// contains the node.
53 /// Note: In the DOT language, edges can be drawn only from nodes to nodes, but
54 /// not between clusters. However, edges can be clipped to the boundary of a
55 /// cluster with `lhead` and `ltail` attributes. Therefore, when creating a new
56 /// cluster, an invisible "anchor" node is created.
57 struct Node {
58 public:
59   Node(int id = 0, Optional<int> clusterId = llvm::None)
60       : id(id), clusterId(clusterId) {}
61 
62   int id;
63   Optional<int> clusterId;
64 };
65 
66 /// This pass generates a Graphviz dataflow visualization of an MLIR operation.
67 /// Note: See https://www.graphviz.org/doc/info/lang.html for more information
68 /// about the Graphviz DOT language.
69 class PrintOpPass : public ViewOpGraphPassBase<PrintOpPass> {
70 public:
71   PrintOpPass(raw_ostream &os) : os(os) {}
72   PrintOpPass(const PrintOpPass &o) : os(o.os.getOStream()) {}
73 
74   void runOnOperation() override {
75     emitGraph([&]() {
76       processOperation(getOperation());
77       emitAllEdgeStmts();
78     });
79   }
80 
81 private:
82   /// Emit all edges. This function should be called after all nodes have been
83   /// emitted.
84   void emitAllEdgeStmts() {
85     for (const std::string &edge : edges)
86       os << edge << ";\n";
87     edges.clear();
88   }
89 
90   /// Emit a cluster (subgraph). The specified builder generates the body of the
91   /// cluster. Return the anchor node of the cluster.
92   Node emitClusterStmt(function_ref<void()> builder, std::string label = "") {
93     int clusterId = ++counter;
94     os << "subgraph cluster_" << clusterId << " {\n";
95     os.indent();
96     // Emit invisible anchor node from/to which arrows can be drawn.
97     Node anchorNode = emitNodeStmt(" ", kShapeNone);
98     os << attrStmt("label", quoteString(escapeString(label))) << ";\n";
99     builder();
100     os.unindent();
101     os << "}\n";
102     return Node(anchorNode.id, clusterId);
103   }
104 
105   /// Generate an attribute statement.
106   std::string attrStmt(const Twine &key, const Twine &value) {
107     return (key + " = " + value).str();
108   }
109 
110   /// Emit an attribute list.
111   void emitAttrList(raw_ostream &os, const AttributeMap &map) {
112     os << "[";
113     interleaveComma(map, os, [&](const auto &it) {
114       os << attrStmt(it.getKey(), it.getValue());
115     });
116     os << "]";
117   }
118 
119   // Print an MLIR attribute to `os`. Large attributes are truncated.
120   void emitMlirAttr(raw_ostream &os, Attribute attr) {
121     // A value used to elide large container attribute.
122     int64_t largeAttrLimit = getLargeAttributeSizeLimit();
123 
124     // Always emit splat attributes.
125     if (attr.isa<SplatElementsAttr>()) {
126       attr.print(os);
127       return;
128     }
129 
130     // Elide "big" elements attributes.
131     auto elements = attr.dyn_cast<ElementsAttr>();
132     if (elements && elements.getNumElements() > largeAttrLimit) {
133       os << std::string(elements.getType().getRank(), '[') << "..."
134          << std::string(elements.getType().getRank(), ']') << " : "
135          << elements.getType();
136       return;
137     }
138 
139     auto array = attr.dyn_cast<ArrayAttr>();
140     if (array && static_cast<int64_t>(array.size()) > largeAttrLimit) {
141       os << "[...]";
142       return;
143     }
144 
145     // Print all other attributes.
146     attr.print(os);
147   }
148 
149   /// Append an edge to the list of edges.
150   /// Note: Edges are written to the output stream via `emitAllEdgeStmts`.
151   void emitEdgeStmt(Node n1, Node n2, std::string label,
152                     StringRef style = kLineStyleDataFlow) {
153     AttributeMap attrs;
154     attrs["style"] = style.str();
155     // Do not label edges that start/end at a cluster boundary. Such edges are
156     // clipped at the boundary, but labels are not. This can lead to labels
157     // floating around without any edge next to them.
158     if (!n1.clusterId && !n2.clusterId)
159       attrs["label"] = quoteString(escapeString(label));
160     // Use `ltail` and `lhead` to draw edges between clusters.
161     if (n1.clusterId)
162       attrs["ltail"] = "cluster_" + std::to_string(*n1.clusterId);
163     if (n2.clusterId)
164       attrs["lhead"] = "cluster_" + std::to_string(*n2.clusterId);
165 
166     edges.push_back(strFromOs([&](raw_ostream &os) {
167       os << llvm::format("v%i -> v%i ", n1.id, n2.id);
168       emitAttrList(os, attrs);
169     }));
170   }
171 
172   /// Emit a graph. The specified builder generates the body of the graph.
173   void emitGraph(function_ref<void()> builder) {
174     os << "digraph G {\n";
175     os.indent();
176     // Edges between clusters are allowed only in compound mode.
177     os << attrStmt("compound", "true") << ";\n";
178     builder();
179     os.unindent();
180     os << "}\n";
181   }
182 
183   /// Emit a node statement.
184   Node emitNodeStmt(std::string label, StringRef shape = kShapeNode) {
185     int nodeId = ++counter;
186     AttributeMap attrs;
187     attrs["label"] = quoteString(escapeString(label));
188     attrs["shape"] = shape.str();
189     os << llvm::format("v%i ", nodeId);
190     emitAttrList(os, attrs);
191     os << ";\n";
192     return Node(nodeId);
193   }
194 
195   /// Generate a label for an operation.
196   std::string getLabel(Operation *op) {
197     return strFromOs([&](raw_ostream &os) {
198       // Print operation name and type.
199       os << op->getName() << " : (";
200       interleaveComma(op->getResultTypes(), os);
201       os << ")\n";
202 
203       // Print attributes.
204       for (const NamedAttribute &attr : op->getAttrs()) {
205         os << '\n' << attr.first << ": ";
206         emitMlirAttr(os, attr.second);
207       }
208     });
209   }
210 
211   /// Generate a label for a block argument.
212   std::string getLabel(BlockArgument arg) {
213     return "arg" + std::to_string(arg.getArgNumber());
214   }
215 
216   /// Process a block. Emit a cluster and one node per block argument and
217   /// operation inside the cluster.
218   void processBlock(Block &block) {
219     emitClusterStmt([&]() {
220       for (BlockArgument &blockArg : block.getArguments())
221         valueToNode[blockArg] = emitNodeStmt(getLabel(blockArg));
222 
223       // Emit a node for each operation.
224       for (Operation &op : block)
225         processOperation(&op);
226     });
227   }
228 
229   /// Process an operation. If the operation has regions, emit a cluster.
230   /// Otherwise, emit a node.
231   void processOperation(Operation *op) {
232     Node node;
233     if (op->getNumRegions() > 0) {
234       // Emit cluster for op with regions.
235       node = emitClusterStmt(
236           [&]() {
237             for (Region &region : op->getRegions())
238               processRegion(region);
239           },
240           getLabel(op));
241     } else {
242       node = emitNodeStmt(getLabel(op));
243     }
244 
245     // Insert edges originating from each operand.
246     unsigned numOperands = op->getNumOperands();
247     for (unsigned i = 0; i < numOperands; i++)
248       emitEdgeStmt(valueToNode[op->getOperand(i)], node,
249                    /*label=*/numOperands == 1 ? "" : std::to_string(i));
250 
251     for (Value result : op->getResults())
252       valueToNode[result] = node;
253   }
254 
255   /// Process a region.
256   void processRegion(Region &region) {
257     for (Block &block : region.getBlocks())
258       processBlock(block);
259   }
260 
261   /// Output stream to write DOT file to.
262   raw_indented_ostream os;
263   /// A list of edges. For simplicity, should be emitted after all nodes were
264   /// emitted.
265   std::vector<std::string> edges;
266   /// Mapping of SSA values to Graphviz nodes/clusters.
267   DenseMap<Value, Node> valueToNode;
268   /// Counter for generating unique node/subgraph identifiers.
269   int counter = 0;
270 };
271 
272 } // namespace
273 
274 std::unique_ptr<Pass>
275 mlir::createPrintOpGraphPass(raw_ostream &os) {
276   return std::make_unique<PrintOpPass>(os);
277 }
278