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