xref: /llvm-project/mlir/tools/mlir-tblgen/RewriterGen.cpp (revision 68f58812e3e99e31d77c0c23b6298489444dc0be)
1 //===- RewriterGen.cpp - MLIR pattern rewriter generator ------------------===//
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 // RewriterGen uses pattern rewrite definitions to generate rewriter matchers.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/Support/IndentedOstream.h"
14 #include "mlir/TableGen/Attribute.h"
15 #include "mlir/TableGen/CodeGenHelpers.h"
16 #include "mlir/TableGen/Format.h"
17 #include "mlir/TableGen/GenInfo.h"
18 #include "mlir/TableGen/Operator.h"
19 #include "mlir/TableGen/Pattern.h"
20 #include "mlir/TableGen/Predicate.h"
21 #include "mlir/TableGen/Type.h"
22 #include "llvm/ADT/FunctionExtras.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSet.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/FormatAdapters.h"
29 #include "llvm/Support/PrettyStackTrace.h"
30 #include "llvm/Support/Signals.h"
31 #include "llvm/TableGen/Error.h"
32 #include "llvm/TableGen/Main.h"
33 #include "llvm/TableGen/Record.h"
34 #include "llvm/TableGen/TableGenBackend.h"
35 
36 using namespace mlir;
37 using namespace mlir::tblgen;
38 
39 using llvm::formatv;
40 using llvm::Record;
41 using llvm::RecordKeeper;
42 
43 #define DEBUG_TYPE "mlir-tblgen-rewritergen"
44 
45 namespace llvm {
46 template <>
47 struct format_provider<mlir::tblgen::Pattern::IdentifierLine> {
48   static void format(const mlir::tblgen::Pattern::IdentifierLine &v,
49                      raw_ostream &os, StringRef style) {
50     os << v.first << ":" << v.second;
51   }
52 };
53 } // namespace llvm
54 
55 //===----------------------------------------------------------------------===//
56 // PatternEmitter
57 //===----------------------------------------------------------------------===//
58 
59 namespace {
60 
61 class StaticMatcherHelper;
62 
63 class PatternEmitter {
64 public:
65   PatternEmitter(Record *pat, RecordOperatorMap *mapper, raw_ostream &os,
66                  StaticMatcherHelper &helper);
67 
68   // Emits the mlir::RewritePattern struct named `rewriteName`.
69   void emit(StringRef rewriteName);
70 
71   // Emits the static function of DAG matcher.
72   void emitStaticMatcher(DagNode tree, std::string funcName);
73 
74 private:
75   // Emits the code for matching ops.
76   void emitMatchLogic(DagNode tree, StringRef opName);
77 
78   // Emits the code for rewriting ops.
79   void emitRewriteLogic();
80 
81   //===--------------------------------------------------------------------===//
82   // Match utilities
83   //===--------------------------------------------------------------------===//
84 
85   // Emits C++ statements for matching the DAG structure.
86   void emitMatch(DagNode tree, StringRef name, int depth);
87 
88   // Emit C++ function call to static DAG matcher.
89   void emitStaticMatchCall(DagNode tree, StringRef name);
90 
91   // Emit C++ function call to static type/attribute constraint function.
92   void emitStaticVerifierCall(StringRef funcName, StringRef opName,
93                               StringRef arg, StringRef failureStr);
94 
95   // Emits C++ statements for matching using a native code call.
96   void emitNativeCodeMatch(DagNode tree, StringRef name, int depth);
97 
98   // Emits C++ statements for matching the op constrained by the given DAG
99   // `tree` returning the op's variable name.
100   void emitOpMatch(DagNode tree, StringRef opName, int depth);
101 
102   // Emits C++ statements for matching the `argIndex`-th argument of the given
103   // DAG `tree` as an operand. `operandName` and `operandMatcher` indicate the
104   // bound name and the constraint of the operand respectively.
105   void emitOperandMatch(DagNode tree, StringRef opName, StringRef operandName,
106                         DagLeaf operandMatcher, StringRef argName,
107                         int argIndex);
108 
109   // Emits C++ statements for matching the operands which can be matched in
110   // either order.
111   void emitEitherOperandMatch(DagNode tree, DagNode eitherArgTree,
112                               StringRef opName, int argIndex, int &operandIndex,
113                               int depth);
114 
115   // Emits C++ statements for matching the `argIndex`-th argument of the given
116   // DAG `tree` as an attribute.
117   void emitAttributeMatch(DagNode tree, StringRef opName, int argIndex,
118                           int depth);
119 
120   // Emits C++ for checking a match with a corresponding match failure
121   // diagnostic.
122   void emitMatchCheck(StringRef opName, const FmtObjectBase &matchFmt,
123                       const llvm::formatv_object_base &failureFmt);
124 
125   // Emits C++ for checking a match with a corresponding match failure
126   // diagnostics.
127   void emitMatchCheck(StringRef opName, const std::string &matchStr,
128                       const std::string &failureStr);
129 
130   //===--------------------------------------------------------------------===//
131   // Rewrite utilities
132   //===--------------------------------------------------------------------===//
133 
134   // The entry point for handling a result pattern rooted at `resultTree`. This
135   // method dispatches to concrete handlers according to `resultTree`'s kind and
136   // returns a symbol representing the whole value pack. Callers are expected to
137   // further resolve the symbol according to the specific use case.
138   //
139   // `depth` is the nesting level of `resultTree`; 0 means top-level result
140   // pattern. For top-level result pattern, `resultIndex` indicates which result
141   // of the matched root op this pattern is intended to replace, which can be
142   // used to deduce the result type of the op generated from this result
143   // pattern.
144   std::string handleResultPattern(DagNode resultTree, int resultIndex,
145                                   int depth);
146 
147   // Emits the C++ statement to replace the matched DAG with a value built via
148   // calling native C++ code.
149   std::string handleReplaceWithNativeCodeCall(DagNode resultTree, int depth);
150 
151   // Returns the symbol of the old value serving as the replacement.
152   StringRef handleReplaceWithValue(DagNode tree);
153 
154   // Trailing directives are used at the end of DAG node argument lists to
155   // specify additional behaviour for op matchers and creators, etc.
156   struct TrailingDirectives {
157     // DAG node containing the `location` directive. Null if there is none.
158     DagNode location;
159 
160     // DAG node containing the `returnType` directive. Null if there is none.
161     DagNode returnType;
162 
163     // Number of found trailing directives.
164     int numDirectives;
165   };
166 
167   // Collect any trailing directives.
168   TrailingDirectives getTrailingDirectives(DagNode tree);
169 
170   // Returns the location value to use.
171   std::string getLocation(TrailingDirectives &tail);
172 
173   // Returns the location value to use.
174   std::string handleLocationDirective(DagNode tree);
175 
176   // Emit return type argument.
177   std::string handleReturnTypeArg(DagNode returnType, int i, int depth);
178 
179   // Emits the C++ statement to build a new op out of the given DAG `tree` and
180   // returns the variable name that this op is assigned to. If the root op in
181   // DAG `tree` has a specified name, the created op will be assigned to a
182   // variable of the given name. Otherwise, a unique name will be used as the
183   // result value name.
184   std::string handleOpCreation(DagNode tree, int resultIndex, int depth);
185 
186   using ChildNodeIndexNameMap = DenseMap<unsigned, std::string>;
187 
188   // Emits a local variable for each value and attribute to be used for creating
189   // an op.
190   void createSeparateLocalVarsForOpArgs(DagNode node,
191                                         ChildNodeIndexNameMap &childNodeNames);
192 
193   // Emits the concrete arguments used to call an op's builder.
194   void supplyValuesForOpArgs(DagNode node,
195                              const ChildNodeIndexNameMap &childNodeNames,
196                              int depth);
197 
198   // Emits the local variables for holding all values as a whole and all named
199   // attributes as a whole to be used for creating an op.
200   void createAggregateLocalVarsForOpArgs(
201       DagNode node, const ChildNodeIndexNameMap &childNodeNames, int depth);
202 
203   // Returns the C++ expression to construct a constant attribute of the given
204   // `value` for the given attribute kind `attr`.
205   std::string handleConstantAttr(Attribute attr, const Twine &value);
206 
207   // Returns the C++ expression to build an argument from the given DAG `leaf`.
208   // `patArgName` is used to bound the argument to the source pattern.
209   std::string handleOpArgument(DagLeaf leaf, StringRef patArgName);
210 
211   //===--------------------------------------------------------------------===//
212   // General utilities
213   //===--------------------------------------------------------------------===//
214 
215   // Collects all of the operations within the given dag tree.
216   void collectOps(DagNode tree, llvm::SmallPtrSetImpl<const Operator *> &ops);
217 
218   // Returns a unique symbol for a local variable of the given `op`.
219   std::string getUniqueSymbol(const Operator *op);
220 
221   //===--------------------------------------------------------------------===//
222   // Symbol utilities
223   //===--------------------------------------------------------------------===//
224 
225   // Returns how many static values the given DAG `node` correspond to.
226   int getNodeValueCount(DagNode node);
227 
228 private:
229   // Pattern instantiation location followed by the location of multiclass
230   // prototypes used. This is intended to be used as a whole to
231   // PrintFatalError() on errors.
232   ArrayRef<SMLoc> loc;
233 
234   // Op's TableGen Record to wrapper object.
235   RecordOperatorMap *opMap;
236 
237   // Handy wrapper for pattern being emitted.
238   Pattern pattern;
239 
240   // Map for all bound symbols' info.
241   SymbolInfoMap symbolInfoMap;
242 
243   StaticMatcherHelper &staticMatcherHelper;
244 
245   // The next unused ID for newly created values.
246   unsigned nextValueId = 0;
247 
248   raw_indented_ostream os;
249 
250   // Format contexts containing placeholder substitutions.
251   FmtContext fmtCtx;
252 };
253 
254 // Tracks DagNode's reference multiple times across patterns. Enables generating
255 // static matcher functions for DagNode's referenced multiple times rather than
256 // inlining them.
257 class StaticMatcherHelper {
258 public:
259   StaticMatcherHelper(raw_ostream &os, const RecordKeeper &recordKeeper,
260                       RecordOperatorMap &mapper);
261 
262   // Determine if we should inline the match logic or delegate to a static
263   // function.
264   bool useStaticMatcher(DagNode node) {
265     return refStats[node] > kStaticMatcherThreshold;
266   }
267 
268   // Get the name of the static DAG matcher function corresponding to the node.
269   std::string getMatcherName(DagNode node) {
270     assert(useStaticMatcher(node));
271     return matcherNames[node];
272   }
273 
274   // Get the name of static type/attribute verification function.
275   StringRef getVerifierName(DagLeaf leaf);
276 
277   // Collect the `Record`s, i.e., the DRR, so that we can get the information of
278   // the duplicated DAGs.
279   void addPattern(Record *record);
280 
281   // Emit all static functions of DAG Matcher.
282   void populateStaticMatchers(raw_ostream &os);
283 
284   // Emit all static functions for Constraints.
285   void populateStaticConstraintFunctions(raw_ostream &os);
286 
287 private:
288   static constexpr unsigned kStaticMatcherThreshold = 1;
289 
290   // Consider two patterns as down below,
291   //   DagNode_Root_A    DagNode_Root_B
292   //       \                 \
293   //     DagNode_C         DagNode_C
294   //         \                 \
295   //       DagNode_D         DagNode_D
296   //
297   // DagNode_Root_A and DagNode_Root_B share the same subtree which consists of
298   // DagNode_C and DagNode_D. Both DagNode_C and DagNode_D are referenced
299   // multiple times so we'll have static matchers for both of them. When we're
300   // emitting the match logic for DagNode_C, we will check if DagNode_D has the
301   // static matcher generated. If so, then we'll generate a call to the
302   // function, inline otherwise. In this case, inlining is not what we want. As
303   // a result, generate the static matcher in topological order to ensure all
304   // the dependent static matchers are generated and we can avoid accidentally
305   // inlining.
306   //
307   // The topological order of all the DagNodes among all patterns.
308   SmallVector<std::pair<DagNode, Record *>> topologicalOrder;
309 
310   RecordOperatorMap &opMap;
311 
312   // Records of the static function name of each DagNode
313   DenseMap<DagNode, std::string> matcherNames;
314 
315   // After collecting all the DagNode in each pattern, `refStats` records the
316   // number of users for each DagNode. We will generate the static matcher for a
317   // DagNode while the number of users exceeds a certain threshold.
318   DenseMap<DagNode, unsigned> refStats;
319 
320   // Number of static matcher generated. This is used to generate a unique name
321   // for each DagNode.
322   int staticMatcherCounter = 0;
323 
324   // The DagLeaf which contains type or attr constraint.
325   SetVector<DagLeaf> constraints;
326 
327   // Static type/attribute verification function emitter.
328   StaticVerifierFunctionEmitter staticVerifierEmitter;
329 };
330 
331 } // namespace
332 
333 PatternEmitter::PatternEmitter(Record *pat, RecordOperatorMap *mapper,
334                                raw_ostream &os, StaticMatcherHelper &helper)
335     : loc(pat->getLoc()), opMap(mapper), pattern(pat, mapper),
336       symbolInfoMap(pat->getLoc()), staticMatcherHelper(helper), os(os) {
337   fmtCtx.withBuilder("rewriter");
338 }
339 
340 std::string PatternEmitter::handleConstantAttr(Attribute attr,
341                                                const Twine &value) {
342   if (!attr.isConstBuildable())
343     PrintFatalError(loc, "Attribute " + attr.getAttrDefName() +
344                              " does not have the 'constBuilderCall' field");
345 
346   // TODO: Verify the constants here
347   return std::string(tgfmt(attr.getConstBuilderTemplate(), &fmtCtx, value));
348 }
349 
350 void PatternEmitter::emitStaticMatcher(DagNode tree, std::string funcName) {
351   os << formatv(
352       "static ::mlir::LogicalResult {0}(::mlir::PatternRewriter &rewriter, "
353       "::mlir::Operation *op0, ::llvm::SmallVector<::mlir::Operation "
354       "*, 4> &tblgen_ops",
355       funcName);
356 
357   // We pass the reference of the variables that need to be captured. Hence we
358   // need to collect all the symbols in the tree first.
359   pattern.collectBoundSymbols(tree, symbolInfoMap, /*isSrcPattern=*/true);
360   symbolInfoMap.assignUniqueAlternativeNames();
361   for (const auto &info : symbolInfoMap)
362     os << formatv(", {0}", info.second.getArgDecl(info.first));
363 
364   os << ") {\n";
365   os.indent();
366   os << "(void)tblgen_ops;\n";
367 
368   // Note that a static matcher is considered at least one step from the match
369   // entry.
370   emitMatch(tree, "op0", /*depth=*/1);
371 
372   os << "return ::mlir::success();\n";
373   os.unindent();
374   os << "}\n\n";
375 }
376 
377 // Helper function to match patterns.
378 void PatternEmitter::emitMatch(DagNode tree, StringRef name, int depth) {
379   if (tree.isNativeCodeCall()) {
380     emitNativeCodeMatch(tree, name, depth);
381     return;
382   }
383 
384   if (tree.isOperation()) {
385     emitOpMatch(tree, name, depth);
386     return;
387   }
388 
389   PrintFatalError(loc, "encountered non-op, non-NativeCodeCall match.");
390 }
391 
392 void PatternEmitter::emitStaticMatchCall(DagNode tree, StringRef opName) {
393   std::string funcName = staticMatcherHelper.getMatcherName(tree);
394   os << formatv("if(::mlir::failed({0}(rewriter, {1}, tblgen_ops", funcName,
395                 opName);
396 
397   // TODO(chiahungduan): Add a lookupBoundSymbols() to do the subtree lookup in
398   // one pass.
399 
400   // In general, bound symbol should have the unique name in the pattern but
401   // for the operand, binding same symbol to multiple operands imply a
402   // constraint at the same time. In this case, we will rename those operands
403   // with different names. As a result, we need to collect all the symbolInfos
404   // from the DagNode then get the updated name of the local variables from the
405   // global symbolInfoMap.
406 
407   // Collect all the bound symbols in the Dag
408   SymbolInfoMap localSymbolMap(loc);
409   pattern.collectBoundSymbols(tree, localSymbolMap, /*isSrcPattern=*/true);
410 
411   for (const auto &info : localSymbolMap) {
412     auto name = info.first;
413     auto symboInfo = info.second;
414     auto ret = symbolInfoMap.findBoundSymbol(name, symboInfo);
415     os << formatv(", {0}", ret->second.getVarName(name));
416   }
417 
418   os << "))) {\n";
419   os.scope().os << "return ::mlir::failure();\n";
420   os << "}\n";
421 }
422 
423 void PatternEmitter::emitStaticVerifierCall(StringRef funcName,
424                                             StringRef opName, StringRef arg,
425                                             StringRef failureStr) {
426   os << formatv("if(::mlir::failed({0}(rewriter, {1}, {2}, {3}))) {{\n",
427                 funcName, opName, arg, failureStr);
428   os.scope().os << "return ::mlir::failure();\n";
429   os << "}\n";
430 }
431 
432 // Helper function to match patterns.
433 void PatternEmitter::emitNativeCodeMatch(DagNode tree, StringRef opName,
434                                          int depth) {
435   LLVM_DEBUG(llvm::dbgs() << "handle NativeCodeCall matcher pattern: ");
436   LLVM_DEBUG(tree.print(llvm::dbgs()));
437   LLVM_DEBUG(llvm::dbgs() << '\n');
438 
439   // The order of generating static matcher follows the topological order so
440   // that for every dependent DagNode already have their static matcher
441   // generated if needed. The reason we check if `getMatcherName(tree).empty()`
442   // is when we are generating the static matcher for a DagNode itself. In this
443   // case, we need to emit the function body rather than a function call.
444   if (staticMatcherHelper.useStaticMatcher(tree) &&
445       !staticMatcherHelper.getMatcherName(tree).empty()) {
446     emitStaticMatchCall(tree, opName);
447 
448     // NativeCodeCall will never be at depth 0 so that we don't need to catch
449     // the root operation as emitOpMatch();
450 
451     return;
452   }
453 
454   // TODO(suderman): iterate through arguments, determine their types, output
455   // names.
456   SmallVector<std::string, 8> capture;
457 
458   raw_indented_ostream::DelimitedScope scope(os);
459 
460   for (int i = 0, e = tree.getNumArgs(); i != e; ++i) {
461     std::string argName = formatv("arg{0}_{1}", depth, i);
462     if (DagNode argTree = tree.getArgAsNestedDag(i)) {
463       if (argTree.isEither())
464         PrintFatalError(loc, "NativeCodeCall cannot have `either` operands");
465 
466       os << "::mlir::Value " << argName << ";\n";
467     } else {
468       auto leaf = tree.getArgAsLeaf(i);
469       if (leaf.isAttrMatcher() || leaf.isConstantAttr()) {
470         os << "::mlir::Attribute " << argName << ";\n";
471       } else {
472         os << "::mlir::Value " << argName << ";\n";
473       }
474     }
475 
476     capture.push_back(std::move(argName));
477   }
478 
479   auto tail = getTrailingDirectives(tree);
480   if (tail.returnType)
481     PrintFatalError(loc, "`NativeCodeCall` cannot have return type specifier");
482   auto locToUse = getLocation(tail);
483 
484   auto fmt = tree.getNativeCodeTemplate();
485   if (fmt.count("$_self") != 1)
486     PrintFatalError(loc, "NativeCodeCall must have $_self as argument for "
487                          "passing the defining Operation");
488 
489   auto nativeCodeCall = std::string(
490       tgfmt(fmt, &fmtCtx.addSubst("_loc", locToUse).withSelf(opName.str()),
491             static_cast<ArrayRef<std::string>>(capture)));
492 
493   emitMatchCheck(opName, formatv("!::mlir::failed({0})", nativeCodeCall),
494                  formatv("\"{0} return ::mlir::failure\"", nativeCodeCall));
495 
496   for (int i = 0, e = tree.getNumArgs() - tail.numDirectives; i != e; ++i) {
497     auto name = tree.getArgName(i);
498     if (!name.empty() && name != "_") {
499       os << formatv("{0} = {1};\n", name, capture[i]);
500     }
501   }
502 
503   for (int i = 0, e = tree.getNumArgs() - tail.numDirectives; i != e; ++i) {
504     std::string argName = capture[i];
505 
506     // Handle nested DAG construct first
507     if (DagNode argTree = tree.getArgAsNestedDag(i)) {
508       PrintFatalError(
509           loc, formatv("Matching nested tree in NativeCodecall not support for "
510                        "{0} as arg {1}",
511                        argName, i));
512     }
513 
514     DagLeaf leaf = tree.getArgAsLeaf(i);
515 
516     // The parameter for native function doesn't bind any constraints.
517     if (leaf.isUnspecified())
518       continue;
519 
520     auto constraint = leaf.getAsConstraint();
521 
522     std::string self;
523     if (leaf.isAttrMatcher() || leaf.isConstantAttr())
524       self = argName;
525     else
526       self = formatv("{0}.getType()", argName);
527     StringRef verifier = staticMatcherHelper.getVerifierName(leaf);
528     emitStaticVerifierCall(
529         verifier, opName, self,
530         formatv("\"operand {0} of native code call '{1}' failed to satisfy "
531                 "constraint: "
532                 "'{2}'\"",
533                 i, tree.getNativeCodeTemplate(),
534                 escapeString(constraint.getSummary()))
535             .str());
536   }
537 
538   LLVM_DEBUG(llvm::dbgs() << "done emitting match for native code call\n");
539 }
540 
541 // Helper function to match patterns.
542 void PatternEmitter::emitOpMatch(DagNode tree, StringRef opName, int depth) {
543   Operator &op = tree.getDialectOp(opMap);
544   LLVM_DEBUG(llvm::dbgs() << "start emitting match for op '"
545                           << op.getOperationName() << "' at depth " << depth
546                           << '\n');
547 
548   auto getCastedName = [depth]() -> std::string {
549     return formatv("castedOp{0}", depth);
550   };
551 
552   // The order of generating static matcher follows the topological order so
553   // that for every dependent DagNode already have their static matcher
554   // generated if needed. The reason we check if `getMatcherName(tree).empty()`
555   // is when we are generating the static matcher for a DagNode itself. In this
556   // case, we need to emit the function body rather than a function call.
557   if (staticMatcherHelper.useStaticMatcher(tree) &&
558       !staticMatcherHelper.getMatcherName(tree).empty()) {
559     emitStaticMatchCall(tree, opName);
560     // In the codegen of rewriter, we suppose that castedOp0 will capture the
561     // root operation. Manually add it if the root DagNode is a static matcher.
562     if (depth == 0)
563       os << formatv("auto {2} = ::llvm::dyn_cast_or_null<{1}>({0}); "
564                     "(void){2};\n",
565                     opName, op.getQualCppClassName(), getCastedName());
566     return;
567   }
568 
569   std::string castedName = getCastedName();
570   os << formatv("auto {0} = ::llvm::dyn_cast<{2}>({1}); "
571                 "(void){0};\n",
572                 castedName, opName, op.getQualCppClassName());
573 
574   // Skip the operand matching at depth 0 as the pattern rewriter already does.
575   if (depth != 0)
576     emitMatchCheck(opName, /*matchStr=*/castedName,
577                    formatv("\"{0} is not {1} type\"", castedName,
578                            op.getQualCppClassName()));
579 
580   // If the operand's name is set, set to that variable.
581   auto name = tree.getSymbol();
582   if (!name.empty())
583     os << formatv("{0} = {1};\n", name, castedName);
584 
585   for (int i = 0, opArgIdx = 0, e = tree.getNumArgs(), nextOperand = 0; i != e;
586        ++i, ++opArgIdx) {
587     auto opArg = op.getArg(opArgIdx);
588     std::string argName = formatv("op{0}", depth + 1);
589 
590     // Handle nested DAG construct first
591     if (DagNode argTree = tree.getArgAsNestedDag(i)) {
592       if (argTree.isEither()) {
593         emitEitherOperandMatch(tree, argTree, castedName, opArgIdx, nextOperand,
594                                depth);
595         ++opArgIdx;
596         continue;
597       }
598       if (auto *operand = llvm::dyn_cast_if_present<NamedTypeConstraint *>(opArg)) {
599         if (operand->isVariableLength()) {
600           auto error = formatv("use nested DAG construct to match op {0}'s "
601                                "variadic operand #{1} unsupported now",
602                                op.getOperationName(), opArgIdx);
603           PrintFatalError(loc, error);
604         }
605       }
606 
607       os << "{\n";
608 
609       // Attributes don't count for getODSOperands.
610       // TODO: Operand is a Value, check if we should remove `getDefiningOp()`.
611       os.indent() << formatv(
612           "auto *{0} = "
613           "(*{1}.getODSOperands({2}).begin()).getDefiningOp();\n",
614           argName, castedName, nextOperand);
615       // Null check of operand's definingOp
616       emitMatchCheck(
617           castedName, /*matchStr=*/argName,
618           formatv("\"There's no operation that defines operand {0} of {1}\"",
619                   nextOperand++, castedName));
620       emitMatch(argTree, argName, depth + 1);
621       os << formatv("tblgen_ops.push_back({0});\n", argName);
622       os.unindent() << "}\n";
623       continue;
624     }
625 
626     // Next handle DAG leaf: operand or attribute
627     if (opArg.is<NamedTypeConstraint *>()) {
628       auto operandName =
629           formatv("{0}.getODSOperands({1})", castedName, nextOperand);
630       emitOperandMatch(tree, castedName, operandName.str(),
631                        /*operandMatcher=*/tree.getArgAsLeaf(i),
632                        /*argName=*/tree.getArgName(i), opArgIdx);
633       ++nextOperand;
634     } else if (opArg.is<NamedAttribute *>()) {
635       emitAttributeMatch(tree, opName, opArgIdx, depth);
636     } else {
637       PrintFatalError(loc, "unhandled case when matching op");
638     }
639   }
640   LLVM_DEBUG(llvm::dbgs() << "done emitting match for op '"
641                           << op.getOperationName() << "' at depth " << depth
642                           << '\n');
643 }
644 
645 void PatternEmitter::emitOperandMatch(DagNode tree, StringRef opName,
646                                       StringRef operandName,
647                                       DagLeaf operandMatcher, StringRef argName,
648                                       int argIndex) {
649   Operator &op = tree.getDialectOp(opMap);
650   auto *operand = op.getArg(argIndex).get<NamedTypeConstraint *>();
651 
652   // If a constraint is specified, we need to generate C++ statements to
653   // check the constraint.
654   if (!operandMatcher.isUnspecified()) {
655     if (!operandMatcher.isOperandMatcher())
656       PrintFatalError(
657           loc, formatv("the {1}-th argument of op '{0}' should be an operand",
658                        op.getOperationName(), argIndex + 1));
659 
660     // Only need to verify if the matcher's type is different from the one
661     // of op definition.
662     Constraint constraint = operandMatcher.getAsConstraint();
663     if (operand->constraint != constraint) {
664       if (operand->isVariableLength()) {
665         auto error = formatv(
666             "further constrain op {0}'s variadic operand #{1} unsupported now",
667             op.getOperationName(), argIndex);
668         PrintFatalError(loc, error);
669       }
670       auto self = formatv("(*{0}.begin()).getType()", operandName);
671       StringRef verifier = staticMatcherHelper.getVerifierName(operandMatcher);
672       emitStaticVerifierCall(
673           verifier, opName, self.str(),
674           formatv(
675               "\"operand {0} of op '{1}' failed to satisfy constraint: '{2}'\"",
676               operand - op.operand_begin(), op.getOperationName(),
677               escapeString(constraint.getSummary()))
678               .str());
679     }
680   }
681 
682   // Capture the value
683   // `$_` is a special symbol to ignore op argument matching.
684   if (!argName.empty() && argName != "_") {
685     auto res = symbolInfoMap.findBoundSymbol(argName, tree, op, argIndex);
686     os << formatv("{0} = {1};\n", res->second.getVarName(argName), operandName);
687   }
688 }
689 
690 void PatternEmitter::emitEitherOperandMatch(DagNode tree, DagNode eitherArgTree,
691                                             StringRef opName, int argIndex,
692                                             int &operandIndex, int depth) {
693   constexpr int numEitherArgs = 2;
694   if (eitherArgTree.getNumArgs() != numEitherArgs)
695     PrintFatalError(loc, "`either` only supports grouping two operands");
696 
697   Operator &op = tree.getDialectOp(opMap);
698 
699   std::string codeBuffer;
700   llvm::raw_string_ostream tblgenOps(codeBuffer);
701 
702   std::string lambda = formatv("eitherLambda{0}", depth);
703   os << formatv(
704       "auto {0} = [&](::mlir::OperandRange v0, ::mlir::OperandRange v1) {{\n",
705       lambda);
706 
707   os.indent();
708 
709   for (int i = 0; i < numEitherArgs; ++i, ++argIndex) {
710     if (DagNode argTree = eitherArgTree.getArgAsNestedDag(i)) {
711       if (argTree.isEither())
712         PrintFatalError(loc, "either cannot be nested");
713 
714       std::string argName = formatv("local_op_{0}", i).str();
715 
716       os << formatv("auto {0} = (*v{1}.begin()).getDefiningOp();\n", argName,
717                     i);
718       emitMatchCheck(
719           opName, /*matchStr=*/argName,
720           formatv("\"There's no operation that defines operand {0} of {1}\"",
721                   operandIndex++, opName));
722       emitMatch(argTree, argName, depth + 1);
723       // `tblgen_ops` is used to collect the matched operations. In either, we
724       // need to queue the operation only if the matching success. Thus we emit
725       // the code at the end.
726       tblgenOps << formatv("tblgen_ops.push_back({0});\n", argName);
727     } else if (op.getArg(argIndex).is<NamedTypeConstraint *>()) {
728       emitOperandMatch(tree, opName, /*operandName=*/formatv("v{0}", i).str(),
729                        /*operandMatcher=*/eitherArgTree.getArgAsLeaf(i),
730                        /*argName=*/eitherArgTree.getArgName(i), argIndex);
731       ++operandIndex;
732     } else {
733       PrintFatalError(loc, "either can only be applied on operand");
734     }
735   }
736 
737   os << tblgenOps.str();
738   os << "return ::mlir::success();\n";
739   os.unindent() << "};\n";
740 
741   os << "{\n";
742   os.indent();
743 
744   os << formatv("auto eitherOperand0 = {0}.getODSOperands({1});\n", opName,
745                 operandIndex - 2);
746   os << formatv("auto eitherOperand1 = {0}.getODSOperands({1});\n", opName,
747                 operandIndex - 1);
748 
749   os << formatv("if(::mlir::failed({0}(eitherOperand0, eitherOperand1)) && "
750                 "::mlir::failed({0}(eitherOperand1, "
751                 "eitherOperand0)))\n",
752                 lambda);
753   os.indent() << "return ::mlir::failure();\n";
754 
755   os.unindent().unindent() << "}\n";
756 }
757 
758 void PatternEmitter::emitAttributeMatch(DagNode tree, StringRef opName,
759                                         int argIndex, int depth) {
760   Operator &op = tree.getDialectOp(opMap);
761   auto *namedAttr = op.getArg(argIndex).get<NamedAttribute *>();
762   const auto &attr = namedAttr->attr;
763 
764   os << "{\n";
765   os.indent() << formatv("auto tblgen_attr = {0}->getAttrOfType<{1}>(\"{2}\");"
766                          "(void)tblgen_attr;\n",
767                          opName, attr.getStorageType(), namedAttr->name);
768 
769   // TODO: This should use getter method to avoid duplication.
770   if (attr.hasDefaultValue()) {
771     os << "if (!tblgen_attr) tblgen_attr = "
772        << std::string(tgfmt(attr.getConstBuilderTemplate(), &fmtCtx,
773                             attr.getDefaultValue()))
774        << ";\n";
775   } else if (attr.isOptional()) {
776     // For a missing attribute that is optional according to definition, we
777     // should just capture a mlir::Attribute() to signal the missing state.
778     // That is precisely what getAttr() returns on missing attributes.
779   } else {
780     emitMatchCheck(opName, tgfmt("tblgen_attr", &fmtCtx),
781                    formatv("\"expected op '{0}' to have attribute '{1}' "
782                            "of type '{2}'\"",
783                            op.getOperationName(), namedAttr->name,
784                            attr.getStorageType()));
785   }
786 
787   auto matcher = tree.getArgAsLeaf(argIndex);
788   if (!matcher.isUnspecified()) {
789     if (!matcher.isAttrMatcher()) {
790       PrintFatalError(
791           loc, formatv("the {1}-th argument of op '{0}' should be an attribute",
792                        op.getOperationName(), argIndex + 1));
793     }
794 
795     // If a constraint is specified, we need to generate function call to its
796     // static verifier.
797     StringRef verifier = staticMatcherHelper.getVerifierName(matcher);
798     if (attr.isOptional()) {
799       // Avoid dereferencing null attribute. This is using a simple heuristic to
800       // avoid common cases of attempting to dereference null attribute. This
801       // will return where there is no check if attribute is null unless the
802       // attribute's value is not used.
803       // FIXME: This could be improved as some null dereferences could slip
804       // through.
805       if (!StringRef(matcher.getConditionTemplate()).contains("!$_self") &&
806           StringRef(matcher.getConditionTemplate()).contains("$_self")) {
807         os << "if (!tblgen_attr) return ::mlir::failure();\n";
808       }
809     }
810     emitStaticVerifierCall(
811         verifier, opName, "tblgen_attr",
812         formatv("\"op '{0}' attribute '{1}' failed to satisfy constraint: "
813                 "'{2}'\"",
814                 op.getOperationName(), namedAttr->name,
815                 escapeString(matcher.getAsConstraint().getSummary()))
816             .str());
817   }
818 
819   // Capture the value
820   auto name = tree.getArgName(argIndex);
821   // `$_` is a special symbol to ignore op argument matching.
822   if (!name.empty() && name != "_") {
823     os << formatv("{0} = tblgen_attr;\n", name);
824   }
825 
826   os.unindent() << "}\n";
827 }
828 
829 void PatternEmitter::emitMatchCheck(
830     StringRef opName, const FmtObjectBase &matchFmt,
831     const llvm::formatv_object_base &failureFmt) {
832   emitMatchCheck(opName, matchFmt.str(), failureFmt.str());
833 }
834 
835 void PatternEmitter::emitMatchCheck(StringRef opName,
836                                     const std::string &matchStr,
837                                     const std::string &failureStr) {
838 
839   os << "if (!(" << matchStr << "))";
840   os.scope("{\n", "\n}\n").os << "return rewriter.notifyMatchFailure(" << opName
841                               << ", [&](::mlir::Diagnostic &diag) {\n  diag << "
842                               << failureStr << ";\n});";
843 }
844 
845 void PatternEmitter::emitMatchLogic(DagNode tree, StringRef opName) {
846   LLVM_DEBUG(llvm::dbgs() << "--- start emitting match logic ---\n");
847   int depth = 0;
848   emitMatch(tree, opName, depth);
849 
850   for (auto &appliedConstraint : pattern.getConstraints()) {
851     auto &constraint = appliedConstraint.constraint;
852     auto &entities = appliedConstraint.entities;
853 
854     auto condition = constraint.getConditionTemplate();
855     if (isa<TypeConstraint>(constraint)) {
856       if (entities.size() != 1)
857         PrintFatalError(loc, "type constraint requires exactly one argument");
858 
859       auto self = formatv("({0}.getType())",
860                           symbolInfoMap.getValueAndRangeUse(entities.front()));
861       emitMatchCheck(
862           opName, tgfmt(condition, &fmtCtx.withSelf(self.str())),
863           formatv("\"value entity '{0}' failed to satisfy constraint: '{1}'\"",
864                   entities.front(), escapeString(constraint.getSummary())));
865 
866     } else if (isa<AttrConstraint>(constraint)) {
867       PrintFatalError(
868           loc, "cannot use AttrConstraint in Pattern multi-entity constraints");
869     } else {
870       // TODO: replace formatv arguments with the exact specified
871       // args.
872       if (entities.size() > 4) {
873         PrintFatalError(loc, "only support up to 4-entity constraints now");
874       }
875       SmallVector<std::string, 4> names;
876       int i = 0;
877       for (int e = entities.size(); i < e; ++i)
878         names.push_back(symbolInfoMap.getValueAndRangeUse(entities[i]));
879       std::string self = appliedConstraint.self;
880       if (!self.empty())
881         self = symbolInfoMap.getValueAndRangeUse(self);
882       for (; i < 4; ++i)
883         names.push_back("<unused>");
884       emitMatchCheck(opName,
885                      tgfmt(condition, &fmtCtx.withSelf(self), names[0],
886                            names[1], names[2], names[3]),
887                      formatv("\"entities '{0}' failed to satisfy constraint: "
888                              "'{1}'\"",
889                              llvm::join(entities, ", "),
890                              escapeString(constraint.getSummary())));
891     }
892   }
893 
894   // Some of the operands could be bound to the same symbol name, we need
895   // to enforce equality constraint on those.
896   // TODO: we should be able to emit equality checks early
897   // and short circuit unnecessary work if vars are not equal.
898   for (auto symbolInfoIt = symbolInfoMap.begin();
899        symbolInfoIt != symbolInfoMap.end();) {
900     auto range = symbolInfoMap.getRangeOfEqualElements(symbolInfoIt->first);
901     auto startRange = range.first;
902     auto endRange = range.second;
903 
904     auto firstOperand = symbolInfoIt->second.getVarName(symbolInfoIt->first);
905     for (++startRange; startRange != endRange; ++startRange) {
906       auto secondOperand = startRange->second.getVarName(symbolInfoIt->first);
907       emitMatchCheck(
908           opName,
909           formatv("*{0}.begin() == *{1}.begin()", firstOperand, secondOperand),
910           formatv("\"Operands '{0}' and '{1}' must be equal\"", firstOperand,
911                   secondOperand));
912     }
913 
914     symbolInfoIt = endRange;
915   }
916 
917   LLVM_DEBUG(llvm::dbgs() << "--- done emitting match logic ---\n");
918 }
919 
920 void PatternEmitter::collectOps(DagNode tree,
921                                 llvm::SmallPtrSetImpl<const Operator *> &ops) {
922   // Check if this tree is an operation.
923   if (tree.isOperation()) {
924     const Operator &op = tree.getDialectOp(opMap);
925     LLVM_DEBUG(llvm::dbgs()
926                << "found operation " << op.getOperationName() << '\n');
927     ops.insert(&op);
928   }
929 
930   // Recurse the arguments of the tree.
931   for (unsigned i = 0, e = tree.getNumArgs(); i != e; ++i)
932     if (auto child = tree.getArgAsNestedDag(i))
933       collectOps(child, ops);
934 }
935 
936 void PatternEmitter::emit(StringRef rewriteName) {
937   // Get the DAG tree for the source pattern.
938   DagNode sourceTree = pattern.getSourcePattern();
939 
940   const Operator &rootOp = pattern.getSourceRootOp();
941   auto rootName = rootOp.getOperationName();
942 
943   // Collect the set of result operations.
944   llvm::SmallPtrSet<const Operator *, 4> resultOps;
945   LLVM_DEBUG(llvm::dbgs() << "start collecting ops used in result patterns\n");
946   for (unsigned i = 0, e = pattern.getNumResultPatterns(); i != e; ++i) {
947     collectOps(pattern.getResultPattern(i), resultOps);
948   }
949   LLVM_DEBUG(llvm::dbgs() << "done collecting ops used in result patterns\n");
950 
951   // Emit RewritePattern for Pattern.
952   auto locs = pattern.getLocation();
953   os << formatv("/* Generated from:\n    {0:$[ instantiating\n    ]}\n*/\n",
954                 make_range(locs.rbegin(), locs.rend()));
955   os << formatv(R"(struct {0} : public ::mlir::RewritePattern {
956   {0}(::mlir::MLIRContext *context)
957       : ::mlir::RewritePattern("{1}", {2}, context, {{)",
958                 rewriteName, rootName, pattern.getBenefit());
959   // Sort result operators by name.
960   llvm::SmallVector<const Operator *, 4> sortedResultOps(resultOps.begin(),
961                                                          resultOps.end());
962   llvm::sort(sortedResultOps, [&](const Operator *lhs, const Operator *rhs) {
963     return lhs->getOperationName() < rhs->getOperationName();
964   });
965   llvm::interleaveComma(sortedResultOps, os, [&](const Operator *op) {
966     os << '"' << op->getOperationName() << '"';
967   });
968   os << "}) {}\n";
969 
970   // Emit matchAndRewrite() function.
971   {
972     auto classScope = os.scope();
973     os.printReindented(R"(
974     ::mlir::LogicalResult matchAndRewrite(::mlir::Operation *op0,
975         ::mlir::PatternRewriter &rewriter) const override {)")
976         << '\n';
977     {
978       auto functionScope = os.scope();
979 
980       // Register all symbols bound in the source pattern.
981       pattern.collectSourcePatternBoundSymbols(symbolInfoMap);
982 
983       LLVM_DEBUG(llvm::dbgs()
984                  << "start creating local variables for capturing matches\n");
985       os << "// Variables for capturing values and attributes used while "
986             "creating ops\n";
987       // Create local variables for storing the arguments and results bound
988       // to symbols.
989       for (const auto &symbolInfoPair : symbolInfoMap) {
990         const auto &symbol = symbolInfoPair.first;
991         const auto &info = symbolInfoPair.second;
992 
993         os << info.getVarDecl(symbol);
994       }
995       // TODO: capture ops with consistent numbering so that it can be
996       // reused for fused loc.
997       os << "::llvm::SmallVector<::mlir::Operation *, 4> tblgen_ops;\n\n";
998       LLVM_DEBUG(llvm::dbgs()
999                  << "done creating local variables for capturing matches\n");
1000 
1001       os << "// Match\n";
1002       os << "tblgen_ops.push_back(op0);\n";
1003       emitMatchLogic(sourceTree, "op0");
1004 
1005       os << "\n// Rewrite\n";
1006       emitRewriteLogic();
1007 
1008       os << "return ::mlir::success();\n";
1009     }
1010     os << "};\n";
1011   }
1012   os << "};\n\n";
1013 }
1014 
1015 void PatternEmitter::emitRewriteLogic() {
1016   LLVM_DEBUG(llvm::dbgs() << "--- start emitting rewrite logic ---\n");
1017   const Operator &rootOp = pattern.getSourceRootOp();
1018   int numExpectedResults = rootOp.getNumResults();
1019   int numResultPatterns = pattern.getNumResultPatterns();
1020 
1021   // First register all symbols bound to ops generated in result patterns.
1022   pattern.collectResultPatternBoundSymbols(symbolInfoMap);
1023 
1024   // Only the last N static values generated are used to replace the matched
1025   // root N-result op. We need to calculate the starting index (of the results
1026   // of the matched op) each result pattern is to replace.
1027   SmallVector<int, 4> offsets(numResultPatterns + 1, numExpectedResults);
1028   // If we don't need to replace any value at all, set the replacement starting
1029   // index as the number of result patterns so we skip all of them when trying
1030   // to replace the matched op's results.
1031   int replStartIndex = numExpectedResults == 0 ? numResultPatterns : -1;
1032   for (int i = numResultPatterns - 1; i >= 0; --i) {
1033     auto numValues = getNodeValueCount(pattern.getResultPattern(i));
1034     offsets[i] = offsets[i + 1] - numValues;
1035     if (offsets[i] == 0) {
1036       if (replStartIndex == -1)
1037         replStartIndex = i;
1038     } else if (offsets[i] < 0 && offsets[i + 1] > 0) {
1039       auto error = formatv(
1040           "cannot use the same multi-result op '{0}' to generate both "
1041           "auxiliary values and values to be used for replacing the matched op",
1042           pattern.getResultPattern(i).getSymbol());
1043       PrintFatalError(loc, error);
1044     }
1045   }
1046 
1047   if (offsets.front() > 0) {
1048     const char error[] =
1049         "not enough values generated to replace the matched op";
1050     PrintFatalError(loc, error);
1051   }
1052 
1053   os << "auto odsLoc = rewriter.getFusedLoc({";
1054   for (int i = 0, e = pattern.getSourcePattern().getNumOps(); i != e; ++i) {
1055     os << (i ? ", " : "") << "tblgen_ops[" << i << "]->getLoc()";
1056   }
1057   os << "}); (void)odsLoc;\n";
1058 
1059   // Process auxiliary result patterns.
1060   for (int i = 0; i < replStartIndex; ++i) {
1061     DagNode resultTree = pattern.getResultPattern(i);
1062     auto val = handleResultPattern(resultTree, offsets[i], 0);
1063     // Normal op creation will be streamed to `os` by the above call; but
1064     // NativeCodeCall will only be materialized to `os` if it is used. Here
1065     // we are handling auxiliary patterns so we want the side effect even if
1066     // NativeCodeCall is not replacing matched root op's results.
1067     if (resultTree.isNativeCodeCall() &&
1068         resultTree.getNumReturnsOfNativeCode() == 0)
1069       os << val << ";\n";
1070   }
1071 
1072   if (numExpectedResults == 0) {
1073     assert(replStartIndex >= numResultPatterns &&
1074            "invalid auxiliary vs. replacement pattern division!");
1075     // No result to replace. Just erase the op.
1076     os << "rewriter.eraseOp(op0);\n";
1077   } else {
1078     // Process replacement result patterns.
1079     os << "::llvm::SmallVector<::mlir::Value, 4> tblgen_repl_values;\n";
1080     for (int i = replStartIndex; i < numResultPatterns; ++i) {
1081       DagNode resultTree = pattern.getResultPattern(i);
1082       auto val = handleResultPattern(resultTree, offsets[i], 0);
1083       os << "\n";
1084       // Resolve each symbol for all range use so that we can loop over them.
1085       // We need an explicit cast to `SmallVector` to capture the cases where
1086       // `{0}` resolves to an `Operation::result_range` as well as cases that
1087       // are not iterable (e.g. vector that gets wrapped in additional braces by
1088       // RewriterGen).
1089       // TODO: Revisit the need for materializing a vector.
1090       os << symbolInfoMap.getAllRangeUse(
1091           val,
1092           "for (auto v: ::llvm::SmallVector<::mlir::Value, 4>{ {0} }) {{\n"
1093           "  tblgen_repl_values.push_back(v);\n}\n",
1094           "\n");
1095     }
1096     os << "\nrewriter.replaceOp(op0, tblgen_repl_values);\n";
1097   }
1098 
1099   LLVM_DEBUG(llvm::dbgs() << "--- done emitting rewrite logic ---\n");
1100 }
1101 
1102 std::string PatternEmitter::getUniqueSymbol(const Operator *op) {
1103   return std::string(
1104       formatv("tblgen_{0}_{1}", op->getCppClassName(), nextValueId++));
1105 }
1106 
1107 std::string PatternEmitter::handleResultPattern(DagNode resultTree,
1108                                                 int resultIndex, int depth) {
1109   LLVM_DEBUG(llvm::dbgs() << "handle result pattern: ");
1110   LLVM_DEBUG(resultTree.print(llvm::dbgs()));
1111   LLVM_DEBUG(llvm::dbgs() << '\n');
1112 
1113   if (resultTree.isLocationDirective()) {
1114     PrintFatalError(loc,
1115                     "location directive can only be used with op creation");
1116   }
1117 
1118   if (resultTree.isNativeCodeCall())
1119     return handleReplaceWithNativeCodeCall(resultTree, depth);
1120 
1121   if (resultTree.isReplaceWithValue())
1122     return handleReplaceWithValue(resultTree).str();
1123 
1124   // Normal op creation.
1125   auto symbol = handleOpCreation(resultTree, resultIndex, depth);
1126   if (resultTree.getSymbol().empty()) {
1127     // This is an op not explicitly bound to a symbol in the rewrite rule.
1128     // Register the auto-generated symbol for it.
1129     symbolInfoMap.bindOpResult(symbol, pattern.getDialectOp(resultTree));
1130   }
1131   return symbol;
1132 }
1133 
1134 StringRef PatternEmitter::handleReplaceWithValue(DagNode tree) {
1135   assert(tree.isReplaceWithValue());
1136 
1137   if (tree.getNumArgs() != 1) {
1138     PrintFatalError(
1139         loc, "replaceWithValue directive must take exactly one argument");
1140   }
1141 
1142   if (!tree.getSymbol().empty()) {
1143     PrintFatalError(loc, "cannot bind symbol to replaceWithValue");
1144   }
1145 
1146   return tree.getArgName(0);
1147 }
1148 
1149 std::string PatternEmitter::handleLocationDirective(DagNode tree) {
1150   assert(tree.isLocationDirective());
1151   auto lookUpArgLoc = [this, &tree](int idx) {
1152     const auto *const lookupFmt = "{0}.getLoc()";
1153     return symbolInfoMap.getValueAndRangeUse(tree.getArgName(idx), lookupFmt);
1154   };
1155 
1156   if (tree.getNumArgs() == 0)
1157     llvm::PrintFatalError(
1158         "At least one argument to location directive required");
1159 
1160   if (!tree.getSymbol().empty())
1161     PrintFatalError(loc, "cannot bind symbol to location");
1162 
1163   if (tree.getNumArgs() == 1) {
1164     DagLeaf leaf = tree.getArgAsLeaf(0);
1165     if (leaf.isStringAttr())
1166       return formatv("::mlir::NameLoc::get(rewriter.getStringAttr(\"{0}\"))",
1167                      leaf.getStringAttr())
1168           .str();
1169     return lookUpArgLoc(0);
1170   }
1171 
1172   std::string ret;
1173   llvm::raw_string_ostream os(ret);
1174   std::string strAttr;
1175   os << "rewriter.getFusedLoc({";
1176   bool first = true;
1177   for (int i = 0, e = tree.getNumArgs(); i != e; ++i) {
1178     DagLeaf leaf = tree.getArgAsLeaf(i);
1179     // Handle the optional string value.
1180     if (leaf.isStringAttr()) {
1181       if (!strAttr.empty())
1182         llvm::PrintFatalError("Only one string attribute may be specified");
1183       strAttr = leaf.getStringAttr();
1184       continue;
1185     }
1186     os << (first ? "" : ", ") << lookUpArgLoc(i);
1187     first = false;
1188   }
1189   os << "}";
1190   if (!strAttr.empty()) {
1191     os << ", rewriter.getStringAttr(\"" << strAttr << "\")";
1192   }
1193   os << ")";
1194   return os.str();
1195 }
1196 
1197 std::string PatternEmitter::handleReturnTypeArg(DagNode returnType, int i,
1198                                                 int depth) {
1199   // Nested NativeCodeCall.
1200   if (auto dagNode = returnType.getArgAsNestedDag(i)) {
1201     if (!dagNode.isNativeCodeCall())
1202       PrintFatalError(loc, "nested DAG in `returnType` must be a native code "
1203                            "call");
1204     return handleReplaceWithNativeCodeCall(dagNode, depth);
1205   }
1206   // String literal.
1207   auto dagLeaf = returnType.getArgAsLeaf(i);
1208   if (dagLeaf.isStringAttr())
1209     return tgfmt(dagLeaf.getStringAttr(), &fmtCtx);
1210   return tgfmt(
1211       "$0.getType()", &fmtCtx,
1212       handleOpArgument(returnType.getArgAsLeaf(i), returnType.getArgName(i)));
1213 }
1214 
1215 std::string PatternEmitter::handleOpArgument(DagLeaf leaf,
1216                                              StringRef patArgName) {
1217   if (leaf.isStringAttr())
1218     PrintFatalError(loc, "raw string not supported as argument");
1219   if (leaf.isConstantAttr()) {
1220     auto constAttr = leaf.getAsConstantAttr();
1221     return handleConstantAttr(constAttr.getAttribute(),
1222                               constAttr.getConstantValue());
1223   }
1224   if (leaf.isEnumAttrCase()) {
1225     auto enumCase = leaf.getAsEnumAttrCase();
1226     // This is an enum case backed by an IntegerAttr. We need to get its value
1227     // to build the constant.
1228     std::string val = std::to_string(enumCase.getValue());
1229     return handleConstantAttr(enumCase, val);
1230   }
1231 
1232   LLVM_DEBUG(llvm::dbgs() << "handle argument '" << patArgName << "'\n");
1233   auto argName = symbolInfoMap.getValueAndRangeUse(patArgName);
1234   if (leaf.isUnspecified() || leaf.isOperandMatcher()) {
1235     LLVM_DEBUG(llvm::dbgs() << "replace " << patArgName << " with '" << argName
1236                             << "' (via symbol ref)\n");
1237     return argName;
1238   }
1239   if (leaf.isNativeCodeCall()) {
1240     auto repl = tgfmt(leaf.getNativeCodeTemplate(), &fmtCtx.withSelf(argName));
1241     LLVM_DEBUG(llvm::dbgs() << "replace " << patArgName << " with '" << repl
1242                             << "' (via NativeCodeCall)\n");
1243     return std::string(repl);
1244   }
1245   PrintFatalError(loc, "unhandled case when rewriting op");
1246 }
1247 
1248 std::string PatternEmitter::handleReplaceWithNativeCodeCall(DagNode tree,
1249                                                             int depth) {
1250   LLVM_DEBUG(llvm::dbgs() << "handle NativeCodeCall pattern: ");
1251   LLVM_DEBUG(tree.print(llvm::dbgs()));
1252   LLVM_DEBUG(llvm::dbgs() << '\n');
1253 
1254   auto fmt = tree.getNativeCodeTemplate();
1255 
1256   SmallVector<std::string, 16> attrs;
1257 
1258   auto tail = getTrailingDirectives(tree);
1259   if (tail.returnType)
1260     PrintFatalError(loc, "`NativeCodeCall` cannot have return type specifier");
1261   auto locToUse = getLocation(tail);
1262 
1263   for (int i = 0, e = tree.getNumArgs() - tail.numDirectives; i != e; ++i) {
1264     if (tree.isNestedDagArg(i)) {
1265       attrs.push_back(
1266           handleResultPattern(tree.getArgAsNestedDag(i), i, depth + 1));
1267     } else {
1268       attrs.push_back(
1269           handleOpArgument(tree.getArgAsLeaf(i), tree.getArgName(i)));
1270     }
1271     LLVM_DEBUG(llvm::dbgs() << "NativeCodeCall argument #" << i
1272                             << " replacement: " << attrs[i] << "\n");
1273   }
1274 
1275   std::string symbol = tgfmt(fmt, &fmtCtx.addSubst("_loc", locToUse),
1276                              static_cast<ArrayRef<std::string>>(attrs));
1277 
1278   // In general, NativeCodeCall without naming binding don't need this. To
1279   // ensure void helper function has been correctly labeled, i.e., use
1280   // NativeCodeCallVoid, we cache the result to a local variable so that we will
1281   // get a compilation error in the auto-generated file.
1282   // Example.
1283   //   // In the td file
1284   //   Pat<(...), (NativeCodeCall<Foo> ...)>
1285   //
1286   //   ---
1287   //
1288   //   // In the auto-generated .cpp
1289   //   ...
1290   //   // Causes compilation error if Foo() returns void.
1291   //   auto nativeVar = Foo();
1292   //   ...
1293   if (tree.getNumReturnsOfNativeCode() != 0) {
1294     // Determine the local variable name for return value.
1295     std::string varName =
1296         SymbolInfoMap::getValuePackName(tree.getSymbol()).str();
1297     if (varName.empty()) {
1298       varName = formatv("nativeVar_{0}", nextValueId++);
1299       // Register the local variable for later uses.
1300       symbolInfoMap.bindValues(varName, tree.getNumReturnsOfNativeCode());
1301     }
1302 
1303     // Catch the return value of helper function.
1304     os << formatv("auto {0} = {1}; (void){0};\n", varName, symbol);
1305 
1306     if (!tree.getSymbol().empty())
1307       symbol = tree.getSymbol().str();
1308     else
1309       symbol = varName;
1310   }
1311 
1312   return symbol;
1313 }
1314 
1315 int PatternEmitter::getNodeValueCount(DagNode node) {
1316   if (node.isOperation()) {
1317     // If the op is bound to a symbol in the rewrite rule, query its result
1318     // count from the symbol info map.
1319     auto symbol = node.getSymbol();
1320     if (!symbol.empty()) {
1321       return symbolInfoMap.getStaticValueCount(symbol);
1322     }
1323     // Otherwise this is an unbound op; we will use all its results.
1324     return pattern.getDialectOp(node).getNumResults();
1325   }
1326 
1327   if (node.isNativeCodeCall())
1328     return node.getNumReturnsOfNativeCode();
1329 
1330   return 1;
1331 }
1332 
1333 PatternEmitter::TrailingDirectives
1334 PatternEmitter::getTrailingDirectives(DagNode tree) {
1335   TrailingDirectives tail = {DagNode(nullptr), DagNode(nullptr), 0};
1336 
1337   // Look backwards through the arguments.
1338   auto numPatArgs = tree.getNumArgs();
1339   for (int i = numPatArgs - 1; i >= 0; --i) {
1340     auto dagArg = tree.getArgAsNestedDag(i);
1341     // A leaf is not a directive. Stop looking.
1342     if (!dagArg)
1343       break;
1344 
1345     auto isLocation = dagArg.isLocationDirective();
1346     auto isReturnType = dagArg.isReturnTypeDirective();
1347     // If encountered a DAG node that isn't a trailing directive, stop looking.
1348     if (!(isLocation || isReturnType))
1349       break;
1350     // Save the directive, but error if one of the same type was already
1351     // found.
1352     ++tail.numDirectives;
1353     if (isLocation) {
1354       if (tail.location)
1355         PrintFatalError(loc, "`location` directive can only be specified "
1356                              "once");
1357       tail.location = dagArg;
1358     } else if (isReturnType) {
1359       if (tail.returnType)
1360         PrintFatalError(loc, "`returnType` directive can only be specified "
1361                              "once");
1362       tail.returnType = dagArg;
1363     }
1364   }
1365 
1366   return tail;
1367 }
1368 
1369 std::string
1370 PatternEmitter::getLocation(PatternEmitter::TrailingDirectives &tail) {
1371   if (tail.location)
1372     return handleLocationDirective(tail.location);
1373 
1374   // If no explicit location is given, use the default, all fused, location.
1375   return "odsLoc";
1376 }
1377 
1378 std::string PatternEmitter::handleOpCreation(DagNode tree, int resultIndex,
1379                                              int depth) {
1380   LLVM_DEBUG(llvm::dbgs() << "create op for pattern: ");
1381   LLVM_DEBUG(tree.print(llvm::dbgs()));
1382   LLVM_DEBUG(llvm::dbgs() << '\n');
1383 
1384   Operator &resultOp = tree.getDialectOp(opMap);
1385   auto numOpArgs = resultOp.getNumArgs();
1386   auto numPatArgs = tree.getNumArgs();
1387 
1388   auto tail = getTrailingDirectives(tree);
1389   auto locToUse = getLocation(tail);
1390 
1391   auto inPattern = numPatArgs - tail.numDirectives;
1392   if (numOpArgs != inPattern) {
1393     PrintFatalError(loc,
1394                     formatv("resultant op '{0}' argument number mismatch: "
1395                             "{1} in pattern vs. {2} in definition",
1396                             resultOp.getOperationName(), inPattern, numOpArgs));
1397   }
1398 
1399   // A map to collect all nested DAG child nodes' names, with operand index as
1400   // the key. This includes both bound and unbound child nodes.
1401   ChildNodeIndexNameMap childNodeNames;
1402 
1403   // First go through all the child nodes who are nested DAG constructs to
1404   // create ops for them and remember the symbol names for them, so that we can
1405   // use the results in the current node. This happens in a recursive manner.
1406   for (int i = 0, e = tree.getNumArgs() - tail.numDirectives; i != e; ++i) {
1407     if (auto child = tree.getArgAsNestedDag(i))
1408       childNodeNames[i] = handleResultPattern(child, i, depth + 1);
1409   }
1410 
1411   // The name of the local variable holding this op.
1412   std::string valuePackName;
1413   // The symbol for holding the result of this pattern. Note that the result of
1414   // this pattern is not necessarily the same as the variable created by this
1415   // pattern because we can use `__N` suffix to refer only a specific result if
1416   // the generated op is a multi-result op.
1417   std::string resultValue;
1418   if (tree.getSymbol().empty()) {
1419     // No symbol is explicitly bound to this op in the pattern. Generate a
1420     // unique name.
1421     valuePackName = resultValue = getUniqueSymbol(&resultOp);
1422   } else {
1423     resultValue = std::string(tree.getSymbol());
1424     // Strip the index to get the name for the value pack and use it to name the
1425     // local variable for the op.
1426     valuePackName = std::string(SymbolInfoMap::getValuePackName(resultValue));
1427   }
1428 
1429   // Create the local variable for this op.
1430   os << formatv("{0} {1};\n{{\n", resultOp.getQualCppClassName(),
1431                 valuePackName);
1432 
1433   // Right now ODS don't have general type inference support. Except a few
1434   // special cases listed below, DRR needs to supply types for all results
1435   // when building an op.
1436   bool isSameOperandsAndResultType =
1437       resultOp.getTrait("::mlir::OpTrait::SameOperandsAndResultType");
1438   bool useFirstAttr =
1439       resultOp.getTrait("::mlir::OpTrait::FirstAttrDerivedResultType");
1440 
1441   if (!tail.returnType && (isSameOperandsAndResultType || useFirstAttr)) {
1442     // We know how to deduce the result type for ops with these traits and we've
1443     // generated builders taking aggregate parameters. Use those builders to
1444     // create the ops.
1445 
1446     // First prepare local variables for op arguments used in builder call.
1447     createAggregateLocalVarsForOpArgs(tree, childNodeNames, depth);
1448 
1449     // Then create the op.
1450     os.scope("", "\n}\n").os << formatv(
1451         "{0} = rewriter.create<{1}>({2}, tblgen_values, tblgen_attrs);",
1452         valuePackName, resultOp.getQualCppClassName(), locToUse);
1453     return resultValue;
1454   }
1455 
1456   bool usePartialResults = valuePackName != resultValue;
1457 
1458   if (!tail.returnType && (usePartialResults || depth > 0 || resultIndex < 0)) {
1459     // For these cases (broadcastable ops, op results used both as auxiliary
1460     // values and replacement values, ops in nested patterns, auxiliary ops), we
1461     // still need to supply the result types when building the op. But because
1462     // we don't generate a builder automatically with ODS for them, it's the
1463     // developer's responsibility to make sure such a builder (with result type
1464     // deduction ability) exists. We go through the separate-parameter builder
1465     // here given that it's easier for developers to write compared to
1466     // aggregate-parameter builders.
1467     createSeparateLocalVarsForOpArgs(tree, childNodeNames);
1468 
1469     os.scope().os << formatv("{0} = rewriter.create<{1}>({2}", valuePackName,
1470                              resultOp.getQualCppClassName(), locToUse);
1471     supplyValuesForOpArgs(tree, childNodeNames, depth);
1472     os << "\n  );\n}\n";
1473     return resultValue;
1474   }
1475 
1476   // If we are provided explicit return types, use them to build the op.
1477   // However, if depth == 0 and resultIndex >= 0, it means we are replacing
1478   // the values generated from the source pattern root op. Then we must use the
1479   // source pattern's value types to determine the value type of the generated
1480   // op here.
1481   if (depth == 0 && resultIndex >= 0 && tail.returnType)
1482     PrintFatalError(loc, "Cannot specify explicit return types in an op whose "
1483                          "return values replace the source pattern's root op");
1484 
1485   // First prepare local variables for op arguments used in builder call.
1486   createAggregateLocalVarsForOpArgs(tree, childNodeNames, depth);
1487 
1488   // Then prepare the result types. We need to specify the types for all
1489   // results.
1490   os.indent() << formatv("::llvm::SmallVector<::mlir::Type, 4> tblgen_types; "
1491                          "(void)tblgen_types;\n");
1492   int numResults = resultOp.getNumResults();
1493   if (tail.returnType) {
1494     auto numRetTys = tail.returnType.getNumArgs();
1495     for (int i = 0; i < numRetTys; ++i) {
1496       auto varName = handleReturnTypeArg(tail.returnType, i, depth + 1);
1497       os << "tblgen_types.push_back(" << varName << ");\n";
1498     }
1499   } else {
1500     if (numResults != 0) {
1501       // Copy the result types from the source pattern.
1502       for (int i = 0; i < numResults; ++i)
1503         os << formatv("for (auto v: castedOp0.getODSResults({0})) {{\n"
1504                       "  tblgen_types.push_back(v.getType());\n}\n",
1505                       resultIndex + i);
1506     }
1507   }
1508   os << formatv("{0} = rewriter.create<{1}>({2}, tblgen_types, "
1509                 "tblgen_values, tblgen_attrs);\n",
1510                 valuePackName, resultOp.getQualCppClassName(), locToUse);
1511   os.unindent() << "}\n";
1512   return resultValue;
1513 }
1514 
1515 void PatternEmitter::createSeparateLocalVarsForOpArgs(
1516     DagNode node, ChildNodeIndexNameMap &childNodeNames) {
1517   Operator &resultOp = node.getDialectOp(opMap);
1518 
1519   // Now prepare operands used for building this op:
1520   // * If the operand is non-variadic, we create a `Value` local variable.
1521   // * If the operand is variadic, we create a `SmallVector<Value>` local
1522   //   variable.
1523 
1524   int valueIndex = 0; // An index for uniquing local variable names.
1525   for (int argIndex = 0, e = resultOp.getNumArgs(); argIndex < e; ++argIndex) {
1526     const auto *operand =
1527         llvm::dyn_cast_if_present<NamedTypeConstraint *>(resultOp.getArg(argIndex));
1528     // We do not need special handling for attributes.
1529     if (!operand)
1530       continue;
1531 
1532     raw_indented_ostream::DelimitedScope scope(os);
1533     std::string varName;
1534     if (operand->isVariadic()) {
1535       varName = std::string(formatv("tblgen_values_{0}", valueIndex++));
1536       os << formatv("::llvm::SmallVector<::mlir::Value, 4> {0};\n", varName);
1537       std::string range;
1538       if (node.isNestedDagArg(argIndex)) {
1539         range = childNodeNames[argIndex];
1540       } else {
1541         range = std::string(node.getArgName(argIndex));
1542       }
1543       // Resolve the symbol for all range use so that we have a uniform way of
1544       // capturing the values.
1545       range = symbolInfoMap.getValueAndRangeUse(range);
1546       os << formatv("for (auto v: {0}) {{\n  {1}.push_back(v);\n}\n", range,
1547                     varName);
1548     } else {
1549       varName = std::string(formatv("tblgen_value_{0}", valueIndex++));
1550       os << formatv("::mlir::Value {0} = ", varName);
1551       if (node.isNestedDagArg(argIndex)) {
1552         os << symbolInfoMap.getValueAndRangeUse(childNodeNames[argIndex]);
1553       } else {
1554         DagLeaf leaf = node.getArgAsLeaf(argIndex);
1555         auto symbol =
1556             symbolInfoMap.getValueAndRangeUse(node.getArgName(argIndex));
1557         if (leaf.isNativeCodeCall()) {
1558           os << std::string(
1559               tgfmt(leaf.getNativeCodeTemplate(), &fmtCtx.withSelf(symbol)));
1560         } else {
1561           os << symbol;
1562         }
1563       }
1564       os << ";\n";
1565     }
1566 
1567     // Update to use the newly created local variable for building the op later.
1568     childNodeNames[argIndex] = varName;
1569   }
1570 }
1571 
1572 void PatternEmitter::supplyValuesForOpArgs(
1573     DagNode node, const ChildNodeIndexNameMap &childNodeNames, int depth) {
1574   Operator &resultOp = node.getDialectOp(opMap);
1575   for (int argIndex = 0, numOpArgs = resultOp.getNumArgs();
1576        argIndex != numOpArgs; ++argIndex) {
1577     // Start each argument on its own line.
1578     os << ",\n    ";
1579 
1580     Argument opArg = resultOp.getArg(argIndex);
1581     // Handle the case of operand first.
1582     if (auto *operand = llvm::dyn_cast_if_present<NamedTypeConstraint *>(opArg)) {
1583       if (!operand->name.empty())
1584         os << "/*" << operand->name << "=*/";
1585       os << childNodeNames.lookup(argIndex);
1586       continue;
1587     }
1588 
1589     // The argument in the op definition.
1590     auto opArgName = resultOp.getArgName(argIndex);
1591     if (auto subTree = node.getArgAsNestedDag(argIndex)) {
1592       if (!subTree.isNativeCodeCall())
1593         PrintFatalError(loc, "only NativeCodeCall allowed in nested dag node "
1594                              "for creating attribute");
1595       os << formatv("/*{0}=*/{1}", opArgName, childNodeNames.lookup(argIndex));
1596     } else {
1597       auto leaf = node.getArgAsLeaf(argIndex);
1598       // The argument in the result DAG pattern.
1599       auto patArgName = node.getArgName(argIndex);
1600       if (leaf.isConstantAttr() || leaf.isEnumAttrCase()) {
1601         // TODO: Refactor out into map to avoid recomputing these.
1602         if (!opArg.is<NamedAttribute *>())
1603           PrintFatalError(loc, Twine("expected attribute ") + Twine(argIndex));
1604         if (!patArgName.empty())
1605           os << "/*" << patArgName << "=*/";
1606       } else {
1607         os << "/*" << opArgName << "=*/";
1608       }
1609       os << handleOpArgument(leaf, patArgName);
1610     }
1611   }
1612 }
1613 
1614 void PatternEmitter::createAggregateLocalVarsForOpArgs(
1615     DagNode node, const ChildNodeIndexNameMap &childNodeNames, int depth) {
1616   Operator &resultOp = node.getDialectOp(opMap);
1617 
1618   auto scope = os.scope();
1619   os << formatv("::llvm::SmallVector<::mlir::Value, 4> "
1620                 "tblgen_values; (void)tblgen_values;\n");
1621   os << formatv("::llvm::SmallVector<::mlir::NamedAttribute, 4> "
1622                 "tblgen_attrs; (void)tblgen_attrs;\n");
1623 
1624   const char *addAttrCmd =
1625       "if (auto tmpAttr = {1}) {\n"
1626       "  tblgen_attrs.emplace_back(rewriter.getStringAttr(\"{0}\"), "
1627       "tmpAttr);\n}\n";
1628   for (int argIndex = 0, e = resultOp.getNumArgs(); argIndex < e; ++argIndex) {
1629     if (resultOp.getArg(argIndex).is<NamedAttribute *>()) {
1630       // The argument in the op definition.
1631       auto opArgName = resultOp.getArgName(argIndex);
1632       if (auto subTree = node.getArgAsNestedDag(argIndex)) {
1633         if (!subTree.isNativeCodeCall())
1634           PrintFatalError(loc, "only NativeCodeCall allowed in nested dag node "
1635                                "for creating attribute");
1636         os << formatv(addAttrCmd, opArgName, childNodeNames.lookup(argIndex));
1637       } else {
1638         auto leaf = node.getArgAsLeaf(argIndex);
1639         // The argument in the result DAG pattern.
1640         auto patArgName = node.getArgName(argIndex);
1641         os << formatv(addAttrCmd, opArgName,
1642                       handleOpArgument(leaf, patArgName));
1643       }
1644       continue;
1645     }
1646 
1647     const auto *operand =
1648         resultOp.getArg(argIndex).get<NamedTypeConstraint *>();
1649     std::string varName;
1650     if (operand->isVariadic()) {
1651       std::string range;
1652       if (node.isNestedDagArg(argIndex)) {
1653         range = childNodeNames.lookup(argIndex);
1654       } else {
1655         range = std::string(node.getArgName(argIndex));
1656       }
1657       // Resolve the symbol for all range use so that we have a uniform way of
1658       // capturing the values.
1659       range = symbolInfoMap.getValueAndRangeUse(range);
1660       os << formatv("for (auto v: {0}) {{\n  tblgen_values.push_back(v);\n}\n",
1661                     range);
1662     } else {
1663       os << formatv("tblgen_values.push_back(");
1664       if (node.isNestedDagArg(argIndex)) {
1665         os << symbolInfoMap.getValueAndRangeUse(
1666             childNodeNames.lookup(argIndex));
1667       } else {
1668         DagLeaf leaf = node.getArgAsLeaf(argIndex);
1669         if (leaf.isConstantAttr())
1670           // TODO: Use better location
1671           PrintFatalError(
1672               loc,
1673               "attribute found where value was expected, if attempting to use "
1674               "constant value, construct a constant op with given attribute "
1675               "instead");
1676 
1677         auto symbol =
1678             symbolInfoMap.getValueAndRangeUse(node.getArgName(argIndex));
1679         if (leaf.isNativeCodeCall()) {
1680           os << std::string(
1681               tgfmt(leaf.getNativeCodeTemplate(), &fmtCtx.withSelf(symbol)));
1682         } else {
1683           os << symbol;
1684         }
1685       }
1686       os << ");\n";
1687     }
1688   }
1689 }
1690 
1691 StaticMatcherHelper::StaticMatcherHelper(raw_ostream &os,
1692                                          const RecordKeeper &recordKeeper,
1693                                          RecordOperatorMap &mapper)
1694     : opMap(mapper), staticVerifierEmitter(os, recordKeeper) {}
1695 
1696 void StaticMatcherHelper::populateStaticMatchers(raw_ostream &os) {
1697   // PatternEmitter will use the static matcher if there's one generated. To
1698   // ensure that all the dependent static matchers are generated before emitting
1699   // the matching logic of the DagNode, we use topological order to achieve it.
1700   for (auto &dagInfo : topologicalOrder) {
1701     DagNode node = dagInfo.first;
1702     if (!useStaticMatcher(node))
1703       continue;
1704 
1705     std::string funcName =
1706         formatv("static_dag_matcher_{0}", staticMatcherCounter++);
1707     assert(!matcherNames.contains(node));
1708     PatternEmitter(dagInfo.second, &opMap, os, *this)
1709         .emitStaticMatcher(node, funcName);
1710     matcherNames[node] = funcName;
1711   }
1712 }
1713 
1714 void StaticMatcherHelper::populateStaticConstraintFunctions(raw_ostream &os) {
1715   staticVerifierEmitter.emitPatternConstraints(constraints.getArrayRef());
1716 }
1717 
1718 void StaticMatcherHelper::addPattern(Record *record) {
1719   Pattern pat(record, &opMap);
1720 
1721   // While generating the function body of the DAG matcher, it may depends on
1722   // other DAG matchers. To ensure the dependent matchers are ready, we compute
1723   // the topological order for all the DAGs and emit the DAG matchers in this
1724   // order.
1725   llvm::unique_function<void(DagNode)> dfs = [&](DagNode node) {
1726     ++refStats[node];
1727 
1728     if (refStats[node] != 1)
1729       return;
1730 
1731     for (unsigned i = 0, e = node.getNumArgs(); i < e; ++i)
1732       if (DagNode sibling = node.getArgAsNestedDag(i))
1733         dfs(sibling);
1734       else {
1735         DagLeaf leaf = node.getArgAsLeaf(i);
1736         if (!leaf.isUnspecified())
1737           constraints.insert(leaf);
1738       }
1739 
1740     topologicalOrder.push_back(std::make_pair(node, record));
1741   };
1742 
1743   dfs(pat.getSourcePattern());
1744 }
1745 
1746 StringRef StaticMatcherHelper::getVerifierName(DagLeaf leaf) {
1747   if (leaf.isAttrMatcher()) {
1748     std::optional<StringRef> constraint =
1749         staticVerifierEmitter.getAttrConstraintFn(leaf.getAsConstraint());
1750     assert(constraint && "attribute constraint was not uniqued");
1751     return *constraint;
1752   }
1753   assert(leaf.isOperandMatcher());
1754   return staticVerifierEmitter.getTypeConstraintFn(leaf.getAsConstraint());
1755 }
1756 
1757 static void emitRewriters(const RecordKeeper &recordKeeper, raw_ostream &os) {
1758   emitSourceFileHeader("Rewriters", os);
1759 
1760   const auto &patterns = recordKeeper.getAllDerivedDefinitions("Pattern");
1761 
1762   // We put the map here because it can be shared among multiple patterns.
1763   RecordOperatorMap recordOpMap;
1764 
1765   // Exam all the patterns and generate static matcher for the duplicated
1766   // DagNode.
1767   StaticMatcherHelper staticMatcher(os, recordKeeper, recordOpMap);
1768   for (Record *p : patterns)
1769     staticMatcher.addPattern(p);
1770   staticMatcher.populateStaticConstraintFunctions(os);
1771   staticMatcher.populateStaticMatchers(os);
1772 
1773   std::vector<std::string> rewriterNames;
1774   rewriterNames.reserve(patterns.size());
1775 
1776   std::string baseRewriterName = "GeneratedConvert";
1777   int rewriterIndex = 0;
1778 
1779   for (Record *p : patterns) {
1780     std::string name;
1781     if (p->isAnonymous()) {
1782       // If no name is provided, ensure unique rewriter names simply by
1783       // appending unique suffix.
1784       name = baseRewriterName + llvm::utostr(rewriterIndex++);
1785     } else {
1786       name = std::string(p->getName());
1787     }
1788     LLVM_DEBUG(llvm::dbgs()
1789                << "=== start generating pattern '" << name << "' ===\n");
1790     PatternEmitter(p, &recordOpMap, os, staticMatcher).emit(name);
1791     LLVM_DEBUG(llvm::dbgs()
1792                << "=== done generating pattern '" << name << "' ===\n");
1793     rewriterNames.push_back(std::move(name));
1794   }
1795 
1796   // Emit function to add the generated matchers to the pattern list.
1797   os << "void LLVM_ATTRIBUTE_UNUSED populateWithGenerated("
1798         "::mlir::RewritePatternSet &patterns) {\n";
1799   for (const auto &name : rewriterNames) {
1800     os << "  patterns.add<" << name << ">(patterns.getContext());\n";
1801   }
1802   os << "}\n";
1803 }
1804 
1805 static mlir::GenRegistration
1806     genRewriters("gen-rewriters", "Generate pattern rewriters",
1807                  [](const RecordKeeper &records, raw_ostream &os) {
1808                    emitRewriters(records, os);
1809                    return false;
1810                  });
1811