1 //===- OpDefinitionsGen.cpp - MLIR op definitions 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 // OpDefinitionsGen uses the description of operations to generate C++
10 // definitions for ops.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "OpFormatGen.h"
15 #include "OpGenHelpers.h"
16 #include "mlir/TableGen/CodeGenHelpers.h"
17 #include "mlir/TableGen/Format.h"
18 #include "mlir/TableGen/GenInfo.h"
19 #include "mlir/TableGen/Interfaces.h"
20 #include "mlir/TableGen/OpClass.h"
21 #include "mlir/TableGen/Operator.h"
22 #include "mlir/TableGen/SideEffects.h"
23 #include "mlir/TableGen/Trait.h"
24 #include "llvm/ADT/MapVector.h"
25 #include "llvm/ADT/Sequence.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSet.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/Signals.h"
30 #include "llvm/TableGen/Error.h"
31 #include "llvm/TableGen/Record.h"
32 #include "llvm/TableGen/TableGenBackend.h"
33 
34 #define DEBUG_TYPE "mlir-tblgen-opdefgen"
35 
36 using namespace llvm;
37 using namespace mlir;
38 using namespace mlir::tblgen;
39 
40 static const char *const tblgenNamePrefix = "tblgen_";
41 static const char *const generatedArgName = "odsArg";
42 static const char *const odsBuilder = "odsBuilder";
43 static const char *const builderOpState = "odsState";
44 
45 // The logic to calculate the actual value range for a declared operand/result
46 // of an op with variadic operands/results. Note that this logic is not for
47 // general use; it assumes all variadic operands/results must have the same
48 // number of values.
49 //
50 // {0}: The list of whether each declared operand/result is variadic.
51 // {1}: The total number of non-variadic operands/results.
52 // {2}: The total number of variadic operands/results.
53 // {3}: The total number of actual values.
54 // {4}: "operand" or "result".
55 const char *sameVariadicSizeValueRangeCalcCode = R"(
56   bool isVariadic[] = {{{0}};
57   int prevVariadicCount = 0;
58   for (unsigned i = 0; i < index; ++i)
59     if (isVariadic[i]) ++prevVariadicCount;
60 
61   // Calculate how many dynamic values a static variadic {4} corresponds to.
62   // This assumes all static variadic {4}s have the same dynamic value count.
63   int variadicSize = ({3} - {1}) / {2};
64   // `index` passed in as the parameter is the static index which counts each
65   // {4} (variadic or not) as size 1. So here for each previous static variadic
66   // {4}, we need to offset by (variadicSize - 1) to get where the dynamic
67   // value pack for this static {4} starts.
68   int start = index + (variadicSize - 1) * prevVariadicCount;
69   int size = isVariadic[index] ? variadicSize : 1;
70   return {{start, size};
71 )";
72 
73 // The logic to calculate the actual value range for a declared operand/result
74 // of an op with variadic operands/results. Note that this logic is assumes
75 // the op has an attribute specifying the size of each operand/result segment
76 // (variadic or not).
77 //
78 // {0}: The name of the attribute specifying the segment sizes.
79 const char *adapterSegmentSizeAttrInitCode = R"(
80   assert(odsAttrs && "missing segment size attribute for op");
81   auto sizeAttr = odsAttrs.get("{0}").cast<::mlir::DenseIntElementsAttr>();
82 )";
83 const char *opSegmentSizeAttrInitCode = R"(
84   auto sizeAttr = (*this)->getAttr({0}).cast<::mlir::DenseIntElementsAttr>();
85 )";
86 const char *attrSizedSegmentValueRangeCalcCode = R"(
87   const uint32_t *sizeAttrValueIt = &*sizeAttr.value_begin<uint32_t>();
88   if (sizeAttr.isSplat())
89     return {*sizeAttrValueIt * index, *sizeAttrValueIt};
90 
91   unsigned start = 0;
92   for (unsigned i = 0; i < index; ++i)
93     start += sizeAttrValueIt[i];
94   return {start, sizeAttrValueIt[index]};
95 )";
96 // The logic to calculate the actual value range for a declared operand
97 // of an op with variadic of variadic operands within the OpAdaptor.
98 //
99 // {0}: The name of the segment attribute.
100 // {1}: The index of the main operand.
101 const char *variadicOfVariadicAdaptorCalcCode = R"(
102   auto tblgenTmpOperands = getODSOperands({1});
103   auto sizeAttrValues = {0}().getValues<uint32_t>();
104   auto sizeAttrIt = sizeAttrValues.begin();
105 
106   ::llvm::SmallVector<::mlir::ValueRange> tblgenTmpOperandGroups;
107   for (int i = 0, e = ::llvm::size(sizeAttrValues); i < e; ++i, ++sizeAttrIt) {{
108     tblgenTmpOperandGroups.push_back(tblgenTmpOperands.take_front(*sizeAttrIt));
109     tblgenTmpOperands = tblgenTmpOperands.drop_front(*sizeAttrIt);
110   }
111   return tblgenTmpOperandGroups;
112 )";
113 
114 // The logic to build a range of either operand or result values.
115 //
116 // {0}: The begin iterator of the actual values.
117 // {1}: The call to generate the start and length of the value range.
118 const char *valueRangeReturnCode = R"(
119   auto valueRange = {1};
120   return {{std::next({0}, valueRange.first),
121            std::next({0}, valueRange.first + valueRange.second)};
122 )";
123 
124 const char *typeVerifierSignature =
125     "static ::mlir::LogicalResult {0}(::mlir::Operation *op, ::mlir::Type "
126     "type, ::llvm::StringRef valueKind, unsigned valueGroupStartIndex)";
127 
128 const char *typeVerifierErrorHandler =
129     " op->emitOpError(valueKind) << \" #\" << valueGroupStartIndex << \" must "
130     "be {0}, but got \" << type";
131 
132 static const char *const opCommentHeader = R"(
133 //===----------------------------------------------------------------------===//
134 // {0} {1}
135 //===----------------------------------------------------------------------===//
136 
137 )";
138 
139 //===----------------------------------------------------------------------===//
140 // Utility structs and functions
141 //===----------------------------------------------------------------------===//
142 
143 // Replaces all occurrences of `match` in `str` with `substitute`.
144 static std::string replaceAllSubstrs(std::string str, const std::string &match,
145                                      const std::string &substitute) {
146   std::string::size_type scanLoc = 0, matchLoc = std::string::npos;
147   while ((matchLoc = str.find(match, scanLoc)) != std::string::npos) {
148     str = str.replace(matchLoc, match.size(), substitute);
149     scanLoc = matchLoc + substitute.size();
150   }
151   return str;
152 }
153 
154 // Returns whether the record has a value of the given name that can be returned
155 // via getValueAsString.
156 static inline bool hasStringAttribute(const Record &record,
157                                       StringRef fieldName) {
158   auto valueInit = record.getValueInit(fieldName);
159   return isa<StringInit>(valueInit);
160 }
161 
162 static std::string getArgumentName(const Operator &op, int index) {
163   const auto &operand = op.getOperand(index);
164   if (!operand.name.empty())
165     return std::string(operand.name);
166   else
167     return std::string(formatv("{0}_{1}", generatedArgName, index));
168 }
169 
170 // Returns true if we can use unwrapped value for the given `attr` in builders.
171 static bool canUseUnwrappedRawValue(const tblgen::Attribute &attr) {
172   return attr.getReturnType() != attr.getStorageType() &&
173          // We need to wrap the raw value into an attribute in the builder impl
174          // so we need to make sure that the attribute specifies how to do that.
175          !attr.getConstBuilderTemplate().empty();
176 }
177 
178 //===----------------------------------------------------------------------===//
179 // Op emitter
180 //===----------------------------------------------------------------------===//
181 
182 namespace {
183 // Helper class to emit a record into the given output stream.
184 class OpEmitter {
185 public:
186   static void
187   emitDecl(const Operator &op, raw_ostream &os,
188            const StaticVerifierFunctionEmitter &staticVerifierEmitter);
189   static void
190   emitDef(const Operator &op, raw_ostream &os,
191           const StaticVerifierFunctionEmitter &staticVerifierEmitter);
192 
193 private:
194   OpEmitter(const Operator &op,
195             const StaticVerifierFunctionEmitter &staticVerifierEmitter);
196 
197   void emitDecl(raw_ostream &os);
198   void emitDef(raw_ostream &os);
199 
200   // Generate methods for accessing the attribute names of this operation.
201   void genAttrNameGetters();
202 
203   // Generates the OpAsmOpInterface for this operation if possible.
204   void genOpAsmInterface();
205 
206   // Generates the `getOperationName` method for this op.
207   void genOpNameGetter();
208 
209   // Generates getters for the attributes.
210   void genAttrGetters();
211 
212   // Generates setter for the attributes.
213   void genAttrSetters();
214 
215   // Generates removers for optional attributes.
216   void genOptionalAttrRemovers();
217 
218   // Generates getters for named operands.
219   void genNamedOperandGetters();
220 
221   // Generates setters for named operands.
222   void genNamedOperandSetters();
223 
224   // Generates getters for named results.
225   void genNamedResultGetters();
226 
227   // Generates getters for named regions.
228   void genNamedRegionGetters();
229 
230   // Generates getters for named successors.
231   void genNamedSuccessorGetters();
232 
233   // Generates builder methods for the operation.
234   void genBuilder();
235 
236   // Generates the build() method that takes each operand/attribute
237   // as a stand-alone parameter.
238   void genSeparateArgParamBuilder();
239 
240   // Generates the build() method that takes each operand/attribute as a
241   // stand-alone parameter. The generated build() method uses first operand's
242   // type as all results' types.
243   void genUseOperandAsResultTypeSeparateParamBuilder();
244 
245   // Generates the build() method that takes all operands/attributes
246   // collectively as one parameter. The generated build() method uses first
247   // operand's type as all results' types.
248   void genUseOperandAsResultTypeCollectiveParamBuilder();
249 
250   // Generates the build() method that takes aggregate operands/attributes
251   // parameters. This build() method uses inferred types as result types.
252   // Requires: The type needs to be inferable via InferTypeOpInterface.
253   void genInferredTypeCollectiveParamBuilder();
254 
255   // Generates the build() method that takes each operand/attribute as a
256   // stand-alone parameter. The generated build() method uses first attribute's
257   // type as all result's types.
258   void genUseAttrAsResultTypeBuilder();
259 
260   // Generates the build() method that takes all result types collectively as
261   // one parameter. Similarly for operands and attributes.
262   void genCollectiveParamBuilder();
263 
264   // The kind of parameter to generate for result types in builders.
265   enum class TypeParamKind {
266     None,       // No result type in parameter list.
267     Separate,   // A separate parameter for each result type.
268     Collective, // An ArrayRef<Type> for all result types.
269   };
270 
271   // The kind of parameter to generate for attributes in builders.
272   enum class AttrParamKind {
273     WrappedAttr,    // A wrapped MLIR Attribute instance.
274     UnwrappedValue, // A raw value without MLIR Attribute wrapper.
275   };
276 
277   // Builds the parameter list for build() method of this op. This method writes
278   // to `paramList` the comma-separated parameter list and updates
279   // `resultTypeNames` with the names for parameters for specifying result
280   // types. `inferredAttributes` is populated with any attributes that are
281   // elided from the build list. The given `typeParamKind` and `attrParamKind`
282   // controls how result types and attributes are placed in the parameter list.
283   void buildParamList(llvm::SmallVectorImpl<OpMethodParameter> &paramList,
284                       llvm::StringSet<> &inferredAttributes,
285                       SmallVectorImpl<std::string> &resultTypeNames,
286                       TypeParamKind typeParamKind,
287                       AttrParamKind attrParamKind = AttrParamKind::WrappedAttr);
288 
289   // Adds op arguments and regions into operation state for build() methods.
290   void
291   genCodeForAddingArgAndRegionForBuilder(OpMethodBody &body,
292                                          llvm::StringSet<> &inferredAttributes,
293                                          bool isRawValueAttr = false);
294 
295   // Generates canonicalizer declaration for the operation.
296   void genCanonicalizerDecls();
297 
298   // Generates the folder declaration for the operation.
299   void genFolderDecls();
300 
301   // Generates the parser for the operation.
302   void genParser();
303 
304   // Generates the printer for the operation.
305   void genPrinter();
306 
307   // Generates verify method for the operation.
308   void genVerifier();
309 
310   // Generates verify statements for operands and results in the operation.
311   // The generated code will be attached to `body`.
312   void genOperandResultVerifier(OpMethodBody &body,
313                                 Operator::value_range values,
314                                 StringRef valueKind);
315 
316   // Generates verify statements for regions in the operation.
317   // The generated code will be attached to `body`.
318   void genRegionVerifier(OpMethodBody &body);
319 
320   // Generates verify statements for successors in the operation.
321   // The generated code will be attached to `body`.
322   void genSuccessorVerifier(OpMethodBody &body);
323 
324   // Generates the traits used by the object.
325   void genTraits();
326 
327   // Generate the OpInterface methods for all interfaces.
328   void genOpInterfaceMethods();
329 
330   // Generate op interface methods for the given interface.
331   void genOpInterfaceMethods(const tblgen::InterfaceTrait *trait);
332 
333   // Generate op interface method for the given interface method. If
334   // 'declaration' is true, generates a declaration, else a definition.
335   OpMethod *genOpInterfaceMethod(const tblgen::InterfaceMethod &method,
336                                  bool declaration = true);
337 
338   // Generate the side effect interface methods.
339   void genSideEffectInterfaceMethods();
340 
341   // Generate the type inference interface methods.
342   void genTypeInterfaceMethods();
343 
344 private:
345   // The TableGen record for this op.
346   // TODO: OpEmitter should not have a Record directly,
347   // it should rather go through the Operator for better abstraction.
348   const Record &def;
349 
350   // The wrapper operator class for querying information from this op.
351   Operator op;
352 
353   // The C++ code builder for this op
354   OpClass opClass;
355 
356   // The format context for verification code generation.
357   FmtContext verifyCtx;
358 
359   // The emitter containing all of the locally emitted verification functions.
360   const StaticVerifierFunctionEmitter &staticVerifierEmitter;
361 };
362 
363 } // end anonymous namespace
364 
365 // Populate the format context `ctx` with substitutions of attributes, operands
366 // and results.
367 // - attrGet corresponds to the name of the function to call to get value of
368 //   attribute (the generated function call returns an Attribute);
369 // - operandGet corresponds to the name of the function with which to retrieve
370 //   an operand (the generated function call returns an OperandRange);
371 // - resultGet corresponds to the name of the function to get an result (the
372 //   generated function call returns a ValueRange);
373 static void populateSubstitutions(const Operator &op, const char *attrGet,
374                                   const char *operandGet, const char *resultGet,
375                                   FmtContext &ctx) {
376   // Populate substitutions for attributes and named operands.
377   for (const auto &namedAttr : op.getAttributes())
378     ctx.addSubst(namedAttr.name,
379                  formatv("{0}(\"{1}\")", attrGet, namedAttr.name));
380   for (int i = 0, e = op.getNumOperands(); i < e; ++i) {
381     auto &value = op.getOperand(i);
382     if (value.name.empty())
383       continue;
384 
385     if (value.isVariadic())
386       ctx.addSubst(value.name, formatv("{0}({1})", operandGet, i));
387     else
388       ctx.addSubst(value.name, formatv("(*{0}({1}).begin())", operandGet, i));
389   }
390 
391   // Populate substitutions for results.
392   for (int i = 0, e = op.getNumResults(); i < e; ++i) {
393     auto &value = op.getResult(i);
394     if (value.name.empty())
395       continue;
396 
397     if (value.isVariadic())
398       ctx.addSubst(value.name, formatv("{0}({1})", resultGet, i));
399     else
400       ctx.addSubst(value.name, formatv("(*{0}({1}).begin())", resultGet, i));
401   }
402 }
403 
404 // Generate attribute verification. If emitVerificationRequiringOp is set then
405 // only verification for attributes whose value depend on op being known are
406 // emitted, else only verification that doesn't depend on the op being known are
407 // generated.
408 // - emitErrorPrefix is the prefix for the error emitting call which consists
409 //   of the entire function call up to start of error message fragment;
410 // - emitVerificationRequiringOp specifies whether verification should be
411 //   emitted for verification that require the op to exist;
412 static void genAttributeVerifier(const Operator &op, const char *attrGet,
413                                  const Twine &emitErrorPrefix,
414                                  bool emitVerificationRequiringOp,
415                                  FmtContext &ctx, OpMethodBody &body) {
416   for (const auto &namedAttr : op.getAttributes()) {
417     const auto &attr = namedAttr.attr;
418     if (attr.isDerivedAttr())
419       continue;
420 
421     auto attrName = namedAttr.name;
422     bool allowMissingAttr = attr.hasDefaultValue() || attr.isOptional();
423     auto attrPred = attr.getPredicate();
424     auto condition = attrPred.isNull() ? "" : attrPred.getCondition();
425     // There is a condition to emit only if the use of $_op and whether to
426     // emit verifications for op matches.
427     bool hasConditionToEmit = (!(condition.find("$_op") != StringRef::npos) ^
428                                emitVerificationRequiringOp);
429 
430     // Prefix with `tblgen_` to avoid hiding the attribute accessor.
431     auto varName = tblgenNamePrefix + attrName;
432 
433     // If the attribute is
434     //  1. Required (not allowed missing) and not in op verification, or
435     //  2. Has a condition that will get verified
436     // then the variable will be used.
437     //
438     // Therefore, for optional attributes whose verification requires that an
439     // op already exists for verification/emitVerificationRequiringOp is set
440     // has nothing that can be verified here.
441     if ((allowMissingAttr || emitVerificationRequiringOp) &&
442         !hasConditionToEmit)
443       continue;
444 
445     body << formatv("  {\n  auto {0} = {1}(\"{2}\");\n", varName, attrGet,
446                     attrName);
447 
448     if (!emitVerificationRequiringOp && !allowMissingAttr) {
449       body << "  if (!" << varName << ") return " << emitErrorPrefix
450            << "\"requires attribute '" << attrName << "'\");\n";
451     }
452 
453     if (!hasConditionToEmit) {
454       body << "  }\n";
455       continue;
456     }
457 
458     if (allowMissingAttr) {
459       // If the attribute has a default value, then only verify the predicate if
460       // set. This does effectively assume that the default value is valid.
461       // TODO: verify the debug value is valid (perhaps in debug mode only).
462       body << "  if (" << varName << ") {\n";
463     }
464 
465     body << tgfmt("    if (!($0)) return $1\"attribute '$2' "
466                   "failed to satisfy constraint: $3\");\n",
467                   /*ctx=*/nullptr, tgfmt(condition, &ctx.withSelf(varName)),
468                   emitErrorPrefix, attrName, escapeString(attr.getSummary()));
469     if (allowMissingAttr)
470       body << "  }\n";
471     body << "  }\n";
472   }
473 }
474 
475 OpEmitter::OpEmitter(const Operator &op,
476                      const StaticVerifierFunctionEmitter &staticVerifierEmitter)
477     : def(op.getDef()), op(op),
478       opClass(op.getCppClassName(), op.getExtraClassDeclaration()),
479       staticVerifierEmitter(staticVerifierEmitter) {
480   verifyCtx.withOp("(*this->getOperation())");
481   verifyCtx.addSubst("_ctxt", "this->getOperation()->getContext()");
482 
483   genTraits();
484 
485   // Generate C++ code for various op methods. The order here determines the
486   // methods in the generated file.
487   genAttrNameGetters();
488   genOpAsmInterface();
489   genOpNameGetter();
490   genNamedOperandGetters();
491   genNamedOperandSetters();
492   genNamedResultGetters();
493   genNamedRegionGetters();
494   genNamedSuccessorGetters();
495   genAttrGetters();
496   genAttrSetters();
497   genOptionalAttrRemovers();
498   genBuilder();
499   genParser();
500   genPrinter();
501   genVerifier();
502   genCanonicalizerDecls();
503   genFolderDecls();
504   genTypeInterfaceMethods();
505   genOpInterfaceMethods();
506   generateOpFormat(op, opClass);
507   genSideEffectInterfaceMethods();
508 }
509 void OpEmitter::emitDecl(
510     const Operator &op, raw_ostream &os,
511     const StaticVerifierFunctionEmitter &staticVerifierEmitter) {
512   OpEmitter(op, staticVerifierEmitter).emitDecl(os);
513 }
514 
515 void OpEmitter::emitDef(
516     const Operator &op, raw_ostream &os,
517     const StaticVerifierFunctionEmitter &staticVerifierEmitter) {
518   OpEmitter(op, staticVerifierEmitter).emitDef(os);
519 }
520 
521 void OpEmitter::emitDecl(raw_ostream &os) { opClass.writeDeclTo(os); }
522 
523 void OpEmitter::emitDef(raw_ostream &os) { opClass.writeDefTo(os); }
524 
525 static void errorIfPruned(size_t line, OpMethod *m, const Twine &methodName,
526                           const Operator &op) {
527   if (m)
528     return;
529   PrintFatalError(op.getLoc(), "Unexpected overlap when generating `" +
530                                    methodName + "` for " +
531                                    op.getOperationName() + " (from line " +
532                                    Twine(line) + ")");
533 }
534 #define ERROR_IF_PRUNED(M, N, O) errorIfPruned(__LINE__, M, N, O)
535 
536 void OpEmitter::genAttrNameGetters() {
537   // A map of attribute names (including implicit attributes) registered to the
538   // current operation, to the relative order in which they were registered.
539   llvm::MapVector<StringRef, unsigned> attributeNames;
540 
541   // Enumerate the attribute names of this op, assigning each a relative
542   // ordering.
543   auto addAttrName = [&](StringRef name) {
544     unsigned index = attributeNames.size();
545     attributeNames.insert({name, index});
546   };
547   for (const NamedAttribute &namedAttr : op.getAttributes())
548     addAttrName(namedAttr.name);
549   // Include key attributes from several traits as implicitly registered.
550   std::string operandSizes = "operand_segment_sizes";
551   if (op.getTrait("::mlir::OpTrait::AttrSizedOperandSegments"))
552     addAttrName(operandSizes);
553   std::string attrSizes = "result_segment_sizes";
554   if (op.getTrait("::mlir::OpTrait::AttrSizedResultSegments"))
555     addAttrName(attrSizes);
556 
557   // Emit the getAttributeNames method.
558   {
559     auto *method = opClass.addMethodAndPrune(
560         "::llvm::ArrayRef<::llvm::StringRef>", "getAttributeNames",
561         OpMethod::Property(OpMethod::MP_Static | OpMethod::MP_Inline));
562     ERROR_IF_PRUNED(method, "getAttributeNames", op);
563     auto &body = method->body();
564     if (attributeNames.empty()) {
565       body << "  return {};";
566     } else {
567       body << "  static ::llvm::StringRef attrNames[] = {";
568       llvm::interleaveComma(llvm::make_first_range(attributeNames), body,
569                             [&](StringRef attrName) {
570                               body << "::llvm::StringRef(\"" << attrName
571                                    << "\")";
572                             });
573       body << "};\n  return ::llvm::makeArrayRef(attrNames);";
574     }
575   }
576   if (attributeNames.empty())
577     return;
578 
579   // Emit the getAttributeNameForIndex methods.
580   {
581     auto *method = opClass.addMethodAndPrune(
582         "::mlir::Identifier", "getAttributeNameForIndex",
583         OpMethod::Property(OpMethod::MP_Private | OpMethod::MP_Inline),
584         "unsigned", "index");
585     ERROR_IF_PRUNED(method, "getAttributeNameForIndex", op);
586     method->body()
587         << "  return getAttributeNameForIndex((*this)->getName(), index);";
588   }
589   {
590     auto *method = opClass.addMethodAndPrune(
591         "::mlir::Identifier", "getAttributeNameForIndex",
592         OpMethod::Property(OpMethod::MP_Private | OpMethod::MP_Inline |
593                            OpMethod::MP_Static),
594         "::mlir::OperationName name, unsigned index");
595     ERROR_IF_PRUNED(method, "getAttributeNameForIndex", op);
596     method->body() << "assert(index < " << attributeNames.size()
597                    << " && \"invalid attribute index\");\n"
598                       "  return name.getAbstractOperation()"
599                       "->getAttributeNames()[index];";
600   }
601 
602   // Generate the <attr>AttrName methods, that expose the attribute names to
603   // users.
604   const char *attrNameMethodBody = "  return getAttributeNameForIndex({0});";
605   for (const std::pair<StringRef, unsigned> &attrIt : attributeNames) {
606     for (StringRef name : op.getGetterNames(attrIt.first)) {
607       std::string methodName = (name + "AttrName").str();
608 
609       // Generate the non-static variant.
610       {
611         auto *method =
612             opClass.addMethodAndPrune("::mlir::Identifier", methodName,
613                                       OpMethod::Property(OpMethod::MP_Inline));
614         ERROR_IF_PRUNED(method, methodName, op);
615         method->body()
616             << llvm::formatv(attrNameMethodBody, attrIt.second).str();
617       }
618 
619       // Generate the static variant.
620       {
621         auto *method = opClass.addMethodAndPrune(
622             "::mlir::Identifier", methodName,
623             OpMethod::Property(OpMethod::MP_Inline | OpMethod::MP_Static),
624             "::mlir::OperationName", "name");
625         ERROR_IF_PRUNED(method, methodName, op);
626         method->body() << llvm::formatv(attrNameMethodBody,
627                                         "name, " + Twine(attrIt.second))
628                               .str();
629       }
630     }
631   }
632 }
633 
634 void OpEmitter::genAttrGetters() {
635   FmtContext fctx;
636   fctx.withBuilder("::mlir::Builder((*this)->getContext())");
637 
638   // Emit the derived attribute body.
639   auto emitDerivedAttr = [&](StringRef name, Attribute attr) {
640     if (auto *method = opClass.addMethodAndPrune(attr.getReturnType(), name))
641       method->body() << "  " << attr.getDerivedCodeBody() << "\n";
642   };
643 
644   // Emit with return type specified.
645   auto emitAttrWithReturnType = [&](StringRef name, Attribute attr) {
646     auto *method = opClass.addMethodAndPrune(attr.getReturnType(), name);
647     ERROR_IF_PRUNED(method, name, op);
648     auto &body = method->body();
649     body << "  auto attr = " << name << "Attr();\n";
650     if (attr.hasDefaultValue()) {
651       // Returns the default value if not set.
652       // TODO: this is inefficient, we are recreating the attribute for every
653       // call. This should be set instead.
654       std::string defaultValue = std::string(
655           tgfmt(attr.getConstBuilderTemplate(), &fctx, attr.getDefaultValue()));
656       body << "    if (!attr)\n      return "
657            << tgfmt(attr.getConvertFromStorageCall(),
658                     &fctx.withSelf(defaultValue))
659            << ";\n";
660     }
661     body << "  return "
662          << tgfmt(attr.getConvertFromStorageCall(), &fctx.withSelf("attr"))
663          << ";\n";
664   };
665 
666   // Generate named accessor with Attribute return type. This is a wrapper class
667   // that allows referring to the attributes via accessors instead of having to
668   // use the string interface for better compile time verification.
669   auto emitAttrWithStorageType = [&](StringRef name, Attribute attr) {
670     auto *method =
671         opClass.addMethodAndPrune(attr.getStorageType(), (name + "Attr").str());
672     if (!method)
673       return;
674     auto &body = method->body();
675     body << "  return (*this)->getAttr(" << name << "AttrName()).template ";
676     if (attr.isOptional() || attr.hasDefaultValue())
677       body << "dyn_cast_or_null<";
678     else
679       body << "cast<";
680     body << attr.getStorageType() << ">();";
681   };
682 
683   for (const NamedAttribute &namedAttr : op.getAttributes()) {
684     for (StringRef name : op.getGetterNames(namedAttr.name)) {
685       if (namedAttr.attr.isDerivedAttr()) {
686         emitDerivedAttr(name, namedAttr.attr);
687       } else {
688         emitAttrWithStorageType(name, namedAttr.attr);
689         emitAttrWithReturnType(name, namedAttr.attr);
690       }
691     }
692   }
693 
694   auto derivedAttrs = make_filter_range(op.getAttributes(),
695                                         [](const NamedAttribute &namedAttr) {
696                                           return namedAttr.attr.isDerivedAttr();
697                                         });
698   if (!derivedAttrs.empty()) {
699     opClass.addTrait("::mlir::DerivedAttributeOpInterface::Trait");
700     // Generate helper method to query whether a named attribute is a derived
701     // attribute. This enables, for example, avoiding adding an attribute that
702     // overlaps with a derived attribute.
703     {
704       auto *method = opClass.addMethodAndPrune("bool", "isDerivedAttribute",
705                                                OpMethod::MP_Static,
706                                                "::llvm::StringRef", "name");
707       ERROR_IF_PRUNED(method, "isDerivedAttribute", op);
708       auto &body = method->body();
709       for (auto namedAttr : derivedAttrs)
710         body << "  if (name == \"" << namedAttr.name << "\") return true;\n";
711       body << " return false;";
712     }
713     // Generate method to materialize derived attributes as a DictionaryAttr.
714     {
715       auto *method = opClass.addMethodAndPrune("::mlir::DictionaryAttr",
716                                                "materializeDerivedAttributes");
717       ERROR_IF_PRUNED(method, "materializeDerivedAttributes", op);
718       auto &body = method->body();
719 
720       auto nonMaterializable =
721           make_filter_range(derivedAttrs, [](const NamedAttribute &namedAttr) {
722             return namedAttr.attr.getConvertFromStorageCall().empty();
723           });
724       if (!nonMaterializable.empty()) {
725         std::string attrs;
726         llvm::raw_string_ostream os(attrs);
727         interleaveComma(nonMaterializable, os, [&](const NamedAttribute &attr) {
728           os << op.getGetterName(attr.name);
729         });
730         PrintWarning(
731             op.getLoc(),
732             formatv(
733                 "op has non-materializable derived attributes '{0}', skipping",
734                 os.str()));
735         body << formatv("  emitOpError(\"op has non-materializable derived "
736                         "attributes '{0}'\");\n",
737                         attrs);
738         body << "  return nullptr;";
739         return;
740       }
741 
742       body << "  ::mlir::MLIRContext* ctx = getContext();\n";
743       body << "  ::mlir::Builder odsBuilder(ctx); (void)odsBuilder;\n";
744       body << "  return ::mlir::DictionaryAttr::get(";
745       body << "  ctx, {\n";
746       interleave(
747           derivedAttrs, body,
748           [&](const NamedAttribute &namedAttr) {
749             auto tmpl = namedAttr.attr.getConvertFromStorageCall();
750             std::string name = op.getGetterName(namedAttr.name);
751             body << "    {" << name << "AttrName(),\n"
752                  << tgfmt(tmpl, &fctx.withSelf(name + "()")
753                                      .withBuilder("odsBuilder")
754                                      .addSubst("_ctx", "ctx"))
755                  << "}";
756           },
757           ",\n");
758       body << "});";
759     }
760   }
761 }
762 
763 void OpEmitter::genAttrSetters() {
764   // Generate raw named setter type. This is a wrapper class that allows setting
765   // to the attributes via setters instead of having to use the string interface
766   // for better compile time verification.
767   auto emitAttrWithStorageType = [&](StringRef setterName, StringRef getterName,
768                                      Attribute attr) {
769     auto *method = opClass.addMethodAndPrune(
770         "void", (setterName + "Attr").str(), attr.getStorageType(), "attr");
771     if (method)
772       method->body() << "  (*this)->setAttr(" << getterName
773                      << "AttrName(), attr);";
774   };
775 
776   for (const NamedAttribute &namedAttr : op.getAttributes()) {
777     if (!namedAttr.attr.isDerivedAttr())
778       for (auto names : llvm::zip(op.getSetterNames(namedAttr.name),
779                                   op.getGetterNames(namedAttr.name)))
780         emitAttrWithStorageType(std::get<0>(names), std::get<1>(names),
781                                 namedAttr.attr);
782   }
783 }
784 
785 void OpEmitter::genOptionalAttrRemovers() {
786   // Generate methods for removing optional attributes, instead of having to
787   // use the string interface. Enables better compile time verification.
788   auto emitRemoveAttr = [&](StringRef name) {
789     auto upperInitial = name.take_front().upper();
790     auto suffix = name.drop_front();
791     auto *method = opClass.addMethodAndPrune(
792         "::mlir::Attribute", ("remove" + upperInitial + suffix + "Attr").str());
793     if (!method)
794       return;
795     method->body() << "  return (*this)->removeAttr(" << op.getGetterName(name)
796                    << "AttrName());";
797   };
798 
799   for (const NamedAttribute &namedAttr : op.getAttributes())
800     if (namedAttr.attr.isOptional())
801       emitRemoveAttr(namedAttr.name);
802 }
803 
804 // Generates the code to compute the start and end index of an operand or result
805 // range.
806 template <typename RangeT>
807 static void
808 generateValueRangeStartAndEnd(Class &opClass, StringRef methodName,
809                               int numVariadic, int numNonVariadic,
810                               StringRef rangeSizeCall, bool hasAttrSegmentSize,
811                               StringRef sizeAttrInit, RangeT &&odsValues) {
812   auto *method = opClass.addMethodAndPrune("std::pair<unsigned, unsigned>",
813                                            methodName, "unsigned", "index");
814   if (!method)
815     return;
816   auto &body = method->body();
817   if (numVariadic == 0) {
818     body << "  return {index, 1};\n";
819   } else if (hasAttrSegmentSize) {
820     body << sizeAttrInit << attrSizedSegmentValueRangeCalcCode;
821   } else {
822     // Because the op can have arbitrarily interleaved variadic and non-variadic
823     // operands, we need to embed a list in the "sink" getter method for
824     // calculation at run-time.
825     llvm::SmallVector<StringRef, 4> isVariadic;
826     isVariadic.reserve(llvm::size(odsValues));
827     for (auto &it : odsValues)
828       isVariadic.push_back(it.isVariableLength() ? "true" : "false");
829     std::string isVariadicList = llvm::join(isVariadic, ", ");
830     body << formatv(sameVariadicSizeValueRangeCalcCode, isVariadicList,
831                     numNonVariadic, numVariadic, rangeSizeCall, "operand");
832   }
833 }
834 
835 // Generates the named operand getter methods for the given Operator `op` and
836 // puts them in `opClass`.  Uses `rangeType` as the return type of getters that
837 // return a range of operands (individual operands are `Value ` and each
838 // element in the range must also be `Value `); use `rangeBeginCall` to get
839 // an iterator to the beginning of the operand range; use `rangeSizeCall` to
840 // obtain the number of operands. `getOperandCallPattern` contains the code
841 // necessary to obtain a single operand whose position will be substituted
842 // instead of
843 // "{0}" marker in the pattern.  Note that the pattern should work for any kind
844 // of ops, in particular for one-operand ops that may not have the
845 // `getOperand(unsigned)` method.
846 static void generateNamedOperandGetters(const Operator &op, Class &opClass,
847                                         bool isAdaptor, StringRef sizeAttrInit,
848                                         StringRef rangeType,
849                                         StringRef rangeBeginCall,
850                                         StringRef rangeSizeCall,
851                                         StringRef getOperandCallPattern) {
852   const int numOperands = op.getNumOperands();
853   const int numVariadicOperands = op.getNumVariableLengthOperands();
854   const int numNormalOperands = numOperands - numVariadicOperands;
855 
856   const auto *sameVariadicSize =
857       op.getTrait("::mlir::OpTrait::SameVariadicOperandSize");
858   const auto *attrSizedOperands =
859       op.getTrait("::mlir::OpTrait::AttrSizedOperandSegments");
860 
861   if (numVariadicOperands > 1 && !sameVariadicSize && !attrSizedOperands) {
862     PrintFatalError(op.getLoc(), "op has multiple variadic operands but no "
863                                  "specification over their sizes");
864   }
865 
866   if (numVariadicOperands < 2 && attrSizedOperands) {
867     PrintFatalError(op.getLoc(), "op must have at least two variadic operands "
868                                  "to use 'AttrSizedOperandSegments' trait");
869   }
870 
871   if (attrSizedOperands && sameVariadicSize) {
872     PrintFatalError(op.getLoc(),
873                     "op cannot have both 'AttrSizedOperandSegments' and "
874                     "'SameVariadicOperandSize' traits");
875   }
876 
877   // First emit a few "sink" getter methods upon which we layer all nicer named
878   // getter methods.
879   generateValueRangeStartAndEnd(opClass, "getODSOperandIndexAndLength",
880                                 numVariadicOperands, numNormalOperands,
881                                 rangeSizeCall, attrSizedOperands, sizeAttrInit,
882                                 const_cast<Operator &>(op).getOperands());
883 
884   auto *m = opClass.addMethodAndPrune(rangeType, "getODSOperands", "unsigned",
885                                       "index");
886   ERROR_IF_PRUNED(m, "getODSOperands", op);
887   auto &body = m->body();
888   body << formatv(valueRangeReturnCode, rangeBeginCall,
889                   "getODSOperandIndexAndLength(index)");
890 
891   // Then we emit nicer named getter methods by redirecting to the "sink" getter
892   // method.
893   for (int i = 0; i != numOperands; ++i) {
894     const auto &operand = op.getOperand(i);
895     if (operand.name.empty())
896       continue;
897     for (StringRef name : op.getGetterNames(operand.name)) {
898       if (operand.isOptional()) {
899         m = opClass.addMethodAndPrune("::mlir::Value", name);
900         ERROR_IF_PRUNED(m, name, op);
901         m->body() << "  auto operands = getODSOperands(" << i << ");\n"
902                   << "  return operands.empty() ? ::mlir::Value() : "
903                      "*operands.begin();";
904       } else if (operand.isVariadicOfVariadic()) {
905         std::string segmentAttr = op.getGetterName(
906             operand.constraint.getVariadicOfVariadicSegmentSizeAttr());
907         if (isAdaptor) {
908           m = opClass.addMethodAndPrune(
909               "::llvm::SmallVector<::mlir::ValueRange>", name);
910           ERROR_IF_PRUNED(m, name, op);
911           m->body() << llvm::formatv(variadicOfVariadicAdaptorCalcCode,
912                                      segmentAttr, i);
913           continue;
914         }
915 
916         m = opClass.addMethodAndPrune("::mlir::OperandRangeRange", name);
917         ERROR_IF_PRUNED(m, name, op);
918         m->body() << "  return getODSOperands(" << i << ").split("
919                   << segmentAttr << "Attr());";
920       } else if (operand.isVariadic()) {
921         m = opClass.addMethodAndPrune(rangeType, name);
922         ERROR_IF_PRUNED(m, name, op);
923         m->body() << "  return getODSOperands(" << i << ");";
924       } else {
925         m = opClass.addMethodAndPrune("::mlir::Value", name);
926         ERROR_IF_PRUNED(m, name, op);
927         m->body() << "  return *getODSOperands(" << i << ").begin();";
928       }
929     }
930   }
931 }
932 
933 void OpEmitter::genNamedOperandGetters() {
934   // Build the code snippet used for initializing the operand_segment_size)s
935   // array.
936   std::string attrSizeInitCode;
937   if (op.getTrait("::mlir::OpTrait::AttrSizedOperandSegments")) {
938     std::string attr = op.getGetterName("operand_segment_sizes") + "AttrName()";
939     attrSizeInitCode = formatv(opSegmentSizeAttrInitCode, attr).str();
940   }
941 
942   generateNamedOperandGetters(
943       op, opClass,
944       /*isAdaptor=*/false,
945       /*sizeAttrInit=*/attrSizeInitCode,
946       /*rangeType=*/"::mlir::Operation::operand_range",
947       /*rangeBeginCall=*/"getOperation()->operand_begin()",
948       /*rangeSizeCall=*/"getOperation()->getNumOperands()",
949       /*getOperandCallPattern=*/"getOperation()->getOperand({0})");
950 }
951 
952 void OpEmitter::genNamedOperandSetters() {
953   auto *attrSizedOperands =
954       op.getTrait("::mlir::OpTrait::AttrSizedOperandSegments");
955   for (int i = 0, e = op.getNumOperands(); i != e; ++i) {
956     const auto &operand = op.getOperand(i);
957     if (operand.name.empty())
958       continue;
959     for (StringRef name : op.getGetterNames(operand.name)) {
960       auto *m = opClass.addMethodAndPrune(
961           operand.isVariadicOfVariadic() ? "::mlir::MutableOperandRangeRange"
962                                          : "::mlir::MutableOperandRange",
963           (name + "Mutable").str());
964       ERROR_IF_PRUNED(m, name, op);
965       auto &body = m->body();
966       body << "  auto range = getODSOperandIndexAndLength(" << i << ");\n"
967            << "  auto mutableRange = "
968               "::mlir::MutableOperandRange(getOperation(), "
969               "range.first, range.second";
970       if (attrSizedOperands)
971         body << ", ::mlir::MutableOperandRange::OperandSegment(" << i
972              << "u, *getOperation()->getAttrDictionary().getNamed("
973              << op.getGetterName("operand_segment_sizes") << "AttrName()))";
974       body << ");\n";
975 
976       // If this operand is a nested variadic, we split the range into a
977       // MutableOperandRangeRange that provides a range over all of the
978       // sub-ranges.
979       if (operand.isVariadicOfVariadic()) {
980         //
981         body << "  return "
982                 "mutableRange.split(*(*this)->getAttrDictionary().getNamed("
983              << op.getGetterName(
984                     operand.constraint.getVariadicOfVariadicSegmentSizeAttr())
985              << "AttrName()));\n";
986       } else {
987         // Otherwise, we use the full range directly.
988         body << "  return mutableRange;\n";
989       }
990     }
991   }
992 }
993 
994 void OpEmitter::genNamedResultGetters() {
995   const int numResults = op.getNumResults();
996   const int numVariadicResults = op.getNumVariableLengthResults();
997   const int numNormalResults = numResults - numVariadicResults;
998 
999   // If we have more than one variadic results, we need more complicated logic
1000   // to calculate the value range for each result.
1001 
1002   const auto *sameVariadicSize =
1003       op.getTrait("::mlir::OpTrait::SameVariadicResultSize");
1004   const auto *attrSizedResults =
1005       op.getTrait("::mlir::OpTrait::AttrSizedResultSegments");
1006 
1007   if (numVariadicResults > 1 && !sameVariadicSize && !attrSizedResults) {
1008     PrintFatalError(op.getLoc(), "op has multiple variadic results but no "
1009                                  "specification over their sizes");
1010   }
1011 
1012   if (numVariadicResults < 2 && attrSizedResults) {
1013     PrintFatalError(op.getLoc(), "op must have at least two variadic results "
1014                                  "to use 'AttrSizedResultSegments' trait");
1015   }
1016 
1017   if (attrSizedResults && sameVariadicSize) {
1018     PrintFatalError(op.getLoc(),
1019                     "op cannot have both 'AttrSizedResultSegments' and "
1020                     "'SameVariadicResultSize' traits");
1021   }
1022 
1023   // Build the initializer string for the result segment size attribute.
1024   std::string attrSizeInitCode;
1025   if (attrSizedResults) {
1026     std::string attr = op.getGetterName("result_segment_sizes") + "AttrName()";
1027     attrSizeInitCode = formatv(opSegmentSizeAttrInitCode, attr).str();
1028   }
1029 
1030   generateValueRangeStartAndEnd(
1031       opClass, "getODSResultIndexAndLength", numVariadicResults,
1032       numNormalResults, "getOperation()->getNumResults()", attrSizedResults,
1033       attrSizeInitCode, op.getResults());
1034 
1035   auto *m = opClass.addMethodAndPrune("::mlir::Operation::result_range",
1036                                       "getODSResults", "unsigned", "index");
1037   ERROR_IF_PRUNED(m, "getODSResults", op);
1038   m->body() << formatv(valueRangeReturnCode, "getOperation()->result_begin()",
1039                        "getODSResultIndexAndLength(index)");
1040 
1041   for (int i = 0; i != numResults; ++i) {
1042     const auto &result = op.getResult(i);
1043     if (result.name.empty())
1044       continue;
1045     for (StringRef name : op.getGetterNames(result.name)) {
1046       if (result.isOptional()) {
1047         m = opClass.addMethodAndPrune("::mlir::Value", name);
1048         ERROR_IF_PRUNED(m, name, op);
1049         m->body()
1050             << "  auto results = getODSResults(" << i << ");\n"
1051             << "  return results.empty() ? ::mlir::Value() : *results.begin();";
1052       } else if (result.isVariadic()) {
1053         m = opClass.addMethodAndPrune("::mlir::Operation::result_range", name);
1054         ERROR_IF_PRUNED(m, name, op);
1055         m->body() << "  return getODSResults(" << i << ");";
1056       } else {
1057         m = opClass.addMethodAndPrune("::mlir::Value", name);
1058         ERROR_IF_PRUNED(m, name, op);
1059         m->body() << "  return *getODSResults(" << i << ").begin();";
1060       }
1061     }
1062   }
1063 }
1064 
1065 void OpEmitter::genNamedRegionGetters() {
1066   unsigned numRegions = op.getNumRegions();
1067   for (unsigned i = 0; i < numRegions; ++i) {
1068     const auto &region = op.getRegion(i);
1069     if (region.name.empty())
1070       continue;
1071 
1072     for (StringRef name : op.getGetterNames(region.name)) {
1073       // Generate the accessors for a variadic region.
1074       if (region.isVariadic()) {
1075         auto *m = opClass.addMethodAndPrune(
1076             "::mlir::MutableArrayRef<::mlir::Region>", name);
1077         ERROR_IF_PRUNED(m, name, op);
1078         m->body() << formatv("  return (*this)->getRegions().drop_front({0});",
1079                              i);
1080         continue;
1081       }
1082 
1083       auto *m = opClass.addMethodAndPrune("::mlir::Region &", name);
1084       ERROR_IF_PRUNED(m, name, op);
1085       m->body() << formatv("  return (*this)->getRegion({0});", i);
1086     }
1087   }
1088 }
1089 
1090 void OpEmitter::genNamedSuccessorGetters() {
1091   unsigned numSuccessors = op.getNumSuccessors();
1092   for (unsigned i = 0; i < numSuccessors; ++i) {
1093     const NamedSuccessor &successor = op.getSuccessor(i);
1094     if (successor.name.empty())
1095       continue;
1096 
1097     for (StringRef name : op.getGetterNames(successor.name)) {
1098       // Generate the accessors for a variadic successor list.
1099       if (successor.isVariadic()) {
1100         auto *m = opClass.addMethodAndPrune("::mlir::SuccessorRange", name);
1101         ERROR_IF_PRUNED(m, name, op);
1102         m->body() << formatv(
1103             "  return {std::next((*this)->successor_begin(), {0}), "
1104             "(*this)->successor_end()};",
1105             i);
1106         continue;
1107       }
1108 
1109       auto *m = opClass.addMethodAndPrune("::mlir::Block *", name);
1110       ERROR_IF_PRUNED(m, name, op);
1111       m->body() << formatv("  return (*this)->getSuccessor({0});", i);
1112     }
1113   }
1114 }
1115 
1116 static bool canGenerateUnwrappedBuilder(Operator &op) {
1117   // If this op does not have native attributes at all, return directly to avoid
1118   // redefining builders.
1119   if (op.getNumNativeAttributes() == 0)
1120     return false;
1121 
1122   bool canGenerate = false;
1123   // We are generating builders that take raw values for attributes. We need to
1124   // make sure the native attributes have a meaningful "unwrapped" value type
1125   // different from the wrapped mlir::Attribute type to avoid redefining
1126   // builders. This checks for the op has at least one such native attribute.
1127   for (int i = 0, e = op.getNumNativeAttributes(); i < e; ++i) {
1128     NamedAttribute &namedAttr = op.getAttribute(i);
1129     if (canUseUnwrappedRawValue(namedAttr.attr)) {
1130       canGenerate = true;
1131       break;
1132     }
1133   }
1134   return canGenerate;
1135 }
1136 
1137 static bool canInferType(Operator &op) {
1138   return op.getTrait("::mlir::InferTypeOpInterface::Trait") &&
1139          op.getNumRegions() == 0;
1140 }
1141 
1142 void OpEmitter::genSeparateArgParamBuilder() {
1143   SmallVector<AttrParamKind, 2> attrBuilderType;
1144   attrBuilderType.push_back(AttrParamKind::WrappedAttr);
1145   if (canGenerateUnwrappedBuilder(op))
1146     attrBuilderType.push_back(AttrParamKind::UnwrappedValue);
1147 
1148   // Emit with separate builders with or without unwrapped attributes and/or
1149   // inferring result type.
1150   auto emit = [&](AttrParamKind attrType, TypeParamKind paramKind,
1151                   bool inferType) {
1152     llvm::SmallVector<OpMethodParameter, 4> paramList;
1153     llvm::SmallVector<std::string, 4> resultNames;
1154     llvm::StringSet<> inferredAttributes;
1155     buildParamList(paramList, inferredAttributes, resultNames, paramKind,
1156                    attrType);
1157 
1158     auto *m = opClass.addMethodAndPrune("void", "build", OpMethod::MP_Static,
1159                                         std::move(paramList));
1160     // If the builder is redundant, skip generating the method.
1161     if (!m)
1162       return;
1163     auto &body = m->body();
1164     genCodeForAddingArgAndRegionForBuilder(body, inferredAttributes,
1165                                            /*isRawValueAttr=*/attrType ==
1166                                                AttrParamKind::UnwrappedValue);
1167 
1168     // Push all result types to the operation state
1169 
1170     if (inferType) {
1171       // Generate builder that infers type too.
1172       // TODO: Subsume this with general checking if type can be
1173       // inferred automatically.
1174       // TODO: Expand to handle regions.
1175       body << formatv(R"(
1176         ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes;
1177         if (::mlir::succeeded({0}::inferReturnTypes(odsBuilder.getContext(),
1178                       {1}.location, {1}.operands,
1179                       {1}.attributes.getDictionary({1}.getContext()),
1180                       /*regions=*/{{}, inferredReturnTypes)))
1181           {1}.addTypes(inferredReturnTypes);
1182         else
1183           ::llvm::report_fatal_error("Failed to infer result type(s).");)",
1184                       opClass.getClassName(), builderOpState);
1185       return;
1186     }
1187 
1188     switch (paramKind) {
1189     case TypeParamKind::None:
1190       return;
1191     case TypeParamKind::Separate:
1192       for (int i = 0, e = op.getNumResults(); i < e; ++i) {
1193         if (op.getResult(i).isOptional())
1194           body << "  if (" << resultNames[i] << ")\n  ";
1195         body << "  " << builderOpState << ".addTypes(" << resultNames[i]
1196              << ");\n";
1197       }
1198       return;
1199     case TypeParamKind::Collective: {
1200       int numResults = op.getNumResults();
1201       int numVariadicResults = op.getNumVariableLengthResults();
1202       int numNonVariadicResults = numResults - numVariadicResults;
1203       bool hasVariadicResult = numVariadicResults != 0;
1204 
1205       // Avoid emitting "resultTypes.size() >= 0u" which is always true.
1206       if (!(hasVariadicResult && numNonVariadicResults == 0))
1207         body << "  "
1208              << "assert(resultTypes.size() "
1209              << (hasVariadicResult ? ">=" : "==") << " "
1210              << numNonVariadicResults
1211              << "u && \"mismatched number of results\");\n";
1212       body << "  " << builderOpState << ".addTypes(resultTypes);\n";
1213     }
1214       return;
1215     }
1216     llvm_unreachable("unhandled TypeParamKind");
1217   };
1218 
1219   // Some of the build methods generated here may be ambiguous, but TableGen's
1220   // ambiguous function detection will elide those ones.
1221   for (auto attrType : attrBuilderType) {
1222     emit(attrType, TypeParamKind::Separate, /*inferType=*/false);
1223     if (canInferType(op))
1224       emit(attrType, TypeParamKind::None, /*inferType=*/true);
1225     emit(attrType, TypeParamKind::Collective, /*inferType=*/false);
1226   }
1227 }
1228 
1229 void OpEmitter::genUseOperandAsResultTypeCollectiveParamBuilder() {
1230   int numResults = op.getNumResults();
1231 
1232   // Signature
1233   llvm::SmallVector<OpMethodParameter, 4> paramList;
1234   paramList.emplace_back("::mlir::OpBuilder &", "odsBuilder");
1235   paramList.emplace_back("::mlir::OperationState &", builderOpState);
1236   paramList.emplace_back("::mlir::ValueRange", "operands");
1237   // Provide default value for `attributes` when its the last parameter
1238   StringRef attributesDefaultValue = op.getNumVariadicRegions() ? "" : "{}";
1239   paramList.emplace_back("::llvm::ArrayRef<::mlir::NamedAttribute>",
1240                          "attributes", attributesDefaultValue);
1241   if (op.getNumVariadicRegions())
1242     paramList.emplace_back("unsigned", "numRegions");
1243 
1244   auto *m = opClass.addMethodAndPrune("void", "build", OpMethod::MP_Static,
1245                                       std::move(paramList));
1246   // If the builder is redundant, skip generating the method
1247   if (!m)
1248     return;
1249   auto &body = m->body();
1250 
1251   // Operands
1252   body << "  " << builderOpState << ".addOperands(operands);\n";
1253 
1254   // Attributes
1255   body << "  " << builderOpState << ".addAttributes(attributes);\n";
1256 
1257   // Create the correct number of regions
1258   if (int numRegions = op.getNumRegions()) {
1259     body << llvm::formatv(
1260         "  for (unsigned i = 0; i != {0}; ++i)\n",
1261         (op.getNumVariadicRegions() ? "numRegions" : Twine(numRegions)));
1262     body << "    (void)" << builderOpState << ".addRegion();\n";
1263   }
1264 
1265   // Result types
1266   SmallVector<std::string, 2> resultTypes(numResults, "operands[0].getType()");
1267   body << "  " << builderOpState << ".addTypes({"
1268        << llvm::join(resultTypes, ", ") << "});\n\n";
1269 }
1270 
1271 void OpEmitter::genInferredTypeCollectiveParamBuilder() {
1272   // TODO: Expand to support regions.
1273   SmallVector<OpMethodParameter, 4> paramList;
1274   paramList.emplace_back("::mlir::OpBuilder &", "odsBuilder");
1275   paramList.emplace_back("::mlir::OperationState &", builderOpState);
1276   paramList.emplace_back("::mlir::ValueRange", "operands");
1277   paramList.emplace_back("::llvm::ArrayRef<::mlir::NamedAttribute>",
1278                          "attributes", "{}");
1279   auto *m = opClass.addMethodAndPrune("void", "build", OpMethod::MP_Static,
1280                                       std::move(paramList));
1281   // If the builder is redundant, skip generating the method
1282   if (!m)
1283     return;
1284   auto &body = m->body();
1285 
1286   int numResults = op.getNumResults();
1287   int numVariadicResults = op.getNumVariableLengthResults();
1288   int numNonVariadicResults = numResults - numVariadicResults;
1289 
1290   int numOperands = op.getNumOperands();
1291   int numVariadicOperands = op.getNumVariableLengthOperands();
1292   int numNonVariadicOperands = numOperands - numVariadicOperands;
1293 
1294   // Operands
1295   if (numVariadicOperands == 0 || numNonVariadicOperands != 0)
1296     body << "  assert(operands.size()"
1297          << (numVariadicOperands != 0 ? " >= " : " == ")
1298          << numNonVariadicOperands
1299          << "u && \"mismatched number of parameters\");\n";
1300   body << "  " << builderOpState << ".addOperands(operands);\n";
1301   body << "  " << builderOpState << ".addAttributes(attributes);\n";
1302 
1303   // Create the correct number of regions
1304   if (int numRegions = op.getNumRegions()) {
1305     body << llvm::formatv(
1306         "  for (unsigned i = 0; i != {0}; ++i)\n",
1307         (op.getNumVariadicRegions() ? "numRegions" : Twine(numRegions)));
1308     body << "    (void)" << builderOpState << ".addRegion();\n";
1309   }
1310 
1311   // Result types
1312   body << formatv(R"(
1313     ::mlir::SmallVector<::mlir::Type, 2> inferredReturnTypes;
1314     if (::mlir::succeeded({0}::inferReturnTypes(odsBuilder.getContext(),
1315                   {1}.location, operands,
1316                   {1}.attributes.getDictionary({1}.getContext()),
1317                   /*regions=*/{{}, inferredReturnTypes))) {{)",
1318                   opClass.getClassName(), builderOpState);
1319   if (numVariadicResults == 0 || numNonVariadicResults != 0)
1320     body << "  assert(inferredReturnTypes.size()"
1321          << (numVariadicResults != 0 ? " >= " : " == ") << numNonVariadicResults
1322          << "u && \"mismatched number of return types\");\n";
1323   body << "      " << builderOpState << ".addTypes(inferredReturnTypes);";
1324 
1325   body << formatv(R"(
1326     } else
1327       ::llvm::report_fatal_error("Failed to infer result type(s).");)",
1328                   opClass.getClassName(), builderOpState);
1329 }
1330 
1331 void OpEmitter::genUseOperandAsResultTypeSeparateParamBuilder() {
1332   llvm::SmallVector<OpMethodParameter, 4> paramList;
1333   llvm::SmallVector<std::string, 4> resultNames;
1334   llvm::StringSet<> inferredAttributes;
1335   buildParamList(paramList, inferredAttributes, resultNames,
1336                  TypeParamKind::None);
1337 
1338   auto *m = opClass.addMethodAndPrune("void", "build", OpMethod::MP_Static,
1339                                       std::move(paramList));
1340   // If the builder is redundant, skip generating the method
1341   if (!m)
1342     return;
1343   auto &body = m->body();
1344   genCodeForAddingArgAndRegionForBuilder(body, inferredAttributes);
1345 
1346   auto numResults = op.getNumResults();
1347   if (numResults == 0)
1348     return;
1349 
1350   // Push all result types to the operation state
1351   const char *index = op.getOperand(0).isVariadic() ? ".front()" : "";
1352   std::string resultType =
1353       formatv("{0}{1}.getType()", getArgumentName(op, 0), index).str();
1354   body << "  " << builderOpState << ".addTypes({" << resultType;
1355   for (int i = 1; i != numResults; ++i)
1356     body << ", " << resultType;
1357   body << "});\n\n";
1358 }
1359 
1360 void OpEmitter::genUseAttrAsResultTypeBuilder() {
1361   SmallVector<OpMethodParameter, 4> paramList;
1362   paramList.emplace_back("::mlir::OpBuilder &", "odsBuilder");
1363   paramList.emplace_back("::mlir::OperationState &", builderOpState);
1364   paramList.emplace_back("::mlir::ValueRange", "operands");
1365   paramList.emplace_back("::llvm::ArrayRef<::mlir::NamedAttribute>",
1366                          "attributes", "{}");
1367   auto *m = opClass.addMethodAndPrune("void", "build", OpMethod::MP_Static,
1368                                       std::move(paramList));
1369   // If the builder is redundant, skip generating the method
1370   if (!m)
1371     return;
1372 
1373   auto &body = m->body();
1374 
1375   // Push all result types to the operation state
1376   std::string resultType;
1377   const auto &namedAttr = op.getAttribute(0);
1378 
1379   body << "  auto attrName = " << op.getGetterName(namedAttr.name)
1380        << "AttrName(" << builderOpState
1381        << ".name);\n"
1382           "  for (auto attr : attributes) {\n"
1383           "    if (attr.first != attrName) continue;\n";
1384   if (namedAttr.attr.isTypeAttr()) {
1385     resultType = "attr.second.cast<::mlir::TypeAttr>().getValue()";
1386   } else {
1387     resultType = "attr.second.getType()";
1388   }
1389 
1390   // Operands
1391   body << "  " << builderOpState << ".addOperands(operands);\n";
1392 
1393   // Attributes
1394   body << "  " << builderOpState << ".addAttributes(attributes);\n";
1395 
1396   // Result types
1397   SmallVector<std::string, 2> resultTypes(op.getNumResults(), resultType);
1398   body << "    " << builderOpState << ".addTypes({"
1399        << llvm::join(resultTypes, ", ") << "});\n";
1400   body << "  }\n";
1401 }
1402 
1403 /// Returns a signature of the builder. Updates the context `fctx` to enable
1404 /// replacement of $_builder and $_state in the body.
1405 static std::string getBuilderSignature(const Builder &builder) {
1406   ArrayRef<Builder::Parameter> params(builder.getParameters());
1407 
1408   // Inject builder and state arguments.
1409   llvm::SmallVector<std::string, 8> arguments;
1410   arguments.reserve(params.size() + 2);
1411   arguments.push_back(
1412       llvm::formatv("::mlir::OpBuilder &{0}", odsBuilder).str());
1413   arguments.push_back(
1414       llvm::formatv("::mlir::OperationState &{0}", builderOpState).str());
1415 
1416   for (unsigned i = 0, e = params.size(); i < e; ++i) {
1417     // If no name is provided, generate one.
1418     Optional<StringRef> paramName = params[i].getName();
1419     std::string name =
1420         paramName ? paramName->str() : "odsArg" + std::to_string(i);
1421 
1422     std::string defaultValue;
1423     if (Optional<StringRef> defaultParamValue = params[i].getDefaultValue())
1424       defaultValue = llvm::formatv(" = {0}", *defaultParamValue).str();
1425     arguments.push_back(
1426         llvm::formatv("{0} {1}{2}", params[i].getCppType(), name, defaultValue)
1427             .str());
1428   }
1429 
1430   return llvm::join(arguments, ", ");
1431 }
1432 
1433 void OpEmitter::genBuilder() {
1434   // Handle custom builders if provided.
1435   for (const Builder &builder : op.getBuilders()) {
1436     std::string paramStr = getBuilderSignature(builder);
1437 
1438     Optional<StringRef> body = builder.getBody();
1439     OpMethod::Property properties =
1440         body ? OpMethod::MP_Static : OpMethod::MP_StaticDeclaration;
1441     auto *method =
1442         opClass.addMethodAndPrune("void", "build", properties, paramStr);
1443     if (body)
1444       ERROR_IF_PRUNED(method, "build", op);
1445 
1446     FmtContext fctx;
1447     fctx.withBuilder(odsBuilder);
1448     fctx.addSubst("_state", builderOpState);
1449     if (body)
1450       method->body() << tgfmt(*body, &fctx);
1451   }
1452 
1453   // Generate default builders that requires all result type, operands, and
1454   // attributes as parameters.
1455   if (op.skipDefaultBuilders())
1456     return;
1457 
1458   // We generate three classes of builders here:
1459   // 1. one having a stand-alone parameter for each operand / attribute, and
1460   genSeparateArgParamBuilder();
1461   // 2. one having an aggregated parameter for all result types / operands /
1462   //    attributes, and
1463   genCollectiveParamBuilder();
1464   // 3. one having a stand-alone parameter for each operand and attribute,
1465   //    use the first operand or attribute's type as all result types
1466   //    to facilitate different call patterns.
1467   if (op.getNumVariableLengthResults() == 0) {
1468     if (op.getTrait("::mlir::OpTrait::SameOperandsAndResultType")) {
1469       genUseOperandAsResultTypeSeparateParamBuilder();
1470       genUseOperandAsResultTypeCollectiveParamBuilder();
1471     }
1472     if (op.getTrait("::mlir::OpTrait::FirstAttrDerivedResultType"))
1473       genUseAttrAsResultTypeBuilder();
1474   }
1475 }
1476 
1477 void OpEmitter::genCollectiveParamBuilder() {
1478   int numResults = op.getNumResults();
1479   int numVariadicResults = op.getNumVariableLengthResults();
1480   int numNonVariadicResults = numResults - numVariadicResults;
1481 
1482   int numOperands = op.getNumOperands();
1483   int numVariadicOperands = op.getNumVariableLengthOperands();
1484   int numNonVariadicOperands = numOperands - numVariadicOperands;
1485 
1486   SmallVector<OpMethodParameter, 4> paramList;
1487   paramList.emplace_back("::mlir::OpBuilder &", "");
1488   paramList.emplace_back("::mlir::OperationState &", builderOpState);
1489   paramList.emplace_back("::mlir::TypeRange", "resultTypes");
1490   paramList.emplace_back("::mlir::ValueRange", "operands");
1491   // Provide default value for `attributes` when its the last parameter
1492   StringRef attributesDefaultValue = op.getNumVariadicRegions() ? "" : "{}";
1493   paramList.emplace_back("::llvm::ArrayRef<::mlir::NamedAttribute>",
1494                          "attributes", attributesDefaultValue);
1495   if (op.getNumVariadicRegions())
1496     paramList.emplace_back("unsigned", "numRegions");
1497 
1498   auto *m = opClass.addMethodAndPrune("void", "build", OpMethod::MP_Static,
1499                                       std::move(paramList));
1500   // If the builder is redundant, skip generating the method
1501   if (!m)
1502     return;
1503   auto &body = m->body();
1504 
1505   // Operands
1506   if (numVariadicOperands == 0 || numNonVariadicOperands != 0)
1507     body << "  assert(operands.size()"
1508          << (numVariadicOperands != 0 ? " >= " : " == ")
1509          << numNonVariadicOperands
1510          << "u && \"mismatched number of parameters\");\n";
1511   body << "  " << builderOpState << ".addOperands(operands);\n";
1512 
1513   // Attributes
1514   body << "  " << builderOpState << ".addAttributes(attributes);\n";
1515 
1516   // Create the correct number of regions
1517   if (int numRegions = op.getNumRegions()) {
1518     body << llvm::formatv(
1519         "  for (unsigned i = 0; i != {0}; ++i)\n",
1520         (op.getNumVariadicRegions() ? "numRegions" : Twine(numRegions)));
1521     body << "    (void)" << builderOpState << ".addRegion();\n";
1522   }
1523 
1524   // Result types
1525   if (numVariadicResults == 0 || numNonVariadicResults != 0)
1526     body << "  assert(resultTypes.size()"
1527          << (numVariadicResults != 0 ? " >= " : " == ") << numNonVariadicResults
1528          << "u && \"mismatched number of return types\");\n";
1529   body << "  " << builderOpState << ".addTypes(resultTypes);\n";
1530 
1531   // Generate builder that infers type too.
1532   // TODO: Expand to handle regions and successors.
1533   if (canInferType(op) && op.getNumSuccessors() == 0)
1534     genInferredTypeCollectiveParamBuilder();
1535 }
1536 
1537 void OpEmitter::buildParamList(SmallVectorImpl<OpMethodParameter> &paramList,
1538                                llvm::StringSet<> &inferredAttributes,
1539                                SmallVectorImpl<std::string> &resultTypeNames,
1540                                TypeParamKind typeParamKind,
1541                                AttrParamKind attrParamKind) {
1542   resultTypeNames.clear();
1543   auto numResults = op.getNumResults();
1544   resultTypeNames.reserve(numResults);
1545 
1546   paramList.emplace_back("::mlir::OpBuilder &", "odsBuilder");
1547   paramList.emplace_back("::mlir::OperationState &", builderOpState);
1548 
1549   switch (typeParamKind) {
1550   case TypeParamKind::None:
1551     break;
1552   case TypeParamKind::Separate: {
1553     // Add parameters for all return types
1554     for (int i = 0; i < numResults; ++i) {
1555       const auto &result = op.getResult(i);
1556       std::string resultName = std::string(result.name);
1557       if (resultName.empty())
1558         resultName = std::string(formatv("resultType{0}", i));
1559 
1560       StringRef type =
1561           result.isVariadic() ? "::mlir::TypeRange" : "::mlir::Type";
1562       OpMethodParameter::Property properties = OpMethodParameter::PP_None;
1563       if (result.isOptional())
1564         properties = OpMethodParameter::PP_Optional;
1565 
1566       paramList.emplace_back(type, resultName, properties);
1567       resultTypeNames.emplace_back(std::move(resultName));
1568     }
1569   } break;
1570   case TypeParamKind::Collective: {
1571     paramList.emplace_back("::mlir::TypeRange", "resultTypes");
1572     resultTypeNames.push_back("resultTypes");
1573   } break;
1574   }
1575 
1576   // Add parameters for all arguments (operands and attributes).
1577   int defaultValuedAttrStartIndex = op.getNumArgs();
1578   // Successors and variadic regions go at the end of the parameter list, so no
1579   // default arguments are possible.
1580   bool hasTrailingParams = op.getNumSuccessors() || op.getNumVariadicRegions();
1581   if (attrParamKind == AttrParamKind::UnwrappedValue && !hasTrailingParams) {
1582     // Calculate the start index from which we can attach default values in the
1583     // builder declaration.
1584     for (int i = op.getNumArgs() - 1; i >= 0; --i) {
1585       auto *namedAttr = op.getArg(i).dyn_cast<tblgen::NamedAttribute *>();
1586       if (!namedAttr || !namedAttr->attr.hasDefaultValue())
1587         break;
1588 
1589       if (!canUseUnwrappedRawValue(namedAttr->attr))
1590         break;
1591 
1592       // Creating an APInt requires us to provide bitwidth, value, and
1593       // signedness, which is complicated compared to others. Similarly
1594       // for APFloat.
1595       // TODO: Adjust the 'returnType' field of such attributes
1596       // to support them.
1597       StringRef retType = namedAttr->attr.getReturnType();
1598       if (retType == "::llvm::APInt" || retType == "::llvm::APFloat")
1599         break;
1600 
1601       defaultValuedAttrStartIndex = i;
1602     }
1603   }
1604 
1605   /// Collect any inferred attributes.
1606   for (const NamedTypeConstraint &operand : op.getOperands()) {
1607     if (operand.isVariadicOfVariadic()) {
1608       inferredAttributes.insert(
1609           operand.constraint.getVariadicOfVariadicSegmentSizeAttr());
1610     }
1611   }
1612 
1613   for (int i = 0, e = op.getNumArgs(), numOperands = 0; i < e; ++i) {
1614     Argument arg = op.getArg(i);
1615     if (const auto *operand = arg.dyn_cast<NamedTypeConstraint *>()) {
1616       StringRef type;
1617       if (operand->isVariadicOfVariadic())
1618         type = "::llvm::ArrayRef<::mlir::ValueRange>";
1619       else if (operand->isVariadic())
1620         type = "::mlir::ValueRange";
1621       else
1622         type = "::mlir::Value";
1623 
1624       OpMethodParameter::Property properties = OpMethodParameter::PP_None;
1625       if (operand->isOptional())
1626         properties = OpMethodParameter::PP_Optional;
1627       paramList.emplace_back(type, getArgumentName(op, numOperands++),
1628                              properties);
1629       continue;
1630     }
1631     const NamedAttribute &namedAttr = *arg.get<NamedAttribute *>();
1632     const Attribute &attr = namedAttr.attr;
1633 
1634     // inferred attributes don't need to be added to the param list.
1635     if (inferredAttributes.contains(namedAttr.name))
1636       continue;
1637 
1638     OpMethodParameter::Property properties = OpMethodParameter::PP_None;
1639     if (attr.isOptional())
1640       properties = OpMethodParameter::PP_Optional;
1641 
1642     StringRef type;
1643     switch (attrParamKind) {
1644     case AttrParamKind::WrappedAttr:
1645       type = attr.getStorageType();
1646       break;
1647     case AttrParamKind::UnwrappedValue:
1648       if (canUseUnwrappedRawValue(attr))
1649         type = attr.getReturnType();
1650       else
1651         type = attr.getStorageType();
1652       break;
1653     }
1654 
1655     // Attach default value if requested and possible.
1656     std::string defaultValue;
1657     if (attrParamKind == AttrParamKind::UnwrappedValue &&
1658         i >= defaultValuedAttrStartIndex) {
1659       defaultValue += attr.getDefaultValue();
1660     }
1661     paramList.emplace_back(type, namedAttr.name, defaultValue, properties);
1662   }
1663 
1664   /// Insert parameters for each successor.
1665   for (const NamedSuccessor &succ : op.getSuccessors()) {
1666     StringRef type =
1667         succ.isVariadic() ? "::mlir::BlockRange" : "::mlir::Block *";
1668     paramList.emplace_back(type, succ.name);
1669   }
1670 
1671   /// Insert parameters for variadic regions.
1672   for (const NamedRegion &region : op.getRegions())
1673     if (region.isVariadic())
1674       paramList.emplace_back("unsigned",
1675                              llvm::formatv("{0}Count", region.name).str());
1676 }
1677 
1678 void OpEmitter::genCodeForAddingArgAndRegionForBuilder(
1679     OpMethodBody &body, llvm::StringSet<> &inferredAttributes,
1680     bool isRawValueAttr) {
1681   // Push all operands to the result.
1682   for (int i = 0, e = op.getNumOperands(); i < e; ++i) {
1683     std::string argName = getArgumentName(op, i);
1684     NamedTypeConstraint &operand = op.getOperand(i);
1685     if (operand.constraint.isVariadicOfVariadic()) {
1686       body << "  for (::mlir::ValueRange range : " << argName << ")\n   "
1687            << builderOpState << ".addOperands(range);\n";
1688 
1689       // Add the segment attribute.
1690       body << "  {\n"
1691            << "    SmallVector<int32_t> rangeSegments;\n"
1692            << "    for (::mlir::ValueRange range : " << argName << ")\n"
1693            << "      rangeSegments.push_back(range.size());\n"
1694            << "    " << builderOpState << ".addAttribute("
1695            << op.getGetterName(
1696                   operand.constraint.getVariadicOfVariadicSegmentSizeAttr())
1697            << "AttrName(" << builderOpState << ".name), " << odsBuilder
1698            << ".getI32TensorAttr(rangeSegments));"
1699            << "  }\n";
1700       continue;
1701     }
1702 
1703     if (operand.isOptional())
1704       body << "  if (" << argName << ")\n  ";
1705     body << "  " << builderOpState << ".addOperands(" << argName << ");\n";
1706   }
1707 
1708   // If the operation has the operand segment size attribute, add it here.
1709   if (op.getTrait("::mlir::OpTrait::AttrSizedOperandSegments")) {
1710     std::string sizes = op.getGetterName("operand_segment_sizes");
1711     body << "  " << builderOpState << ".addAttribute(" << sizes << "AttrName("
1712          << builderOpState << ".name), "
1713          << "odsBuilder.getI32VectorAttr({";
1714     interleaveComma(llvm::seq<int>(0, op.getNumOperands()), body, [&](int i) {
1715       const NamedTypeConstraint &operand = op.getOperand(i);
1716       if (!operand.isVariableLength()) {
1717         body << "1";
1718         return;
1719       }
1720 
1721       std::string operandName = getArgumentName(op, i);
1722       if (operand.isOptional()) {
1723         body << "(" << operandName << " ? 1 : 0)";
1724       } else if (operand.isVariadicOfVariadic()) {
1725         body << llvm::formatv(
1726             "static_cast<int32_t>(std::accumulate({0}.begin(), {0}.end(), 0, "
1727             "[](int32_t curSum, ::mlir::ValueRange range) {{ return curSum + "
1728             "range.size(); }))",
1729             operandName);
1730       } else {
1731         body << "static_cast<int32_t>(" << getArgumentName(op, i) << ".size())";
1732       }
1733     });
1734     body << "}));\n";
1735   }
1736 
1737   // Push all attributes to the result.
1738   for (const auto &namedAttr : op.getAttributes()) {
1739     auto &attr = namedAttr.attr;
1740     if (attr.isDerivedAttr() || inferredAttributes.contains(namedAttr.name))
1741       continue;
1742 
1743     bool emitNotNullCheck = attr.isOptional();
1744     if (emitNotNullCheck)
1745       body << formatv("  if ({0}) ", namedAttr.name) << "{\n";
1746 
1747     if (isRawValueAttr && canUseUnwrappedRawValue(attr)) {
1748       // If this is a raw value, then we need to wrap it in an Attribute
1749       // instance.
1750       FmtContext fctx;
1751       fctx.withBuilder("odsBuilder");
1752 
1753       std::string builderTemplate = std::string(attr.getConstBuilderTemplate());
1754 
1755       // For StringAttr, its constant builder call will wrap the input in
1756       // quotes, which is correct for normal string literals, but incorrect
1757       // here given we use function arguments. So we need to strip the
1758       // wrapping quotes.
1759       if (StringRef(builderTemplate).contains("\"$0\""))
1760         builderTemplate = replaceAllSubstrs(builderTemplate, "\"$0\"", "$0");
1761 
1762       std::string value =
1763           std::string(tgfmt(builderTemplate, &fctx, namedAttr.name));
1764       body << formatv("  {0}.addAttribute({1}AttrName({0}.name), {2});\n",
1765                       builderOpState, op.getGetterName(namedAttr.name), value);
1766     } else {
1767       body << formatv("  {0}.addAttribute({1}AttrName({0}.name), {2});\n",
1768                       builderOpState, op.getGetterName(namedAttr.name),
1769                       namedAttr.name);
1770     }
1771     if (emitNotNullCheck)
1772       body << "  }\n";
1773   }
1774 
1775   // Create the correct number of regions.
1776   for (const NamedRegion &region : op.getRegions()) {
1777     if (region.isVariadic())
1778       body << formatv("  for (unsigned i = 0; i < {0}Count; ++i)\n  ",
1779                       region.name);
1780 
1781     body << "  (void)" << builderOpState << ".addRegion();\n";
1782   }
1783 
1784   // Push all successors to the result.
1785   for (const NamedSuccessor &namedSuccessor : op.getSuccessors()) {
1786     body << formatv("  {0}.addSuccessors({1});\n", builderOpState,
1787                     namedSuccessor.name);
1788   }
1789 }
1790 
1791 void OpEmitter::genCanonicalizerDecls() {
1792   bool hasCanonicalizeMethod = def.getValueAsBit("hasCanonicalizeMethod");
1793   if (hasCanonicalizeMethod) {
1794     // static LogicResult FooOp::
1795     // canonicalize(FooOp op, PatternRewriter &rewriter);
1796     SmallVector<OpMethodParameter, 2> paramList;
1797     paramList.emplace_back(op.getCppClassName(), "op");
1798     paramList.emplace_back("::mlir::PatternRewriter &", "rewriter");
1799     auto *m = opClass.addMethodAndPrune("::mlir::LogicalResult", "canonicalize",
1800                                         OpMethod::MP_StaticDeclaration,
1801                                         std::move(paramList));
1802     ERROR_IF_PRUNED(m, "canonicalize", op);
1803   }
1804 
1805   // We get a prototype for 'getCanonicalizationPatterns' if requested directly
1806   // or if using a 'canonicalize' method.
1807   bool hasCanonicalizer = def.getValueAsBit("hasCanonicalizer");
1808   if (!hasCanonicalizeMethod && !hasCanonicalizer)
1809     return;
1810 
1811   // We get a body for 'getCanonicalizationPatterns' when using a 'canonicalize'
1812   // method, but not implementing 'getCanonicalizationPatterns' manually.
1813   bool hasBody = hasCanonicalizeMethod && !hasCanonicalizer;
1814 
1815   // Add a signature for getCanonicalizationPatterns if implemented by the
1816   // dialect or if synthesized to call 'canonicalize'.
1817   SmallVector<OpMethodParameter, 2> paramList;
1818   paramList.emplace_back("::mlir::RewritePatternSet &", "results");
1819   paramList.emplace_back("::mlir::MLIRContext *", "context");
1820   auto kind = hasBody ? OpMethod::MP_Static : OpMethod::MP_StaticDeclaration;
1821   auto *method = opClass.addMethodAndPrune(
1822       "void", "getCanonicalizationPatterns", kind, std::move(paramList));
1823 
1824   // If synthesizing the method, fill it it.
1825   if (hasBody) {
1826     ERROR_IF_PRUNED(method, "getCanonicalizationPatterns", op);
1827     method->body() << "  results.add(canonicalize);\n";
1828   }
1829 }
1830 
1831 void OpEmitter::genFolderDecls() {
1832   bool hasSingleResult =
1833       op.getNumResults() == 1 && op.getNumVariableLengthResults() == 0;
1834 
1835   if (def.getValueAsBit("hasFolder")) {
1836     if (hasSingleResult) {
1837       auto *m = opClass.addMethodAndPrune(
1838           "::mlir::OpFoldResult", "fold", OpMethod::MP_Declaration,
1839           "::llvm::ArrayRef<::mlir::Attribute>", "operands");
1840       ERROR_IF_PRUNED(m, "operands", op);
1841     } else {
1842       SmallVector<OpMethodParameter, 2> paramList;
1843       paramList.emplace_back("::llvm::ArrayRef<::mlir::Attribute>", "operands");
1844       paramList.emplace_back("::llvm::SmallVectorImpl<::mlir::OpFoldResult> &",
1845                              "results");
1846       auto *m = opClass.addMethodAndPrune("::mlir::LogicalResult", "fold",
1847                                           OpMethod::MP_Declaration,
1848                                           std::move(paramList));
1849       ERROR_IF_PRUNED(m, "fold", op);
1850     }
1851   }
1852 }
1853 
1854 void OpEmitter::genOpInterfaceMethods(const tblgen::InterfaceTrait *opTrait) {
1855   Interface interface = opTrait->getInterface();
1856 
1857   // Get the set of methods that should always be declared.
1858   auto alwaysDeclaredMethodsVec = opTrait->getAlwaysDeclaredMethods();
1859   llvm::StringSet<> alwaysDeclaredMethods;
1860   alwaysDeclaredMethods.insert(alwaysDeclaredMethodsVec.begin(),
1861                                alwaysDeclaredMethodsVec.end());
1862 
1863   for (const InterfaceMethod &method : interface.getMethods()) {
1864     // Don't declare if the method has a body.
1865     if (method.getBody())
1866       continue;
1867     // Don't declare if the method has a default implementation and the op
1868     // didn't request that it always be declared.
1869     if (method.getDefaultImplementation() &&
1870         !alwaysDeclaredMethods.count(method.getName()))
1871       continue;
1872     // Interface methods are allowed to overlap with existing methods, so don't
1873     // check if pruned.
1874     (void)genOpInterfaceMethod(method);
1875   }
1876 }
1877 
1878 OpMethod *OpEmitter::genOpInterfaceMethod(const InterfaceMethod &method,
1879                                           bool declaration) {
1880   SmallVector<OpMethodParameter, 4> paramList;
1881   for (const InterfaceMethod::Argument &arg : method.getArguments())
1882     paramList.emplace_back(arg.type, arg.name);
1883 
1884   auto properties = method.isStatic() ? OpMethod::MP_Static : OpMethod::MP_None;
1885   if (declaration)
1886     properties =
1887         static_cast<OpMethod::Property>(properties | OpMethod::MP_Declaration);
1888   return opClass.addMethodAndPrune(method.getReturnType(), method.getName(),
1889                                    properties, std::move(paramList));
1890 }
1891 
1892 void OpEmitter::genOpInterfaceMethods() {
1893   for (const auto &trait : op.getTraits()) {
1894     if (const auto *opTrait = dyn_cast<tblgen::InterfaceTrait>(&trait))
1895       if (opTrait->shouldDeclareMethods())
1896         genOpInterfaceMethods(opTrait);
1897   }
1898 }
1899 
1900 void OpEmitter::genSideEffectInterfaceMethods() {
1901   enum EffectKind { Operand, Result, Symbol, Static };
1902   struct EffectLocation {
1903     /// The effect applied.
1904     SideEffect effect;
1905 
1906     /// The index if the kind is not static.
1907     unsigned index : 30;
1908 
1909     /// The kind of the location.
1910     unsigned kind : 2;
1911   };
1912 
1913   StringMap<SmallVector<EffectLocation, 1>> interfaceEffects;
1914   auto resolveDecorators = [&](Operator::var_decorator_range decorators,
1915                                unsigned index, unsigned kind) {
1916     for (auto decorator : decorators)
1917       if (SideEffect *effect = dyn_cast<SideEffect>(&decorator)) {
1918         opClass.addTrait(effect->getInterfaceTrait());
1919         interfaceEffects[effect->getBaseEffectName()].push_back(
1920             EffectLocation{*effect, index, kind});
1921       }
1922   };
1923 
1924   // Collect effects that were specified via:
1925   /// Traits.
1926   for (const auto &trait : op.getTraits()) {
1927     const auto *opTrait = dyn_cast<tblgen::SideEffectTrait>(&trait);
1928     if (!opTrait)
1929       continue;
1930     auto &effects = interfaceEffects[opTrait->getBaseEffectName()];
1931     for (auto decorator : opTrait->getEffects())
1932       effects.push_back(EffectLocation{cast<SideEffect>(decorator),
1933                                        /*index=*/0, EffectKind::Static});
1934   }
1935   /// Attributes and Operands.
1936   for (unsigned i = 0, operandIt = 0, e = op.getNumArgs(); i != e; ++i) {
1937     Argument arg = op.getArg(i);
1938     if (arg.is<NamedTypeConstraint *>()) {
1939       resolveDecorators(op.getArgDecorators(i), operandIt, EffectKind::Operand);
1940       ++operandIt;
1941       continue;
1942     }
1943     const NamedAttribute *attr = arg.get<NamedAttribute *>();
1944     if (attr->attr.getBaseAttr().isSymbolRefAttr())
1945       resolveDecorators(op.getArgDecorators(i), i, EffectKind::Symbol);
1946   }
1947   /// Results.
1948   for (unsigned i = 0, e = op.getNumResults(); i != e; ++i)
1949     resolveDecorators(op.getResultDecorators(i), i, EffectKind::Result);
1950 
1951   // The code used to add an effect instance.
1952   // {0}: The effect class.
1953   // {1}: Optional value or symbol reference.
1954   // {1}: The resource class.
1955   const char *addEffectCode =
1956       "  effects.emplace_back({0}::get(), {1}{2}::get());\n";
1957 
1958   for (auto &it : interfaceEffects) {
1959     // Generate the 'getEffects' method.
1960     std::string type = llvm::formatv("::mlir::SmallVectorImpl<::mlir::"
1961                                      "SideEffects::EffectInstance<{0}>> &",
1962                                      it.first())
1963                            .str();
1964     auto *getEffects =
1965         opClass.addMethodAndPrune("void", "getEffects", type, "effects");
1966     ERROR_IF_PRUNED(getEffects, "getEffects", op);
1967     auto &body = getEffects->body();
1968 
1969     // Add effect instances for each of the locations marked on the operation.
1970     for (auto &location : it.second) {
1971       StringRef effect = location.effect.getName();
1972       StringRef resource = location.effect.getResource();
1973       if (location.kind == EffectKind::Static) {
1974         // A static instance has no attached value.
1975         body << llvm::formatv(addEffectCode, effect, "", resource).str();
1976       } else if (location.kind == EffectKind::Symbol) {
1977         // A symbol reference requires adding the proper attribute.
1978         const auto *attr = op.getArg(location.index).get<NamedAttribute *>();
1979         if (attr->attr.isOptional()) {
1980           body << "  if (auto symbolRef = " << attr->name << "Attr())\n  "
1981                << llvm::formatv(addEffectCode, effect, "symbolRef, ", resource)
1982                       .str();
1983         } else {
1984           body << llvm::formatv(addEffectCode, effect, attr->name + "(), ",
1985                                 resource)
1986                       .str();
1987         }
1988       } else {
1989         // Otherwise this is an operand/result, so we need to attach the Value.
1990         body << "  for (::mlir::Value value : getODS"
1991              << (location.kind == EffectKind::Operand ? "Operands" : "Results")
1992              << "(" << location.index << "))\n  "
1993              << llvm::formatv(addEffectCode, effect, "value, ", resource).str();
1994       }
1995     }
1996   }
1997 }
1998 
1999 void OpEmitter::genTypeInterfaceMethods() {
2000   if (!op.allResultTypesKnown())
2001     return;
2002   // Generate 'inferReturnTypes' method declaration using the interface method
2003   // declared in 'InferTypeOpInterface' op interface.
2004   const auto *trait = dyn_cast<InterfaceTrait>(
2005       op.getTrait("::mlir::InferTypeOpInterface::Trait"));
2006   Interface interface = trait->getInterface();
2007   OpMethod *method = [&]() -> OpMethod * {
2008     for (const InterfaceMethod &interfaceMethod : interface.getMethods()) {
2009       if (interfaceMethod.getName() == "inferReturnTypes") {
2010         return genOpInterfaceMethod(interfaceMethod, /*declaration=*/false);
2011       }
2012     }
2013     assert(0 && "unable to find inferReturnTypes interface method");
2014     return nullptr;
2015   }();
2016   ERROR_IF_PRUNED(method, "inferReturnTypes", op);
2017   auto &body = method->body();
2018   body << "  inferredReturnTypes.resize(" << op.getNumResults() << ");\n";
2019 
2020   FmtContext fctx;
2021   fctx.withBuilder("odsBuilder");
2022   body << "  ::mlir::Builder odsBuilder(context);\n";
2023 
2024   auto emitType =
2025       [&](const tblgen::Operator::ArgOrType &type) -> OpMethodBody & {
2026     if (type.isArg()) {
2027       auto argIndex = type.getArg();
2028       assert(!op.getArg(argIndex).is<NamedAttribute *>());
2029       auto arg = op.getArgToOperandOrAttribute(argIndex);
2030       if (arg.kind() == Operator::OperandOrAttribute::Kind::Operand)
2031         return body << "operands[" << arg.operandOrAttributeIndex()
2032                     << "].getType()";
2033       return body << "attributes[" << arg.operandOrAttributeIndex()
2034                   << "].getType()";
2035     } else {
2036       return body << tgfmt(*type.getType().getBuilderCall(), &fctx);
2037     }
2038   };
2039 
2040   for (int i = 0, e = op.getNumResults(); i != e; ++i) {
2041     body << "  inferredReturnTypes[" << i << "] = ";
2042     auto types = op.getSameTypeAsResult(i);
2043     emitType(types[0]) << ";\n";
2044     if (types.size() == 1)
2045       continue;
2046     // TODO: We could verify equality here, but skipping that for verification.
2047   }
2048   body << "  return ::mlir::success();";
2049 }
2050 
2051 void OpEmitter::genParser() {
2052   if (!hasStringAttribute(def, "parser") ||
2053       hasStringAttribute(def, "assemblyFormat"))
2054     return;
2055 
2056   SmallVector<OpMethodParameter, 2> paramList;
2057   paramList.emplace_back("::mlir::OpAsmParser &", "parser");
2058   paramList.emplace_back("::mlir::OperationState &", "result");
2059   auto *method =
2060       opClass.addMethodAndPrune("::mlir::ParseResult", "parse",
2061                                 OpMethod::MP_Static, std::move(paramList));
2062   ERROR_IF_PRUNED(method, "parse", op);
2063 
2064   FmtContext fctx;
2065   fctx.addSubst("cppClass", opClass.getClassName());
2066   auto parser = def.getValueAsString("parser").ltrim().rtrim(" \t\v\f\r");
2067   method->body() << "  " << tgfmt(parser, &fctx);
2068 }
2069 
2070 void OpEmitter::genPrinter() {
2071   if (hasStringAttribute(def, "assemblyFormat"))
2072     return;
2073 
2074   auto valueInit = def.getValueInit("printer");
2075   StringInit *stringInit = dyn_cast<StringInit>(valueInit);
2076   if (!stringInit)
2077     return;
2078 
2079   auto *method =
2080       opClass.addMethodAndPrune("void", "print", "::mlir::OpAsmPrinter &", "p");
2081   ERROR_IF_PRUNED(method, "print", op);
2082   FmtContext fctx;
2083   fctx.addSubst("cppClass", opClass.getClassName());
2084   auto printer = stringInit->getValue().ltrim().rtrim(" \t\v\f\r");
2085   method->body() << "  " << tgfmt(printer, &fctx);
2086 }
2087 
2088 void OpEmitter::genVerifier() {
2089   auto *method = opClass.addMethodAndPrune("::mlir::LogicalResult", "verify");
2090   ERROR_IF_PRUNED(method, "verify", op);
2091   auto &body = method->body();
2092   body << "  if (::mlir::failed(" << op.getAdaptorName()
2093        << "(*this).verify((*this)->getLoc()))) "
2094        << "return ::mlir::failure();\n";
2095 
2096   auto *valueInit = def.getValueInit("verifier");
2097   StringInit *stringInit = dyn_cast<StringInit>(valueInit);
2098   bool hasCustomVerify = stringInit && !stringInit->getValue().empty();
2099   populateSubstitutions(op, "(*this)->getAttr", "this->getODSOperands",
2100                         "this->getODSResults", verifyCtx);
2101 
2102   genAttributeVerifier(op, "(*this)->getAttr", "emitOpError(",
2103                        /*emitVerificationRequiringOp=*/true, verifyCtx, body);
2104   genOperandResultVerifier(body, op.getOperands(), "operand");
2105   genOperandResultVerifier(body, op.getResults(), "result");
2106 
2107   for (auto &trait : op.getTraits()) {
2108     if (auto *t = dyn_cast<tblgen::PredTrait>(&trait)) {
2109       body << tgfmt("  if (!($0))\n    "
2110                     "return emitOpError(\"failed to verify that $1\");\n",
2111                     &verifyCtx, tgfmt(t->getPredTemplate(), &verifyCtx),
2112                     t->getSummary());
2113     }
2114   }
2115 
2116   genRegionVerifier(body);
2117   genSuccessorVerifier(body);
2118 
2119   if (hasCustomVerify) {
2120     FmtContext fctx;
2121     fctx.addSubst("cppClass", opClass.getClassName());
2122     auto printer = stringInit->getValue().ltrim().rtrim(" \t\v\f\r");
2123     body << "  " << tgfmt(printer, &fctx);
2124   } else {
2125     body << "  return ::mlir::success();\n";
2126   }
2127 }
2128 
2129 void OpEmitter::genOperandResultVerifier(OpMethodBody &body,
2130                                          Operator::value_range values,
2131                                          StringRef valueKind) {
2132   FmtContext fctx;
2133 
2134   body << "  {\n";
2135   body << "    unsigned index = 0; (void)index;\n";
2136 
2137   for (auto staticValue : llvm::enumerate(values)) {
2138     const NamedTypeConstraint &value = staticValue.value();
2139 
2140     bool hasPredicate = value.hasPredicate();
2141     bool isOptional = value.isOptional();
2142     bool isVariadicOfVariadic = value.isVariadicOfVariadic();
2143     if (!hasPredicate && !isOptional && !isVariadicOfVariadic)
2144       continue;
2145     body << formatv("    auto valueGroup{2} = getODS{0}{1}s({2});\n",
2146                     // Capitalize the first letter to match the function name
2147                     valueKind.substr(0, 1).upper(), valueKind.substr(1),
2148                     staticValue.index());
2149 
2150     // If the constraint is optional check that the value group has at most 1
2151     // value.
2152     if (isOptional) {
2153       body << formatv("    if (valueGroup{0}.size() > 1)\n"
2154                       "      return emitOpError(\"{1} group starting at #\") "
2155                       "<< index << \" requires 0 or 1 element, but found \" << "
2156                       "valueGroup{0}.size();\n",
2157                       staticValue.index(), valueKind);
2158     } else if (isVariadicOfVariadic) {
2159       body << formatv(
2160           "    if (::mlir::failed(::mlir::OpTrait::impl::verifyValueSizeAttr("
2161           "*this, \"{0}\", \"{1}\", valueGroup{2}.size())))\n"
2162           "      return ::mlir::failure();\n",
2163           value.constraint.getVariadicOfVariadicSegmentSizeAttr(), value.name,
2164           staticValue.index());
2165     }
2166 
2167     // Otherwise, if there is no predicate there is nothing left to do.
2168     if (!hasPredicate)
2169       continue;
2170     // Emit a loop to check all the dynamic values in the pack.
2171     StringRef constraintFn =
2172         staticVerifierEmitter.getTypeConstraintFn(value.constraint);
2173     body << "    for (::mlir::Value v : valueGroup" << staticValue.index()
2174          << ") {\n"
2175          << "      if (::mlir::failed(" << constraintFn
2176          << "(getOperation(), v.getType(), \"" << valueKind << "\", index)))\n"
2177          << "        return ::mlir::failure();\n"
2178          << "      ++index;\n"
2179          << "    }\n";
2180   }
2181 
2182   body << "  }\n";
2183 }
2184 
2185 void OpEmitter::genRegionVerifier(OpMethodBody &body) {
2186   // If we have no regions, there is nothing more to do.
2187   unsigned numRegions = op.getNumRegions();
2188   if (numRegions == 0)
2189     return;
2190 
2191   body << "{\n";
2192   body << "    unsigned index = 0; (void)index;\n";
2193 
2194   for (unsigned i = 0; i < numRegions; ++i) {
2195     const auto &region = op.getRegion(i);
2196     if (region.constraint.getPredicate().isNull())
2197       continue;
2198 
2199     body << "    for (::mlir::Region &region : ";
2200     body << formatv(region.isVariadic()
2201                         ? "{0}()"
2202                         : "::mlir::MutableArrayRef<::mlir::Region>((*this)"
2203                           "->getRegion({1}))",
2204                     op.getGetterName(region.name), i);
2205     body << ") {\n";
2206     auto constraint = tgfmt(region.constraint.getConditionTemplate(),
2207                             &verifyCtx.withSelf("region"))
2208                           .str();
2209 
2210     body << formatv("      (void)region;\n"
2211                     "      if (!({0})) {\n        "
2212                     "return emitOpError(\"region #\") << index << \" {1}"
2213                     "failed to "
2214                     "verify constraint: {2}\";\n      }\n",
2215                     constraint,
2216                     region.name.empty() ? "" : "('" + region.name + "') ",
2217                     region.constraint.getSummary())
2218          << "      ++index;\n"
2219          << "    }\n";
2220   }
2221   body << "  }\n";
2222 }
2223 
2224 void OpEmitter::genSuccessorVerifier(OpMethodBody &body) {
2225   // If we have no successors, there is nothing more to do.
2226   unsigned numSuccessors = op.getNumSuccessors();
2227   if (numSuccessors == 0)
2228     return;
2229 
2230   body << "{\n";
2231   body << "    unsigned index = 0; (void)index;\n";
2232 
2233   for (unsigned i = 0; i < numSuccessors; ++i) {
2234     const auto &successor = op.getSuccessor(i);
2235     if (successor.constraint.getPredicate().isNull())
2236       continue;
2237 
2238     if (successor.isVariadic()) {
2239       body << formatv("    for (::mlir::Block *successor : {0}()) {\n",
2240                       successor.name);
2241     } else {
2242       body << "    {\n";
2243       body << formatv("      ::mlir::Block *successor = {0}();\n",
2244                       successor.name);
2245     }
2246     auto constraint = tgfmt(successor.constraint.getConditionTemplate(),
2247                             &verifyCtx.withSelf("successor"))
2248                           .str();
2249 
2250     body << formatv("      (void)successor;\n"
2251                     "      if (!({0})) {\n        "
2252                     "return emitOpError(\"successor #\") << index << \"('{1}') "
2253                     "failed to "
2254                     "verify constraint: {2}\";\n      }\n",
2255                     constraint, successor.name,
2256                     successor.constraint.getSummary())
2257          << "      ++index;\n"
2258          << "    }\n";
2259   }
2260   body << "  }\n";
2261 }
2262 
2263 /// Add a size count trait to the given operation class.
2264 static void addSizeCountTrait(OpClass &opClass, StringRef traitKind,
2265                               int numTotal, int numVariadic) {
2266   if (numVariadic != 0) {
2267     if (numTotal == numVariadic)
2268       opClass.addTrait("::mlir::OpTrait::Variadic" + traitKind + "s");
2269     else
2270       opClass.addTrait("::mlir::OpTrait::AtLeastN" + traitKind + "s<" +
2271                        Twine(numTotal - numVariadic) + ">::Impl");
2272     return;
2273   }
2274   switch (numTotal) {
2275   case 0:
2276     opClass.addTrait("::mlir::OpTrait::Zero" + traitKind);
2277     break;
2278   case 1:
2279     opClass.addTrait("::mlir::OpTrait::One" + traitKind);
2280     break;
2281   default:
2282     opClass.addTrait("::mlir::OpTrait::N" + traitKind + "s<" + Twine(numTotal) +
2283                      ">::Impl");
2284     break;
2285   }
2286 }
2287 
2288 void OpEmitter::genTraits() {
2289   // Add region size trait.
2290   unsigned numRegions = op.getNumRegions();
2291   unsigned numVariadicRegions = op.getNumVariadicRegions();
2292   addSizeCountTrait(opClass, "Region", numRegions, numVariadicRegions);
2293 
2294   // Add result size traits.
2295   int numResults = op.getNumResults();
2296   int numVariadicResults = op.getNumVariableLengthResults();
2297   addSizeCountTrait(opClass, "Result", numResults, numVariadicResults);
2298 
2299   // For single result ops with a known specific type, generate a OneTypedResult
2300   // trait.
2301   if (numResults == 1 && numVariadicResults == 0) {
2302     auto cppName = op.getResults().begin()->constraint.getCPPClassName();
2303     opClass.addTrait("::mlir::OpTrait::OneTypedResult<" + cppName + ">::Impl");
2304   }
2305 
2306   // Add successor size trait.
2307   unsigned numSuccessors = op.getNumSuccessors();
2308   unsigned numVariadicSuccessors = op.getNumVariadicSuccessors();
2309   addSizeCountTrait(opClass, "Successor", numSuccessors, numVariadicSuccessors);
2310 
2311   // Add variadic size trait and normal op traits.
2312   int numOperands = op.getNumOperands();
2313   int numVariadicOperands = op.getNumVariableLengthOperands();
2314 
2315   // Add operand size trait.
2316   if (numVariadicOperands != 0) {
2317     if (numOperands == numVariadicOperands)
2318       opClass.addTrait("::mlir::OpTrait::VariadicOperands");
2319     else
2320       opClass.addTrait("::mlir::OpTrait::AtLeastNOperands<" +
2321                        Twine(numOperands - numVariadicOperands) + ">::Impl");
2322   } else {
2323     switch (numOperands) {
2324     case 0:
2325       opClass.addTrait("::mlir::OpTrait::ZeroOperands");
2326       break;
2327     case 1:
2328       opClass.addTrait("::mlir::OpTrait::OneOperand");
2329       break;
2330     default:
2331       opClass.addTrait("::mlir::OpTrait::NOperands<" + Twine(numOperands) +
2332                        ">::Impl");
2333       break;
2334     }
2335   }
2336 
2337   // Add the native and interface traits.
2338   for (const auto &trait : op.getTraits()) {
2339     if (auto opTrait = dyn_cast<tblgen::NativeTrait>(&trait))
2340       opClass.addTrait(opTrait->getFullyQualifiedTraitName());
2341     else if (auto opTrait = dyn_cast<tblgen::InterfaceTrait>(&trait))
2342       opClass.addTrait(opTrait->getFullyQualifiedTraitName());
2343   }
2344 }
2345 
2346 void OpEmitter::genOpNameGetter() {
2347   auto *method = opClass.addMethodAndPrune(
2348       "::llvm::StringLiteral", "getOperationName",
2349       OpMethod::Property(OpMethod::MP_Static | OpMethod::MP_Constexpr));
2350   ERROR_IF_PRUNED(method, "getOperationName", op);
2351   method->body() << "  return ::llvm::StringLiteral(\"" << op.getOperationName()
2352                  << "\");";
2353 }
2354 
2355 void OpEmitter::genOpAsmInterface() {
2356   // If the user only has one results or specifically added the Asm trait,
2357   // then don't generate it for them. We specifically only handle multi result
2358   // operations, because the name of a single result in the common case is not
2359   // interesting(generally 'result'/'output'/etc.).
2360   // TODO: We could also add a flag to allow operations to opt in to this
2361   // generation, even if they only have a single operation.
2362   int numResults = op.getNumResults();
2363   if (numResults <= 1 || op.getTrait("::mlir::OpAsmOpInterface::Trait"))
2364     return;
2365 
2366   SmallVector<StringRef, 4> resultNames(numResults);
2367   for (int i = 0; i != numResults; ++i)
2368     resultNames[i] = op.getResultName(i);
2369 
2370   // Don't add the trait if none of the results have a valid name.
2371   if (llvm::all_of(resultNames, [](StringRef name) { return name.empty(); }))
2372     return;
2373   opClass.addTrait("::mlir::OpAsmOpInterface::Trait");
2374 
2375   // Generate the right accessor for the number of results.
2376   auto *method = opClass.addMethodAndPrune(
2377       "void", "getAsmResultNames", "::mlir::OpAsmSetValueNameFn", "setNameFn");
2378   ERROR_IF_PRUNED(method, "getAsmResultNames", op);
2379   auto &body = method->body();
2380   for (int i = 0; i != numResults; ++i) {
2381     body << "  auto resultGroup" << i << " = getODSResults(" << i << ");\n"
2382          << "  if (!llvm::empty(resultGroup" << i << "))\n"
2383          << "    setNameFn(*resultGroup" << i << ".begin(), \""
2384          << resultNames[i] << "\");\n";
2385   }
2386 }
2387 
2388 //===----------------------------------------------------------------------===//
2389 // OpOperandAdaptor emitter
2390 //===----------------------------------------------------------------------===//
2391 
2392 namespace {
2393 // Helper class to emit Op operand adaptors to an output stream.  Operand
2394 // adaptors are wrappers around ArrayRef<Value> that provide named operand
2395 // getters identical to those defined in the Op.
2396 class OpOperandAdaptorEmitter {
2397 public:
2398   static void emitDecl(const Operator &op, raw_ostream &os);
2399   static void emitDef(const Operator &op, raw_ostream &os);
2400 
2401 private:
2402   explicit OpOperandAdaptorEmitter(const Operator &op);
2403 
2404   // Add verification function. This generates a verify method for the adaptor
2405   // which verifies all the op-independent attribute constraints.
2406   void addVerification();
2407 
2408   const Operator &op;
2409   Class adaptor;
2410 };
2411 } // end namespace
2412 
2413 OpOperandAdaptorEmitter::OpOperandAdaptorEmitter(const Operator &op)
2414     : op(op), adaptor(op.getAdaptorName()) {
2415   adaptor.newField("::mlir::ValueRange", "odsOperands");
2416   adaptor.newField("::mlir::DictionaryAttr", "odsAttrs");
2417   adaptor.newField("::mlir::RegionRange", "odsRegions");
2418   const auto *attrSizedOperands =
2419       op.getTrait("::mlir::OpTrait::AttrSizedOperandSegments");
2420   {
2421     SmallVector<OpMethodParameter, 2> paramList;
2422     paramList.emplace_back("::mlir::ValueRange", "values");
2423     paramList.emplace_back("::mlir::DictionaryAttr", "attrs",
2424                            attrSizedOperands ? "" : "nullptr");
2425     paramList.emplace_back("::mlir::RegionRange", "regions", "{}");
2426     auto *constructor = adaptor.addConstructorAndPrune(std::move(paramList));
2427 
2428     constructor->addMemberInitializer("odsOperands", "values");
2429     constructor->addMemberInitializer("odsAttrs", "attrs");
2430     constructor->addMemberInitializer("odsRegions", "regions");
2431   }
2432 
2433   {
2434     auto *constructor = adaptor.addConstructorAndPrune(
2435         llvm::formatv("{0}&", op.getCppClassName()).str(), "op");
2436     constructor->addMemberInitializer("odsOperands", "op->getOperands()");
2437     constructor->addMemberInitializer("odsAttrs", "op->getAttrDictionary()");
2438     constructor->addMemberInitializer("odsRegions", "op->getRegions()");
2439   }
2440 
2441   {
2442     auto *m = adaptor.addMethodAndPrune("::mlir::ValueRange", "getOperands");
2443     ERROR_IF_PRUNED(m, "getOperands", op);
2444     m->body() << "  return odsOperands;";
2445   }
2446   std::string attr = "operand_segment_sizes";
2447   std::string sizeAttrInit = formatv(adapterSegmentSizeAttrInitCode, attr);
2448   generateNamedOperandGetters(op, adaptor,
2449                               /*isAdaptor=*/true, sizeAttrInit,
2450                               /*rangeType=*/"::mlir::ValueRange",
2451                               /*rangeBeginCall=*/"odsOperands.begin()",
2452                               /*rangeSizeCall=*/"odsOperands.size()",
2453                               /*getOperandCallPattern=*/"odsOperands[{0}]");
2454 
2455   FmtContext fctx;
2456   fctx.withBuilder("::mlir::Builder(odsAttrs.getContext())");
2457 
2458   auto emitAttr = [&](StringRef name, Attribute attr) {
2459     auto *method = adaptor.addMethodAndPrune(attr.getStorageType(), name);
2460     ERROR_IF_PRUNED(method, "Adaptor::" + name, op);
2461     auto &body = method->body();
2462     body << "  assert(odsAttrs && \"no attributes when constructing adapter\");"
2463          << "\n  " << attr.getStorageType() << " attr = "
2464          << "odsAttrs.get(\"" << name << "\").";
2465     if (attr.hasDefaultValue() || attr.isOptional())
2466       body << "dyn_cast_or_null<";
2467     else
2468       body << "cast<";
2469     body << attr.getStorageType() << ">();\n";
2470 
2471     if (attr.hasDefaultValue()) {
2472       // Use the default value if attribute is not set.
2473       // TODO: this is inefficient, we are recreating the attribute for every
2474       // call. This should be set instead.
2475       std::string defaultValue = std::string(
2476           tgfmt(attr.getConstBuilderTemplate(), &fctx, attr.getDefaultValue()));
2477       body << "  if (!attr)\n    attr = " << defaultValue << ";\n";
2478     }
2479     body << "  return attr;\n";
2480   };
2481 
2482   {
2483     auto *m =
2484         adaptor.addMethodAndPrune("::mlir::DictionaryAttr", "getAttributes");
2485     ERROR_IF_PRUNED(m, "Adaptor::getAttributes", op);
2486     m->body() << "  return odsAttrs;";
2487   }
2488   for (auto &namedAttr : op.getAttributes()) {
2489     const auto &name = namedAttr.name;
2490     const auto &attr = namedAttr.attr;
2491     if (!attr.isDerivedAttr()) {
2492       for (auto emitName : op.getGetterNames(name))
2493         emitAttr(emitName, attr);
2494     }
2495   }
2496 
2497   unsigned numRegions = op.getNumRegions();
2498   if (numRegions > 0) {
2499     auto *m = adaptor.addMethodAndPrune("::mlir::RegionRange", "getRegions");
2500     ERROR_IF_PRUNED(m, "Adaptor::getRegions", op);
2501     m->body() << "  return odsRegions;";
2502   }
2503   for (unsigned i = 0; i < numRegions; ++i) {
2504     const auto &region = op.getRegion(i);
2505     if (region.name.empty())
2506       continue;
2507 
2508     // Generate the accessors for a variadic region.
2509     for (StringRef name : op.getGetterNames(region.name)) {
2510       if (region.isVariadic()) {
2511         auto *m = adaptor.addMethodAndPrune("::mlir::RegionRange", name);
2512         ERROR_IF_PRUNED(m, "Adaptor::" + name, op);
2513         m->body() << formatv("  return odsRegions.drop_front({0});", i);
2514         continue;
2515       }
2516 
2517       auto *m = adaptor.addMethodAndPrune("::mlir::Region &", name);
2518       ERROR_IF_PRUNED(m, "Adaptor::" + name, op);
2519       m->body() << formatv("  return *odsRegions[{0}];", i);
2520     }
2521   }
2522 
2523   // Add verification function.
2524   addVerification();
2525 }
2526 
2527 void OpOperandAdaptorEmitter::addVerification() {
2528   auto *method = adaptor.addMethodAndPrune("::mlir::LogicalResult", "verify",
2529                                            "::mlir::Location", "loc");
2530   ERROR_IF_PRUNED(method, "verify", op);
2531   auto &body = method->body();
2532 
2533   const char *checkAttrSizedValueSegmentsCode = R"(
2534   {
2535     auto sizeAttr = odsAttrs.get("{0}").cast<::mlir::DenseIntElementsAttr>();
2536     auto numElements = sizeAttr.getType().cast<::mlir::ShapedType>().getNumElements();
2537     if (numElements != {1})
2538       return emitError(loc, "'{0}' attribute for specifying {2} segments "
2539                        "must have {1} elements, but got ") << numElements;
2540   }
2541   )";
2542 
2543   // Verify a few traits first so that we can use
2544   // getODSOperands()/getODSResults() in the rest of the verifier.
2545   for (auto &trait : op.getTraits()) {
2546     if (auto *t = dyn_cast<tblgen::NativeTrait>(&trait)) {
2547       if (t->getFullyQualifiedTraitName() ==
2548           "::mlir::OpTrait::AttrSizedOperandSegments") {
2549         body << formatv(checkAttrSizedValueSegmentsCode,
2550                         "operand_segment_sizes", op.getNumOperands(),
2551                         "operand");
2552       } else if (t->getFullyQualifiedTraitName() ==
2553                  "::mlir::OpTrait::AttrSizedResultSegments") {
2554         body << formatv(checkAttrSizedValueSegmentsCode, "result_segment_sizes",
2555                         op.getNumResults(), "result");
2556       }
2557     }
2558   }
2559 
2560   FmtContext verifyCtx;
2561   populateSubstitutions(op, "odsAttrs.get", "getODSOperands",
2562                         "<no results should be generated>", verifyCtx);
2563   genAttributeVerifier(op, "odsAttrs.get",
2564                        Twine("emitError(loc, \"'") + op.getOperationName() +
2565                            "' op \"",
2566                        /*emitVerificationRequiringOp*/ false, verifyCtx, body);
2567 
2568   body << "  return ::mlir::success();";
2569 }
2570 
2571 void OpOperandAdaptorEmitter::emitDecl(const Operator &op, raw_ostream &os) {
2572   OpOperandAdaptorEmitter(op).adaptor.writeDeclTo(os);
2573 }
2574 
2575 void OpOperandAdaptorEmitter::emitDef(const Operator &op, raw_ostream &os) {
2576   OpOperandAdaptorEmitter(op).adaptor.writeDefTo(os);
2577 }
2578 
2579 // Emits the opcode enum and op classes.
2580 static void emitOpClasses(const RecordKeeper &recordKeeper,
2581                           const std::vector<Record *> &defs, raw_ostream &os,
2582                           bool emitDecl) {
2583   // First emit forward declaration for each class, this allows them to refer
2584   // to each others in traits for example.
2585   if (emitDecl) {
2586     os << "#if defined(GET_OP_CLASSES) || defined(GET_OP_FWD_DEFINES)\n";
2587     os << "#undef GET_OP_FWD_DEFINES\n";
2588     for (auto *def : defs) {
2589       Operator op(*def);
2590       NamespaceEmitter emitter(os, op.getCppNamespace());
2591       os << "class " << op.getCppClassName() << ";\n";
2592     }
2593     os << "#endif\n\n";
2594   }
2595 
2596   IfDefScope scope("GET_OP_CLASSES", os);
2597   if (defs.empty())
2598     return;
2599 
2600   // Generate all of the locally instantiated methods first.
2601   StaticVerifierFunctionEmitter staticVerifierEmitter(recordKeeper, os);
2602   os << formatv(opCommentHeader, "Local Utility Method", "Definitions");
2603   staticVerifierEmitter.emitFunctionsFor(
2604       typeVerifierSignature, typeVerifierErrorHandler, /*typeArgName=*/"type",
2605       defs, emitDecl);
2606 
2607   for (auto *def : defs) {
2608     Operator op(*def);
2609     if (emitDecl) {
2610       {
2611         NamespaceEmitter emitter(os, op.getCppNamespace());
2612         os << formatv(opCommentHeader, op.getQualCppClassName(),
2613                       "declarations");
2614         OpOperandAdaptorEmitter::emitDecl(op, os);
2615         OpEmitter::emitDecl(op, os, staticVerifierEmitter);
2616       }
2617       // Emit the TypeID explicit specialization to have a single definition.
2618       if (!op.getCppNamespace().empty())
2619         os << "DECLARE_EXPLICIT_TYPE_ID(" << op.getCppNamespace()
2620            << "::" << op.getCppClassName() << ")\n\n";
2621     } else {
2622       {
2623         NamespaceEmitter emitter(os, op.getCppNamespace());
2624         os << formatv(opCommentHeader, op.getQualCppClassName(), "definitions");
2625         OpOperandAdaptorEmitter::emitDef(op, os);
2626         OpEmitter::emitDef(op, os, staticVerifierEmitter);
2627       }
2628       // Emit the TypeID explicit specialization to have a single definition.
2629       if (!op.getCppNamespace().empty())
2630         os << "DEFINE_EXPLICIT_TYPE_ID(" << op.getCppNamespace()
2631            << "::" << op.getCppClassName() << ")\n\n";
2632     }
2633   }
2634 }
2635 
2636 // Emits a comma-separated list of the ops.
2637 static void emitOpList(const std::vector<Record *> &defs, raw_ostream &os) {
2638   IfDefScope scope("GET_OP_LIST", os);
2639 
2640   interleave(
2641       // TODO: We are constructing the Operator wrapper instance just for
2642       // getting it's qualified class name here. Reduce the overhead by having a
2643       // lightweight version of Operator class just for that purpose.
2644       defs, [&os](Record *def) { os << Operator(def).getQualCppClassName(); },
2645       [&os]() { os << ",\n"; });
2646 }
2647 
2648 static bool emitOpDecls(const RecordKeeper &recordKeeper, raw_ostream &os) {
2649   emitSourceFileHeader("Op Declarations", os);
2650 
2651   std::vector<Record *> defs = getRequestedOpDefinitions(recordKeeper);
2652   emitOpClasses(recordKeeper, defs, os, /*emitDecl=*/true);
2653 
2654   return false;
2655 }
2656 
2657 static bool emitOpDefs(const RecordKeeper &recordKeeper, raw_ostream &os) {
2658   emitSourceFileHeader("Op Definitions", os);
2659 
2660   std::vector<Record *> defs = getRequestedOpDefinitions(recordKeeper);
2661   emitOpList(defs, os);
2662   emitOpClasses(recordKeeper, defs, os, /*emitDecl=*/false);
2663 
2664   return false;
2665 }
2666 
2667 static mlir::GenRegistration
2668     genOpDecls("gen-op-decls", "Generate op declarations",
2669                [](const RecordKeeper &records, raw_ostream &os) {
2670                  return emitOpDecls(records, os);
2671                });
2672 
2673 static mlir::GenRegistration genOpDefs("gen-op-defs", "Generate op definitions",
2674                                        [](const RecordKeeper &records,
2675                                           raw_ostream &os) {
2676                                          return emitOpDefs(records, os);
2677                                        });
2678