[mlir] Use StringRef::{starts,ends}_with (NFC)
[llvm-project.git] / mlir / tools / mlir-tblgen / OpDefinitionsGen.cpp
blobcd37c8dcd3d5e0eb018a6f3899d064a180738ea1
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.
12 //===----------------------------------------------------------------------===//
14 #include "OpClass.h"
15 #include "OpFormatGen.h"
16 #include "OpGenHelpers.h"
17 #include "mlir/TableGen/Argument.h"
18 #include "mlir/TableGen/Attribute.h"
19 #include "mlir/TableGen/Class.h"
20 #include "mlir/TableGen/CodeGenHelpers.h"
21 #include "mlir/TableGen/Format.h"
22 #include "mlir/TableGen/GenInfo.h"
23 #include "mlir/TableGen/Interfaces.h"
24 #include "mlir/TableGen/Operator.h"
25 #include "mlir/TableGen/Property.h"
26 #include "mlir/TableGen/SideEffects.h"
27 #include "mlir/TableGen/Trait.h"
28 #include "llvm/ADT/BitVector.h"
29 #include "llvm/ADT/MapVector.h"
30 #include "llvm/ADT/Sequence.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/ADT/StringSet.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/Signals.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/TableGen/Error.h"
39 #include "llvm/TableGen/Record.h"
40 #include "llvm/TableGen/TableGenBackend.h"
42 #define DEBUG_TYPE "mlir-tblgen-opdefgen"
44 using namespace llvm;
45 using namespace mlir;
46 using namespace mlir::tblgen;
48 static const char *const tblgenNamePrefix = "tblgen_";
49 static const char *const generatedArgName = "odsArg";
50 static const char *const odsBuilder = "odsBuilder";
51 static const char *const builderOpState = "odsState";
52 static const char *const propertyStorage = "propStorage";
53 static const char *const propertyValue = "propValue";
54 static const char *const propertyAttr = "propAttr";
55 static const char *const propertyDiag = "emitError";
57 /// The names of the implicit attributes that contain variadic operand and
58 /// result segment sizes.
59 static const char *const operandSegmentAttrName = "operandSegmentSizes";
60 static const char *const resultSegmentAttrName = "resultSegmentSizes";
62 /// Code for an Op to lookup an attribute. Uses cached identifiers and subrange
63 /// lookup.
64 ///
65 /// {0}: Code snippet to get the attribute's name or identifier.
66 /// {1}: The lower bound on the sorted subrange.
67 /// {2}: The upper bound on the sorted subrange.
68 /// {3}: Code snippet to get the array of named attributes.
69 /// {4}: "Named" to get the named attribute.
70 static const char *const subrangeGetAttr =
71 "::mlir::impl::get{4}AttrFromSortedRange({3}.begin() + {1}, {3}.end() - "
72 "{2}, {0})";
74 /// The logic to calculate the actual value range for a declared operand/result
75 /// of an op with variadic operands/results. Note that this logic is not for
76 /// general use; it assumes all variadic operands/results must have the same
77 /// number of values.
78 ///
79 /// {0}: The list of whether each declared operand/result is variadic.
80 /// {1}: The total number of non-variadic operands/results.
81 /// {2}: The total number of variadic operands/results.
82 /// {3}: The total number of actual values.
83 /// {4}: "operand" or "result".
84 static const char *const sameVariadicSizeValueRangeCalcCode = R"(
85 bool isVariadic[] = {{{0}};
86 int prevVariadicCount = 0;
87 for (unsigned i = 0; i < index; ++i)
88 if (isVariadic[i]) ++prevVariadicCount;
90 // Calculate how many dynamic values a static variadic {4} corresponds to.
91 // This assumes all static variadic {4}s have the same dynamic value count.
92 int variadicSize = ({3} - {1}) / {2};
93 // `index` passed in as the parameter is the static index which counts each
94 // {4} (variadic or not) as size 1. So here for each previous static variadic
95 // {4}, we need to offset by (variadicSize - 1) to get where the dynamic
96 // value pack for this static {4} starts.
97 int start = index + (variadicSize - 1) * prevVariadicCount;
98 int size = isVariadic[index] ? variadicSize : 1;
99 return {{start, size};
102 /// The logic to calculate the actual value range for a declared operand/result
103 /// of an op with variadic operands/results. Note that this logic is assumes
104 /// the op has an attribute specifying the size of each operand/result segment
105 /// (variadic or not).
106 static const char *const attrSizedSegmentValueRangeCalcCode = R"(
107 unsigned start = 0;
108 for (unsigned i = 0; i < index; ++i)
109 start += sizeAttr[i];
110 return {start, sizeAttr[index]};
112 /// The code snippet to initialize the sizes for the value range calculation.
114 /// {0}: The code to get the attribute.
115 static const char *const adapterSegmentSizeAttrInitCode = R"(
116 assert({0} && "missing segment size attribute for op");
117 auto sizeAttr = ::llvm::cast<::mlir::DenseI32ArrayAttr>({0});
119 static const char *const adapterSegmentSizeAttrInitCodeProperties = R"(
120 ::llvm::ArrayRef<int32_t> sizeAttr = {0};
123 /// The code snippet to initialize the sizes for the value range calculation.
125 /// {0}: The code to get the attribute.
126 static const char *const opSegmentSizeAttrInitCode = R"(
127 auto sizeAttr = ::llvm::cast<::mlir::DenseI32ArrayAttr>({0});
130 /// The logic to calculate the actual value range for a declared operand
131 /// of an op with variadic of variadic operands within the OpAdaptor.
133 /// {0}: The name of the segment attribute.
134 /// {1}: The index of the main operand.
135 /// {2}: The range type of adaptor.
136 static const char *const variadicOfVariadicAdaptorCalcCode = R"(
137 auto tblgenTmpOperands = getODSOperands({1});
138 auto sizes = {0}();
140 ::llvm::SmallVector<{2}> tblgenTmpOperandGroups;
141 for (int i = 0, e = sizes.size(); i < e; ++i) {{
142 tblgenTmpOperandGroups.push_back(tblgenTmpOperands.take_front(sizes[i]));
143 tblgenTmpOperands = tblgenTmpOperands.drop_front(sizes[i]);
145 return tblgenTmpOperandGroups;
148 /// The logic to build a range of either operand or result values.
150 /// {0}: The begin iterator of the actual values.
151 /// {1}: The call to generate the start and length of the value range.
152 static const char *const valueRangeReturnCode = R"(
153 auto valueRange = {1};
154 return {{std::next({0}, valueRange.first),
155 std::next({0}, valueRange.first + valueRange.second)};
158 /// Read operand/result segment_size from bytecode.
159 static const char *const readBytecodeSegmentSizeNative = R"(
160 if ($_reader.getBytecodeVersion() >= /*kNativePropertiesODSSegmentSize=*/6)
161 return $_reader.readSparseArray(::llvm::MutableArrayRef($_storage));
164 static const char *const readBytecodeSegmentSizeLegacy = R"(
165 if ($_reader.getBytecodeVersion() < /*kNativePropertiesODSSegmentSize=*/6) {
166 auto &$_storage = prop.$_propName;
167 ::mlir::DenseI32ArrayAttr attr;
168 if (::mlir::failed($_reader.readAttribute(attr))) return ::mlir::failure();
169 if (attr.size() > static_cast<int64_t>(sizeof($_storage) / sizeof(int32_t))) {
170 $_reader.emitError("size mismatch for operand/result_segment_size");
171 return ::mlir::failure();
173 ::llvm::copy(::llvm::ArrayRef<int32_t>(attr), $_storage.begin());
177 /// Write operand/result segment_size to bytecode.
178 static const char *const writeBytecodeSegmentSizeNative = R"(
179 if ($_writer.getBytecodeVersion() >= /*kNativePropertiesODSSegmentSize=*/6)
180 $_writer.writeSparseArray(::llvm::ArrayRef($_storage));
183 /// Write operand/result segment_size to bytecode.
184 static const char *const writeBytecodeSegmentSizeLegacy = R"(
185 if ($_writer.getBytecodeVersion() < /*kNativePropertiesODSSegmentSize=*/6) {
186 auto &$_storage = prop.$_propName;
187 $_writer.writeAttribute(::mlir::DenseI32ArrayAttr::get($_ctxt, $_storage));
191 /// A header for indicating code sections.
193 /// {0}: Some text, or a class name.
194 /// {1}: Some text.
195 static const char *const opCommentHeader = R"(
196 //===----------------------------------------------------------------------===//
197 // {0} {1}
198 //===----------------------------------------------------------------------===//
202 //===----------------------------------------------------------------------===//
203 // Utility structs and functions
204 //===----------------------------------------------------------------------===//
206 // Replaces all occurrences of `match` in `str` with `substitute`.
207 static std::string replaceAllSubstrs(std::string str, const std::string &match,
208 const std::string &substitute) {
209 std::string::size_type scanLoc = 0, matchLoc = std::string::npos;
210 while ((matchLoc = str.find(match, scanLoc)) != std::string::npos) {
211 str = str.replace(matchLoc, match.size(), substitute);
212 scanLoc = matchLoc + substitute.size();
214 return str;
217 // Returns whether the record has a value of the given name that can be returned
218 // via getValueAsString.
219 static inline bool hasStringAttribute(const Record &record,
220 StringRef fieldName) {
221 auto *valueInit = record.getValueInit(fieldName);
222 return isa<StringInit>(valueInit);
225 static std::string getArgumentName(const Operator &op, int index) {
226 const auto &operand = op.getOperand(index);
227 if (!operand.name.empty())
228 return std::string(operand.name);
229 return std::string(formatv("{0}_{1}", generatedArgName, index));
232 // Returns true if we can use unwrapped value for the given `attr` in builders.
233 static bool canUseUnwrappedRawValue(const tblgen::Attribute &attr) {
234 return attr.getReturnType() != attr.getStorageType() &&
235 // We need to wrap the raw value into an attribute in the builder impl
236 // so we need to make sure that the attribute specifies how to do that.
237 !attr.getConstBuilderTemplate().empty();
240 /// Build an attribute from a parameter value using the constant builder.
241 static std::string constBuildAttrFromParam(const tblgen::Attribute &attr,
242 FmtContext &fctx,
243 StringRef paramName) {
244 std::string builderTemplate = attr.getConstBuilderTemplate().str();
246 // For StringAttr, its constant builder call will wrap the input in
247 // quotes, which is correct for normal string literals, but incorrect
248 // here given we use function arguments. So we need to strip the
249 // wrapping quotes.
250 if (StringRef(builderTemplate).contains("\"$0\""))
251 builderTemplate = replaceAllSubstrs(builderTemplate, "\"$0\"", "$0");
253 return tgfmt(builderTemplate, &fctx, paramName).str();
256 namespace {
257 /// Metadata on a registered attribute. Given that attributes are stored in
258 /// sorted order on operations, we can use information from ODS to deduce the
259 /// number of required attributes less and and greater than each attribute,
260 /// allowing us to search only a subrange of the attributes in ODS-generated
261 /// getters.
262 struct AttributeMetadata {
263 /// The attribute name.
264 StringRef attrName;
265 /// Whether the attribute is required.
266 bool isRequired;
267 /// The ODS attribute constraint. Not present for implicit attributes.
268 std::optional<Attribute> constraint;
269 /// The number of required attributes less than this attribute.
270 unsigned lowerBound = 0;
271 /// The number of required attributes greater than this attribute.
272 unsigned upperBound = 0;
275 /// Helper class to select between OpAdaptor and Op code templates.
276 class OpOrAdaptorHelper {
277 public:
278 OpOrAdaptorHelper(const Operator &op, bool emitForOp)
279 : op(op), emitForOp(emitForOp) {
280 computeAttrMetadata();
283 /// Object that wraps a functor in a stream operator for interop with
284 /// llvm::formatv.
285 class Formatter {
286 public:
287 template <typename Functor>
288 Formatter(Functor &&func) : func(std::forward<Functor>(func)) {}
290 std::string str() const {
291 std::string result;
292 llvm::raw_string_ostream os(result);
293 os << *this;
294 return os.str();
297 private:
298 std::function<raw_ostream &(raw_ostream &)> func;
300 friend raw_ostream &operator<<(raw_ostream &os, const Formatter &fmt) {
301 return fmt.func(os);
305 // Generate code for getting an attribute.
306 Formatter getAttr(StringRef attrName, bool isNamed = false) const {
307 assert(attrMetadata.count(attrName) && "expected attribute metadata");
308 return [this, attrName, isNamed](raw_ostream &os) -> raw_ostream & {
309 const AttributeMetadata &attr = attrMetadata.find(attrName)->second;
310 if (hasProperties()) {
311 assert(!isNamed);
312 return os << "getProperties()." << attrName;
314 return os << formatv(subrangeGetAttr, getAttrName(attrName),
315 attr.lowerBound, attr.upperBound, getAttrRange(),
316 isNamed ? "Named" : "");
320 // Generate code for getting the name of an attribute.
321 Formatter getAttrName(StringRef attrName) const {
322 return [this, attrName](raw_ostream &os) -> raw_ostream & {
323 if (emitForOp)
324 return os << op.getGetterName(attrName) << "AttrName()";
325 return os << formatv("{0}::{1}AttrName(*odsOpName)", op.getCppClassName(),
326 op.getGetterName(attrName));
330 // Get the code snippet for getting the named attribute range.
331 StringRef getAttrRange() const {
332 return emitForOp ? "(*this)->getAttrs()" : "odsAttrs";
335 // Get the prefix code for emitting an error.
336 Formatter emitErrorPrefix() const {
337 return [this](raw_ostream &os) -> raw_ostream & {
338 if (emitForOp)
339 return os << "emitOpError(";
340 return os << formatv("emitError(loc, \"'{0}' op \"",
341 op.getOperationName());
345 // Get the call to get an operand or segment of operands.
346 Formatter getOperand(unsigned index) const {
347 return [this, index](raw_ostream &os) -> raw_ostream & {
348 return os << formatv(op.getOperand(index).isVariadic()
349 ? "this->getODSOperands({0})"
350 : "(*this->getODSOperands({0}).begin())",
351 index);
355 // Get the call to get a result of segment of results.
356 Formatter getResult(unsigned index) const {
357 return [this, index](raw_ostream &os) -> raw_ostream & {
358 if (!emitForOp)
359 return os << "<no results should be generated>";
360 return os << formatv(op.getResult(index).isVariadic()
361 ? "this->getODSResults({0})"
362 : "(*this->getODSResults({0}).begin())",
363 index);
367 // Return whether an op instance is available.
368 bool isEmittingForOp() const { return emitForOp; }
370 // Return the ODS operation wrapper.
371 const Operator &getOp() const { return op; }
373 // Get the attribute metadata sorted by name.
374 const llvm::MapVector<StringRef, AttributeMetadata> &getAttrMetadata() const {
375 return attrMetadata;
378 /// Returns whether to emit a `Properties` struct for this operation or not.
379 bool hasProperties() const {
380 if (!op.getProperties().empty())
381 return true;
382 if (!op.getDialect().usePropertiesForAttributes())
383 return false;
384 if (op.getTrait("::mlir::OpTrait::AttrSizedOperandSegments") ||
385 op.getTrait("::mlir::OpTrait::AttrSizedResultSegments"))
386 return true;
387 return llvm::any_of(getAttrMetadata(),
388 [](const std::pair<StringRef, AttributeMetadata> &it) {
389 return !it.second.constraint ||
390 !it.second.constraint->isDerivedAttr();
394 std::optional<NamedProperty> &getOperandSegmentsSize() {
395 return operandSegmentsSize;
398 std::optional<NamedProperty> &getResultSegmentsSize() {
399 return resultSegmentsSize;
402 uint32_t getOperandSegmentSizesLegacyIndex() {
403 return operandSegmentSizesLegacyIndex;
406 uint32_t getResultSegmentSizesLegacyIndex() {
407 return resultSegmentSizesLegacyIndex;
410 private:
411 // Compute the attribute metadata.
412 void computeAttrMetadata();
414 // The operation ODS wrapper.
415 const Operator &op;
416 // True if code is being generate for an op. False for an adaptor.
417 const bool emitForOp;
419 // The attribute metadata, mapped by name.
420 llvm::MapVector<StringRef, AttributeMetadata> attrMetadata;
422 // Property
423 std::optional<NamedProperty> operandSegmentsSize;
424 std::string operandSegmentsSizeStorage;
425 std::optional<NamedProperty> resultSegmentsSize;
426 std::string resultSegmentsSizeStorage;
428 // Indices to store the position in the emission order of the operand/result
429 // segment sizes attribute if emitted as part of the properties for legacy
430 // bytecode encodings, i.e. versions less than 6.
431 uint32_t operandSegmentSizesLegacyIndex = 0;
432 uint32_t resultSegmentSizesLegacyIndex = 0;
434 // The number of required attributes.
435 unsigned numRequired;
438 } // namespace
440 void OpOrAdaptorHelper::computeAttrMetadata() {
441 // Enumerate the attribute names of this op, ensuring the attribute names are
442 // unique in case implicit attributes are explicitly registered.
443 for (const NamedAttribute &namedAttr : op.getAttributes()) {
444 Attribute attr = namedAttr.attr;
445 bool isOptional =
446 attr.hasDefaultValue() || attr.isOptional() || attr.isDerivedAttr();
447 attrMetadata.insert(
448 {namedAttr.name, AttributeMetadata{namedAttr.name, !isOptional, attr}});
451 auto makeProperty = [&](StringRef storageType) {
452 return Property(
453 /*storageType=*/storageType,
454 /*interfaceType=*/"::llvm::ArrayRef<int32_t>",
455 /*convertFromStorageCall=*/"$_storage",
456 /*assignToStorageCall=*/
457 "::llvm::copy($_value, $_storage.begin())",
458 /*convertToAttributeCall=*/
459 "::mlir::DenseI32ArrayAttr::get($_ctxt, $_storage)",
460 /*convertFromAttributeCall=*/
461 "return convertFromAttribute($_storage, $_attr, $_diag);",
462 /*readFromMlirBytecodeCall=*/readBytecodeSegmentSizeNative,
463 /*writeToMlirBytecodeCall=*/writeBytecodeSegmentSizeNative,
464 /*hashPropertyCall=*/
465 "::llvm::hash_combine_range(std::begin($_storage), "
466 "std::end($_storage));",
467 /*StringRef defaultValue=*/"");
469 // Include key attributes from several traits as implicitly registered.
470 if (op.getTrait("::mlir::OpTrait::AttrSizedOperandSegments")) {
471 if (op.getDialect().usePropertiesForAttributes()) {
472 operandSegmentsSizeStorage =
473 llvm::formatv("std::array<int32_t, {0}>", op.getNumOperands());
474 operandSegmentsSize = {"operandSegmentSizes",
475 makeProperty(operandSegmentsSizeStorage)};
476 } else {
477 attrMetadata.insert(
478 {operandSegmentAttrName, AttributeMetadata{operandSegmentAttrName,
479 /*isRequired=*/true,
480 /*attr=*/std::nullopt}});
483 if (op.getTrait("::mlir::OpTrait::AttrSizedResultSegments")) {
484 if (op.getDialect().usePropertiesForAttributes()) {
485 resultSegmentsSizeStorage =
486 llvm::formatv("std::array<int32_t, {0}>", op.getNumResults());
487 resultSegmentsSize = {"resultSegmentSizes",
488 makeProperty(resultSegmentsSizeStorage)};
489 } else {
490 attrMetadata.insert(
491 {resultSegmentAttrName,
492 AttributeMetadata{resultSegmentAttrName, /*isRequired=*/true,
493 /*attr=*/std::nullopt}});
497 // Store the metadata in sorted order.
498 SmallVector<AttributeMetadata> sortedAttrMetadata =
499 llvm::to_vector(llvm::make_second_range(attrMetadata.takeVector()));
500 llvm::sort(sortedAttrMetadata,
501 [](const AttributeMetadata &lhs, const AttributeMetadata &rhs) {
502 return lhs.attrName < rhs.attrName;
505 // Store the position of the legacy operand_segment_sizes /
506 // result_segment_sizes so we can emit a backward compatible property readers
507 // and writers.
508 StringRef legacyOperandSegmentSizeName =
509 StringLiteral("operand_segment_sizes");
510 StringRef legacyResultSegmentSizeName = StringLiteral("result_segment_sizes");
511 operandSegmentSizesLegacyIndex = 0;
512 resultSegmentSizesLegacyIndex = 0;
513 for (auto item : sortedAttrMetadata) {
514 if (item.attrName < legacyOperandSegmentSizeName)
515 ++operandSegmentSizesLegacyIndex;
516 if (item.attrName < legacyResultSegmentSizeName)
517 ++resultSegmentSizesLegacyIndex;
520 // Compute the subrange bounds for each attribute.
521 numRequired = 0;
522 for (AttributeMetadata &attr : sortedAttrMetadata) {
523 attr.lowerBound = numRequired;
524 numRequired += attr.isRequired;
526 for (AttributeMetadata &attr : sortedAttrMetadata)
527 attr.upperBound = numRequired - attr.lowerBound - attr.isRequired;
529 // Store the results back into the map.
530 for (const AttributeMetadata &attr : sortedAttrMetadata)
531 attrMetadata.insert({attr.attrName, attr});
534 //===----------------------------------------------------------------------===//
535 // Op emitter
536 //===----------------------------------------------------------------------===//
538 namespace {
539 // Helper class to emit a record into the given output stream.
540 class OpEmitter {
541 using ConstArgument =
542 llvm::PointerUnion<const AttributeMetadata *, const NamedProperty *>;
544 public:
545 static void
546 emitDecl(const Operator &op, raw_ostream &os,
547 const StaticVerifierFunctionEmitter &staticVerifierEmitter);
548 static void
549 emitDef(const Operator &op, raw_ostream &os,
550 const StaticVerifierFunctionEmitter &staticVerifierEmitter);
552 private:
553 OpEmitter(const Operator &op,
554 const StaticVerifierFunctionEmitter &staticVerifierEmitter);
556 void emitDecl(raw_ostream &os);
557 void emitDef(raw_ostream &os);
559 // Generate methods for accessing the attribute names of this operation.
560 void genAttrNameGetters();
562 // Generates the OpAsmOpInterface for this operation if possible.
563 void genOpAsmInterface();
565 // Generates the `getOperationName` method for this op.
566 void genOpNameGetter();
568 // Generates code to manage the properties, if any!
569 void genPropertiesSupport();
571 // Generates code to manage the encoding of properties to bytecode.
572 void
573 genPropertiesSupportForBytecode(ArrayRef<ConstArgument> attrOrProperties);
575 // Generates getters for the attributes.
576 void genAttrGetters();
578 // Generates setter for the attributes.
579 void genAttrSetters();
581 // Generates removers for optional attributes.
582 void genOptionalAttrRemovers();
584 // Generates getters for named operands.
585 void genNamedOperandGetters();
587 // Generates setters for named operands.
588 void genNamedOperandSetters();
590 // Generates getters for named results.
591 void genNamedResultGetters();
593 // Generates getters for named regions.
594 void genNamedRegionGetters();
596 // Generates getters for named successors.
597 void genNamedSuccessorGetters();
599 // Generates the method to populate default attributes.
600 void genPopulateDefaultAttributes();
602 // Generates builder methods for the operation.
603 void genBuilder();
605 // Generates the build() method that takes each operand/attribute
606 // as a stand-alone parameter.
607 void genSeparateArgParamBuilder();
609 // Generates the build() method that takes each operand/attribute as a
610 // stand-alone parameter. The generated build() method uses first operand's
611 // type as all results' types.
612 void genUseOperandAsResultTypeSeparateParamBuilder();
614 // Generates the build() method that takes all operands/attributes
615 // collectively as one parameter. The generated build() method uses first
616 // operand's type as all results' types.
617 void genUseOperandAsResultTypeCollectiveParamBuilder();
619 // Generates the build() method that takes aggregate operands/attributes
620 // parameters. This build() method uses inferred types as result types.
621 // Requires: The type needs to be inferable via InferTypeOpInterface.
622 void genInferredTypeCollectiveParamBuilder();
624 // Generates the build() method that takes each operand/attribute as a
625 // stand-alone parameter. The generated build() method uses first attribute's
626 // type as all result's types.
627 void genUseAttrAsResultTypeBuilder();
629 // Generates the build() method that takes all result types collectively as
630 // one parameter. Similarly for operands and attributes.
631 void genCollectiveParamBuilder();
633 // The kind of parameter to generate for result types in builders.
634 enum class TypeParamKind {
635 None, // No result type in parameter list.
636 Separate, // A separate parameter for each result type.
637 Collective, // An ArrayRef<Type> for all result types.
640 // The kind of parameter to generate for attributes in builders.
641 enum class AttrParamKind {
642 WrappedAttr, // A wrapped MLIR Attribute instance.
643 UnwrappedValue, // A raw value without MLIR Attribute wrapper.
646 // Builds the parameter list for build() method of this op. This method writes
647 // to `paramList` the comma-separated parameter list and updates
648 // `resultTypeNames` with the names for parameters for specifying result
649 // types. `inferredAttributes` is populated with any attributes that are
650 // elided from the build list. The given `typeParamKind` and `attrParamKind`
651 // controls how result types and attributes are placed in the parameter list.
652 void buildParamList(SmallVectorImpl<MethodParameter> &paramList,
653 llvm::StringSet<> &inferredAttributes,
654 SmallVectorImpl<std::string> &resultTypeNames,
655 TypeParamKind typeParamKind,
656 AttrParamKind attrParamKind = AttrParamKind::WrappedAttr);
658 // Adds op arguments and regions into operation state for build() methods.
659 void
660 genCodeForAddingArgAndRegionForBuilder(MethodBody &body,
661 llvm::StringSet<> &inferredAttributes,
662 bool isRawValueAttr = false);
664 // Generates canonicalizer declaration for the operation.
665 void genCanonicalizerDecls();
667 // Generates the folder declaration for the operation.
668 void genFolderDecls();
670 // Generates the parser for the operation.
671 void genParser();
673 // Generates the printer for the operation.
674 void genPrinter();
676 // Generates verify method for the operation.
677 void genVerifier();
679 // Generates custom verify methods for the operation.
680 void genCustomVerifier();
682 // Generates verify statements for operands and results in the operation.
683 // The generated code will be attached to `body`.
684 void genOperandResultVerifier(MethodBody &body,
685 Operator::const_value_range values,
686 StringRef valueKind);
688 // Generates verify statements for regions in the operation.
689 // The generated code will be attached to `body`.
690 void genRegionVerifier(MethodBody &body);
692 // Generates verify statements for successors in the operation.
693 // The generated code will be attached to `body`.
694 void genSuccessorVerifier(MethodBody &body);
696 // Generates the traits used by the object.
697 void genTraits();
699 // Generate the OpInterface methods for all interfaces.
700 void genOpInterfaceMethods();
702 // Generate op interface methods for the given interface.
703 void genOpInterfaceMethods(const tblgen::InterfaceTrait *trait);
705 // Generate op interface method for the given interface method. If
706 // 'declaration' is true, generates a declaration, else a definition.
707 Method *genOpInterfaceMethod(const tblgen::InterfaceMethod &method,
708 bool declaration = true);
710 // Generate the side effect interface methods.
711 void genSideEffectInterfaceMethods();
713 // Generate the type inference interface methods.
714 void genTypeInterfaceMethods();
716 private:
717 // The TableGen record for this op.
718 // TODO: OpEmitter should not have a Record directly,
719 // it should rather go through the Operator for better abstraction.
720 const Record &def;
722 // The wrapper operator class for querying information from this op.
723 const Operator &op;
725 // The C++ code builder for this op
726 OpClass opClass;
728 // The format context for verification code generation.
729 FmtContext verifyCtx;
731 // The emitter containing all of the locally emitted verification functions.
732 const StaticVerifierFunctionEmitter &staticVerifierEmitter;
734 // Helper for emitting op code.
735 OpOrAdaptorHelper emitHelper;
738 } // namespace
740 // Populate the format context `ctx` with substitutions of attributes, operands
741 // and results.
742 static void populateSubstitutions(const OpOrAdaptorHelper &emitHelper,
743 FmtContext &ctx) {
744 // Populate substitutions for attributes.
745 auto &op = emitHelper.getOp();
746 for (const auto &namedAttr : op.getAttributes())
747 ctx.addSubst(namedAttr.name,
748 emitHelper.getOp().getGetterName(namedAttr.name) + "()");
750 // Populate substitutions for named operands.
751 for (int i = 0, e = op.getNumOperands(); i < e; ++i) {
752 auto &value = op.getOperand(i);
753 if (!value.name.empty())
754 ctx.addSubst(value.name, emitHelper.getOperand(i).str());
757 // Populate substitutions for results.
758 for (int i = 0, e = op.getNumResults(); i < e; ++i) {
759 auto &value = op.getResult(i);
760 if (!value.name.empty())
761 ctx.addSubst(value.name, emitHelper.getResult(i).str());
765 /// Generate verification on native traits requiring attributes.
766 static void genNativeTraitAttrVerifier(MethodBody &body,
767 const OpOrAdaptorHelper &emitHelper) {
768 // Check that the variadic segment sizes attribute exists and contains the
769 // expected number of elements.
771 // {0}: Attribute name.
772 // {1}: Expected number of elements.
773 // {2}: "operand" or "result".
774 // {3}: Emit error prefix.
775 const char *const checkAttrSizedValueSegmentsCode = R"(
777 auto sizeAttr = ::llvm::cast<::mlir::DenseI32ArrayAttr>(tblgen_{0});
778 auto numElements = sizeAttr.asArrayRef().size();
779 if (numElements != {1})
780 return {3}"'{0}' attribute for specifying {2} segments must have {1} "
781 "elements, but got ") << numElements;
785 // Verify a few traits first so that we can use getODSOperands() and
786 // getODSResults() in the rest of the verifier.
787 auto &op = emitHelper.getOp();
788 if (!op.getDialect().usePropertiesForAttributes()) {
789 if (op.getTrait("::mlir::OpTrait::AttrSizedOperandSegments")) {
790 body << formatv(checkAttrSizedValueSegmentsCode, operandSegmentAttrName,
791 op.getNumOperands(), "operand",
792 emitHelper.emitErrorPrefix());
794 if (op.getTrait("::mlir::OpTrait::AttrSizedResultSegments")) {
795 body << formatv(checkAttrSizedValueSegmentsCode, resultSegmentAttrName,
796 op.getNumResults(), "result",
797 emitHelper.emitErrorPrefix());
802 // Return true if a verifier can be emitted for the attribute: it is not a
803 // derived attribute, it has a predicate, its condition is not empty, and, for
804 // adaptors, the condition does not reference the op.
805 static bool canEmitAttrVerifier(Attribute attr, bool isEmittingForOp) {
806 if (attr.isDerivedAttr())
807 return false;
808 Pred pred = attr.getPredicate();
809 if (pred.isNull())
810 return false;
811 std::string condition = pred.getCondition();
812 return !condition.empty() &&
813 (!StringRef(condition).contains("$_op") || isEmittingForOp);
816 // Generate attribute verification. If an op instance is not available, then
817 // attribute checks that require one will not be emitted.
819 // Attribute verification is performed as follows:
821 // 1. Verify that all required attributes are present in sorted order. This
822 // ensures that we can use subrange lookup even with potentially missing
823 // attributes.
824 // 2. Verify native trait attributes so that other attributes may call methods
825 // that depend on the validity of these attributes, e.g. segment size attributes
826 // and operand or result getters.
827 // 3. Verify the constraints on all present attributes.
828 static void
829 genAttributeVerifier(const OpOrAdaptorHelper &emitHelper, FmtContext &ctx,
830 MethodBody &body,
831 const StaticVerifierFunctionEmitter &staticVerifierEmitter,
832 bool useProperties) {
833 if (emitHelper.getAttrMetadata().empty())
834 return;
836 // Verify the attribute if it is present. This assumes that default values
837 // are valid. This code snippet pastes the condition inline.
839 // TODO: verify the default value is valid (perhaps in debug mode only).
841 // {0}: Attribute variable name.
842 // {1}: Attribute condition code.
843 // {2}: Emit error prefix.
844 // {3}: Attribute name.
845 // {4}: Attribute/constraint description.
846 const char *const verifyAttrInline = R"(
847 if ({0} && !({1}))
848 return {2}"attribute '{3}' failed to satisfy constraint: {4}");
850 // Verify the attribute using a uniqued constraint. Can only be used within
851 // the context of an op.
853 // {0}: Unique constraint name.
854 // {1}: Attribute variable name.
855 // {2}: Attribute name.
856 const char *const verifyAttrUnique = R"(
857 if (::mlir::failed({0}(*this, {1}, "{2}")))
858 return ::mlir::failure();
861 // Traverse the array until the required attribute is found. Return an error
862 // if the traversal reached the end.
864 // {0}: Code to get the name of the attribute.
865 // {1}: The emit error prefix.
866 // {2}: The name of the attribute.
867 const char *const findRequiredAttr = R"(
868 while (true) {{
869 if (namedAttrIt == namedAttrRange.end())
870 return {1}"requires attribute '{2}'");
871 if (namedAttrIt->getName() == {0}) {{
872 tblgen_{2} = namedAttrIt->getValue();
873 break;
874 })";
876 // Emit a check to see if the iteration has encountered an optional attribute.
878 // {0}: Code to get the name of the attribute.
879 // {1}: The name of the attribute.
880 const char *const checkOptionalAttr = R"(
881 else if (namedAttrIt->getName() == {0}) {{
882 tblgen_{1} = namedAttrIt->getValue();
883 })";
885 // Emit the start of the loop for checking trailing attributes.
886 const char *const checkTrailingAttrs = R"(while (true) {
887 if (namedAttrIt == namedAttrRange.end()) {
888 break;
889 })";
891 // Emit the verifier for the attribute.
892 const auto emitVerifier = [&](Attribute attr, StringRef attrName,
893 StringRef varName) {
894 std::string condition = attr.getPredicate().getCondition();
896 std::optional<StringRef> constraintFn;
897 if (emitHelper.isEmittingForOp() &&
898 (constraintFn = staticVerifierEmitter.getAttrConstraintFn(attr))) {
899 body << formatv(verifyAttrUnique, *constraintFn, varName, attrName);
900 } else {
901 body << formatv(verifyAttrInline, varName,
902 tgfmt(condition, &ctx.withSelf(varName)),
903 emitHelper.emitErrorPrefix(), attrName,
904 escapeString(attr.getSummary()));
908 // Prefix variables with `tblgen_` to avoid hiding the attribute accessor.
909 const auto getVarName = [&](StringRef attrName) {
910 return (tblgenNamePrefix + attrName).str();
913 body.indent();
914 if (useProperties) {
915 for (const std::pair<StringRef, AttributeMetadata> &it :
916 emitHelper.getAttrMetadata()) {
917 const AttributeMetadata &metadata = it.second;
918 if (metadata.constraint && metadata.constraint->isDerivedAttr())
919 continue;
920 body << formatv(
921 "auto tblgen_{0} = getProperties().{0}; (void)tblgen_{0};\n",
922 it.first);
923 if (metadata.isRequired)
924 body << formatv(
925 "if (!tblgen_{0}) return {1}\"requires attribute '{0}'\");\n",
926 it.first, emitHelper.emitErrorPrefix());
928 } else {
929 body << formatv("auto namedAttrRange = {0};\n", emitHelper.getAttrRange());
930 body << "auto namedAttrIt = namedAttrRange.begin();\n";
932 // Iterate over the attributes in sorted order. Keep track of the optional
933 // attributes that may be encountered along the way.
934 SmallVector<const AttributeMetadata *> optionalAttrs;
936 for (const std::pair<StringRef, AttributeMetadata> &it :
937 emitHelper.getAttrMetadata()) {
938 const AttributeMetadata &metadata = it.second;
939 if (!metadata.isRequired) {
940 optionalAttrs.push_back(&metadata);
941 continue;
944 body << formatv("::mlir::Attribute {0};\n", getVarName(it.first));
945 for (const AttributeMetadata *optional : optionalAttrs) {
946 body << formatv("::mlir::Attribute {0};\n",
947 getVarName(optional->attrName));
949 body << formatv(findRequiredAttr, emitHelper.getAttrName(it.first),
950 emitHelper.emitErrorPrefix(), it.first);
951 for (const AttributeMetadata *optional : optionalAttrs) {
952 body << formatv(checkOptionalAttr,
953 emitHelper.getAttrName(optional->attrName),
954 optional->attrName);
956 body << "\n ++namedAttrIt;\n}\n";
957 optionalAttrs.clear();
959 // Get trailing optional attributes.
960 if (!optionalAttrs.empty()) {
961 for (const AttributeMetadata *optional : optionalAttrs) {
962 body << formatv("::mlir::Attribute {0};\n",
963 getVarName(optional->attrName));
965 body << checkTrailingAttrs;
966 for (const AttributeMetadata *optional : optionalAttrs) {
967 body << formatv(checkOptionalAttr,
968 emitHelper.getAttrName(optional->attrName),
969 optional->attrName);
971 body << "\n ++namedAttrIt;\n}\n";
974 body.unindent();
976 // Emit the checks for segment attributes first so that the other
977 // constraints can call operand and result getters.
978 genNativeTraitAttrVerifier(body, emitHelper);
980 bool isEmittingForOp = emitHelper.isEmittingForOp();
981 for (const auto &namedAttr : emitHelper.getOp().getAttributes())
982 if (canEmitAttrVerifier(namedAttr.attr, isEmittingForOp))
983 emitVerifier(namedAttr.attr, namedAttr.name, getVarName(namedAttr.name));
986 /// Include declarations specified on NativeTrait
987 static std::string formatExtraDeclarations(const Operator &op) {
988 SmallVector<StringRef> extraDeclarations;
989 // Include extra class declarations from NativeTrait
990 for (const auto &trait : op.getTraits()) {
991 if (auto *opTrait = dyn_cast<tblgen::NativeTrait>(&trait)) {
992 StringRef value = opTrait->getExtraConcreteClassDeclaration();
993 if (value.empty())
994 continue;
995 extraDeclarations.push_back(value);
998 extraDeclarations.push_back(op.getExtraClassDeclaration());
999 return llvm::join(extraDeclarations, "\n");
1002 /// Op extra class definitions have a `$cppClass` substitution that is to be
1003 /// replaced by the C++ class name.
1004 /// Include declarations specified on NativeTrait
1005 static std::string formatExtraDefinitions(const Operator &op) {
1006 SmallVector<StringRef> extraDefinitions;
1007 // Include extra class definitions from NativeTrait
1008 for (const auto &trait : op.getTraits()) {
1009 if (auto *opTrait = dyn_cast<tblgen::NativeTrait>(&trait)) {
1010 StringRef value = opTrait->getExtraConcreteClassDefinition();
1011 if (value.empty())
1012 continue;
1013 extraDefinitions.push_back(value);
1016 extraDefinitions.push_back(op.getExtraClassDefinition());
1017 FmtContext ctx = FmtContext().addSubst("cppClass", op.getCppClassName());
1018 return tgfmt(llvm::join(extraDefinitions, "\n"), &ctx).str();
1021 OpEmitter::OpEmitter(const Operator &op,
1022 const StaticVerifierFunctionEmitter &staticVerifierEmitter)
1023 : def(op.getDef()), op(op),
1024 opClass(op.getCppClassName(), formatExtraDeclarations(op),
1025 formatExtraDefinitions(op)),
1026 staticVerifierEmitter(staticVerifierEmitter),
1027 emitHelper(op, /*emitForOp=*/true) {
1028 verifyCtx.addSubst("_op", "(*this->getOperation())");
1029 verifyCtx.addSubst("_ctxt", "this->getOperation()->getContext()");
1031 genTraits();
1033 // Generate C++ code for various op methods. The order here determines the
1034 // methods in the generated file.
1035 genAttrNameGetters();
1036 genOpAsmInterface();
1037 genOpNameGetter();
1038 genNamedOperandGetters();
1039 genNamedOperandSetters();
1040 genNamedResultGetters();
1041 genNamedRegionGetters();
1042 genNamedSuccessorGetters();
1043 genPropertiesSupport();
1044 genAttrGetters();
1045 genAttrSetters();
1046 genOptionalAttrRemovers();
1047 genBuilder();
1048 genPopulateDefaultAttributes();
1049 genParser();
1050 genPrinter();
1051 genVerifier();
1052 genCustomVerifier();
1053 genCanonicalizerDecls();
1054 genFolderDecls();
1055 genTypeInterfaceMethods();
1056 genOpInterfaceMethods();
1057 generateOpFormat(op, opClass);
1058 genSideEffectInterfaceMethods();
1060 void OpEmitter::emitDecl(
1061 const Operator &op, raw_ostream &os,
1062 const StaticVerifierFunctionEmitter &staticVerifierEmitter) {
1063 OpEmitter(op, staticVerifierEmitter).emitDecl(os);
1066 void OpEmitter::emitDef(
1067 const Operator &op, raw_ostream &os,
1068 const StaticVerifierFunctionEmitter &staticVerifierEmitter) {
1069 OpEmitter(op, staticVerifierEmitter).emitDef(os);
1072 void OpEmitter::emitDecl(raw_ostream &os) {
1073 opClass.finalize();
1074 opClass.writeDeclTo(os);
1077 void OpEmitter::emitDef(raw_ostream &os) {
1078 opClass.finalize();
1079 opClass.writeDefTo(os);
1082 static void errorIfPruned(size_t line, Method *m, const Twine &methodName,
1083 const Operator &op) {
1084 if (m)
1085 return;
1086 PrintFatalError(op.getLoc(), "Unexpected overlap when generating `" +
1087 methodName + "` for " +
1088 op.getOperationName() + " (from line " +
1089 Twine(line) + ")");
1092 #define ERROR_IF_PRUNED(M, N, O) errorIfPruned(__LINE__, M, N, O)
1094 void OpEmitter::genAttrNameGetters() {
1095 const llvm::MapVector<StringRef, AttributeMetadata> &attributes =
1096 emitHelper.getAttrMetadata();
1097 bool hasOperandSegmentsSize =
1098 op.getDialect().usePropertiesForAttributes() &&
1099 op.getTrait("::mlir::OpTrait::AttrSizedOperandSegments");
1100 // Emit the getAttributeNames method.
1102 auto *method = opClass.addStaticInlineMethod(
1103 "::llvm::ArrayRef<::llvm::StringRef>", "getAttributeNames");
1104 ERROR_IF_PRUNED(method, "getAttributeNames", op);
1105 auto &body = method->body();
1106 if (!hasOperandSegmentsSize && attributes.empty()) {
1107 body << " return {};";
1108 // Nothing else to do if there are no registered attributes. Exit early.
1109 return;
1111 body << " static ::llvm::StringRef attrNames[] = {";
1112 llvm::interleaveComma(llvm::make_first_range(attributes), body,
1113 [&](StringRef attrName) {
1114 body << "::llvm::StringRef(\"" << attrName << "\")";
1116 if (hasOperandSegmentsSize) {
1117 if (!attributes.empty())
1118 body << ", ";
1119 body << "::llvm::StringRef(\"" << operandSegmentAttrName << "\")";
1121 body << "};\n return ::llvm::ArrayRef(attrNames);";
1124 // Emit the getAttributeNameForIndex methods.
1126 auto *method = opClass.addInlineMethod<Method::Private>(
1127 "::mlir::StringAttr", "getAttributeNameForIndex",
1128 MethodParameter("unsigned", "index"));
1129 ERROR_IF_PRUNED(method, "getAttributeNameForIndex", op);
1130 method->body()
1131 << " return getAttributeNameForIndex((*this)->getName(), index);";
1134 auto *method = opClass.addStaticInlineMethod<Method::Private>(
1135 "::mlir::StringAttr", "getAttributeNameForIndex",
1136 MethodParameter("::mlir::OperationName", "name"),
1137 MethodParameter("unsigned", "index"));
1138 ERROR_IF_PRUNED(method, "getAttributeNameForIndex", op);
1140 if (attributes.empty()) {
1141 method->body() << " return {};";
1142 } else {
1143 const char *const getAttrName = R"(
1144 assert(index < {0} && "invalid attribute index");
1145 assert(name.getStringRef() == getOperationName() && "invalid operation name");
1146 assert(name.isRegistered() && "Operation isn't registered, missing a "
1147 "dependent dialect loading?");
1148 return name.getAttributeNames()[index];
1150 method->body() << formatv(getAttrName, attributes.size());
1154 // Generate the <attr>AttrName methods, that expose the attribute names to
1155 // users.
1156 const char *attrNameMethodBody = " return getAttributeNameForIndex({0});";
1157 for (auto [index, attr] :
1158 llvm::enumerate(llvm::make_first_range(attributes))) {
1159 std::string name = op.getGetterName(attr);
1160 std::string methodName = name + "AttrName";
1162 // Generate the non-static variant.
1164 auto *method = opClass.addInlineMethod("::mlir::StringAttr", methodName);
1165 ERROR_IF_PRUNED(method, methodName, op);
1166 method->body() << llvm::formatv(attrNameMethodBody, index);
1169 // Generate the static variant.
1171 auto *method = opClass.addStaticInlineMethod(
1172 "::mlir::StringAttr", methodName,
1173 MethodParameter("::mlir::OperationName", "name"));
1174 ERROR_IF_PRUNED(method, methodName, op);
1175 method->body() << llvm::formatv(attrNameMethodBody,
1176 "name, " + Twine(index));
1179 if (hasOperandSegmentsSize) {
1180 std::string name = op.getGetterName(operandSegmentAttrName);
1181 std::string methodName = name + "AttrName";
1182 // Generate the non-static variant.
1184 auto *method = opClass.addInlineMethod("::mlir::StringAttr", methodName);
1185 ERROR_IF_PRUNED(method, methodName, op);
1186 method->body()
1187 << " return (*this)->getName().getAttributeNames().back();";
1190 // Generate the static variant.
1192 auto *method = opClass.addStaticInlineMethod(
1193 "::mlir::StringAttr", methodName,
1194 MethodParameter("::mlir::OperationName", "name"));
1195 ERROR_IF_PRUNED(method, methodName, op);
1196 method->body() << " return name.getAttributeNames().back();";
1201 // Emit the getter for an attribute with the return type specified.
1202 // It is templated to be shared between the Op and the adaptor class.
1203 template <typename OpClassOrAdaptor>
1204 static void emitAttrGetterWithReturnType(FmtContext &fctx,
1205 OpClassOrAdaptor &opClass,
1206 const Operator &op, StringRef name,
1207 Attribute attr) {
1208 auto *method = opClass.addMethod(attr.getReturnType(), name);
1209 ERROR_IF_PRUNED(method, name, op);
1210 auto &body = method->body();
1211 body << " auto attr = " << name << "Attr();\n";
1212 if (attr.hasDefaultValue() && attr.isOptional()) {
1213 // Returns the default value if not set.
1214 // TODO: this is inefficient, we are recreating the attribute for every
1215 // call. This should be set instead.
1216 if (!attr.isConstBuildable()) {
1217 PrintFatalError("DefaultValuedAttr of type " + attr.getAttrDefName() +
1218 " must have a constBuilder");
1220 std::string defaultValue = std::string(
1221 tgfmt(attr.getConstBuilderTemplate(), &fctx, attr.getDefaultValue()));
1222 body << " if (!attr)\n return "
1223 << tgfmt(attr.getConvertFromStorageCall(),
1224 &fctx.withSelf(defaultValue))
1225 << ";\n";
1227 body << " return "
1228 << tgfmt(attr.getConvertFromStorageCall(), &fctx.withSelf("attr"))
1229 << ";\n";
1232 void OpEmitter::genPropertiesSupport() {
1233 if (!emitHelper.hasProperties())
1234 return;
1236 SmallVector<ConstArgument> attrOrProperties;
1237 for (const std::pair<StringRef, AttributeMetadata> &it :
1238 emitHelper.getAttrMetadata()) {
1239 if (!it.second.constraint || !it.second.constraint->isDerivedAttr())
1240 attrOrProperties.push_back(&it.second);
1242 for (const NamedProperty &prop : op.getProperties())
1243 attrOrProperties.push_back(&prop);
1244 if (emitHelper.getOperandSegmentsSize())
1245 attrOrProperties.push_back(&emitHelper.getOperandSegmentsSize().value());
1246 if (emitHelper.getResultSegmentsSize())
1247 attrOrProperties.push_back(&emitHelper.getResultSegmentsSize().value());
1248 if (attrOrProperties.empty())
1249 return;
1250 auto &setPropMethod =
1251 opClass
1252 .addStaticMethod(
1253 "::mlir::LogicalResult", "setPropertiesFromAttr",
1254 MethodParameter("Properties &", "prop"),
1255 MethodParameter("::mlir::Attribute", "attr"),
1256 MethodParameter(
1257 "::llvm::function_ref<::mlir::InFlightDiagnostic()>",
1258 "emitError"))
1259 ->body();
1260 auto &getPropMethod =
1261 opClass
1262 .addStaticMethod("::mlir::Attribute", "getPropertiesAsAttr",
1263 MethodParameter("::mlir::MLIRContext *", "ctx"),
1264 MethodParameter("const Properties &", "prop"))
1265 ->body();
1266 auto &hashMethod =
1267 opClass
1268 .addStaticMethod("llvm::hash_code", "computePropertiesHash",
1269 MethodParameter("const Properties &", "prop"))
1270 ->body();
1271 auto &getInherentAttrMethod =
1272 opClass
1273 .addStaticMethod("std::optional<mlir::Attribute>", "getInherentAttr",
1274 MethodParameter("::mlir::MLIRContext *", "ctx"),
1275 MethodParameter("const Properties &", "prop"),
1276 MethodParameter("llvm::StringRef", "name"))
1277 ->body();
1278 auto &setInherentAttrMethod =
1279 opClass
1280 .addStaticMethod("void", "setInherentAttr",
1281 MethodParameter("Properties &", "prop"),
1282 MethodParameter("llvm::StringRef", "name"),
1283 MethodParameter("mlir::Attribute", "value"))
1284 ->body();
1285 auto &populateInherentAttrsMethod =
1286 opClass
1287 .addStaticMethod("void", "populateInherentAttrs",
1288 MethodParameter("::mlir::MLIRContext *", "ctx"),
1289 MethodParameter("const Properties &", "prop"),
1290 MethodParameter("::mlir::NamedAttrList &", "attrs"))
1291 ->body();
1292 auto &verifyInherentAttrsMethod =
1293 opClass
1294 .addStaticMethod(
1295 "::mlir::LogicalResult", "verifyInherentAttrs",
1296 MethodParameter("::mlir::OperationName", "opName"),
1297 MethodParameter("::mlir::NamedAttrList &", "attrs"),
1298 MethodParameter(
1299 "llvm::function_ref<::mlir::InFlightDiagnostic()>",
1300 "emitError"))
1301 ->body();
1303 opClass.declare<UsingDeclaration>("Properties", "FoldAdaptor::Properties");
1305 // Convert the property to the attribute form.
1307 setPropMethod << R"decl(
1308 ::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr);
1309 if (!dict) {
1310 emitError() << "expected DictionaryAttr to set properties";
1311 return ::mlir::failure();
1313 )decl";
1314 // TODO: properties might be optional as well.
1315 const char *propFromAttrFmt = R"decl(;
1317 auto setFromAttr = [] (auto &propStorage, ::mlir::Attribute propAttr,
1318 ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) {{
1319 {0};
1321 {2};
1322 if (!attr) {{
1323 emitError() << "expected key entry for {1} in DictionaryAttr to set "
1324 "Properties.";
1325 return ::mlir::failure();
1327 if (::mlir::failed(setFromAttr(prop.{1}, attr, emitError)))
1328 return ::mlir::failure();
1330 )decl";
1332 for (const auto &attrOrProp : attrOrProperties) {
1333 if (const auto *namedProperty =
1334 llvm::dyn_cast_if_present<const NamedProperty *>(attrOrProp)) {
1335 StringRef name = namedProperty->name;
1336 auto &prop = namedProperty->prop;
1337 FmtContext fctx;
1339 std::string getAttr;
1340 llvm::raw_string_ostream os(getAttr);
1341 os << " auto attr = dict.get(\"" << name << "\");";
1342 if (name == operandSegmentAttrName) {
1343 // Backward compat for now, TODO: Remove at some point.
1344 os << " if (!attr) attr = dict.get(\"operand_segment_sizes\");";
1346 if (name == resultSegmentAttrName) {
1347 // Backward compat for now, TODO: Remove at some point.
1348 os << " if (!attr) attr = dict.get(\"result_segment_sizes\");";
1350 os.flush();
1352 setPropMethod << formatv(propFromAttrFmt,
1353 tgfmt(prop.getConvertFromAttributeCall(),
1354 &fctx.addSubst("_attr", propertyAttr)
1355 .addSubst("_storage", propertyStorage)
1356 .addSubst("_diag", propertyDiag)),
1357 name, getAttr);
1359 } else {
1360 const auto *namedAttr =
1361 llvm::dyn_cast_if_present<const AttributeMetadata *>(attrOrProp);
1362 StringRef name = namedAttr->attrName;
1363 std::string getAttr;
1364 llvm::raw_string_ostream os(getAttr);
1365 os << " auto attr = dict.get(\"" << name << "\");";
1366 if (name == operandSegmentAttrName) {
1367 // Backward compat for now
1368 os << " if (!attr) attr = dict.get(\"operand_segment_sizes\");";
1370 if (name == resultSegmentAttrName) {
1371 // Backward compat for now
1372 os << " if (!attr) attr = dict.get(\"result_segment_sizes\");";
1374 os.flush();
1376 setPropMethod << formatv(R"decl(
1378 auto &propStorage = prop.{0};
1380 if (attr || /*isRequired=*/{1}) {{
1381 if (!attr) {{
1382 emitError() << "expected key entry for {0} in DictionaryAttr to set "
1383 "Properties.";
1384 return ::mlir::failure();
1386 auto convertedAttr = ::llvm::dyn_cast<std::remove_reference_t<decltype(propStorage)>>(attr);
1387 if (convertedAttr) {{
1388 propStorage = convertedAttr;
1389 } else {{
1390 emitError() << "Invalid attribute `{0}` in property conversion: " << attr;
1391 return ::mlir::failure();
1395 )decl",
1396 name, namedAttr->isRequired, getAttr);
1399 setPropMethod << " return ::mlir::success();\n";
1401 // Convert the attribute form to the property.
1403 getPropMethod << " ::mlir::SmallVector<::mlir::NamedAttribute> attrs;\n"
1404 << " ::mlir::Builder odsBuilder{ctx};\n";
1405 const char *propToAttrFmt = R"decl(
1407 const auto &propStorage = prop.{0};
1408 attrs.push_back(odsBuilder.getNamedAttr("{0}",
1409 {1}));
1411 )decl";
1412 for (const auto &attrOrProp : attrOrProperties) {
1413 if (const auto *namedProperty =
1414 llvm::dyn_cast_if_present<const NamedProperty *>(attrOrProp)) {
1415 StringRef name = namedProperty->name;
1416 auto &prop = namedProperty->prop;
1417 FmtContext fctx;
1418 getPropMethod << formatv(
1419 propToAttrFmt, name,
1420 tgfmt(prop.getConvertToAttributeCall(),
1421 &fctx.addSubst("_ctxt", "ctx")
1422 .addSubst("_storage", propertyStorage)));
1423 continue;
1425 const auto *namedAttr =
1426 llvm::dyn_cast_if_present<const AttributeMetadata *>(attrOrProp);
1427 StringRef name = namedAttr->attrName;
1428 getPropMethod << formatv(R"decl(
1430 const auto &propStorage = prop.{0};
1431 if (propStorage)
1432 attrs.push_back(odsBuilder.getNamedAttr("{0}",
1433 propStorage));
1435 )decl",
1436 name);
1438 getPropMethod << R"decl(
1439 if (!attrs.empty())
1440 return odsBuilder.getDictionaryAttr(attrs);
1441 return {};
1442 )decl";
1444 // Hashing for the property
1446 const char *propHashFmt = R"decl(
1447 auto hash_{0} = [] (const auto &propStorage) -> llvm::hash_code {
1448 return {1};
1450 )decl";
1451 for (const auto &attrOrProp : attrOrProperties) {
1452 if (const auto *namedProperty =
1453 llvm::dyn_cast_if_present<const NamedProperty *>(attrOrProp)) {
1454 StringRef name = namedProperty->name;
1455 auto &prop = namedProperty->prop;
1456 FmtContext fctx;
1457 hashMethod << formatv(propHashFmt, name,
1458 tgfmt(prop.getHashPropertyCall(),
1459 &fctx.addSubst("_storage", propertyStorage)));
1462 hashMethod << " return llvm::hash_combine(";
1463 llvm::interleaveComma(
1464 attrOrProperties, hashMethod, [&](const ConstArgument &attrOrProp) {
1465 if (const auto *namedProperty =
1466 llvm::dyn_cast_if_present<const NamedProperty *>(attrOrProp)) {
1467 hashMethod << "\n hash_" << namedProperty->name << "(prop."
1468 << namedProperty->name << ")";
1469 return;
1471 const auto *namedAttr =
1472 llvm::dyn_cast_if_present<const AttributeMetadata *>(attrOrProp);
1473 StringRef name = namedAttr->attrName;
1474 hashMethod << "\n llvm::hash_value(prop." << name
1475 << ".getAsOpaquePointer())";
1477 hashMethod << ");\n";
1479 const char *getInherentAttrMethodFmt = R"decl(
1480 if (name == "{0}")
1481 return prop.{0};
1482 )decl";
1483 const char *setInherentAttrMethodFmt = R"decl(
1484 if (name == "{0}") {{
1485 prop.{0} = ::llvm::dyn_cast_or_null<std::remove_reference_t<decltype(prop.{0})>>(value);
1486 return;
1488 )decl";
1489 const char *populateInherentAttrsMethodFmt = R"decl(
1490 if (prop.{0}) attrs.append("{0}", prop.{0});
1491 )decl";
1492 for (const auto &attrOrProp : attrOrProperties) {
1493 if (const auto *namedAttr =
1494 llvm::dyn_cast_if_present<const AttributeMetadata *>(attrOrProp)) {
1495 StringRef name = namedAttr->attrName;
1496 getInherentAttrMethod << formatv(getInherentAttrMethodFmt, name);
1497 setInherentAttrMethod << formatv(setInherentAttrMethodFmt, name);
1498 populateInherentAttrsMethod
1499 << formatv(populateInherentAttrsMethodFmt, name);
1500 continue;
1502 // The ODS segment size property is "special": we expose it as an attribute
1503 // even though it is a native property.
1504 const auto *namedProperty = cast<const NamedProperty *>(attrOrProp);
1505 StringRef name = namedProperty->name;
1506 if (name != operandSegmentAttrName && name != resultSegmentAttrName)
1507 continue;
1508 auto &prop = namedProperty->prop;
1509 FmtContext fctx;
1510 fctx.addSubst("_ctxt", "ctx");
1511 fctx.addSubst("_storage", Twine("prop.") + name);
1512 if (name == operandSegmentAttrName) {
1513 getInherentAttrMethod
1514 << formatv(" if (name == \"operand_segment_sizes\" || name == "
1515 "\"{0}\") return ",
1516 operandSegmentAttrName);
1517 } else {
1518 getInherentAttrMethod
1519 << formatv(" if (name == \"result_segment_sizes\" || name == "
1520 "\"{0}\") return ",
1521 resultSegmentAttrName);
1523 getInherentAttrMethod << tgfmt(prop.getConvertToAttributeCall(), &fctx)
1524 << ";\n";
1526 if (name == operandSegmentAttrName) {
1527 setInherentAttrMethod
1528 << formatv(" if (name == \"operand_segment_sizes\" || name == "
1529 "\"{0}\") {{",
1530 operandSegmentAttrName);
1531 } else {
1532 setInherentAttrMethod
1533 << formatv(" if (name == \"result_segment_sizes\" || name == "
1534 "\"{0}\") {{",
1535 resultSegmentAttrName);
1537 setInherentAttrMethod << formatv(R"decl(
1538 auto arrAttr = ::llvm::dyn_cast_or_null<::mlir::DenseI32ArrayAttr>(value);
1539 if (!arrAttr) return;
1540 if (arrAttr.size() != sizeof(prop.{0}) / sizeof(int32_t))
1541 return;
1542 llvm::copy(arrAttr.asArrayRef(), prop.{0}.begin());
1543 return;
1545 )decl",
1546 name);
1547 if (name == operandSegmentAttrName) {
1548 populateInherentAttrsMethod
1549 << formatv(" attrs.append(\"{0}\", {1});\n", operandSegmentAttrName,
1550 tgfmt(prop.getConvertToAttributeCall(), &fctx));
1551 } else {
1552 populateInherentAttrsMethod
1553 << formatv(" attrs.append(\"{0}\", {1});\n", resultSegmentAttrName,
1554 tgfmt(prop.getConvertToAttributeCall(), &fctx));
1557 getInherentAttrMethod << " return std::nullopt;\n";
1559 // Emit the verifiers method for backward compatibility with the generic
1560 // syntax. This method verifies the constraint on the properties attributes
1561 // before they are set, since dyn_cast<> will silently omit failures.
1562 for (const auto &attrOrProp : attrOrProperties) {
1563 const auto *namedAttr =
1564 llvm::dyn_cast_if_present<const AttributeMetadata *>(attrOrProp);
1565 if (!namedAttr || !namedAttr->constraint)
1566 continue;
1567 Attribute attr = *namedAttr->constraint;
1568 std::optional<StringRef> constraintFn =
1569 staticVerifierEmitter.getAttrConstraintFn(attr);
1570 if (!constraintFn)
1571 continue;
1572 if (canEmitAttrVerifier(attr,
1573 /*isEmittingForOp=*/false)) {
1574 std::string name = op.getGetterName(namedAttr->attrName);
1575 verifyInherentAttrsMethod
1576 << formatv(R"(
1578 ::mlir::Attribute attr = attrs.get({0}AttrName(opName));
1579 if (attr && ::mlir::failed({1}(attr, "{2}", emitError)))
1580 return ::mlir::failure();
1583 name, constraintFn, namedAttr->attrName);
1586 verifyInherentAttrsMethod << " return ::mlir::success();";
1588 // Generate methods to interact with bytecode.
1589 genPropertiesSupportForBytecode(attrOrProperties);
1592 void OpEmitter::genPropertiesSupportForBytecode(
1593 ArrayRef<ConstArgument> attrOrProperties) {
1594 if (op.useCustomPropertiesEncoding()) {
1595 opClass.declareStaticMethod(
1596 "::mlir::LogicalResult", "readProperties",
1597 MethodParameter("::mlir::DialectBytecodeReader &", "reader"),
1598 MethodParameter("::mlir::OperationState &", "state"));
1599 opClass.declareMethod(
1600 "void", "writeProperties",
1601 MethodParameter("::mlir::DialectBytecodeWriter &", "writer"));
1602 return;
1605 auto &readPropertiesMethod =
1606 opClass
1607 .addStaticMethod(
1608 "::mlir::LogicalResult", "readProperties",
1609 MethodParameter("::mlir::DialectBytecodeReader &", "reader"),
1610 MethodParameter("::mlir::OperationState &", "state"))
1611 ->body();
1613 auto &writePropertiesMethod =
1614 opClass
1615 .addMethod(
1616 "void", "writeProperties",
1617 MethodParameter("::mlir::DialectBytecodeWriter &", "writer"))
1618 ->body();
1620 // Populate bytecode serialization logic.
1621 readPropertiesMethod
1622 << " auto &prop = state.getOrAddProperties<Properties>(); (void)prop;";
1623 writePropertiesMethod << " auto &prop = getProperties(); (void)prop;\n";
1624 for (const auto &item : llvm::enumerate(attrOrProperties)) {
1625 auto &attrOrProp = item.value();
1626 FmtContext fctx;
1627 fctx.addSubst("_reader", "reader")
1628 .addSubst("_writer", "writer")
1629 .addSubst("_storage", propertyStorage)
1630 .addSubst("_ctxt", "this->getContext()");
1631 // If the op emits operand/result segment sizes as a property, emit the
1632 // legacy reader/writer in the appropriate order to allow backward
1633 // compatibility and back deployment.
1634 if (emitHelper.getOperandSegmentsSize().has_value() &&
1635 item.index() == emitHelper.getOperandSegmentSizesLegacyIndex()) {
1636 FmtContext fmtCtxt(fctx);
1637 fmtCtxt.addSubst("_propName", operandSegmentAttrName);
1638 readPropertiesMethod << tgfmt(readBytecodeSegmentSizeLegacy, &fmtCtxt);
1639 writePropertiesMethod << tgfmt(writeBytecodeSegmentSizeLegacy, &fmtCtxt);
1641 if (emitHelper.getResultSegmentsSize().has_value() &&
1642 item.index() == emitHelper.getResultSegmentSizesLegacyIndex()) {
1643 FmtContext fmtCtxt(fctx);
1644 fmtCtxt.addSubst("_propName", resultSegmentAttrName);
1645 readPropertiesMethod << tgfmt(readBytecodeSegmentSizeLegacy, &fmtCtxt);
1646 writePropertiesMethod << tgfmt(writeBytecodeSegmentSizeLegacy, &fmtCtxt);
1648 if (const auto *namedProperty =
1649 attrOrProp.dyn_cast<const NamedProperty *>()) {
1650 StringRef name = namedProperty->name;
1651 readPropertiesMethod << formatv(
1654 auto &propStorage = prop.{0};
1655 auto readProp = [&]() {
1656 {1};
1657 return ::mlir::success();
1659 if (::mlir::failed(readProp()))
1660 return ::mlir::failure();
1663 name,
1664 tgfmt(namedProperty->prop.getReadFromMlirBytecodeCall(), &fctx));
1665 writePropertiesMethod << formatv(
1668 auto &propStorage = prop.{0};
1669 {1};
1672 name, tgfmt(namedProperty->prop.getWriteToMlirBytecodeCall(), &fctx));
1673 continue;
1675 const auto *namedAttr = attrOrProp.dyn_cast<const AttributeMetadata *>();
1676 StringRef name = namedAttr->attrName;
1677 if (namedAttr->isRequired) {
1678 readPropertiesMethod << formatv(R"(
1679 if (::mlir::failed(reader.readAttribute(prop.{0})))
1680 return ::mlir::failure();
1682 name);
1683 writePropertiesMethod
1684 << formatv(" writer.writeAttribute(prop.{0});\n", name);
1685 } else {
1686 readPropertiesMethod << formatv(R"(
1687 if (::mlir::failed(reader.readOptionalAttribute(prop.{0})))
1688 return ::mlir::failure();
1690 name);
1691 writePropertiesMethod << formatv(R"(
1692 writer.writeOptionalAttribute(prop.{0});
1694 name);
1697 readPropertiesMethod << " return ::mlir::success();";
1700 void OpEmitter::genAttrGetters() {
1701 FmtContext fctx;
1702 fctx.withBuilder("::mlir::Builder((*this)->getContext())");
1704 // Emit the derived attribute body.
1705 auto emitDerivedAttr = [&](StringRef name, Attribute attr) {
1706 if (auto *method = opClass.addMethod(attr.getReturnType(), name))
1707 method->body() << " " << attr.getDerivedCodeBody() << "\n";
1710 // Generate named accessor with Attribute return type. This is a wrapper
1711 // class that allows referring to the attributes via accessors instead of
1712 // having to use the string interface for better compile time verification.
1713 auto emitAttrWithStorageType = [&](StringRef name, StringRef attrName,
1714 Attribute attr) {
1715 auto *method = opClass.addMethod(attr.getStorageType(), name + "Attr");
1716 if (!method)
1717 return;
1718 method->body() << formatv(
1719 " return ::llvm::{1}<{2}>({0});", emitHelper.getAttr(attrName),
1720 attr.isOptional() || attr.hasDefaultValue() ? "dyn_cast_or_null"
1721 : "cast",
1722 attr.getStorageType());
1725 for (const NamedAttribute &namedAttr : op.getAttributes()) {
1726 std::string name = op.getGetterName(namedAttr.name);
1727 if (namedAttr.attr.isDerivedAttr()) {
1728 emitDerivedAttr(name, namedAttr.attr);
1729 } else {
1730 emitAttrWithStorageType(name, namedAttr.name, namedAttr.attr);
1731 emitAttrGetterWithReturnType(fctx, opClass, op, name, namedAttr.attr);
1735 auto derivedAttrs = make_filter_range(op.getAttributes(),
1736 [](const NamedAttribute &namedAttr) {
1737 return namedAttr.attr.isDerivedAttr();
1739 if (derivedAttrs.empty())
1740 return;
1742 opClass.addTrait("::mlir::DerivedAttributeOpInterface::Trait");
1743 // Generate helper method to query whether a named attribute is a derived
1744 // attribute. This enables, for example, avoiding adding an attribute that
1745 // overlaps with a derived attribute.
1747 auto *method =
1748 opClass.addStaticMethod("bool", "isDerivedAttribute",
1749 MethodParameter("::llvm::StringRef", "name"));
1750 ERROR_IF_PRUNED(method, "isDerivedAttribute", op);
1751 auto &body = method->body();
1752 for (auto namedAttr : derivedAttrs)
1753 body << " if (name == \"" << namedAttr.name << "\") return true;\n";
1754 body << " return false;";
1756 // Generate method to materialize derived attributes as a DictionaryAttr.
1758 auto *method = opClass.addMethod("::mlir::DictionaryAttr",
1759 "materializeDerivedAttributes");
1760 ERROR_IF_PRUNED(method, "materializeDerivedAttributes", op);
1761 auto &body = method->body();
1763 auto nonMaterializable =
1764 make_filter_range(derivedAttrs, [](const NamedAttribute &namedAttr) {
1765 return namedAttr.attr.getConvertFromStorageCall().empty();
1767 if (!nonMaterializable.empty()) {
1768 std::string attrs;
1769 llvm::raw_string_ostream os(attrs);
1770 interleaveComma(nonMaterializable, os, [&](const NamedAttribute &attr) {
1771 os << op.getGetterName(attr.name);
1773 PrintWarning(
1774 op.getLoc(),
1775 formatv(
1776 "op has non-materializable derived attributes '{0}', skipping",
1777 os.str()));
1778 body << formatv(" emitOpError(\"op has non-materializable derived "
1779 "attributes '{0}'\");\n",
1780 attrs);
1781 body << " return nullptr;";
1782 return;
1785 body << " ::mlir::MLIRContext* ctx = getContext();\n";
1786 body << " ::mlir::Builder odsBuilder(ctx); (void)odsBuilder;\n";
1787 body << " return ::mlir::DictionaryAttr::get(";
1788 body << " ctx, {\n";
1789 interleave(
1790 derivedAttrs, body,
1791 [&](const NamedAttribute &namedAttr) {
1792 auto tmpl = namedAttr.attr.getConvertFromStorageCall();
1793 std::string name = op.getGetterName(namedAttr.name);
1794 body << " {" << name << "AttrName(),\n"
1795 << tgfmt(tmpl, &fctx.withSelf(name + "()")
1796 .withBuilder("odsBuilder")
1797 .addSubst("_ctxt", "ctx")
1798 .addSubst("_storage", "ctx"))
1799 << "}";
1801 ",\n");
1802 body << "});";
1806 void OpEmitter::genAttrSetters() {
1807 // Generate raw named setter type. This is a wrapper class that allows setting
1808 // to the attributes via setters instead of having to use the string interface
1809 // for better compile time verification.
1810 auto emitAttrWithStorageType = [&](StringRef setterName, StringRef getterName,
1811 Attribute attr) {
1812 auto *method =
1813 opClass.addMethod("void", setterName + "Attr",
1814 MethodParameter(attr.getStorageType(), "attr"));
1815 if (method)
1816 method->body() << formatv(" (*this)->setAttr({0}AttrName(), attr);",
1817 getterName);
1820 // Generate a setter that accepts the underlying C++ type as opposed to the
1821 // attribute type.
1822 auto emitAttrWithReturnType = [&](StringRef setterName, StringRef getterName,
1823 Attribute attr) {
1824 Attribute baseAttr = attr.getBaseAttr();
1825 if (!canUseUnwrappedRawValue(baseAttr))
1826 return;
1827 FmtContext fctx;
1828 fctx.withBuilder("::mlir::Builder((*this)->getContext())");
1829 bool isUnitAttr = attr.getAttrDefName() == "UnitAttr";
1830 bool isOptional = attr.isOptional();
1832 auto createMethod = [&](const Twine &paramType) {
1833 return opClass.addMethod("void", setterName,
1834 MethodParameter(paramType.str(), "attrValue"));
1837 // Build the method using the correct parameter type depending on
1838 // optionality.
1839 Method *method = nullptr;
1840 if (isUnitAttr)
1841 method = createMethod("bool");
1842 else if (isOptional)
1843 method =
1844 createMethod("::std::optional<" + baseAttr.getReturnType() + ">");
1845 else
1846 method = createMethod(attr.getReturnType());
1847 if (!method)
1848 return;
1850 // If the value isn't optional, just set it directly.
1851 if (!isOptional) {
1852 method->body() << formatv(
1853 " (*this)->setAttr({0}AttrName(), {1});", getterName,
1854 constBuildAttrFromParam(attr, fctx, "attrValue"));
1855 return;
1858 // Otherwise, we only set if the provided value is valid. If it isn't, we
1859 // remove the attribute.
1861 // TODO: Handle unit attr parameters specially, given that it is treated as
1862 // optional but not in the same way as the others (i.e. it uses bool over
1863 // std::optional<>).
1864 StringRef paramStr = isUnitAttr ? "attrValue" : "*attrValue";
1865 const char *optionalCodeBody = R"(
1866 if (attrValue)
1867 return (*this)->setAttr({0}AttrName(), {1});
1868 (*this)->removeAttr({0}AttrName());)";
1869 method->body() << formatv(
1870 optionalCodeBody, getterName,
1871 constBuildAttrFromParam(baseAttr, fctx, paramStr));
1874 for (const NamedAttribute &namedAttr : op.getAttributes()) {
1875 if (namedAttr.attr.isDerivedAttr())
1876 continue;
1877 std::string setterName = op.getSetterName(namedAttr.name);
1878 std::string getterName = op.getGetterName(namedAttr.name);
1879 emitAttrWithStorageType(setterName, getterName, namedAttr.attr);
1880 emitAttrWithReturnType(setterName, getterName, namedAttr.attr);
1884 void OpEmitter::genOptionalAttrRemovers() {
1885 // Generate methods for removing optional attributes, instead of having to
1886 // use the string interface. Enables better compile time verification.
1887 auto emitRemoveAttr = [&](StringRef name, bool useProperties) {
1888 auto upperInitial = name.take_front().upper();
1889 auto *method = opClass.addMethod("::mlir::Attribute",
1890 op.getRemoverName(name) + "Attr");
1891 if (!method)
1892 return;
1893 if (useProperties) {
1894 method->body() << formatv(R"(
1895 auto &attr = getProperties().{0};
1896 attr = {{};
1897 return attr;
1899 name);
1900 return;
1902 method->body() << formatv("return (*this)->removeAttr({0}AttrName());",
1903 op.getGetterName(name));
1906 for (const NamedAttribute &namedAttr : op.getAttributes())
1907 if (namedAttr.attr.isOptional())
1908 emitRemoveAttr(namedAttr.name,
1909 op.getDialect().usePropertiesForAttributes());
1912 // Generates the code to compute the start and end index of an operand or result
1913 // range.
1914 template <typename RangeT>
1915 static void generateValueRangeStartAndEnd(
1916 Class &opClass, bool isGenericAdaptorBase, StringRef methodName,
1917 int numVariadic, int numNonVariadic, StringRef rangeSizeCall,
1918 bool hasAttrSegmentSize, StringRef sizeAttrInit, RangeT &&odsValues) {
1920 SmallVector<MethodParameter> parameters{MethodParameter("unsigned", "index")};
1921 if (isGenericAdaptorBase) {
1922 parameters.emplace_back("unsigned", "odsOperandsSize");
1923 // The range size is passed per parameter for generic adaptor bases as
1924 // using the rangeSizeCall would require the operands, which are not
1925 // accessible in the base class.
1926 rangeSizeCall = "odsOperandsSize";
1929 auto *method = opClass.addMethod("std::pair<unsigned, unsigned>", methodName,
1930 parameters);
1931 if (!method)
1932 return;
1933 auto &body = method->body();
1934 if (numVariadic == 0) {
1935 body << " return {index, 1};\n";
1936 } else if (hasAttrSegmentSize) {
1937 body << sizeAttrInit << attrSizedSegmentValueRangeCalcCode;
1938 } else {
1939 // Because the op can have arbitrarily interleaved variadic and non-variadic
1940 // operands, we need to embed a list in the "sink" getter method for
1941 // calculation at run-time.
1942 SmallVector<StringRef, 4> isVariadic;
1943 isVariadic.reserve(llvm::size(odsValues));
1944 for (auto &it : odsValues)
1945 isVariadic.push_back(it.isVariableLength() ? "true" : "false");
1946 std::string isVariadicList = llvm::join(isVariadic, ", ");
1947 body << formatv(sameVariadicSizeValueRangeCalcCode, isVariadicList,
1948 numNonVariadic, numVariadic, rangeSizeCall, "operand");
1952 static std::string generateTypeForGetter(const NamedTypeConstraint &value) {
1953 std::string str = "::mlir::Value";
1954 /// If the CPPClassName is not a fully qualified type. Uses of types
1955 /// across Dialect fail because they are not in the correct namespace. So we
1956 /// dont generate TypedValue unless the type is fully qualified.
1957 /// getCPPClassName doesn't return the fully qualified path for
1958 /// `mlir::pdl::OperationType` see
1959 /// https://github.com/llvm/llvm-project/issues/57279.
1960 /// Adaptor will have values that are not from the type of their operation and
1961 /// this is expected, so we dont generate TypedValue for Adaptor
1962 if (value.constraint.getCPPClassName() != "::mlir::Type" &&
1963 StringRef(value.constraint.getCPPClassName()).starts_with("::"))
1964 str = llvm::formatv("::mlir::TypedValue<{0}>",
1965 value.constraint.getCPPClassName())
1966 .str();
1967 return str;
1970 // Generates the named operand getter methods for the given Operator `op` and
1971 // puts them in `opClass`. Uses `rangeType` as the return type of getters that
1972 // return a range of operands (individual operands are `Value ` and each
1973 // element in the range must also be `Value `); use `rangeBeginCall` to get
1974 // an iterator to the beginning of the operand range; use `rangeSizeCall` to
1975 // obtain the number of operands. `getOperandCallPattern` contains the code
1976 // necessary to obtain a single operand whose position will be substituted
1977 // instead of
1978 // "{0}" marker in the pattern. Note that the pattern should work for any kind
1979 // of ops, in particular for one-operand ops that may not have the
1980 // `getOperand(unsigned)` method.
1981 static void
1982 generateNamedOperandGetters(const Operator &op, Class &opClass,
1983 Class *genericAdaptorBase, StringRef sizeAttrInit,
1984 StringRef rangeType, StringRef rangeElementType,
1985 StringRef rangeBeginCall, StringRef rangeSizeCall,
1986 StringRef getOperandCallPattern) {
1987 const int numOperands = op.getNumOperands();
1988 const int numVariadicOperands = op.getNumVariableLengthOperands();
1989 const int numNormalOperands = numOperands - numVariadicOperands;
1991 const auto *sameVariadicSize =
1992 op.getTrait("::mlir::OpTrait::SameVariadicOperandSize");
1993 const auto *attrSizedOperands =
1994 op.getTrait("::mlir::OpTrait::AttrSizedOperandSegments");
1996 if (numVariadicOperands > 1 && !sameVariadicSize && !attrSizedOperands) {
1997 PrintFatalError(op.getLoc(), "op has multiple variadic operands but no "
1998 "specification over their sizes");
2001 if (numVariadicOperands < 2 && attrSizedOperands) {
2002 PrintFatalError(op.getLoc(), "op must have at least two variadic operands "
2003 "to use 'AttrSizedOperandSegments' trait");
2006 if (attrSizedOperands && sameVariadicSize) {
2007 PrintFatalError(op.getLoc(),
2008 "op cannot have both 'AttrSizedOperandSegments' and "
2009 "'SameVariadicOperandSize' traits");
2012 // First emit a few "sink" getter methods upon which we layer all nicer named
2013 // getter methods.
2014 // If generating for an adaptor, the method is put into the non-templated
2015 // generic base class, to not require being defined in the header.
2016 // Since the operand size can't be determined from the base class however,
2017 // it has to be passed as an additional argument. The trampoline below
2018 // generates the function with the same signature as the Op in the generic
2019 // adaptor.
2020 bool isGenericAdaptorBase = genericAdaptorBase != nullptr;
2021 generateValueRangeStartAndEnd(
2022 /*opClass=*/isGenericAdaptorBase ? *genericAdaptorBase : opClass,
2023 isGenericAdaptorBase,
2024 /*methodName=*/"getODSOperandIndexAndLength", numVariadicOperands,
2025 numNormalOperands, rangeSizeCall, attrSizedOperands, sizeAttrInit,
2026 const_cast<Operator &>(op).getOperands());
2027 if (isGenericAdaptorBase) {
2028 // Generate trampoline for calling 'getODSOperandIndexAndLength' with just
2029 // the index. This just calls the implementation in the base class but
2030 // passes the operand size as parameter.
2031 Method *method = opClass.addMethod("std::pair<unsigned, unsigned>",
2032 "getODSOperandIndexAndLength",
2033 MethodParameter("unsigned", "index"));
2034 ERROR_IF_PRUNED(method, "getODSOperandIndexAndLength", op);
2035 MethodBody &body = method->body();
2036 body.indent() << formatv(
2037 "return Base::getODSOperandIndexAndLength(index, {0});", rangeSizeCall);
2040 auto *m = opClass.addMethod(rangeType, "getODSOperands",
2041 MethodParameter("unsigned", "index"));
2042 ERROR_IF_PRUNED(m, "getODSOperands", op);
2043 auto &body = m->body();
2044 body << formatv(valueRangeReturnCode, rangeBeginCall,
2045 "getODSOperandIndexAndLength(index)");
2047 // Then we emit nicer named getter methods by redirecting to the "sink" getter
2048 // method.
2049 for (int i = 0; i != numOperands; ++i) {
2050 const auto &operand = op.getOperand(i);
2051 if (operand.name.empty())
2052 continue;
2053 std::string name = op.getGetterName(operand.name);
2054 if (operand.isOptional()) {
2055 m = opClass.addMethod(isGenericAdaptorBase
2056 ? rangeElementType
2057 : generateTypeForGetter(operand),
2058 name);
2059 ERROR_IF_PRUNED(m, name, op);
2060 m->body().indent() << formatv("auto operands = getODSOperands({0});\n"
2061 "return operands.empty() ? {1}{{} : ",
2062 i, m->getReturnType());
2063 if (!isGenericAdaptorBase)
2064 m->body() << llvm::formatv("::llvm::cast<{0}>", m->getReturnType());
2065 m->body() << "(*operands.begin());";
2066 } else if (operand.isVariadicOfVariadic()) {
2067 std::string segmentAttr = op.getGetterName(
2068 operand.constraint.getVariadicOfVariadicSegmentSizeAttr());
2069 if (genericAdaptorBase) {
2070 m = opClass.addMethod("::llvm::SmallVector<" + rangeType + ">", name);
2071 ERROR_IF_PRUNED(m, name, op);
2072 m->body() << llvm::formatv(variadicOfVariadicAdaptorCalcCode,
2073 segmentAttr, i, rangeType);
2074 continue;
2077 m = opClass.addMethod("::mlir::OperandRangeRange", name);
2078 ERROR_IF_PRUNED(m, name, op);
2079 m->body() << " return getODSOperands(" << i << ").split(" << segmentAttr
2080 << "Attr());";
2081 } else if (operand.isVariadic()) {
2082 m = opClass.addMethod(rangeType, name);
2083 ERROR_IF_PRUNED(m, name, op);
2084 m->body() << " return getODSOperands(" << i << ");";
2085 } else {
2086 m = opClass.addMethod(isGenericAdaptorBase
2087 ? rangeElementType
2088 : generateTypeForGetter(operand),
2089 name);
2090 ERROR_IF_PRUNED(m, name, op);
2091 m->body().indent() << "return ";
2092 if (!isGenericAdaptorBase)
2093 m->body() << llvm::formatv("::llvm::cast<{0}>", m->getReturnType());
2094 m->body() << llvm::formatv("(*getODSOperands({0}).begin());", i);
2099 void OpEmitter::genNamedOperandGetters() {
2100 // Build the code snippet used for initializing the operand_segment_size)s
2101 // array.
2102 std::string attrSizeInitCode;
2103 if (op.getTrait("::mlir::OpTrait::AttrSizedOperandSegments")) {
2104 if (op.getDialect().usePropertiesForAttributes())
2105 attrSizeInitCode = formatv(adapterSegmentSizeAttrInitCodeProperties,
2106 "getProperties().operandSegmentSizes");
2108 else
2109 attrSizeInitCode = formatv(opSegmentSizeAttrInitCode,
2110 emitHelper.getAttr(operandSegmentAttrName));
2113 generateNamedOperandGetters(
2114 op, opClass,
2115 /*genericAdaptorBase=*/nullptr,
2116 /*sizeAttrInit=*/attrSizeInitCode,
2117 /*rangeType=*/"::mlir::Operation::operand_range",
2118 /*rangeElementType=*/"::mlir::Value",
2119 /*rangeBeginCall=*/"getOperation()->operand_begin()",
2120 /*rangeSizeCall=*/"getOperation()->getNumOperands()",
2121 /*getOperandCallPattern=*/"getOperation()->getOperand({0})");
2124 void OpEmitter::genNamedOperandSetters() {
2125 auto *attrSizedOperands =
2126 op.getTrait("::mlir::OpTrait::AttrSizedOperandSegments");
2127 for (int i = 0, e = op.getNumOperands(); i != e; ++i) {
2128 const auto &operand = op.getOperand(i);
2129 if (operand.name.empty())
2130 continue;
2131 std::string name = op.getGetterName(operand.name);
2133 StringRef returnType;
2134 if (operand.isVariadicOfVariadic()) {
2135 returnType = "::mlir::MutableOperandRangeRange";
2136 } else if (operand.isVariableLength()) {
2137 returnType = "::mlir::MutableOperandRange";
2138 } else {
2139 returnType = "::mlir::OpOperand &";
2141 auto *m = opClass.addMethod(returnType, name + "Mutable");
2142 ERROR_IF_PRUNED(m, name, op);
2143 auto &body = m->body();
2144 body << " auto range = getODSOperandIndexAndLength(" << i << ");\n";
2146 if (!operand.isVariadicOfVariadic() && !operand.isVariableLength()) {
2147 // In case of a single operand, return a single OpOperand.
2148 body << " return getOperation()->getOpOperand(range.first);\n";
2149 continue;
2152 body << " auto mutableRange = "
2153 "::mlir::MutableOperandRange(getOperation(), "
2154 "range.first, range.second";
2155 if (attrSizedOperands) {
2156 if (emitHelper.hasProperties())
2157 body << formatv(", ::mlir::MutableOperandRange::OperandSegment({0}u, "
2158 "{{getOperandSegmentSizesAttrName(), "
2159 "::mlir::DenseI32ArrayAttr::get(getContext(), "
2160 "getProperties().operandSegmentSizes)})",
2162 else
2163 body << formatv(
2164 ", ::mlir::MutableOperandRange::OperandSegment({0}u, *{1})", i,
2165 emitHelper.getAttr(operandSegmentAttrName, /*isNamed=*/true));
2167 body << ");\n";
2169 // If this operand is a nested variadic, we split the range into a
2170 // MutableOperandRangeRange that provides a range over all of the
2171 // sub-ranges.
2172 if (operand.isVariadicOfVariadic()) {
2173 body << " return "
2174 "mutableRange.split(*(*this)->getAttrDictionary().getNamed("
2175 << op.getGetterName(
2176 operand.constraint.getVariadicOfVariadicSegmentSizeAttr())
2177 << "AttrName()));\n";
2178 } else {
2179 // Otherwise, we use the full range directly.
2180 body << " return mutableRange;\n";
2185 void OpEmitter::genNamedResultGetters() {
2186 const int numResults = op.getNumResults();
2187 const int numVariadicResults = op.getNumVariableLengthResults();
2188 const int numNormalResults = numResults - numVariadicResults;
2190 // If we have more than one variadic results, we need more complicated logic
2191 // to calculate the value range for each result.
2193 const auto *sameVariadicSize =
2194 op.getTrait("::mlir::OpTrait::SameVariadicResultSize");
2195 const auto *attrSizedResults =
2196 op.getTrait("::mlir::OpTrait::AttrSizedResultSegments");
2198 if (numVariadicResults > 1 && !sameVariadicSize && !attrSizedResults) {
2199 PrintFatalError(op.getLoc(), "op has multiple variadic results but no "
2200 "specification over their sizes");
2203 if (numVariadicResults < 2 && attrSizedResults) {
2204 PrintFatalError(op.getLoc(), "op must have at least two variadic results "
2205 "to use 'AttrSizedResultSegments' trait");
2208 if (attrSizedResults && sameVariadicSize) {
2209 PrintFatalError(op.getLoc(),
2210 "op cannot have both 'AttrSizedResultSegments' and "
2211 "'SameVariadicResultSize' traits");
2214 // Build the initializer string for the result segment size attribute.
2215 std::string attrSizeInitCode;
2216 if (attrSizedResults) {
2217 if (op.getDialect().usePropertiesForAttributes())
2218 attrSizeInitCode = formatv(adapterSegmentSizeAttrInitCodeProperties,
2219 "getProperties().resultSegmentSizes");
2221 else
2222 attrSizeInitCode = formatv(opSegmentSizeAttrInitCode,
2223 emitHelper.getAttr(resultSegmentAttrName));
2226 generateValueRangeStartAndEnd(
2227 opClass, /*isGenericAdaptorBase=*/false, "getODSResultIndexAndLength",
2228 numVariadicResults, numNormalResults, "getOperation()->getNumResults()",
2229 attrSizedResults, attrSizeInitCode, op.getResults());
2231 auto *m =
2232 opClass.addMethod("::mlir::Operation::result_range", "getODSResults",
2233 MethodParameter("unsigned", "index"));
2234 ERROR_IF_PRUNED(m, "getODSResults", op);
2235 m->body() << formatv(valueRangeReturnCode, "getOperation()->result_begin()",
2236 "getODSResultIndexAndLength(index)");
2238 for (int i = 0; i != numResults; ++i) {
2239 const auto &result = op.getResult(i);
2240 if (result.name.empty())
2241 continue;
2242 std::string name = op.getGetterName(result.name);
2243 if (result.isOptional()) {
2244 m = opClass.addMethod(generateTypeForGetter(result), name);
2245 ERROR_IF_PRUNED(m, name, op);
2246 m->body() << " auto results = getODSResults(" << i << ");\n"
2247 << llvm::formatv(" return results.empty()"
2248 " ? {0}()"
2249 " : ::llvm::cast<{0}>(*results.begin());",
2250 m->getReturnType());
2251 } else if (result.isVariadic()) {
2252 m = opClass.addMethod("::mlir::Operation::result_range", name);
2253 ERROR_IF_PRUNED(m, name, op);
2254 m->body() << " return getODSResults(" << i << ");";
2255 } else {
2256 m = opClass.addMethod(generateTypeForGetter(result), name);
2257 ERROR_IF_PRUNED(m, name, op);
2258 m->body() << llvm::formatv(
2259 " return ::llvm::cast<{0}>(*getODSResults({1}).begin());",
2260 m->getReturnType(), i);
2265 void OpEmitter::genNamedRegionGetters() {
2266 unsigned numRegions = op.getNumRegions();
2267 for (unsigned i = 0; i < numRegions; ++i) {
2268 const auto &region = op.getRegion(i);
2269 if (region.name.empty())
2270 continue;
2271 std::string name = op.getGetterName(region.name);
2273 // Generate the accessors for a variadic region.
2274 if (region.isVariadic()) {
2275 auto *m =
2276 opClass.addMethod("::mlir::MutableArrayRef<::mlir::Region>", name);
2277 ERROR_IF_PRUNED(m, name, op);
2278 m->body() << formatv(" return (*this)->getRegions().drop_front({0});",
2280 continue;
2283 auto *m = opClass.addMethod("::mlir::Region &", name);
2284 ERROR_IF_PRUNED(m, name, op);
2285 m->body() << formatv(" return (*this)->getRegion({0});", i);
2289 void OpEmitter::genNamedSuccessorGetters() {
2290 unsigned numSuccessors = op.getNumSuccessors();
2291 for (unsigned i = 0; i < numSuccessors; ++i) {
2292 const NamedSuccessor &successor = op.getSuccessor(i);
2293 if (successor.name.empty())
2294 continue;
2295 std::string name = op.getGetterName(successor.name);
2296 // Generate the accessors for a variadic successor list.
2297 if (successor.isVariadic()) {
2298 auto *m = opClass.addMethod("::mlir::SuccessorRange", name);
2299 ERROR_IF_PRUNED(m, name, op);
2300 m->body() << formatv(
2301 " return {std::next((*this)->successor_begin(), {0}), "
2302 "(*this)->successor_end()};",
2304 continue;
2307 auto *m = opClass.addMethod("::mlir::Block *", name);
2308 ERROR_IF_PRUNED(m, name, op);
2309 m->body() << formatv(" return (*this)->getSuccessor({0});", i);
2313 static bool canGenerateUnwrappedBuilder(const Operator &op) {
2314 // If this op does not have native attributes at all, return directly to avoid
2315 // redefining builders.
2316 if (op.getNumNativeAttributes() == 0)
2317 return false;
2319 bool canGenerate = false;
2320 // We are generating builders that take raw values for attributes. We need to
2321 // make sure the native attributes have a meaningful "unwrapped" value type
2322 // different from the wrapped mlir::Attribute type to avoid redefining
2323 // builders. This checks for the op has at least one such native attribute.
2324 for (int i = 0, e = op.getNumNativeAttributes(); i < e; ++i) {
2325 const NamedAttribute &namedAttr = op.getAttribute(i);
2326 if (canUseUnwrappedRawValue(namedAttr.attr)) {
2327 canGenerate = true;
2328 break;
2331 return canGenerate;
2334 static bool canInferType(const Operator &op) {
2335 return op.getTrait("::mlir::InferTypeOpInterface::Trait");
2338 void OpEmitter::genSeparateArgParamBuilder() {
2339 SmallVector<AttrParamKind, 2> attrBuilderType;
2340 attrBuilderType.push_back(AttrParamKind::WrappedAttr);
2341 if (canGenerateUnwrappedBuilder(op))
2342 attrBuilderType.push_back(AttrParamKind::UnwrappedValue);
2344 // Emit with separate builders with or without unwrapped attributes and/or
2345 // inferring result type.
2346 auto emit = [&](AttrParamKind attrType, TypeParamKind paramKind,
2347 bool inferType) {
2348 SmallVector<MethodParameter> paramList;
2349 SmallVector<std::string, 4> resultNames;
2350 llvm::StringSet<> inferredAttributes;
2351 buildParamList(paramList, inferredAttributes, resultNames, paramKind,
2352 attrType);
2354 auto *m = opClass.addStaticMethod("void", "build", std::move(paramList));
2355 // If the builder is redundant, skip generating the method.
2356 if (!m)
2357 return;
2358 auto &body = m->body();
2359 genCodeForAddingArgAndRegionForBuilder(body, inferredAttributes,
2360 /*isRawValueAttr=*/attrType ==
2361 AttrParamKind::UnwrappedValue);
2363 // Push all result types to the operation state
2365 if (inferType) {
2366 // Generate builder that infers type too.
2367 // TODO: Subsume this with general checking if type can be
2368 // inferred automatically.
2369 body << formatv(R"(
2370 ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes;
2371 if (::mlir::succeeded({0}::inferReturnTypes(odsBuilder.getContext(),
2372 {1}.location, {1}.operands,
2373 {1}.attributes.getDictionary({1}.getContext()),
2374 {1}.getRawProperties(),
2375 {1}.regions, inferredReturnTypes)))
2376 {1}.addTypes(inferredReturnTypes);
2377 else
2378 ::llvm::report_fatal_error("Failed to infer result type(s).");)",
2379 opClass.getClassName(), builderOpState);
2380 return;
2383 switch (paramKind) {
2384 case TypeParamKind::None:
2385 return;
2386 case TypeParamKind::Separate:
2387 for (int i = 0, e = op.getNumResults(); i < e; ++i) {
2388 if (op.getResult(i).isOptional())
2389 body << " if (" << resultNames[i] << ")\n ";
2390 body << " " << builderOpState << ".addTypes(" << resultNames[i]
2391 << ");\n";
2394 // Automatically create the 'resultSegmentSizes' attribute using
2395 // the length of the type ranges.
2396 if (op.getTrait("::mlir::OpTrait::AttrSizedResultSegments")) {
2397 if (op.getDialect().usePropertiesForAttributes()) {
2398 body << " ::llvm::copy(::llvm::ArrayRef<int32_t>({";
2399 } else {
2400 std::string getterName = op.getGetterName(resultSegmentAttrName);
2401 body << " " << builderOpState << ".addAttribute(" << getterName
2402 << "AttrName(" << builderOpState << ".name), "
2403 << "odsBuilder.getDenseI32ArrayAttr({";
2405 interleaveComma(
2406 llvm::seq<int>(0, op.getNumResults()), body, [&](int i) {
2407 const NamedTypeConstraint &result = op.getResult(i);
2408 if (!result.isVariableLength()) {
2409 body << "1";
2410 } else if (result.isOptional()) {
2411 body << "(" << resultNames[i] << " ? 1 : 0)";
2412 } else {
2413 // VariadicOfVariadic of results are currently unsupported in
2414 // MLIR, hence it can only be a simple variadic.
2415 // TODO: Add implementation for VariadicOfVariadic results here
2416 // once supported.
2417 assert(result.isVariadic());
2418 body << "static_cast<int32_t>(" << resultNames[i] << ".size())";
2421 if (op.getDialect().usePropertiesForAttributes()) {
2422 body << "}), " << builderOpState
2423 << ".getOrAddProperties<Properties>()."
2424 "resultSegmentSizes.begin());\n";
2425 } else {
2426 body << "}));\n";
2430 return;
2431 case TypeParamKind::Collective: {
2432 int numResults = op.getNumResults();
2433 int numVariadicResults = op.getNumVariableLengthResults();
2434 int numNonVariadicResults = numResults - numVariadicResults;
2435 bool hasVariadicResult = numVariadicResults != 0;
2437 // Avoid emitting "resultTypes.size() >= 0u" which is always true.
2438 if (!hasVariadicResult || numNonVariadicResults != 0)
2439 body << " "
2440 << "assert(resultTypes.size() "
2441 << (hasVariadicResult ? ">=" : "==") << " "
2442 << numNonVariadicResults
2443 << "u && \"mismatched number of results\");\n";
2444 body << " " << builderOpState << ".addTypes(resultTypes);\n";
2446 return;
2448 llvm_unreachable("unhandled TypeParamKind");
2451 // Some of the build methods generated here may be ambiguous, but TableGen's
2452 // ambiguous function detection will elide those ones.
2453 for (auto attrType : attrBuilderType) {
2454 emit(attrType, TypeParamKind::Separate, /*inferType=*/false);
2455 if (canInferType(op))
2456 emit(attrType, TypeParamKind::None, /*inferType=*/true);
2457 emit(attrType, TypeParamKind::Collective, /*inferType=*/false);
2461 void OpEmitter::genUseOperandAsResultTypeCollectiveParamBuilder() {
2462 int numResults = op.getNumResults();
2464 // Signature
2465 SmallVector<MethodParameter> paramList;
2466 paramList.emplace_back("::mlir::OpBuilder &", "odsBuilder");
2467 paramList.emplace_back("::mlir::OperationState &", builderOpState);
2468 paramList.emplace_back("::mlir::ValueRange", "operands");
2469 // Provide default value for `attributes` when its the last parameter
2470 StringRef attributesDefaultValue = op.getNumVariadicRegions() ? "" : "{}";
2471 paramList.emplace_back("::llvm::ArrayRef<::mlir::NamedAttribute>",
2472 "attributes", attributesDefaultValue);
2473 if (op.getNumVariadicRegions())
2474 paramList.emplace_back("unsigned", "numRegions");
2476 auto *m = opClass.addStaticMethod("void", "build", std::move(paramList));
2477 // If the builder is redundant, skip generating the method
2478 if (!m)
2479 return;
2480 auto &body = m->body();
2482 // Operands
2483 body << " " << builderOpState << ".addOperands(operands);\n";
2485 // Attributes
2486 body << " " << builderOpState << ".addAttributes(attributes);\n";
2488 // Create the correct number of regions
2489 if (int numRegions = op.getNumRegions()) {
2490 body << llvm::formatv(
2491 " for (unsigned i = 0; i != {0}; ++i)\n",
2492 (op.getNumVariadicRegions() ? "numRegions" : Twine(numRegions)));
2493 body << " (void)" << builderOpState << ".addRegion();\n";
2496 // Result types
2497 SmallVector<std::string, 2> resultTypes(numResults, "operands[0].getType()");
2498 body << " " << builderOpState << ".addTypes({"
2499 << llvm::join(resultTypes, ", ") << "});\n\n";
2502 void OpEmitter::genPopulateDefaultAttributes() {
2503 // All done if no attributes, except optional ones, have default values.
2504 if (llvm::all_of(op.getAttributes(), [](const NamedAttribute &named) {
2505 return !named.attr.hasDefaultValue() || named.attr.isOptional();
2507 return;
2509 if (op.getDialect().usePropertiesForAttributes()) {
2510 SmallVector<MethodParameter> paramList;
2511 paramList.emplace_back("::mlir::OperationName", "opName");
2512 paramList.emplace_back("Properties &", "properties");
2513 auto *m =
2514 opClass.addStaticMethod("void", "populateDefaultProperties", paramList);
2515 ERROR_IF_PRUNED(m, "populateDefaultProperties", op);
2516 auto &body = m->body();
2517 body.indent();
2518 body << "::mlir::Builder " << odsBuilder << "(opName.getContext());\n";
2519 for (const NamedAttribute &namedAttr : op.getAttributes()) {
2520 auto &attr = namedAttr.attr;
2521 if (!attr.hasDefaultValue() || attr.isOptional())
2522 continue;
2523 StringRef name = namedAttr.name;
2524 FmtContext fctx;
2525 fctx.withBuilder(odsBuilder);
2526 body << "if (!properties." << name << ")\n"
2527 << " properties." << name << " = "
2528 << std::string(tgfmt(attr.getConstBuilderTemplate(), &fctx,
2529 tgfmt(attr.getDefaultValue(), &fctx)))
2530 << ";\n";
2532 return;
2535 SmallVector<MethodParameter> paramList;
2536 paramList.emplace_back("const ::mlir::OperationName &", "opName");
2537 paramList.emplace_back("::mlir::NamedAttrList &", "attributes");
2538 auto *m = opClass.addStaticMethod("void", "populateDefaultAttrs", paramList);
2539 ERROR_IF_PRUNED(m, "populateDefaultAttrs", op);
2540 auto &body = m->body();
2541 body.indent();
2543 // Set default attributes that are unset.
2544 body << "auto attrNames = opName.getAttributeNames();\n";
2545 body << "::mlir::Builder " << odsBuilder
2546 << "(attrNames.front().getContext());\n";
2547 StringMap<int> attrIndex;
2548 for (const auto &it : llvm::enumerate(emitHelper.getAttrMetadata())) {
2549 attrIndex[it.value().first] = it.index();
2551 for (const NamedAttribute &namedAttr : op.getAttributes()) {
2552 auto &attr = namedAttr.attr;
2553 if (!attr.hasDefaultValue() || attr.isOptional())
2554 continue;
2555 auto index = attrIndex[namedAttr.name];
2556 body << "if (!attributes.get(attrNames[" << index << "])) {\n";
2557 FmtContext fctx;
2558 fctx.withBuilder(odsBuilder);
2560 std::string defaultValue =
2561 std::string(tgfmt(attr.getConstBuilderTemplate(), &fctx,
2562 tgfmt(attr.getDefaultValue(), &fctx)));
2563 body.indent() << formatv("attributes.append(attrNames[{0}], {1});\n", index,
2564 defaultValue);
2565 body.unindent() << "}\n";
2569 void OpEmitter::genInferredTypeCollectiveParamBuilder() {
2570 SmallVector<MethodParameter> paramList;
2571 paramList.emplace_back("::mlir::OpBuilder &", "odsBuilder");
2572 paramList.emplace_back("::mlir::OperationState &", builderOpState);
2573 paramList.emplace_back("::mlir::ValueRange", "operands");
2574 StringRef attributesDefaultValue = op.getNumVariadicRegions() ? "" : "{}";
2575 paramList.emplace_back("::llvm::ArrayRef<::mlir::NamedAttribute>",
2576 "attributes", attributesDefaultValue);
2577 if (op.getNumVariadicRegions())
2578 paramList.emplace_back("unsigned", "numRegions");
2580 auto *m = opClass.addStaticMethod("void", "build", std::move(paramList));
2581 // If the builder is redundant, skip generating the method
2582 if (!m)
2583 return;
2584 auto &body = m->body();
2586 int numResults = op.getNumResults();
2587 int numVariadicResults = op.getNumVariableLengthResults();
2588 int numNonVariadicResults = numResults - numVariadicResults;
2590 int numOperands = op.getNumOperands();
2591 int numVariadicOperands = op.getNumVariableLengthOperands();
2592 int numNonVariadicOperands = numOperands - numVariadicOperands;
2594 // Operands
2595 if (numVariadicOperands == 0 || numNonVariadicOperands != 0)
2596 body << " assert(operands.size()"
2597 << (numVariadicOperands != 0 ? " >= " : " == ")
2598 << numNonVariadicOperands
2599 << "u && \"mismatched number of parameters\");\n";
2600 body << " " << builderOpState << ".addOperands(operands);\n";
2601 body << " " << builderOpState << ".addAttributes(attributes);\n";
2603 // Create the correct number of regions
2604 if (int numRegions = op.getNumRegions()) {
2605 body << llvm::formatv(
2606 " for (unsigned i = 0; i != {0}; ++i)\n",
2607 (op.getNumVariadicRegions() ? "numRegions" : Twine(numRegions)));
2608 body << " (void)" << builderOpState << ".addRegion();\n";
2611 // Result types
2612 body << formatv(R"(
2613 ::llvm::SmallVector<::mlir::Type, 2> inferredReturnTypes;
2614 if (::mlir::succeeded({0}::inferReturnTypes(odsBuilder.getContext(),
2615 {1}.location, operands,
2616 {1}.attributes.getDictionary({1}.getContext()),
2617 {1}.getRawProperties(),
2618 {1}.regions, inferredReturnTypes))) {{)",
2619 opClass.getClassName(), builderOpState);
2620 if (numVariadicResults == 0 || numNonVariadicResults != 0)
2621 body << "\n assert(inferredReturnTypes.size()"
2622 << (numVariadicResults != 0 ? " >= " : " == ") << numNonVariadicResults
2623 << "u && \"mismatched number of return types\");";
2624 body << "\n " << builderOpState << ".addTypes(inferredReturnTypes);";
2626 body << formatv(R"(
2627 } else {{
2628 ::llvm::report_fatal_error("Failed to infer result type(s).");
2629 })",
2630 opClass.getClassName(), builderOpState);
2633 void OpEmitter::genUseOperandAsResultTypeSeparateParamBuilder() {
2634 auto emit = [&](AttrParamKind attrType) {
2635 SmallVector<MethodParameter> paramList;
2636 SmallVector<std::string, 4> resultNames;
2637 llvm::StringSet<> inferredAttributes;
2638 buildParamList(paramList, inferredAttributes, resultNames,
2639 TypeParamKind::None, attrType);
2641 auto *m = opClass.addStaticMethod("void", "build", std::move(paramList));
2642 // If the builder is redundant, skip generating the method
2643 if (!m)
2644 return;
2645 auto &body = m->body();
2646 genCodeForAddingArgAndRegionForBuilder(body, inferredAttributes,
2647 /*isRawValueAttr=*/attrType ==
2648 AttrParamKind::UnwrappedValue);
2650 auto numResults = op.getNumResults();
2651 if (numResults == 0)
2652 return;
2654 // Push all result types to the operation state
2655 const char *index = op.getOperand(0).isVariadic() ? ".front()" : "";
2656 std::string resultType =
2657 formatv("{0}{1}.getType()", getArgumentName(op, 0), index).str();
2658 body << " " << builderOpState << ".addTypes({" << resultType;
2659 for (int i = 1; i != numResults; ++i)
2660 body << ", " << resultType;
2661 body << "});\n\n";
2664 emit(AttrParamKind::WrappedAttr);
2665 // Generate additional builder(s) if any attributes can be "unwrapped"
2666 if (canGenerateUnwrappedBuilder(op))
2667 emit(AttrParamKind::UnwrappedValue);
2670 void OpEmitter::genUseAttrAsResultTypeBuilder() {
2671 SmallVector<MethodParameter> paramList;
2672 paramList.emplace_back("::mlir::OpBuilder &", "odsBuilder");
2673 paramList.emplace_back("::mlir::OperationState &", builderOpState);
2674 paramList.emplace_back("::mlir::ValueRange", "operands");
2675 paramList.emplace_back("::llvm::ArrayRef<::mlir::NamedAttribute>",
2676 "attributes", "{}");
2677 auto *m = opClass.addStaticMethod("void", "build", std::move(paramList));
2678 // If the builder is redundant, skip generating the method
2679 if (!m)
2680 return;
2682 auto &body = m->body();
2684 // Push all result types to the operation state
2685 std::string resultType;
2686 const auto &namedAttr = op.getAttribute(0);
2688 body << " auto attrName = " << op.getGetterName(namedAttr.name)
2689 << "AttrName(" << builderOpState
2690 << ".name);\n"
2691 " for (auto attr : attributes) {\n"
2692 " if (attr.getName() != attrName) continue;\n";
2693 if (namedAttr.attr.isTypeAttr()) {
2694 resultType = "::llvm::cast<::mlir::TypeAttr>(attr.getValue()).getValue()";
2695 } else {
2696 resultType = "::llvm::cast<::mlir::TypedAttr>(attr.getValue()).getType()";
2699 // Operands
2700 body << " " << builderOpState << ".addOperands(operands);\n";
2702 // Attributes
2703 body << " " << builderOpState << ".addAttributes(attributes);\n";
2705 // Result types
2706 SmallVector<std::string, 2> resultTypes(op.getNumResults(), resultType);
2707 body << " " << builderOpState << ".addTypes({"
2708 << llvm::join(resultTypes, ", ") << "});\n";
2709 body << " }\n";
2712 /// Returns a signature of the builder. Updates the context `fctx` to enable
2713 /// replacement of $_builder and $_state in the body.
2714 static SmallVector<MethodParameter>
2715 getBuilderSignature(const Builder &builder) {
2716 ArrayRef<Builder::Parameter> params(builder.getParameters());
2718 // Inject builder and state arguments.
2719 SmallVector<MethodParameter> arguments;
2720 arguments.reserve(params.size() + 2);
2721 arguments.emplace_back("::mlir::OpBuilder &", odsBuilder);
2722 arguments.emplace_back("::mlir::OperationState &", builderOpState);
2724 for (unsigned i = 0, e = params.size(); i < e; ++i) {
2725 // If no name is provided, generate one.
2726 std::optional<StringRef> paramName = params[i].getName();
2727 std::string name =
2728 paramName ? paramName->str() : "odsArg" + std::to_string(i);
2730 StringRef defaultValue;
2731 if (std::optional<StringRef> defaultParamValue =
2732 params[i].getDefaultValue())
2733 defaultValue = *defaultParamValue;
2735 arguments.emplace_back(params[i].getCppType(), std::move(name),
2736 defaultValue);
2739 return arguments;
2742 void OpEmitter::genBuilder() {
2743 // Handle custom builders if provided.
2744 for (const Builder &builder : op.getBuilders()) {
2745 SmallVector<MethodParameter> arguments = getBuilderSignature(builder);
2747 std::optional<StringRef> body = builder.getBody();
2748 auto properties = body ? Method::Static : Method::StaticDeclaration;
2749 auto *method =
2750 opClass.addMethod("void", "build", properties, std::move(arguments));
2751 if (body)
2752 ERROR_IF_PRUNED(method, "build", op);
2754 if (method)
2755 method->setDeprecated(builder.getDeprecatedMessage());
2757 FmtContext fctx;
2758 fctx.withBuilder(odsBuilder);
2759 fctx.addSubst("_state", builderOpState);
2760 if (body)
2761 method->body() << tgfmt(*body, &fctx);
2764 // Generate default builders that requires all result type, operands, and
2765 // attributes as parameters.
2766 if (op.skipDefaultBuilders())
2767 return;
2769 // We generate three classes of builders here:
2770 // 1. one having a stand-alone parameter for each operand / attribute, and
2771 genSeparateArgParamBuilder();
2772 // 2. one having an aggregated parameter for all result types / operands /
2773 // attributes, and
2774 genCollectiveParamBuilder();
2775 // 3. one having a stand-alone parameter for each operand and attribute,
2776 // use the first operand or attribute's type as all result types
2777 // to facilitate different call patterns.
2778 if (op.getNumVariableLengthResults() == 0) {
2779 if (op.getTrait("::mlir::OpTrait::SameOperandsAndResultType")) {
2780 genUseOperandAsResultTypeSeparateParamBuilder();
2781 genUseOperandAsResultTypeCollectiveParamBuilder();
2783 if (op.getTrait("::mlir::OpTrait::FirstAttrDerivedResultType"))
2784 genUseAttrAsResultTypeBuilder();
2788 void OpEmitter::genCollectiveParamBuilder() {
2789 int numResults = op.getNumResults();
2790 int numVariadicResults = op.getNumVariableLengthResults();
2791 int numNonVariadicResults = numResults - numVariadicResults;
2793 int numOperands = op.getNumOperands();
2794 int numVariadicOperands = op.getNumVariableLengthOperands();
2795 int numNonVariadicOperands = numOperands - numVariadicOperands;
2797 SmallVector<MethodParameter> paramList;
2798 paramList.emplace_back("::mlir::OpBuilder &", "");
2799 paramList.emplace_back("::mlir::OperationState &", builderOpState);
2800 paramList.emplace_back("::mlir::TypeRange", "resultTypes");
2801 paramList.emplace_back("::mlir::ValueRange", "operands");
2802 // Provide default value for `attributes` when its the last parameter
2803 StringRef attributesDefaultValue = op.getNumVariadicRegions() ? "" : "{}";
2804 paramList.emplace_back("::llvm::ArrayRef<::mlir::NamedAttribute>",
2805 "attributes", attributesDefaultValue);
2806 if (op.getNumVariadicRegions())
2807 paramList.emplace_back("unsigned", "numRegions");
2809 auto *m = opClass.addStaticMethod("void", "build", std::move(paramList));
2810 // If the builder is redundant, skip generating the method
2811 if (!m)
2812 return;
2813 auto &body = m->body();
2815 // Operands
2816 if (numVariadicOperands == 0 || numNonVariadicOperands != 0)
2817 body << " assert(operands.size()"
2818 << (numVariadicOperands != 0 ? " >= " : " == ")
2819 << numNonVariadicOperands
2820 << "u && \"mismatched number of parameters\");\n";
2821 body << " " << builderOpState << ".addOperands(operands);\n";
2823 // Attributes
2824 body << " " << builderOpState << ".addAttributes(attributes);\n";
2826 // Create the correct number of regions
2827 if (int numRegions = op.getNumRegions()) {
2828 body << llvm::formatv(
2829 " for (unsigned i = 0; i != {0}; ++i)\n",
2830 (op.getNumVariadicRegions() ? "numRegions" : Twine(numRegions)));
2831 body << " (void)" << builderOpState << ".addRegion();\n";
2834 // Result types
2835 if (numVariadicResults == 0 || numNonVariadicResults != 0)
2836 body << " assert(resultTypes.size()"
2837 << (numVariadicResults != 0 ? " >= " : " == ") << numNonVariadicResults
2838 << "u && \"mismatched number of return types\");\n";
2839 body << " " << builderOpState << ".addTypes(resultTypes);\n";
2841 // Generate builder that infers type too.
2842 // TODO: Expand to handle successors.
2843 if (canInferType(op) && op.getNumSuccessors() == 0)
2844 genInferredTypeCollectiveParamBuilder();
2847 void OpEmitter::buildParamList(SmallVectorImpl<MethodParameter> &paramList,
2848 llvm::StringSet<> &inferredAttributes,
2849 SmallVectorImpl<std::string> &resultTypeNames,
2850 TypeParamKind typeParamKind,
2851 AttrParamKind attrParamKind) {
2852 resultTypeNames.clear();
2853 auto numResults = op.getNumResults();
2854 resultTypeNames.reserve(numResults);
2856 paramList.emplace_back("::mlir::OpBuilder &", odsBuilder);
2857 paramList.emplace_back("::mlir::OperationState &", builderOpState);
2859 switch (typeParamKind) {
2860 case TypeParamKind::None:
2861 break;
2862 case TypeParamKind::Separate: {
2863 // Add parameters for all return types
2864 for (int i = 0; i < numResults; ++i) {
2865 const auto &result = op.getResult(i);
2866 std::string resultName = std::string(result.name);
2867 if (resultName.empty())
2868 resultName = std::string(formatv("resultType{0}", i));
2870 StringRef type =
2871 result.isVariadic() ? "::mlir::TypeRange" : "::mlir::Type";
2873 paramList.emplace_back(type, resultName, result.isOptional());
2874 resultTypeNames.emplace_back(std::move(resultName));
2876 } break;
2877 case TypeParamKind::Collective: {
2878 paramList.emplace_back("::mlir::TypeRange", "resultTypes");
2879 resultTypeNames.push_back("resultTypes");
2880 } break;
2883 // Add parameters for all arguments (operands and attributes).
2884 int defaultValuedAttrStartIndex = op.getNumArgs();
2885 // Successors and variadic regions go at the end of the parameter list, so no
2886 // default arguments are possible.
2887 bool hasTrailingParams = op.getNumSuccessors() || op.getNumVariadicRegions();
2888 if (!hasTrailingParams) {
2889 // Calculate the start index from which we can attach default values in the
2890 // builder declaration.
2891 for (int i = op.getNumArgs() - 1; i >= 0; --i) {
2892 auto *namedAttr =
2893 llvm::dyn_cast_if_present<tblgen::NamedAttribute *>(op.getArg(i));
2894 if (!namedAttr)
2895 break;
2897 Attribute attr = namedAttr->attr;
2898 // TODO: Currently we can't differentiate between optional meaning do not
2899 // verify/not always error if missing or optional meaning need not be
2900 // specified in builder. Expand isOptional once we can differentiate.
2901 if (!attr.hasDefaultValue() && !attr.isDerivedAttr())
2902 break;
2904 // Creating an APInt requires us to provide bitwidth, value, and
2905 // signedness, which is complicated compared to others. Similarly
2906 // for APFloat.
2907 // TODO: Adjust the 'returnType' field of such attributes
2908 // to support them.
2909 StringRef retType = namedAttr->attr.getReturnType();
2910 if (retType == "::llvm::APInt" || retType == "::llvm::APFloat")
2911 break;
2913 defaultValuedAttrStartIndex = i;
2916 // Avoid generating build methods that are ambiguous due to default values by
2917 // requiring at least one attribute.
2918 if (defaultValuedAttrStartIndex < op.getNumArgs()) {
2919 // TODO: This should have been possible as a cast<NamedAttribute> but
2920 // required template instantiations is not yet defined for the tblgen helper
2921 // classes.
2922 auto *namedAttr =
2923 cast<NamedAttribute *>(op.getArg(defaultValuedAttrStartIndex));
2924 Attribute attr = namedAttr->attr;
2925 if ((attrParamKind == AttrParamKind::WrappedAttr &&
2926 canUseUnwrappedRawValue(attr)) ||
2927 (attrParamKind == AttrParamKind::UnwrappedValue &&
2928 !canUseUnwrappedRawValue(attr)))
2929 ++defaultValuedAttrStartIndex;
2932 /// Collect any inferred attributes.
2933 for (const NamedTypeConstraint &operand : op.getOperands()) {
2934 if (operand.isVariadicOfVariadic()) {
2935 inferredAttributes.insert(
2936 operand.constraint.getVariadicOfVariadicSegmentSizeAttr());
2940 for (int i = 0, e = op.getNumArgs(), numOperands = 0; i < e; ++i) {
2941 Argument arg = op.getArg(i);
2942 if (const auto *operand =
2943 llvm::dyn_cast_if_present<NamedTypeConstraint *>(arg)) {
2944 StringRef type;
2945 if (operand->isVariadicOfVariadic())
2946 type = "::llvm::ArrayRef<::mlir::ValueRange>";
2947 else if (operand->isVariadic())
2948 type = "::mlir::ValueRange";
2949 else
2950 type = "::mlir::Value";
2952 paramList.emplace_back(type, getArgumentName(op, numOperands++),
2953 operand->isOptional());
2954 continue;
2956 if ([[maybe_unused]] const auto *operand =
2957 llvm::dyn_cast_if_present<NamedProperty *>(arg)) {
2958 // TODO
2959 continue;
2961 const NamedAttribute &namedAttr = *arg.get<NamedAttribute *>();
2962 const Attribute &attr = namedAttr.attr;
2964 // Inferred attributes don't need to be added to the param list.
2965 if (inferredAttributes.contains(namedAttr.name))
2966 continue;
2968 StringRef type;
2969 switch (attrParamKind) {
2970 case AttrParamKind::WrappedAttr:
2971 type = attr.getStorageType();
2972 break;
2973 case AttrParamKind::UnwrappedValue:
2974 if (canUseUnwrappedRawValue(attr))
2975 type = attr.getReturnType();
2976 else
2977 type = attr.getStorageType();
2978 break;
2981 // Attach default value if requested and possible.
2982 std::string defaultValue;
2983 if (i >= defaultValuedAttrStartIndex) {
2984 if (attrParamKind == AttrParamKind::UnwrappedValue &&
2985 canUseUnwrappedRawValue(attr))
2986 defaultValue += attr.getDefaultValue();
2987 else
2988 defaultValue += "nullptr";
2990 paramList.emplace_back(type, namedAttr.name, StringRef(defaultValue),
2991 attr.isOptional());
2994 /// Insert parameters for each successor.
2995 for (const NamedSuccessor &succ : op.getSuccessors()) {
2996 StringRef type =
2997 succ.isVariadic() ? "::mlir::BlockRange" : "::mlir::Block *";
2998 paramList.emplace_back(type, succ.name);
3001 /// Insert parameters for variadic regions.
3002 for (const NamedRegion &region : op.getRegions())
3003 if (region.isVariadic())
3004 paramList.emplace_back("unsigned",
3005 llvm::formatv("{0}Count", region.name).str());
3008 void OpEmitter::genCodeForAddingArgAndRegionForBuilder(
3009 MethodBody &body, llvm::StringSet<> &inferredAttributes,
3010 bool isRawValueAttr) {
3011 // Push all operands to the result.
3012 for (int i = 0, e = op.getNumOperands(); i < e; ++i) {
3013 std::string argName = getArgumentName(op, i);
3014 const NamedTypeConstraint &operand = op.getOperand(i);
3015 if (operand.constraint.isVariadicOfVariadic()) {
3016 body << " for (::mlir::ValueRange range : " << argName << ")\n "
3017 << builderOpState << ".addOperands(range);\n";
3019 // Add the segment attribute.
3020 body << " {\n"
3021 << " ::llvm::SmallVector<int32_t> rangeSegments;\n"
3022 << " for (::mlir::ValueRange range : " << argName << ")\n"
3023 << " rangeSegments.push_back(range.size());\n"
3024 << " auto rangeAttr = " << odsBuilder
3025 << ".getDenseI32ArrayAttr(rangeSegments);\n";
3026 if (op.getDialect().usePropertiesForAttributes()) {
3027 body << " " << builderOpState << ".getOrAddProperties<Properties>()."
3028 << operand.constraint.getVariadicOfVariadicSegmentSizeAttr()
3029 << " = rangeAttr;";
3030 } else {
3031 body << " " << builderOpState << ".addAttribute("
3032 << op.getGetterName(
3033 operand.constraint.getVariadicOfVariadicSegmentSizeAttr())
3034 << "AttrName(" << builderOpState << ".name), rangeAttr);";
3036 body << " }\n";
3037 continue;
3040 if (operand.isOptional())
3041 body << " if (" << argName << ")\n ";
3042 body << " " << builderOpState << ".addOperands(" << argName << ");\n";
3045 // If the operation has the operand segment size attribute, add it here.
3046 auto emitSegment = [&]() {
3047 interleaveComma(llvm::seq<int>(0, op.getNumOperands()), body, [&](int i) {
3048 const NamedTypeConstraint &operand = op.getOperand(i);
3049 if (!operand.isVariableLength()) {
3050 body << "1";
3051 return;
3054 std::string operandName = getArgumentName(op, i);
3055 if (operand.isOptional()) {
3056 body << "(" << operandName << " ? 1 : 0)";
3057 } else if (operand.isVariadicOfVariadic()) {
3058 body << llvm::formatv(
3059 "static_cast<int32_t>(std::accumulate({0}.begin(), {0}.end(), 0, "
3060 "[](int32_t curSum, ::mlir::ValueRange range) {{ return curSum + "
3061 "range.size(); }))",
3062 operandName);
3063 } else {
3064 body << "static_cast<int32_t>(" << getArgumentName(op, i) << ".size())";
3068 if (op.getTrait("::mlir::OpTrait::AttrSizedOperandSegments")) {
3069 std::string sizes = op.getGetterName(operandSegmentAttrName);
3070 if (op.getDialect().usePropertiesForAttributes()) {
3071 body << " ::llvm::copy(::llvm::ArrayRef<int32_t>({";
3072 emitSegment();
3073 body << "}), " << builderOpState
3074 << ".getOrAddProperties<Properties>()."
3075 "operandSegmentSizes.begin());\n";
3076 } else {
3077 body << " " << builderOpState << ".addAttribute(" << sizes << "AttrName("
3078 << builderOpState << ".name), "
3079 << "odsBuilder.getDenseI32ArrayAttr({";
3080 emitSegment();
3081 body << "}));\n";
3085 // Push all attributes to the result.
3086 for (const auto &namedAttr : op.getAttributes()) {
3087 auto &attr = namedAttr.attr;
3088 if (attr.isDerivedAttr() || inferredAttributes.contains(namedAttr.name))
3089 continue;
3091 // TODO: The wrapping of optional is different for default or not, so don't
3092 // unwrap for default ones that would fail below.
3093 bool emitNotNullCheck =
3094 (attr.isOptional() && !attr.hasDefaultValue()) ||
3095 (attr.hasDefaultValue() && !isRawValueAttr) ||
3096 // TODO: UnitAttr is optional, not wrapped, but needs to be guarded as
3097 // the constant materialization is only for true case.
3098 (isRawValueAttr && attr.getAttrDefName() == "UnitAttr");
3099 if (emitNotNullCheck)
3100 body.indent() << formatv("if ({0}) ", namedAttr.name) << "{\n";
3102 if (isRawValueAttr && canUseUnwrappedRawValue(attr)) {
3103 // If this is a raw value, then we need to wrap it in an Attribute
3104 // instance.
3105 FmtContext fctx;
3106 fctx.withBuilder("odsBuilder");
3107 if (op.getDialect().usePropertiesForAttributes()) {
3108 body << formatv(" {0}.getOrAddProperties<Properties>().{1} = {2};\n",
3109 builderOpState, namedAttr.name,
3110 constBuildAttrFromParam(attr, fctx, namedAttr.name));
3111 } else {
3112 body << formatv(" {0}.addAttribute({1}AttrName({0}.name), {2});\n",
3113 builderOpState, op.getGetterName(namedAttr.name),
3114 constBuildAttrFromParam(attr, fctx, namedAttr.name));
3116 } else {
3117 if (op.getDialect().usePropertiesForAttributes()) {
3118 body << formatv(" {0}.getOrAddProperties<Properties>().{1} = {1};\n",
3119 builderOpState, namedAttr.name);
3120 } else {
3121 body << formatv(" {0}.addAttribute({1}AttrName({0}.name), {2});\n",
3122 builderOpState, op.getGetterName(namedAttr.name),
3123 namedAttr.name);
3126 if (emitNotNullCheck)
3127 body.unindent() << " }\n";
3130 // Create the correct number of regions.
3131 for (const NamedRegion &region : op.getRegions()) {
3132 if (region.isVariadic())
3133 body << formatv(" for (unsigned i = 0; i < {0}Count; ++i)\n ",
3134 region.name);
3136 body << " (void)" << builderOpState << ".addRegion();\n";
3139 // Push all successors to the result.
3140 for (const NamedSuccessor &namedSuccessor : op.getSuccessors()) {
3141 body << formatv(" {0}.addSuccessors({1});\n", builderOpState,
3142 namedSuccessor.name);
3146 void OpEmitter::genCanonicalizerDecls() {
3147 bool hasCanonicalizeMethod = def.getValueAsBit("hasCanonicalizeMethod");
3148 if (hasCanonicalizeMethod) {
3149 // static LogicResult FooOp::
3150 // canonicalize(FooOp op, PatternRewriter &rewriter);
3151 SmallVector<MethodParameter> paramList;
3152 paramList.emplace_back(op.getCppClassName(), "op");
3153 paramList.emplace_back("::mlir::PatternRewriter &", "rewriter");
3154 auto *m = opClass.declareStaticMethod("::mlir::LogicalResult",
3155 "canonicalize", std::move(paramList));
3156 ERROR_IF_PRUNED(m, "canonicalize", op);
3159 // We get a prototype for 'getCanonicalizationPatterns' if requested directly
3160 // or if using a 'canonicalize' method.
3161 bool hasCanonicalizer = def.getValueAsBit("hasCanonicalizer");
3162 if (!hasCanonicalizeMethod && !hasCanonicalizer)
3163 return;
3165 // We get a body for 'getCanonicalizationPatterns' when using a 'canonicalize'
3166 // method, but not implementing 'getCanonicalizationPatterns' manually.
3167 bool hasBody = hasCanonicalizeMethod && !hasCanonicalizer;
3169 // Add a signature for getCanonicalizationPatterns if implemented by the
3170 // dialect or if synthesized to call 'canonicalize'.
3171 SmallVector<MethodParameter> paramList;
3172 paramList.emplace_back("::mlir::RewritePatternSet &", "results");
3173 paramList.emplace_back("::mlir::MLIRContext *", "context");
3174 auto kind = hasBody ? Method::Static : Method::StaticDeclaration;
3175 auto *method = opClass.addMethod("void", "getCanonicalizationPatterns", kind,
3176 std::move(paramList));
3178 // If synthesizing the method, fill it.
3179 if (hasBody) {
3180 ERROR_IF_PRUNED(method, "getCanonicalizationPatterns", op);
3181 method->body() << " results.add(canonicalize);\n";
3185 void OpEmitter::genFolderDecls() {
3186 if (!op.hasFolder())
3187 return;
3189 SmallVector<MethodParameter> paramList;
3190 paramList.emplace_back("FoldAdaptor", "adaptor");
3192 StringRef retType;
3193 bool hasSingleResult =
3194 op.getNumResults() == 1 && op.getNumVariableLengthResults() == 0;
3195 if (hasSingleResult) {
3196 retType = "::mlir::OpFoldResult";
3197 } else {
3198 paramList.emplace_back("::llvm::SmallVectorImpl<::mlir::OpFoldResult> &",
3199 "results");
3200 retType = "::mlir::LogicalResult";
3203 auto *m = opClass.declareMethod(retType, "fold", std::move(paramList));
3204 ERROR_IF_PRUNED(m, "fold", op);
3207 void OpEmitter::genOpInterfaceMethods(const tblgen::InterfaceTrait *opTrait) {
3208 Interface interface = opTrait->getInterface();
3210 // Get the set of methods that should always be declared.
3211 auto alwaysDeclaredMethodsVec = opTrait->getAlwaysDeclaredMethods();
3212 llvm::StringSet<> alwaysDeclaredMethods;
3213 alwaysDeclaredMethods.insert(alwaysDeclaredMethodsVec.begin(),
3214 alwaysDeclaredMethodsVec.end());
3216 for (const InterfaceMethod &method : interface.getMethods()) {
3217 // Don't declare if the method has a body.
3218 if (method.getBody())
3219 continue;
3220 // Don't declare if the method has a default implementation and the op
3221 // didn't request that it always be declared.
3222 if (method.getDefaultImplementation() &&
3223 !alwaysDeclaredMethods.count(method.getName()))
3224 continue;
3225 // Interface methods are allowed to overlap with existing methods, so don't
3226 // check if pruned.
3227 (void)genOpInterfaceMethod(method);
3231 Method *OpEmitter::genOpInterfaceMethod(const InterfaceMethod &method,
3232 bool declaration) {
3233 SmallVector<MethodParameter> paramList;
3234 for (const InterfaceMethod::Argument &arg : method.getArguments())
3235 paramList.emplace_back(arg.type, arg.name);
3237 auto props = (method.isStatic() ? Method::Static : Method::None) |
3238 (declaration ? Method::Declaration : Method::None);
3239 return opClass.addMethod(method.getReturnType(), method.getName(), props,
3240 std::move(paramList));
3243 void OpEmitter::genOpInterfaceMethods() {
3244 for (const auto &trait : op.getTraits()) {
3245 if (const auto *opTrait = dyn_cast<tblgen::InterfaceTrait>(&trait))
3246 if (opTrait->shouldDeclareMethods())
3247 genOpInterfaceMethods(opTrait);
3251 void OpEmitter::genSideEffectInterfaceMethods() {
3252 enum EffectKind { Operand, Result, Symbol, Static };
3253 struct EffectLocation {
3254 /// The effect applied.
3255 SideEffect effect;
3257 /// The index if the kind is not static.
3258 unsigned index;
3260 /// The kind of the location.
3261 unsigned kind;
3264 StringMap<SmallVector<EffectLocation, 1>> interfaceEffects;
3265 auto resolveDecorators = [&](Operator::var_decorator_range decorators,
3266 unsigned index, unsigned kind) {
3267 for (auto decorator : decorators)
3268 if (SideEffect *effect = dyn_cast<SideEffect>(&decorator)) {
3269 opClass.addTrait(effect->getInterfaceTrait());
3270 interfaceEffects[effect->getBaseEffectName()].push_back(
3271 EffectLocation{*effect, index, kind});
3275 // Collect effects that were specified via:
3276 /// Traits.
3277 for (const auto &trait : op.getTraits()) {
3278 const auto *opTrait = dyn_cast<tblgen::SideEffectTrait>(&trait);
3279 if (!opTrait)
3280 continue;
3281 auto &effects = interfaceEffects[opTrait->getBaseEffectName()];
3282 for (auto decorator : opTrait->getEffects())
3283 effects.push_back(EffectLocation{cast<SideEffect>(decorator),
3284 /*index=*/0, EffectKind::Static});
3286 /// Attributes and Operands.
3287 for (unsigned i = 0, operandIt = 0, e = op.getNumArgs(); i != e; ++i) {
3288 Argument arg = op.getArg(i);
3289 if (arg.is<NamedTypeConstraint *>()) {
3290 resolveDecorators(op.getArgDecorators(i), operandIt, EffectKind::Operand);
3291 ++operandIt;
3292 continue;
3294 if (arg.is<NamedProperty *>())
3295 continue;
3296 const NamedAttribute *attr = arg.get<NamedAttribute *>();
3297 if (attr->attr.getBaseAttr().isSymbolRefAttr())
3298 resolveDecorators(op.getArgDecorators(i), i, EffectKind::Symbol);
3300 /// Results.
3301 for (unsigned i = 0, e = op.getNumResults(); i != e; ++i)
3302 resolveDecorators(op.getResultDecorators(i), i, EffectKind::Result);
3304 // The code used to add an effect instance.
3305 // {0}: The effect class.
3306 // {1}: Optional value or symbol reference.
3307 // {2}: The side effect stage.
3308 // {3}: Does this side effect act on every single value of resource.
3309 // {4}: The resource class.
3310 const char *addEffectCode =
3311 " effects.emplace_back({0}::get(), {1}{2}, {3}, {4}::get());\n";
3313 for (auto &it : interfaceEffects) {
3314 // Generate the 'getEffects' method.
3315 std::string type = llvm::formatv("::llvm::SmallVectorImpl<::mlir::"
3316 "SideEffects::EffectInstance<{0}>> &",
3317 it.first())
3318 .str();
3319 auto *getEffects = opClass.addMethod("void", "getEffects",
3320 MethodParameter(type, "effects"));
3321 ERROR_IF_PRUNED(getEffects, "getEffects", op);
3322 auto &body = getEffects->body();
3324 // Add effect instances for each of the locations marked on the operation.
3325 for (auto &location : it.second) {
3326 StringRef effect = location.effect.getName();
3327 StringRef resource = location.effect.getResource();
3328 int stage = (int)location.effect.getStage();
3329 bool effectOnFullRegion = (int)location.effect.getEffectOnfullRegion();
3330 if (location.kind == EffectKind::Static) {
3331 // A static instance has no attached value.
3332 body << llvm::formatv(addEffectCode, effect, "", stage,
3333 effectOnFullRegion, resource)
3334 .str();
3335 } else if (location.kind == EffectKind::Symbol) {
3336 // A symbol reference requires adding the proper attribute.
3337 const auto *attr = op.getArg(location.index).get<NamedAttribute *>();
3338 std::string argName = op.getGetterName(attr->name);
3339 if (attr->attr.isOptional()) {
3340 body << " if (auto symbolRef = " << argName << "Attr())\n "
3341 << llvm::formatv(addEffectCode, effect, "symbolRef, ", stage,
3342 effectOnFullRegion, resource)
3343 .str();
3344 } else {
3345 body << llvm::formatv(addEffectCode, effect, argName + "Attr(), ",
3346 stage, effectOnFullRegion, resource)
3347 .str();
3349 } else {
3350 // Otherwise this is an operand/result, so we need to attach the Value.
3351 body << " for (::mlir::Value value : getODS"
3352 << (location.kind == EffectKind::Operand ? "Operands" : "Results")
3353 << "(" << location.index << "))\n "
3354 << llvm::formatv(addEffectCode, effect, "value, ", stage,
3355 effectOnFullRegion, resource)
3356 .str();
3362 void OpEmitter::genTypeInterfaceMethods() {
3363 if (!op.allResultTypesKnown())
3364 return;
3365 // Generate 'inferReturnTypes' method declaration using the interface method
3366 // declared in 'InferTypeOpInterface' op interface.
3367 const auto *trait =
3368 cast<InterfaceTrait>(op.getTrait("::mlir::InferTypeOpInterface::Trait"));
3369 Interface interface = trait->getInterface();
3370 Method *method = [&]() -> Method * {
3371 for (const InterfaceMethod &interfaceMethod : interface.getMethods()) {
3372 if (interfaceMethod.getName() == "inferReturnTypes") {
3373 return genOpInterfaceMethod(interfaceMethod, /*declaration=*/false);
3376 assert(0 && "unable to find inferReturnTypes interface method");
3377 return nullptr;
3378 }();
3379 ERROR_IF_PRUNED(method, "inferReturnTypes", op);
3380 auto &body = method->body();
3381 body << " inferredReturnTypes.resize(" << op.getNumResults() << ");\n";
3383 FmtContext fctx;
3384 fctx.withBuilder("odsBuilder");
3385 fctx.addSubst("_ctxt", "context");
3386 body << " ::mlir::Builder odsBuilder(context);\n";
3388 // Process the type inference graph in topological order, starting from types
3389 // that are always fully-inferred: operands and results with constructible
3390 // types. The type inference graph here will always be a DAG, so this gives
3391 // us the correct order for generating the types. -1 is a placeholder to
3392 // indicate the type for a result has not been generated.
3393 SmallVector<int> constructedIndices(op.getNumResults(), -1);
3394 int inferredTypeIdx = 0;
3395 for (int numResults = op.getNumResults(); inferredTypeIdx != numResults;) {
3396 for (int i = 0, e = op.getNumResults(); i != e; ++i) {
3397 if (constructedIndices[i] >= 0)
3398 continue;
3399 const InferredResultType &infer = op.getInferredResultType(i);
3400 std::string typeStr;
3401 if (infer.isArg()) {
3402 // If this is an operand, just index into operand list to access the
3403 // type.
3404 auto arg = op.getArgToOperandOrAttribute(infer.getIndex());
3405 if (arg.kind() == Operator::OperandOrAttribute::Kind::Operand) {
3406 typeStr = ("operands[" + Twine(arg.operandOrAttributeIndex()) +
3407 "].getType()")
3408 .str();
3410 // If this is an attribute, index into the attribute dictionary.
3411 } else {
3412 auto *attr =
3413 op.getArg(arg.operandOrAttributeIndex()).get<NamedAttribute *>();
3414 body << " ::mlir::TypedAttr odsInferredTypeAttr" << inferredTypeIdx
3415 << " = ";
3416 if (op.getDialect().usePropertiesForAttributes()) {
3417 body << "(properties ? properties.as<Properties *>()->"
3418 << attr->name
3419 << " : "
3420 "::llvm::dyn_cast_or_null<::mlir::TypedAttr>(attributes."
3421 "get(\"" +
3422 attr->name + "\")));\n";
3423 } else {
3424 body << "::llvm::dyn_cast_or_null<::mlir::TypedAttr>(attributes."
3425 "get(\"" +
3426 attr->name + "\"));\n";
3428 body << " if (!odsInferredTypeAttr" << inferredTypeIdx
3429 << ") return ::mlir::failure();\n";
3430 typeStr =
3431 ("odsInferredTypeAttr" + Twine(inferredTypeIdx) + ".getType()")
3432 .str();
3434 } else if (std::optional<StringRef> builder =
3435 op.getResult(infer.getResultIndex())
3436 .constraint.getBuilderCall()) {
3437 typeStr = tgfmt(*builder, &fctx).str();
3438 } else if (int index = constructedIndices[infer.getResultIndex()];
3439 index >= 0) {
3440 typeStr = ("odsInferredType" + Twine(index)).str();
3441 } else {
3442 continue;
3444 body << " ::mlir::Type odsInferredType" << inferredTypeIdx++ << " = "
3445 << tgfmt(infer.getTransformer(), &fctx.withSelf(typeStr)) << ";\n";
3446 constructedIndices[i] = inferredTypeIdx - 1;
3449 for (auto [i, index] : llvm::enumerate(constructedIndices))
3450 body << " inferredReturnTypes[" << i << "] = odsInferredType" << index
3451 << ";\n";
3452 body << " return ::mlir::success();";
3455 void OpEmitter::genParser() {
3456 if (hasStringAttribute(def, "assemblyFormat"))
3457 return;
3459 if (!def.getValueAsBit("hasCustomAssemblyFormat"))
3460 return;
3462 SmallVector<MethodParameter> paramList;
3463 paramList.emplace_back("::mlir::OpAsmParser &", "parser");
3464 paramList.emplace_back("::mlir::OperationState &", "result");
3466 auto *method = opClass.declareStaticMethod("::mlir::ParseResult", "parse",
3467 std::move(paramList));
3468 ERROR_IF_PRUNED(method, "parse", op);
3471 void OpEmitter::genPrinter() {
3472 if (hasStringAttribute(def, "assemblyFormat"))
3473 return;
3475 // Check to see if this op uses a c++ format.
3476 if (!def.getValueAsBit("hasCustomAssemblyFormat"))
3477 return;
3478 auto *method = opClass.declareMethod(
3479 "void", "print", MethodParameter("::mlir::OpAsmPrinter &", "p"));
3480 ERROR_IF_PRUNED(method, "print", op);
3483 void OpEmitter::genVerifier() {
3484 auto *implMethod =
3485 opClass.addMethod("::mlir::LogicalResult", "verifyInvariantsImpl");
3486 ERROR_IF_PRUNED(implMethod, "verifyInvariantsImpl", op);
3487 auto &implBody = implMethod->body();
3488 bool useProperties = emitHelper.hasProperties();
3490 populateSubstitutions(emitHelper, verifyCtx);
3491 genAttributeVerifier(emitHelper, verifyCtx, implBody, staticVerifierEmitter,
3492 useProperties);
3493 genOperandResultVerifier(implBody, op.getOperands(), "operand");
3494 genOperandResultVerifier(implBody, op.getResults(), "result");
3496 for (auto &trait : op.getTraits()) {
3497 if (auto *t = dyn_cast<tblgen::PredTrait>(&trait)) {
3498 implBody << tgfmt(" if (!($0))\n "
3499 "return emitOpError(\"failed to verify that $1\");\n",
3500 &verifyCtx, tgfmt(t->getPredTemplate(), &verifyCtx),
3501 t->getSummary());
3505 genRegionVerifier(implBody);
3506 genSuccessorVerifier(implBody);
3508 implBody << " return ::mlir::success();\n";
3510 // TODO: Some places use the `verifyInvariants` to do operation verification.
3511 // This may not act as their expectation because this doesn't call any
3512 // verifiers of native/interface traits. Needs to review those use cases and
3513 // see if we should use the mlir::verify() instead.
3514 auto *method = opClass.addMethod("::mlir::LogicalResult", "verifyInvariants");
3515 ERROR_IF_PRUNED(method, "verifyInvariants", op);
3516 auto &body = method->body();
3517 if (def.getValueAsBit("hasVerifier")) {
3518 body << " if(::mlir::succeeded(verifyInvariantsImpl()) && "
3519 "::mlir::succeeded(verify()))\n";
3520 body << " return ::mlir::success();\n";
3521 body << " return ::mlir::failure();";
3522 } else {
3523 body << " return verifyInvariantsImpl();";
3527 void OpEmitter::genCustomVerifier() {
3528 if (def.getValueAsBit("hasVerifier")) {
3529 auto *method = opClass.declareMethod("::mlir::LogicalResult", "verify");
3530 ERROR_IF_PRUNED(method, "verify", op);
3533 if (def.getValueAsBit("hasRegionVerifier")) {
3534 auto *method =
3535 opClass.declareMethod("::mlir::LogicalResult", "verifyRegions");
3536 ERROR_IF_PRUNED(method, "verifyRegions", op);
3540 void OpEmitter::genOperandResultVerifier(MethodBody &body,
3541 Operator::const_value_range values,
3542 StringRef valueKind) {
3543 // Check that an optional value is at most 1 element.
3545 // {0}: Value index.
3546 // {1}: "operand" or "result"
3547 const char *const verifyOptional = R"(
3548 if (valueGroup{0}.size() > 1) {
3549 return emitOpError("{1} group starting at #") << index
3550 << " requires 0 or 1 element, but found " << valueGroup{0}.size();
3553 // Check the types of a range of values.
3555 // {0}: Value index.
3556 // {1}: Type constraint function.
3557 // {2}: "operand" or "result"
3558 const char *const verifyValues = R"(
3559 for (auto v : valueGroup{0}) {
3560 if (::mlir::failed({1}(*this, v.getType(), "{2}", index++)))
3561 return ::mlir::failure();
3565 const auto canSkip = [](const NamedTypeConstraint &value) {
3566 return !value.hasPredicate() && !value.isOptional() &&
3567 !value.isVariadicOfVariadic();
3569 if (values.empty() || llvm::all_of(values, canSkip))
3570 return;
3572 FmtContext fctx;
3574 body << " {\n unsigned index = 0; (void)index;\n";
3576 for (const auto &staticValue : llvm::enumerate(values)) {
3577 const NamedTypeConstraint &value = staticValue.value();
3579 bool hasPredicate = value.hasPredicate();
3580 bool isOptional = value.isOptional();
3581 bool isVariadicOfVariadic = value.isVariadicOfVariadic();
3582 if (!hasPredicate && !isOptional && !isVariadicOfVariadic)
3583 continue;
3584 body << formatv(" auto valueGroup{2} = getODS{0}{1}s({2});\n",
3585 // Capitalize the first letter to match the function name
3586 valueKind.substr(0, 1).upper(), valueKind.substr(1),
3587 staticValue.index());
3589 // If the constraint is optional check that the value group has at most 1
3590 // value.
3591 if (isOptional) {
3592 body << formatv(verifyOptional, staticValue.index(), valueKind);
3593 } else if (isVariadicOfVariadic) {
3594 body << formatv(
3595 " if (::mlir::failed(::mlir::OpTrait::impl::verifyValueSizeAttr("
3596 "*this, \"{0}\", \"{1}\", valueGroup{2}.size())))\n"
3597 " return ::mlir::failure();\n",
3598 value.constraint.getVariadicOfVariadicSegmentSizeAttr(), value.name,
3599 staticValue.index());
3602 // Otherwise, if there is no predicate there is nothing left to do.
3603 if (!hasPredicate)
3604 continue;
3605 // Emit a loop to check all the dynamic values in the pack.
3606 StringRef constraintFn =
3607 staticVerifierEmitter.getTypeConstraintFn(value.constraint);
3608 body << formatv(verifyValues, staticValue.index(), constraintFn, valueKind);
3611 body << " }\n";
3614 void OpEmitter::genRegionVerifier(MethodBody &body) {
3615 /// Code to verify a region.
3617 /// {0}: Getter for the regions.
3618 /// {1}: The region constraint.
3619 /// {2}: The region's name.
3620 /// {3}: The region description.
3621 const char *const verifyRegion = R"(
3622 for (auto &region : {0})
3623 if (::mlir::failed({1}(*this, region, "{2}", index++)))
3624 return ::mlir::failure();
3626 /// Get a single region.
3628 /// {0}: The region's index.
3629 const char *const getSingleRegion =
3630 "::llvm::MutableArrayRef((*this)->getRegion({0}))";
3632 // If we have no regions, there is nothing more to do.
3633 const auto canSkip = [](const NamedRegion &region) {
3634 return region.constraint.getPredicate().isNull();
3636 auto regions = op.getRegions();
3637 if (regions.empty() && llvm::all_of(regions, canSkip))
3638 return;
3640 body << " {\n unsigned index = 0; (void)index;\n";
3641 for (const auto &it : llvm::enumerate(regions)) {
3642 const auto &region = it.value();
3643 if (canSkip(region))
3644 continue;
3646 auto getRegion = region.isVariadic()
3647 ? formatv("{0}()", op.getGetterName(region.name)).str()
3648 : formatv(getSingleRegion, it.index()).str();
3649 auto constraintFn =
3650 staticVerifierEmitter.getRegionConstraintFn(region.constraint);
3651 body << formatv(verifyRegion, getRegion, constraintFn, region.name);
3653 body << " }\n";
3656 void OpEmitter::genSuccessorVerifier(MethodBody &body) {
3657 const char *const verifySuccessor = R"(
3658 for (auto *successor : {0})
3659 if (::mlir::failed({1}(*this, successor, "{2}", index++)))
3660 return ::mlir::failure();
3662 /// Get a single successor.
3664 /// {0}: The successor's name.
3665 const char *const getSingleSuccessor = "::llvm::MutableArrayRef({0}())";
3667 // If we have no successors, there is nothing more to do.
3668 const auto canSkip = [](const NamedSuccessor &successor) {
3669 return successor.constraint.getPredicate().isNull();
3671 auto successors = op.getSuccessors();
3672 if (successors.empty() && llvm::all_of(successors, canSkip))
3673 return;
3675 body << " {\n unsigned index = 0; (void)index;\n";
3677 for (auto it : llvm::enumerate(successors)) {
3678 const auto &successor = it.value();
3679 if (canSkip(successor))
3680 continue;
3682 auto getSuccessor =
3683 formatv(successor.isVariadic() ? "{0}()" : getSingleSuccessor,
3684 successor.name, it.index())
3685 .str();
3686 auto constraintFn =
3687 staticVerifierEmitter.getSuccessorConstraintFn(successor.constraint);
3688 body << formatv(verifySuccessor, getSuccessor, constraintFn,
3689 successor.name);
3691 body << " }\n";
3694 /// Add a size count trait to the given operation class.
3695 static void addSizeCountTrait(OpClass &opClass, StringRef traitKind,
3696 int numTotal, int numVariadic) {
3697 if (numVariadic != 0) {
3698 if (numTotal == numVariadic)
3699 opClass.addTrait("::mlir::OpTrait::Variadic" + traitKind + "s");
3700 else
3701 opClass.addTrait("::mlir::OpTrait::AtLeastN" + traitKind + "s<" +
3702 Twine(numTotal - numVariadic) + ">::Impl");
3703 return;
3705 switch (numTotal) {
3706 case 0:
3707 opClass.addTrait("::mlir::OpTrait::Zero" + traitKind + "s");
3708 break;
3709 case 1:
3710 opClass.addTrait("::mlir::OpTrait::One" + traitKind);
3711 break;
3712 default:
3713 opClass.addTrait("::mlir::OpTrait::N" + traitKind + "s<" + Twine(numTotal) +
3714 ">::Impl");
3715 break;
3719 void OpEmitter::genTraits() {
3720 // Add region size trait.
3721 unsigned numRegions = op.getNumRegions();
3722 unsigned numVariadicRegions = op.getNumVariadicRegions();
3723 addSizeCountTrait(opClass, "Region", numRegions, numVariadicRegions);
3725 // Add result size traits.
3726 int numResults = op.getNumResults();
3727 int numVariadicResults = op.getNumVariableLengthResults();
3728 addSizeCountTrait(opClass, "Result", numResults, numVariadicResults);
3730 // For single result ops with a known specific type, generate a OneTypedResult
3731 // trait.
3732 if (numResults == 1 && numVariadicResults == 0) {
3733 auto cppName = op.getResults().begin()->constraint.getCPPClassName();
3734 opClass.addTrait("::mlir::OpTrait::OneTypedResult<" + cppName + ">::Impl");
3737 // Add successor size trait.
3738 unsigned numSuccessors = op.getNumSuccessors();
3739 unsigned numVariadicSuccessors = op.getNumVariadicSuccessors();
3740 addSizeCountTrait(opClass, "Successor", numSuccessors, numVariadicSuccessors);
3742 // Add variadic size trait and normal op traits.
3743 int numOperands = op.getNumOperands();
3744 int numVariadicOperands = op.getNumVariableLengthOperands();
3746 // Add operand size trait.
3747 addSizeCountTrait(opClass, "Operand", numOperands, numVariadicOperands);
3749 // The op traits defined internal are ensured that they can be verified
3750 // earlier.
3751 for (const auto &trait : op.getTraits()) {
3752 if (auto *opTrait = dyn_cast<tblgen::NativeTrait>(&trait)) {
3753 if (opTrait->isStructuralOpTrait())
3754 opClass.addTrait(opTrait->getFullyQualifiedTraitName());
3758 // OpInvariants wrapps the verifyInvariants which needs to be run before
3759 // native/interface traits and after all the traits with `StructuralOpTrait`.
3760 opClass.addTrait("::mlir::OpTrait::OpInvariants");
3762 if (emitHelper.hasProperties())
3763 opClass.addTrait("::mlir::BytecodeOpInterface::Trait");
3765 // Add the native and interface traits.
3766 for (const auto &trait : op.getTraits()) {
3767 if (auto *opTrait = dyn_cast<tblgen::NativeTrait>(&trait)) {
3768 if (!opTrait->isStructuralOpTrait())
3769 opClass.addTrait(opTrait->getFullyQualifiedTraitName());
3770 } else if (auto *opTrait = dyn_cast<tblgen::InterfaceTrait>(&trait)) {
3771 opClass.addTrait(opTrait->getFullyQualifiedTraitName());
3776 void OpEmitter::genOpNameGetter() {
3777 auto *method = opClass.addStaticMethod<Method::Constexpr>(
3778 "::llvm::StringLiteral", "getOperationName");
3779 ERROR_IF_PRUNED(method, "getOperationName", op);
3780 method->body() << " return ::llvm::StringLiteral(\"" << op.getOperationName()
3781 << "\");";
3784 void OpEmitter::genOpAsmInterface() {
3785 // If the user only has one results or specifically added the Asm trait,
3786 // then don't generate it for them. We specifically only handle multi result
3787 // operations, because the name of a single result in the common case is not
3788 // interesting(generally 'result'/'output'/etc.).
3789 // TODO: We could also add a flag to allow operations to opt in to this
3790 // generation, even if they only have a single operation.
3791 int numResults = op.getNumResults();
3792 if (numResults <= 1 || op.getTrait("::mlir::OpAsmOpInterface::Trait"))
3793 return;
3795 SmallVector<StringRef, 4> resultNames(numResults);
3796 for (int i = 0; i != numResults; ++i)
3797 resultNames[i] = op.getResultName(i);
3799 // Don't add the trait if none of the results have a valid name.
3800 if (llvm::all_of(resultNames, [](StringRef name) { return name.empty(); }))
3801 return;
3802 opClass.addTrait("::mlir::OpAsmOpInterface::Trait");
3804 // Generate the right accessor for the number of results.
3805 auto *method = opClass.addMethod(
3806 "void", "getAsmResultNames",
3807 MethodParameter("::mlir::OpAsmSetValueNameFn", "setNameFn"));
3808 ERROR_IF_PRUNED(method, "getAsmResultNames", op);
3809 auto &body = method->body();
3810 for (int i = 0; i != numResults; ++i) {
3811 body << " auto resultGroup" << i << " = getODSResults(" << i << ");\n"
3812 << " if (!resultGroup" << i << ".empty())\n"
3813 << " setNameFn(*resultGroup" << i << ".begin(), \""
3814 << resultNames[i] << "\");\n";
3818 //===----------------------------------------------------------------------===//
3819 // OpOperandAdaptor emitter
3820 //===----------------------------------------------------------------------===//
3822 namespace {
3823 // Helper class to emit Op operand adaptors to an output stream. Operand
3824 // adaptors are wrappers around random access ranges that provide named operand
3825 // getters identical to those defined in the Op.
3826 // This currently generates 3 classes per Op:
3827 // * A Base class within the 'detail' namespace, which contains all logic and
3828 // members independent of the random access range that is indexed into.
3829 // In other words, it contains all the attribute and region getters.
3830 // * A templated class named '{OpName}GenericAdaptor' with a template parameter
3831 // 'RangeT' that is indexed into by the getters to access the operands.
3832 // It contains all getters to access operands and inherits from the previous
3833 // class.
3834 // * A class named '{OpName}Adaptor', which inherits from the 'GenericAdaptor'
3835 // with 'mlir::ValueRange' as template parameter. It adds a constructor from
3836 // an instance of the op type and a verify function.
3837 class OpOperandAdaptorEmitter {
3838 public:
3839 static void
3840 emitDecl(const Operator &op,
3841 const StaticVerifierFunctionEmitter &staticVerifierEmitter,
3842 raw_ostream &os);
3843 static void
3844 emitDef(const Operator &op,
3845 const StaticVerifierFunctionEmitter &staticVerifierEmitter,
3846 raw_ostream &os);
3848 private:
3849 explicit OpOperandAdaptorEmitter(
3850 const Operator &op,
3851 const StaticVerifierFunctionEmitter &staticVerifierEmitter);
3853 // Add verification function. This generates a verify method for the adaptor
3854 // which verifies all the op-independent attribute constraints.
3855 void addVerification();
3857 // The operation for which to emit an adaptor.
3858 const Operator &op;
3860 // The generated adaptor classes.
3861 Class genericAdaptorBase;
3862 Class genericAdaptor;
3863 Class adaptor;
3865 // The emitter containing all of the locally emitted verification functions.
3866 const StaticVerifierFunctionEmitter &staticVerifierEmitter;
3868 // Helper for emitting adaptor code.
3869 OpOrAdaptorHelper emitHelper;
3871 } // namespace
3873 OpOperandAdaptorEmitter::OpOperandAdaptorEmitter(
3874 const Operator &op,
3875 const StaticVerifierFunctionEmitter &staticVerifierEmitter)
3876 : op(op), genericAdaptorBase(op.getGenericAdaptorName() + "Base"),
3877 genericAdaptor(op.getGenericAdaptorName()), adaptor(op.getAdaptorName()),
3878 staticVerifierEmitter(staticVerifierEmitter),
3879 emitHelper(op, /*emitForOp=*/false) {
3881 genericAdaptorBase.declare<VisibilityDeclaration>(Visibility::Public);
3882 bool useProperties = emitHelper.hasProperties();
3883 if (useProperties) {
3884 // Define the properties struct with multiple members.
3885 using ConstArgument =
3886 llvm::PointerUnion<const AttributeMetadata *, const NamedProperty *>;
3887 SmallVector<ConstArgument> attrOrProperties;
3888 for (const std::pair<StringRef, AttributeMetadata> &it :
3889 emitHelper.getAttrMetadata()) {
3890 if (!it.second.constraint || !it.second.constraint->isDerivedAttr())
3891 attrOrProperties.push_back(&it.second);
3893 for (const NamedProperty &prop : op.getProperties())
3894 attrOrProperties.push_back(&prop);
3895 if (emitHelper.getOperandSegmentsSize())
3896 attrOrProperties.push_back(&emitHelper.getOperandSegmentsSize().value());
3897 if (emitHelper.getResultSegmentsSize())
3898 attrOrProperties.push_back(&emitHelper.getResultSegmentsSize().value());
3899 assert(!attrOrProperties.empty());
3900 std::string declarations = " struct Properties {\n";
3901 llvm::raw_string_ostream os(declarations);
3902 std::string comparator =
3903 " bool operator==(const Properties &rhs) const {\n"
3904 " return \n";
3905 llvm::raw_string_ostream comparatorOs(comparator);
3906 for (const auto &attrOrProp : attrOrProperties) {
3907 if (const auto *namedProperty =
3908 llvm::dyn_cast_if_present<const NamedProperty *>(attrOrProp)) {
3909 StringRef name = namedProperty->name;
3910 if (name.empty())
3911 report_fatal_error("missing name for property");
3912 std::string camelName =
3913 convertToCamelFromSnakeCase(name, /*capitalizeFirst=*/true);
3914 auto &prop = namedProperty->prop;
3915 // Generate the data member using the storage type.
3916 os << " using " << name << "Ty = " << prop.getStorageType() << ";\n"
3917 << " " << name << "Ty " << name;
3918 if (prop.hasDefaultValue())
3919 os << " = " << prop.getDefaultValue();
3920 comparatorOs << " rhs." << name << " == this->" << name
3921 << " &&\n";
3922 // Emit accessors using the interface type.
3923 const char *accessorFmt = R"decl(;
3924 {0} get{1}() {
3925 auto &propStorage = this->{2};
3926 return {3};
3928 void set{1}(const {0} &propValue) {
3929 auto &propStorage = this->{2};
3930 {4};
3932 )decl";
3933 FmtContext fctx;
3934 os << formatv(accessorFmt, prop.getInterfaceType(), camelName, name,
3935 tgfmt(prop.getConvertFromStorageCall(),
3936 &fctx.addSubst("_storage", propertyStorage)),
3937 tgfmt(prop.getAssignToStorageCall(),
3938 &fctx.addSubst("_value", propertyValue)
3939 .addSubst("_storage", propertyStorage)));
3940 continue;
3942 const auto *namedAttr =
3943 llvm::dyn_cast_if_present<const AttributeMetadata *>(attrOrProp);
3944 const Attribute *attr = nullptr;
3945 if (namedAttr->constraint)
3946 attr = &*namedAttr->constraint;
3947 StringRef name = namedAttr->attrName;
3948 if (name.empty())
3949 report_fatal_error("missing name for property attr");
3950 std::string camelName =
3951 convertToCamelFromSnakeCase(name, /*capitalizeFirst=*/true);
3952 // Generate the data member using the storage type.
3953 StringRef storageType;
3954 if (attr) {
3955 storageType = attr->getStorageType();
3956 } else {
3957 if (name != operandSegmentAttrName && name != resultSegmentAttrName) {
3958 report_fatal_error("unexpected AttributeMetadata");
3960 // TODO: update to use native integers.
3961 storageType = "::mlir::DenseI32ArrayAttr";
3963 os << " using " << name << "Ty = " << storageType << ";\n"
3964 << " " << name << "Ty " << name << ";\n";
3965 comparatorOs << " rhs." << name << " == this->" << name << " &&\n";
3967 // Emit accessors using the interface type.
3968 if (attr) {
3969 const char *accessorFmt = R"decl(
3970 auto get{0}() {
3971 auto &propStorage = this->{1};
3972 return ::llvm::{2}<{3}>(propStorage);
3974 void set{0}(const {3} &propValue) {
3975 this->{1} = propValue;
3977 )decl";
3978 os << formatv(accessorFmt, camelName, name,
3979 attr->isOptional() || attr->hasDefaultValue()
3980 ? "dyn_cast_or_null"
3981 : "cast",
3982 storageType);
3985 comparatorOs << " true;\n }\n"
3986 " bool operator!=(const Properties &rhs) const {\n"
3987 " return !(*this == rhs);\n"
3988 " }\n";
3989 comparatorOs.flush();
3990 os << comparator;
3991 os << " };\n";
3992 os.flush();
3994 genericAdaptorBase.declare<ExtraClassDeclaration>(std::move(declarations));
3996 genericAdaptorBase.declare<VisibilityDeclaration>(Visibility::Protected);
3997 genericAdaptorBase.declare<Field>("::mlir::DictionaryAttr", "odsAttrs");
3998 genericAdaptorBase.declare<Field>("::std::optional<::mlir::OperationName>",
3999 "odsOpName");
4000 if (useProperties)
4001 genericAdaptorBase.declare<Field>("Properties", "properties");
4002 genericAdaptorBase.declare<Field>("::mlir::RegionRange", "odsRegions");
4004 genericAdaptor.addTemplateParam("RangeT");
4005 genericAdaptor.addField("RangeT", "odsOperands");
4006 genericAdaptor.addParent(
4007 ParentClass("detail::" + genericAdaptorBase.getClassName()));
4008 genericAdaptor.declare<UsingDeclaration>(
4009 "ValueT", "::llvm::detail::ValueOfRange<RangeT>");
4010 genericAdaptor.declare<UsingDeclaration>(
4011 "Base", "detail::" + genericAdaptorBase.getClassName());
4013 const auto *attrSizedOperands =
4014 op.getTrait("::mlir::OpTrait::AttrSizedOperandSegments");
4016 SmallVector<MethodParameter> paramList;
4017 paramList.emplace_back("::mlir::DictionaryAttr", "attrs",
4018 attrSizedOperands ? "" : "nullptr");
4019 if (useProperties)
4020 paramList.emplace_back("const Properties &", "properties", "{}");
4021 else
4022 paramList.emplace_back("const ::mlir::EmptyProperties &", "properties",
4023 "{}");
4024 paramList.emplace_back("::mlir::RegionRange", "regions", "{}");
4025 auto *baseConstructor = genericAdaptorBase.addConstructor(paramList);
4026 baseConstructor->addMemberInitializer("odsAttrs", "attrs");
4027 if (useProperties)
4028 baseConstructor->addMemberInitializer("properties", "properties");
4029 baseConstructor->addMemberInitializer("odsRegions", "regions");
4031 MethodBody &body = baseConstructor->body();
4032 body.indent() << "if (odsAttrs)\n";
4033 body.indent() << formatv(
4034 "odsOpName.emplace(\"{0}\", odsAttrs.getContext());\n",
4035 op.getOperationName());
4037 paramList.insert(paramList.begin(), MethodParameter("RangeT", "values"));
4038 auto *constructor = genericAdaptor.addConstructor(paramList);
4039 constructor->addMemberInitializer("Base", "attrs, properties, regions");
4040 constructor->addMemberInitializer("odsOperands", "values");
4042 // Add a forwarding constructor to the previous one that accepts
4043 // OpaqueProperties instead and check for null and perform the cast to the
4044 // actual properties type.
4045 paramList[1] = MethodParameter("::mlir::DictionaryAttr", "attrs");
4046 paramList[2] = MethodParameter("::mlir::OpaqueProperties", "properties");
4047 auto *opaquePropertiesConstructor =
4048 genericAdaptor.addConstructor(std::move(paramList));
4049 if (useProperties) {
4050 opaquePropertiesConstructor->addMemberInitializer(
4051 genericAdaptor.getClassName(),
4052 "values, "
4053 "attrs, "
4054 "(properties ? *properties.as<Properties *>() : Properties{}), "
4055 "regions");
4056 } else {
4057 opaquePropertiesConstructor->addMemberInitializer(
4058 genericAdaptor.getClassName(),
4059 "values, "
4060 "attrs, "
4061 "(properties ? *properties.as<::mlir::EmptyProperties *>() : "
4062 "::mlir::EmptyProperties{}), "
4063 "regions");
4067 // Create constructors constructing the adaptor from an instance of the op.
4068 // This takes the attributes, properties and regions from the op instance
4069 // and the value range from the parameter.
4071 // Base class is in the cpp file and can simply access the members of the op
4072 // class to initialize the template independent fields.
4073 auto *constructor = genericAdaptorBase.addConstructor(
4074 MethodParameter(op.getCppClassName(), "op"));
4075 constructor->addMemberInitializer(
4076 genericAdaptorBase.getClassName(),
4077 llvm::Twine(!useProperties ? "op->getAttrDictionary()"
4078 : "op->getDiscardableAttrDictionary()") +
4079 ", op.getProperties(), op->getRegions()");
4081 // Generic adaptor is templated and therefore defined inline in the header.
4082 // We cannot use the Op class here as it is an incomplete type (we have a
4083 // circular reference between the two).
4084 // Use a template trick to make the constructor be instantiated at call site
4085 // when the op class is complete.
4086 constructor = genericAdaptor.addConstructor(
4087 MethodParameter("RangeT", "values"), MethodParameter("LateInst", "op"));
4088 constructor->addTemplateParam("LateInst = " + op.getCppClassName());
4089 constructor->addTemplateParam(
4090 "= std::enable_if_t<std::is_same_v<LateInst, " + op.getCppClassName() +
4091 ">>");
4092 constructor->addMemberInitializer("Base", "op");
4093 constructor->addMemberInitializer("odsOperands", "values");
4096 std::string sizeAttrInit;
4097 if (op.getTrait("::mlir::OpTrait::AttrSizedOperandSegments")) {
4098 if (op.getDialect().usePropertiesForAttributes())
4099 sizeAttrInit =
4100 formatv(adapterSegmentSizeAttrInitCodeProperties,
4101 llvm::formatv("getProperties().operandSegmentSizes"));
4102 else
4103 sizeAttrInit = formatv(adapterSegmentSizeAttrInitCode,
4104 emitHelper.getAttr(operandSegmentAttrName));
4106 generateNamedOperandGetters(op, genericAdaptor,
4107 /*genericAdaptorBase=*/&genericAdaptorBase,
4108 /*sizeAttrInit=*/sizeAttrInit,
4109 /*rangeType=*/"RangeT",
4110 /*rangeElementType=*/"ValueT",
4111 /*rangeBeginCall=*/"odsOperands.begin()",
4112 /*rangeSizeCall=*/"odsOperands.size()",
4113 /*getOperandCallPattern=*/"odsOperands[{0}]");
4115 // Any invalid overlap for `getOperands` will have been diagnosed before
4116 // here already.
4117 if (auto *m = genericAdaptor.addMethod("RangeT", "getOperands"))
4118 m->body() << " return odsOperands;";
4120 FmtContext fctx;
4121 fctx.withBuilder("::mlir::Builder(odsAttrs.getContext())");
4123 // Generate named accessor with Attribute return type.
4124 auto emitAttrWithStorageType = [&](StringRef name, StringRef emitName,
4125 Attribute attr) {
4126 auto *method =
4127 genericAdaptorBase.addMethod(attr.getStorageType(), emitName + "Attr");
4128 ERROR_IF_PRUNED(method, "Adaptor::" + emitName + "Attr", op);
4129 auto &body = method->body().indent();
4130 if (!useProperties)
4131 body << "assert(odsAttrs && \"no attributes when constructing "
4132 "adapter\");\n";
4133 body << formatv(
4134 "auto attr = ::llvm::{1}<{2}>({0});\n", emitHelper.getAttr(name),
4135 attr.hasDefaultValue() || attr.isOptional() ? "dyn_cast_or_null"
4136 : "cast",
4137 attr.getStorageType());
4139 if (attr.hasDefaultValue() && attr.isOptional()) {
4140 // Use the default value if attribute is not set.
4141 // TODO: this is inefficient, we are recreating the attribute for every
4142 // call. This should be set instead.
4143 std::string defaultValue = std::string(
4144 tgfmt(attr.getConstBuilderTemplate(), &fctx, attr.getDefaultValue()));
4145 body << "if (!attr)\n attr = " << defaultValue << ";\n";
4147 body << "return attr;\n";
4150 if (useProperties) {
4151 auto *m = genericAdaptorBase.addInlineMethod("const Properties &",
4152 "getProperties");
4153 ERROR_IF_PRUNED(m, "Adaptor::getProperties", op);
4154 m->body() << " return properties;";
4157 auto *m =
4158 genericAdaptorBase.addMethod("::mlir::DictionaryAttr", "getAttributes");
4159 ERROR_IF_PRUNED(m, "Adaptor::getAttributes", op);
4160 m->body() << " return odsAttrs;";
4162 for (auto &namedAttr : op.getAttributes()) {
4163 const auto &name = namedAttr.name;
4164 const auto &attr = namedAttr.attr;
4165 if (attr.isDerivedAttr())
4166 continue;
4167 std::string emitName = op.getGetterName(name);
4168 emitAttrWithStorageType(name, emitName, attr);
4169 emitAttrGetterWithReturnType(fctx, genericAdaptorBase, op, emitName, attr);
4172 unsigned numRegions = op.getNumRegions();
4173 for (unsigned i = 0; i < numRegions; ++i) {
4174 const auto &region = op.getRegion(i);
4175 if (region.name.empty())
4176 continue;
4178 // Generate the accessors for a variadic region.
4179 std::string name = op.getGetterName(region.name);
4180 if (region.isVariadic()) {
4181 auto *m = genericAdaptorBase.addMethod("::mlir::RegionRange", name);
4182 ERROR_IF_PRUNED(m, "Adaptor::" + name, op);
4183 m->body() << formatv(" return odsRegions.drop_front({0});", i);
4184 continue;
4187 auto *m = genericAdaptorBase.addMethod("::mlir::Region &", name);
4188 ERROR_IF_PRUNED(m, "Adaptor::" + name, op);
4189 m->body() << formatv(" return *odsRegions[{0}];", i);
4191 if (numRegions > 0) {
4192 // Any invalid overlap for `getRegions` will have been diagnosed before
4193 // here already.
4194 if (auto *m =
4195 genericAdaptorBase.addMethod("::mlir::RegionRange", "getRegions"))
4196 m->body() << " return odsRegions;";
4199 StringRef genericAdaptorClassName = genericAdaptor.getClassName();
4200 adaptor.addParent(ParentClass(genericAdaptorClassName))
4201 .addTemplateParam("::mlir::ValueRange");
4202 adaptor.declare<VisibilityDeclaration>(Visibility::Public);
4203 adaptor.declare<UsingDeclaration>(genericAdaptorClassName +
4204 "::" + genericAdaptorClassName);
4206 // Constructor taking the Op as single parameter.
4207 auto *constructor =
4208 adaptor.addConstructor(MethodParameter(op.getCppClassName(), "op"));
4209 constructor->addMemberInitializer(genericAdaptorClassName,
4210 "op->getOperands(), op");
4213 // Add verification function.
4214 addVerification();
4216 genericAdaptorBase.finalize();
4217 genericAdaptor.finalize();
4218 adaptor.finalize();
4221 void OpOperandAdaptorEmitter::addVerification() {
4222 auto *method = adaptor.addMethod("::mlir::LogicalResult", "verify",
4223 MethodParameter("::mlir::Location", "loc"));
4224 ERROR_IF_PRUNED(method, "verify", op);
4225 auto &body = method->body();
4226 bool useProperties = emitHelper.hasProperties();
4228 FmtContext verifyCtx;
4229 populateSubstitutions(emitHelper, verifyCtx);
4230 genAttributeVerifier(emitHelper, verifyCtx, body, staticVerifierEmitter,
4231 useProperties);
4233 body << " return ::mlir::success();";
4236 void OpOperandAdaptorEmitter::emitDecl(
4237 const Operator &op,
4238 const StaticVerifierFunctionEmitter &staticVerifierEmitter,
4239 raw_ostream &os) {
4240 OpOperandAdaptorEmitter emitter(op, staticVerifierEmitter);
4242 NamespaceEmitter ns(os, "detail");
4243 emitter.genericAdaptorBase.writeDeclTo(os);
4245 emitter.genericAdaptor.writeDeclTo(os);
4246 emitter.adaptor.writeDeclTo(os);
4249 void OpOperandAdaptorEmitter::emitDef(
4250 const Operator &op,
4251 const StaticVerifierFunctionEmitter &staticVerifierEmitter,
4252 raw_ostream &os) {
4253 OpOperandAdaptorEmitter emitter(op, staticVerifierEmitter);
4255 NamespaceEmitter ns(os, "detail");
4256 emitter.genericAdaptorBase.writeDefTo(os);
4258 emitter.genericAdaptor.writeDefTo(os);
4259 emitter.adaptor.writeDefTo(os);
4262 // Emits the opcode enum and op classes.
4263 static void emitOpClasses(const RecordKeeper &recordKeeper,
4264 const std::vector<Record *> &defs, raw_ostream &os,
4265 bool emitDecl) {
4266 // First emit forward declaration for each class, this allows them to refer
4267 // to each others in traits for example.
4268 if (emitDecl) {
4269 os << "#if defined(GET_OP_CLASSES) || defined(GET_OP_FWD_DEFINES)\n";
4270 os << "#undef GET_OP_FWD_DEFINES\n";
4271 for (auto *def : defs) {
4272 Operator op(*def);
4273 NamespaceEmitter emitter(os, op.getCppNamespace());
4274 os << "class " << op.getCppClassName() << ";\n";
4276 os << "#endif\n\n";
4279 IfDefScope scope("GET_OP_CLASSES", os);
4280 if (defs.empty())
4281 return;
4283 // Generate all of the locally instantiated methods first.
4284 StaticVerifierFunctionEmitter staticVerifierEmitter(os, recordKeeper);
4285 os << formatv(opCommentHeader, "Local Utility Method", "Definitions");
4286 staticVerifierEmitter.emitOpConstraints(defs, emitDecl);
4288 for (auto *def : defs) {
4289 Operator op(*def);
4290 if (emitDecl) {
4292 NamespaceEmitter emitter(os, op.getCppNamespace());
4293 os << formatv(opCommentHeader, op.getQualCppClassName(),
4294 "declarations");
4295 OpOperandAdaptorEmitter::emitDecl(op, staticVerifierEmitter, os);
4296 OpEmitter::emitDecl(op, os, staticVerifierEmitter);
4298 // Emit the TypeID explicit specialization to have a single definition.
4299 if (!op.getCppNamespace().empty())
4300 os << "MLIR_DECLARE_EXPLICIT_TYPE_ID(" << op.getCppNamespace()
4301 << "::" << op.getCppClassName() << ")\n\n";
4302 } else {
4304 NamespaceEmitter emitter(os, op.getCppNamespace());
4305 os << formatv(opCommentHeader, op.getQualCppClassName(), "definitions");
4306 OpOperandAdaptorEmitter::emitDef(op, staticVerifierEmitter, os);
4307 OpEmitter::emitDef(op, os, staticVerifierEmitter);
4309 // Emit the TypeID explicit specialization to have a single definition.
4310 if (!op.getCppNamespace().empty())
4311 os << "MLIR_DEFINE_EXPLICIT_TYPE_ID(" << op.getCppNamespace()
4312 << "::" << op.getCppClassName() << ")\n\n";
4317 // Emits a comma-separated list of the ops.
4318 static void emitOpList(const std::vector<Record *> &defs, raw_ostream &os) {
4319 IfDefScope scope("GET_OP_LIST", os);
4321 interleave(
4322 // TODO: We are constructing the Operator wrapper instance just for
4323 // getting it's qualified class name here. Reduce the overhead by having a
4324 // lightweight version of Operator class just for that purpose.
4325 defs, [&os](Record *def) { os << Operator(def).getQualCppClassName(); },
4326 [&os]() { os << ",\n"; });
4329 static bool emitOpDecls(const RecordKeeper &recordKeeper, raw_ostream &os) {
4330 emitSourceFileHeader("Op Declarations", os, recordKeeper);
4332 std::vector<Record *> defs = getRequestedOpDefinitions(recordKeeper);
4333 emitOpClasses(recordKeeper, defs, os, /*emitDecl=*/true);
4335 return false;
4338 static bool emitOpDefs(const RecordKeeper &recordKeeper, raw_ostream &os) {
4339 emitSourceFileHeader("Op Definitions", os, recordKeeper);
4341 std::vector<Record *> defs = getRequestedOpDefinitions(recordKeeper);
4342 emitOpList(defs, os);
4343 emitOpClasses(recordKeeper, defs, os, /*emitDecl=*/false);
4345 return false;
4348 static mlir::GenRegistration
4349 genOpDecls("gen-op-decls", "Generate op declarations",
4350 [](const RecordKeeper &records, raw_ostream &os) {
4351 return emitOpDecls(records, os);
4354 static mlir::GenRegistration genOpDefs("gen-op-defs", "Generate op definitions",
4355 [](const RecordKeeper &records,
4356 raw_ostream &os) {
4357 return emitOpDefs(records, os);