xref: /llvm-project/mlir/tools/mlir-tblgen/RewriterGen.cpp (revision c396c044e6553d953dfda1e43533ba3918e2c88f)
1 //===- RewriterGen.cpp - MLIR pattern rewriter generator ------------===//
2 //
3 // Copyright 2019 The MLIR Authors.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //   http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 // =============================================================================
17 //
18 // RewriterGen uses pattern rewrite definitions to generate rewriter matchers.
19 //
20 //===----------------------------------------------------------------------===//
21 
22 #include "mlir/TableGen/GenInfo.h"
23 #include "mlir/TableGen/Operator.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSet.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/FormatVariadic.h"
28 #include "llvm/Support/PrettyStackTrace.h"
29 #include "llvm/Support/Signals.h"
30 #include "llvm/TableGen/Error.h"
31 #include "llvm/TableGen/Main.h"
32 #include "llvm/TableGen/Record.h"
33 #include "llvm/TableGen/TableGenBackend.h"
34 
35 using namespace llvm;
36 using namespace mlir;
37 
38 namespace {
39 
40 // Wrapper around dag argument.
41 struct DagArg {
42   DagArg(Init *init) : init(init){};
43   bool isAttr();
44 
45   Init *init;
46 };
47 
48 } // end namespace
49 
50 bool DagArg::isAttr() {
51   if (auto defInit = dyn_cast<DefInit>(init))
52     return defInit->getDef()->isSubClassOf("Attr");
53   return false;
54 }
55 
56 namespace {
57 class Pattern {
58 public:
59   static void emit(StringRef rewriteName, Record *p, raw_ostream &os);
60 
61 private:
62   Pattern(Record *pattern, raw_ostream &os) : pattern(pattern), os(os){};
63 
64   // Emit the rewrite pattern named `rewriteName`.
65   void emit(StringRef rewriteName);
66 
67   // Emit the matcher.
68   void emitMatcher(DagInit *tree);
69 
70   // Emits the value of constant attribute to `os`.
71   void emitAttributeValue(Record *constAttr);
72 
73   // Collect bound arguments.
74   void collectBoundArguments(DagInit *tree);
75 
76   // Map from bound argument name to DagArg.
77   StringMap<DagArg> boundArguments;
78 
79   // Number of the operations in the input pattern.
80   int numberOfOpsMatched = 0;
81 
82   Record *pattern;
83   raw_ostream &os;
84 };
85 } // end namespace
86 
87 void Pattern::emitAttributeValue(Record *constAttr) {
88   Record *attr = constAttr->getValueAsDef("attr");
89   auto value = constAttr->getValue("value");
90   Record *type = attr->getValueAsDef("type");
91   auto storageType = attr->getValueAsString("storageType").trim();
92 
93   // For attributes stored as strings we do not need to query builder etc.
94   if (storageType == "StringAttr") {
95     os << formatv("rewriter.getStringAttr({0})",
96                   value->getValue()->getAsString());
97     return;
98   }
99 
100   // Construct the attribute based on storage type and builder.
101   if (auto b = type->getValue("builderCall")) {
102     if (isa<UnsetInit>(b->getValue()))
103       PrintFatalError(pattern->getLoc(),
104                       "no builder specified for " + type->getName());
105     CodeInit *builder = cast<CodeInit>(b->getValue());
106     // TODO(jpienaar): Verify the constants here
107     os << formatv("{0}::get(rewriter.{1}, {2})", storageType,
108                   builder->getValue(),
109                   value->getValue()->getAsUnquotedString());
110     return;
111   }
112 
113   PrintFatalError(pattern->getLoc(), "unable to emit attribute");
114 }
115 
116 void Pattern::collectBoundArguments(DagInit *tree) {
117   ++numberOfOpsMatched;
118   // TODO(jpienaar): Expand to multiple matches.
119   for (int i = 0, e = tree->getNumArgs(); i != e; ++i) {
120     auto arg = tree->getArg(i);
121     if (auto argTree = dyn_cast<DagInit>(arg)) {
122       collectBoundArguments(argTree);
123       continue;
124     }
125     auto name = tree->getArgNameStr(i);
126     if (name.empty())
127       continue;
128     boundArguments.try_emplace(name, arg);
129   }
130 }
131 
132 // Helper function to match patterns.
133 static void matchOp(DagInit *tree, int depth, raw_ostream &os) {
134   Operator op(cast<DefInit>(tree->getOperator())->getDef());
135   int indent = 4 + 2 * depth;
136   // Skip the operand matching at depth 0 as the pattern rewriter already does.
137   if (depth != 0) {
138     // Skip if there is no defining instruction (e.g., arguments to function).
139     os.indent(indent) << formatv("if (!op{0}) return matchFailure();\n", depth);
140     os.indent(indent) << formatv(
141         "if (!op{0}->isa<{1}>()) return matchFailure();\n", depth,
142         op.qualifiedCppClassName());
143   }
144   for (int i = 0, e = tree->getNumArgs(); i != e; ++i) {
145     auto arg = tree->getArg(i);
146     if (auto argTree = dyn_cast<DagInit>(arg)) {
147       os.indent(indent) << "{\n";
148       os.indent(indent + 2) << formatv(
149           "auto op{0} = op{1}->getOperand({2})->getDefiningInst();\n",
150           depth + 1, depth, i);
151       matchOp(argTree, depth + 1, os);
152       os.indent(indent) << "}\n";
153       continue;
154     }
155     auto name = tree->getArgNameStr(i);
156     if (name.empty())
157       continue;
158     os.indent(indent) << "state->" << name << " = op" << depth
159                       << "->getOperand(" << i << ");\n";
160   }
161 }
162 
163 void Pattern::emitMatcher(DagInit *tree) {
164   // Emit the heading.
165   os << R"(
166   PatternMatchResult match(OperationInst *op0) const override {
167     // TODO: This just handle 1 result
168     if (op0->getNumResults() != 1) return matchFailure();
169     auto state = std::make_unique<MatchedState>();)"
170      << "\n";
171   matchOp(tree, 0, os);
172   os.indent(4) << "return matchSuccess(std::move(state));\n  }\n";
173 }
174 
175 void Pattern::emit(StringRef rewriteName) {
176   DagInit *tree = pattern->getValueAsDag("PatternToMatch");
177   // Collect bound arguments and compute number of ops matched.
178   // TODO(jpienaar): the benefit metric is simply number of ops matched at the
179   // moment, revise.
180   collectBoundArguments(tree);
181 
182   // Emit RewritePattern for Pattern.
183   DefInit *root = cast<DefInit>(tree->getOperator());
184   auto *rootName = cast<StringInit>(root->getDef()->getValueInit("opName"));
185   os << formatv(R"(struct {0} : public RewritePattern {
186   {0}(MLIRContext *context) : RewritePattern({1}, {2}, context) {{})",
187                 rewriteName, rootName->getAsString(), numberOfOpsMatched)
188      << "\n";
189 
190   // Emit matched state.
191   os << "  struct MatchedState : public PatternState {\n";
192   for (auto &arg : boundArguments) {
193     if (arg.second.isAttr()) {
194       DefInit *defInit = cast<DefInit>(arg.second.init);
195       os.indent(4) << defInit->getDef()->getValueAsString("storageType").trim()
196                    << " " << arg.first() << ";\n";
197     } else {
198       os.indent(4) << "Value* " << arg.first() << ";\n";
199     }
200   }
201   os << "  };\n";
202 
203   emitMatcher(tree);
204   ListInit *resultOps = pattern->getValueAsListInit("ResultOps");
205   if (resultOps->size() != 1)
206     PrintFatalError("only single result rules supported");
207   DagInit *resultTree = cast<DagInit>(resultOps->getElement(0));
208 
209   // TODO(jpienaar): Expand to multiple results.
210   for (auto result : resultTree->getArgs()) {
211     if (isa<DagInit>(result))
212       PrintFatalError(pattern->getLoc(), "only single op result supported");
213   }
214 
215   DefInit *resultRoot = cast<DefInit>(resultTree->getOperator());
216   Operator resultOp(*resultRoot->getDef());
217   auto resultOperands = resultRoot->getDef()->getValueAsDag("arguments");
218 
219   os << formatv(R"(
220   void rewrite(OperationInst *op, std::unique_ptr<PatternState> state,
221                PatternRewriter &rewriter) const override {
222     auto& s = *static_cast<MatchedState *>(state.get());
223     rewriter.replaceOpWithNewOp<{0}>(op, op->getResult(0)->getType())",
224                 resultOp.cppClassName());
225   if (resultOperands->getNumArgs() != resultTree->getNumArgs()) {
226     PrintFatalError(pattern->getLoc(),
227                     Twine("mismatch between arguments of resultant op (") +
228                         Twine(resultOperands->getNumArgs()) +
229                         ") and arguments provided for rewrite (" +
230                         Twine(resultTree->getNumArgs()) + Twine(')'));
231   }
232 
233   // Create the builder call for the result.
234   // Add operands.
235   int i = 0;
236   for (auto operand : resultOp.getOperands()) {
237     // Start each operand on its own line.
238     (os << ",\n").indent(6);
239 
240     auto name = resultTree->getArgNameStr(i);
241     if (boundArguments.find(name) == boundArguments.end())
242       PrintFatalError(pattern->getLoc(),
243                       Twine("referencing unbound variable '") + name + "'");
244     if (operand.name)
245       os << "/*" << operand.name->getAsUnquotedString() << "=*/";
246     os << "s." << name;
247     // TODO(jpienaar): verify types
248     ++i;
249   }
250 
251   // Add attributes.
252   for (int e = resultTree->getNumArgs(); i != e; ++i) {
253     // Start each attribute on its own line.
254     (os << ",\n").indent(6);
255 
256     // The argument in the result DAG pattern.
257     auto name = resultOp.getArgName(i);
258     auto defInit = dyn_cast<DefInit>(resultTree->getArg(i));
259     auto *value = defInit ? defInit->getDef()->getValue("value") : nullptr;
260     if (!value)
261       PrintFatalError(pattern->getLoc(),
262                       Twine("attribute '") + name +
263                           "' needs to be constant initialized");
264 
265     // TODO(jpienaar): Refactor out into map to avoid recomputing these.
266     auto argument = resultOp.getArg(i);
267     if (!argument.is<mlir::Operator::Attribute *>())
268       PrintFatalError(pattern->getLoc(),
269                       Twine("expected attribute ") + Twine(i));
270 
271     if (!name.empty())
272       os << "/*" << name << "=*/";
273     emitAttributeValue(defInit->getDef());
274     // TODO(jpienaar): verify types
275   }
276   os << "\n    );\n  }\n};\n";
277 }
278 
279 void Pattern::emit(StringRef rewriteName, Record *p, raw_ostream &os) {
280   Pattern pattern(p, os);
281   pattern.emit(rewriteName);
282 }
283 
284 static void emitRewriters(const RecordKeeper &recordKeeper, raw_ostream &os) {
285   emitSourceFileHeader("Rewriters", os);
286   const auto &patterns = recordKeeper.getAllDerivedDefinitions("Pattern");
287 
288   // Ensure unique patterns simply by appending unique suffix.
289   std::string baseRewriteName = "GeneratedConvert";
290   int rewritePatternCount = 0;
291   for (Record *p : patterns) {
292     Pattern::emit(baseRewriteName + llvm::utostr(rewritePatternCount++), p, os);
293   }
294 
295   // Emit function to add the generated matchers to the pattern list.
296   os << "void populateWithGenerated(MLIRContext *context, "
297      << "OwningRewritePatternList *patterns) {\n";
298   for (unsigned i = 0; i != rewritePatternCount; ++i) {
299     os.indent(2) << "patterns->push_back(std::make_unique<" << baseRewriteName
300                  << i << ">(context));\n";
301   }
302   os << "}\n";
303 }
304 
305 mlir::GenRegistration
306     genRewriters("gen-rewriters", "Generate pattern rewriters",
307                  [](const RecordKeeper &records, raw_ostream &os) {
308                    emitRewriters(records, os);
309                    return false;
310                  });
311