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 "mlir/IR/Block.h"
11 #include "mlir/IR/Operation.h"
12 #include "mlir/IR/StandardTypes.h"
13 #include "mlir/Pass/Pass.h"
14 #include "mlir/Support/STLExtras.h"
15 #include "llvm/Support/CommandLine.h"
16 
17 static llvm::cl::opt<int> elideIfLarger(
18     "print-op-graph-elide-if-larger",
19     llvm::cl::desc("Upper limit to emit elements attribute rather than elide"),
20     llvm::cl::init(16));
21 
22 using namespace mlir;
23 
24 namespace llvm {
25 
26 // Specialize GraphTraits to treat Block as a graph of Operations as nodes and
27 // uses as edges.
28 template <> struct GraphTraits<Block *> {
29   using GraphType = Block *;
30   using NodeRef = Operation *;
31 
32   using ChildIteratorType = Operation::user_iterator;
33   static ChildIteratorType child_begin(NodeRef n) { return n->user_begin(); }
34   static ChildIteratorType child_end(NodeRef n) { return n->user_end(); }
35 
36   // Operation's destructor is private so use Operation* instead and use
37   // mapped iterator.
38   static Operation *AddressOf(Operation &op) { return &op; }
39   using nodes_iterator = mapped_iterator<Block::iterator, decltype(&AddressOf)>;
40   static nodes_iterator nodes_begin(Block *b) {
41     return nodes_iterator(b->begin(), &AddressOf);
42   }
43   static nodes_iterator nodes_end(Block *b) {
44     return nodes_iterator(b->end(), &AddressOf);
45   }
46 };
47 
48 // Specialize DOTGraphTraits to produce more readable output.
49 template <> struct DOTGraphTraits<Block *> : public DefaultDOTGraphTraits {
50   using DefaultDOTGraphTraits::DefaultDOTGraphTraits;
51   static std::string getNodeLabel(Operation *op, Block *);
52 };
53 
54 std::string DOTGraphTraits<Block *>::getNodeLabel(Operation *op, Block *b) {
55   // Reuse the print output for the node labels.
56   std::string ostr;
57   raw_string_ostream os(ostr);
58   os << op->getName() << "\n";
59 
60   if (!op->getLoc().isa<UnknownLoc>()) {
61     os << op->getLoc() << "\n";
62   }
63 
64   // Print resultant types
65   interleaveComma(op->getResultTypes(), os);
66   os << "\n";
67 
68   for (auto attr : op->getAttrs()) {
69     os << '\n' << attr.first << ": ";
70     // Always emit splat attributes.
71     if (attr.second.isa<SplatElementsAttr>()) {
72       attr.second.print(os);
73       continue;
74     }
75 
76     // Elide "big" elements attributes.
77     auto elements = attr.second.dyn_cast<ElementsAttr>();
78     if (elements && elements.getNumElements() > elideIfLarger) {
79       os << std::string(elements.getType().getRank(), '[') << "..."
80          << std::string(elements.getType().getRank(), ']') << " : "
81          << elements.getType();
82       continue;
83     }
84 
85     auto array = attr.second.dyn_cast<ArrayAttr>();
86     if (array && static_cast<int64_t>(array.size()) > elideIfLarger) {
87       os << "[...]";
88       continue;
89     }
90 
91     // Print all other attributes.
92     attr.second.print(os);
93   }
94   return os.str();
95 }
96 
97 } // end namespace llvm
98 
99 namespace {
100 // PrintOpPass is simple pass to write graph per function.
101 // Note: this is a module pass only to avoid interleaving on the same ostream
102 // due to multi-threading over functions.
103 struct PrintOpPass : public ModulePass<PrintOpPass> {
104   explicit PrintOpPass(raw_ostream &os = llvm::errs(), bool short_names = false,
105                        const Twine &title = "")
106       : os(os), title(title.str()), short_names(short_names) {}
107 
108   std::string getOpName(Operation &op) {
109     auto symbolAttr =
110         op.getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName());
111     if (symbolAttr)
112       return std::string(symbolAttr.getValue());
113     ++unnamedOpCtr;
114     return (op.getName().getStringRef() + llvm::utostr(unnamedOpCtr)).str();
115   }
116 
117   // Print all the ops in a module.
118   void processModule(ModuleOp module) {
119     for (Operation &op : module) {
120       // Modules may actually be nested, recurse on nesting.
121       if (auto nestedModule = dyn_cast<ModuleOp>(op)) {
122         processModule(nestedModule);
123         continue;
124       }
125       auto opName = getOpName(op);
126       for (Region &region : op.getRegions()) {
127         for (auto indexed_block : llvm::enumerate(region)) {
128           // Suffix block number if there are more than 1 block.
129           auto blockName = region.getBlocks().size() == 1
130                                ? ""
131                                : ("__" + llvm::utostr(indexed_block.index()));
132           llvm::WriteGraph(os, &indexed_block.value(), short_names,
133                            Twine(title) + opName + blockName);
134         }
135       }
136     }
137   }
138 
139   void runOnModule() override { processModule(getModule()); }
140 
141 private:
142   raw_ostream &os;
143   std::string title;
144   int unnamedOpCtr = 0;
145   bool short_names;
146 };
147 } // namespace
148 
149 void mlir::viewGraph(Block &block, const Twine &name, bool shortNames,
150                      const Twine &title, llvm::GraphProgram::Name program) {
151   llvm::ViewGraph(&block, name, shortNames, title, program);
152 }
153 
154 raw_ostream &mlir::writeGraph(raw_ostream &os, Block &block, bool shortNames,
155                               const Twine &title) {
156   return llvm::WriteGraph(os, &block, shortNames, title);
157 }
158 
159 std::unique_ptr<OpPassBase<ModuleOp>>
160 mlir::createPrintOpGraphPass(raw_ostream &os, bool shortNames,
161                              const Twine &title) {
162   return std::make_unique<PrintOpPass>(os, shortNames, title);
163 }
164 
165 static PassRegistration<PrintOpPass> pass("print-op-graph",
166                                           "Print op graph per region");
167