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