1//===- OpFormatGen.cpp - MLIR operation asm format 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#include "OpFormatGen.h"
10#include "FormatGen.h"
11#include "OpClass.h"
12#include "mlir/Support/LLVM.h"
13#include "mlir/TableGen/Class.h"
14#include "mlir/TableGen/EnumInfo.h"
15#include "mlir/TableGen/Format.h"
16#include "mlir/TableGen/Operator.h"
17#include "mlir/TableGen/Trait.h"
18#include "llvm/ADT/MapVector.h"
19#include "llvm/ADT/Sequence.h"
20#include "llvm/ADT/SetVector.h"
21#include "llvm/ADT/SmallBitVector.h"
22#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/StringExtras.h"
24#include "llvm/ADT/Twine.h"
25#include "llvm/ADT/TypeSwitch.h"
26#include "llvm/Support/Signals.h"
27#include "llvm/Support/SourceMgr.h"
28#include "llvm/TableGen/Record.h"
29
30#define DEBUG_TYPE "mlir-tblgen-opformatgen"
31
32using namespace mlir;
33using namespace mlir::tblgen;
34using llvm::formatv;
35using llvm::Record;
36using llvm::StringMap;
37
38//===----------------------------------------------------------------------===//
39// VariableElement
40//===----------------------------------------------------------------------===//
41
42namespace {
43/// This class represents an instance of an op variable element. A variable
44/// refers to something registered on the operation itself, e.g. an operand,
45/// result, attribute, region, or successor.
46template <typename VarT, VariableElement::Kind VariableKind>
47class OpVariableElement : public VariableElementBase<VariableKind> {
48public:
49 using Base = OpVariableElement<VarT, VariableKind>;
50
51 /// Create an op variable element with the variable value.
52 OpVariableElement(const VarT *var) : var(var) {}
53
54 /// Get the variable.
55 const VarT *getVar() const { return var; }
56
57protected:
58 /// The op variable, e.g. a type or attribute constraint.
59 const VarT *var;
60};
61
62/// This class represents a variable that refers to an attribute argument.
63struct AttributeVariable
64 : public OpVariableElement<NamedAttribute, VariableElement::Attribute> {
65 using Base::Base;
66
67 /// Return the constant builder call for the type of this attribute, or
68 /// std::nullopt if it doesn't have one.
69 std::optional<StringRef> getTypeBuilder() const {
70 std::optional<Type> attrType = var->attr.getValueType();
71 return attrType ? attrType->getBuilderCall() : std::nullopt;
72 }
73
74 /// Indicate if this attribute is printed "qualified" (that is it is
75 /// prefixed with the `#dialect.mnemonic`).
76 bool shouldBeQualified() { return shouldBeQualifiedFlag; }
77 void setShouldBeQualified(bool qualified = true) {
78 shouldBeQualifiedFlag = qualified;
79 }
80
81 /// Indicate if this attribute is formatted using its underlying enum value.
82 bool shouldFormatAsEnum() const { return shouldFormatAsEnumFlag; }
83 void setShouldFormatAsEnum() { shouldFormatAsEnumFlag = true; }
84
85private:
86 bool shouldBeQualifiedFlag = false;
87 bool shouldFormatAsEnumFlag = false;
88};
89
90/// This class represents a variable that refers to an operand argument.
91using OperandVariable =
92 OpVariableElement<NamedTypeConstraint, VariableElement::Operand>;
93
94/// This class represents a variable that refers to a result.
95using ResultVariable =
96 OpVariableElement<NamedTypeConstraint, VariableElement::Result>;
97
98/// This class represents a variable that refers to a region.
99using RegionVariable = OpVariableElement<NamedRegion, VariableElement::Region>;
100
101/// This class represents a variable that refers to a successor.
102using SuccessorVariable =
103 OpVariableElement<NamedSuccessor, VariableElement::Successor>;
104
105/// This class represents a variable that refers to a property argument.
106using PropertyVariable =
107 OpVariableElement<NamedProperty, VariableElement::Property>;
108
109/// LLVM RTTI helper for attribute-like variables, that is, attributes or
110/// properties. This allows for common handling of attributes and properties in
111/// parts of the code that are oblivious to whether something is stored as an
112/// attribute or a property.
113struct AttributeLikeVariable : public VariableElement {
114 enum { AttributeLike = 1 << 0 };
115
116 static bool classof(const VariableElement *ve) {
117 return ve->getKind() == VariableElement::Attribute ||
118 ve->getKind() == VariableElement::Property;
119 }
120
121 static bool classof(const FormatElement *fe) {
122 return isa<VariableElement>(Val: fe) && classof(ve: cast<VariableElement>(Val: fe));
123 }
124
125 /// Returns true if the variable is a UnitAttr or a UnitProp.
126 bool isUnit() const {
127 if (const auto *attr = dyn_cast<AttributeVariable>(Val: this))
128 return attr->getVar()->attr.getBaseAttr().getAttrDefName() == "UnitAttr";
129 if (const auto *prop = dyn_cast<PropertyVariable>(Val: this)) {
130 StringRef baseDefName =
131 prop->getVar()->prop.getBaseProperty().getPropertyDefName();
132 // Note: remove the `UnitProperty` case once the deprecation period is
133 // over.
134 return baseDefName == "UnitProp" || baseDefName == "UnitProperty";
135 }
136 llvm_unreachable("Type that wasn't listed in classof()");
137 }
138
139 StringRef getName() const {
140 if (const auto *attr = dyn_cast<AttributeVariable>(Val: this))
141 return attr->getVar()->name;
142 if (const auto *prop = dyn_cast<PropertyVariable>(Val: this))
143 return prop->getVar()->name;
144 llvm_unreachable("Type that wasn't listed in classof()");
145 }
146};
147} // namespace
148
149//===----------------------------------------------------------------------===//
150// DirectiveElement
151//===----------------------------------------------------------------------===//
152
153namespace {
154/// This class represents the `operands` directive. This directive represents
155/// all of the operands of an operation.
156using OperandsDirective = DirectiveElementBase<DirectiveElement::Operands>;
157
158/// This class represents the `results` directive. This directive represents
159/// all of the results of an operation.
160using ResultsDirective = DirectiveElementBase<DirectiveElement::Results>;
161
162/// This class represents the `regions` directive. This directive represents
163/// all of the regions of an operation.
164using RegionsDirective = DirectiveElementBase<DirectiveElement::Regions>;
165
166/// This class represents the `successors` directive. This directive represents
167/// all of the successors of an operation.
168using SuccessorsDirective = DirectiveElementBase<DirectiveElement::Successors>;
169
170/// This class represents the `attr-dict` directive. This directive represents
171/// the attribute dictionary of the operation.
172class AttrDictDirective
173 : public DirectiveElementBase<DirectiveElement::AttrDict> {
174public:
175 explicit AttrDictDirective(bool withKeyword) : withKeyword(withKeyword) {}
176
177 /// Return whether the dictionary should be printed with the 'attributes'
178 /// keyword.
179 bool isWithKeyword() const { return withKeyword; }
180
181private:
182 /// If the dictionary should be printed with the 'attributes' keyword.
183 bool withKeyword;
184};
185
186/// This class represents the `prop-dict` directive. This directive represents
187/// the properties of the operation, expressed as a directionary.
188class PropDictDirective
189 : public DirectiveElementBase<DirectiveElement::PropDict> {
190public:
191 explicit PropDictDirective() = default;
192};
193
194/// This class represents the `functional-type` directive. This directive takes
195/// two arguments and formats them, respectively, as the inputs and results of a
196/// FunctionType.
197class FunctionalTypeDirective
198 : public DirectiveElementBase<DirectiveElement::FunctionalType> {
199public:
200 FunctionalTypeDirective(FormatElement *inputs, FormatElement *results)
201 : inputs(inputs), results(results) {}
202
203 FormatElement *getInputs() const { return inputs; }
204 FormatElement *getResults() const { return results; }
205
206private:
207 /// The input and result arguments.
208 FormatElement *inputs, *results;
209};
210
211/// This class represents the `type` directive.
212class TypeDirective : public DirectiveElementBase<DirectiveElement::Type> {
213public:
214 TypeDirective(FormatElement *arg) : arg(arg) {}
215
216 FormatElement *getArg() const { return arg; }
217
218 /// Indicate if this type is printed "qualified" (that is it is
219 /// prefixed with the `!dialect.mnemonic`).
220 bool shouldBeQualified() { return shouldBeQualifiedFlag; }
221 void setShouldBeQualified(bool qualified = true) {
222 shouldBeQualifiedFlag = qualified;
223 }
224
225private:
226 /// The argument that is used to format the directive.
227 FormatElement *arg;
228
229 bool shouldBeQualifiedFlag = false;
230};
231
232/// This class represents a group of order-independent optional clauses. Each
233/// clause starts with a literal element and has a corresponding parsing
234/// element. A parsing element is a continuous sequence of format elements.
235/// Each clause can appear 0 or 1 time. An optional literal separates clauses.
236class OIListElement : public DirectiveElementBase<DirectiveElement::OIList> {
237public:
238 OIListElement(LiteralElement *separator,
239 std::vector<FormatElement *> &&literalElements,
240 std::vector<std::vector<FormatElement *>> &&parsingElements)
241 : separator(separator), literalElements(std::move(literalElements)),
242 parsingElements(std::move(parsingElements)) {}
243
244 /// Returns the optional separator between clauses.
245 LiteralElement *getSeparator() const { return separator; }
246
247 /// Returns a range to iterate over the LiteralElements.
248 auto getLiteralElements() const {
249 return llvm::map_range(C: literalElements, F: [](FormatElement *el) {
250 return cast<LiteralElement>(Val: el);
251 });
252 }
253
254 /// Returns a range to iterate over the parsing elements corresponding to the
255 /// clauses.
256 ArrayRef<std::vector<FormatElement *>> getParsingElements() const {
257 return parsingElements;
258 }
259
260 /// Returns a range to iterate over tuples of parsing and literal elements.
261 auto getClauses() const {
262 return llvm::zip(t: getLiteralElements(), u: getParsingElements());
263 }
264
265 /// If the parsing element is a single UnitAttr element, then it returns the
266 /// attribute variable. Otherwise, returns nullptr.
267 AttributeLikeVariable *
268 getUnitVariableParsingElement(ArrayRef<FormatElement *> pelement) {
269 if (pelement.size() == 1) {
270 auto *attrElem = dyn_cast<AttributeLikeVariable>(Val: pelement[0]);
271 if (attrElem && attrElem->isUnit())
272 return attrElem;
273 }
274 return nullptr;
275 }
276
277private:
278 /// An optional literal printed and parsed between clauses.
279 LiteralElement *separator;
280
281 /// A vector of `LiteralElement` objects. Each element stores the keyword
282 /// for one case of oilist element. For example, an oilist element along with
283 /// the `literalElements` vector:
284 /// ```
285 /// oilist [ `keyword` `=` `(` $arg0 `)` | `otherKeyword` `<` $arg1 `>`]
286 /// literalElements = { `keyword`, `otherKeyword` }
287 /// ```
288 std::vector<FormatElement *> literalElements;
289
290 /// A vector of valid declarative assembly format vectors. Each object in
291 /// parsing elements is a vector of elements in assembly format syntax.
292 /// For example, an oilist element along with the parsingElements vector:
293 /// ```
294 /// oilist [ `keyword` `=` `(` $arg0 `)` | `otherKeyword` `<` $arg1 `>`]
295 /// parsingElements = {
296 /// { `=`, `(`, $arg0, `)` },
297 /// { `<`, $arg1, `>` }
298 /// }
299 /// ```
300 std::vector<std::vector<FormatElement *>> parsingElements;
301};
302} // namespace
303
304//===----------------------------------------------------------------------===//
305// OperationFormat
306//===----------------------------------------------------------------------===//
307
308namespace {
309
310using ConstArgument =
311 llvm::PointerUnion<const NamedAttribute *, const NamedTypeConstraint *>;
312
313struct OperationFormat {
314 /// This class represents a specific resolver for an operand or result type.
315 class TypeResolution {
316 public:
317 TypeResolution() = default;
318
319 /// Get the index into the buildable types for this type, or std::nullopt.
320 std::optional<int> getBuilderIdx() const { return builderIdx; }
321 void setBuilderIdx(int idx) { builderIdx = idx; }
322
323 /// Get the variable this type is resolved to, or nullptr.
324 const NamedTypeConstraint *getVariable() const {
325 return llvm::dyn_cast_if_present<const NamedTypeConstraint *>(Val: resolver);
326 }
327 /// Get the attribute this type is resolved to, or nullptr.
328 const NamedAttribute *getAttribute() const {
329 return llvm::dyn_cast_if_present<const NamedAttribute *>(Val: resolver);
330 }
331 /// Get the transformer for the type of the variable, or std::nullopt.
332 std::optional<StringRef> getVarTransformer() const {
333 return variableTransformer;
334 }
335 /// Returns true if the type is parsed directly from the assembly format.
336 bool isDirectlyParsed() const {
337 return !builderIdx && !getVariable() && !getAttribute();
338 }
339 void setResolver(ConstArgument arg, std::optional<StringRef> transformer) {
340 resolver = arg;
341 variableTransformer = transformer;
342 assert(getVariable() || getAttribute());
343 }
344
345 private:
346 /// If the type is resolved with a buildable type, this is the index into
347 /// 'buildableTypes' in the parent format.
348 std::optional<int> builderIdx;
349 /// If the type is resolved based upon another operand or result, this is
350 /// the variable or the attribute that this type is resolved to.
351 ConstArgument resolver;
352 /// If the type is resolved based upon another operand or result, this is
353 /// a transformer to apply to the variable when resolving.
354 std::optional<StringRef> variableTransformer;
355 };
356
357 /// The context used to generate an element's parser. This controls whether
358 /// attribute variables are parsed optionally; it does not change the parsing
359 /// of other element kinds.
360 enum class GenContext {
361 /// Use the default parsing behaviour: an ODS optional attribute may be
362 /// absent. Used at the top level and by callers using the default context.
363 Normal,
364 /// Generate an element in a selected branch of an optional group. Attribute
365 /// variables must be present, even if they are optional in ODS. The group
366 /// is optional, but its contents are required once the branch is selected.
367 /// The group's first element is parsed separately to select the branch.
368 Optional
369 };
370
371 OperationFormat(const Operator &op)
372 : useStrictPropertiesInAssemblyFormat(
373 op.getDialect().useStrictPropertiesInAssemblyFormat()),
374 opCppClassName(op.getCppClassName()) {
375 operandTypes.resize(new_size: op.getNumOperands(), x: TypeResolution());
376 resultTypes.resize(new_size: op.getNumResults(), x: TypeResolution());
377
378 hasImplicitTermTrait = llvm::any_of(Range: op.getTraits(), P: [](const Trait &trait) {
379 return trait.getDef().isSubClassOf(Name: "SingleBlockImplicitTerminatorImpl");
380 });
381
382 hasSingleBlockTrait = op.getTrait(trait: "::mlir::OpTrait::SingleBlock");
383
384 for (const NamedAttribute &attr : op.getAttributes()) {
385 if (!attr.attr.isDerivedAttr())
386 inherentAttrNames.push_back(Elt: attr.name);
387 }
388 }
389
390 /// Generate the operation parser from this format.
391 void genParser(Operator &op, OpClass &opClass);
392 /// Generate the parser code for a specific format element.
393 /// `genCtx`, together with ODS optionality, determines whether attribute
394 /// variables may be absent at this position.
395 void genElementParser(FormatElement *element, MethodBody &body,
396 FmtContext &attrTypeCtx,
397 GenContext genCtx = GenContext::Normal);
398 /// Generate the C++ to resolve the types of operands and results during
399 /// parsing.
400 void genParserTypeResolution(Operator &op, MethodBody &body);
401 /// Generate the C++ to resolve the types of the operands during parsing.
402 void genParserOperandTypeResolution(
403 Operator &op, MethodBody &body,
404 function_ref<void(TypeResolution &, StringRef)> emitTypeResolver);
405 /// Generate the C++ to resolve regions during parsing.
406 void genParserRegionResolution(Operator &op, MethodBody &body);
407 /// Generate the C++ to resolve successors during parsing.
408 void genParserSuccessorResolution(Operator &op, MethodBody &body);
409 /// Generate the C++ to handling variadic segment size traits.
410 void genParserVariadicSegmentResolution(Operator &op, MethodBody &body);
411
412 /// Generate the operation printer from this format.
413 void genPrinter(Operator &op, OpClass &opClass);
414
415 /// Generate the printer code for a specific format element.
416 void genElementPrinter(FormatElement *element, MethodBody &body, Operator &op,
417 bool &shouldEmitSpace, bool &lastWasPunctuation);
418
419 /// The various elements in this format.
420 std::vector<FormatElement *> elements;
421
422 /// A flag indicating if all operand/result types were seen. If the format
423 /// contains these, it can not contain individual type resolvers.
424 bool allOperands = false, allOperandTypes = false, allResultTypes = false;
425
426 /// A flag indicating if this operation infers its result types
427 bool infersResultTypes = false;
428
429 /// A flag indicating if this operation has the SingleBlockImplicitTerminator
430 /// trait.
431 bool hasImplicitTermTrait;
432
433 /// A flag indicating if this operation has the SingleBlock trait.
434 bool hasSingleBlockTrait;
435
436 /// Indicate whether the dialect uses strict properties in assembly formats.
437 bool useStrictPropertiesInAssemblyFormat;
438
439 /// Indicate whether prop-dict is used in the format
440 bool hasPropDict = false;
441
442 /// The Operation class name
443 StringRef opCppClassName;
444
445 /// The names of inherent attributes for this operation.
446 SmallVector<StringRef> inherentAttrNames;
447
448 /// A map of buildable types to indices.
449 llvm::MapVector<StringRef, int, StringMap<int>> buildableTypes;
450
451 /// The index of the buildable type, if valid, for every operand and result.
452 std::vector<TypeResolution> operandTypes, resultTypes;
453
454 /// The set of attributes explicitly used within the format.
455 llvm::SmallSetVector<const NamedAttribute *, 8> usedAttributes;
456 llvm::StringSet<> inferredAttributes;
457
458 /// The set of properties explicitly used within the format.
459 llvm::SmallSetVector<const NamedProperty *, 8> usedProperties;
460};
461} // namespace
462
463//===----------------------------------------------------------------------===//
464// Parser Gen
465//===----------------------------------------------------------------------===//
466
467/// Returns the Record to use when constructing an EnumInfo for the given
468/// attribute. For legacy EnumAttrInfo-based attributes, this is the attribute
469/// def itself (which extends both EnumInfo and Attr). For newer EnumAttr-based
470/// attributes (which extend AttrDef), this is the `enum` sub-field.
471static const llvm::Record *getEnumInfoRecord(const Attribute &attr) {
472 if (attr.isSubClassOf(className: "EnumAttr"))
473 return attr.getDef().getValueAsDef(FieldName: "enum");
474 return &attr.getDef();
475}
476
477/// Returns true if we can format the given attribute as an enum in the
478/// parser format.
479static bool canFormatEnumAttr(const NamedAttribute *attr) {
480 Attribute baseAttr = attr->attr.getBaseAttr();
481 if (!baseAttr.isEnumAttr())
482 return false;
483
484 // New-style EnumAttr-based attributes have a custom AttrDef parser and
485 // printer. Only format their symbolic value directly when requested with an
486 // `enum` directive.
487 if (baseAttr.isSubClassOf(className: "EnumAttr"))
488 return false;
489
490 // The attribute must have a valid underlying type and a constant builder.
491 EnumInfo enumInfo(getEnumInfoRecord(attr: baseAttr));
492 return !enumInfo.getUnderlyingType().empty() &&
493 !baseAttr.getConstBuilderTemplate().empty();
494}
495
496/// Returns true if a keyed `prop-dict` field should use the underlying enum
497/// syntax instead of the default EnumAttr body syntax. Custom EnumAttr formats
498/// continue to use their own parser and printer.
499static bool shouldStripEnumAttrInPropDict(const NamedAttribute *attr) {
500 Attribute baseAttr = attr->attr.getBaseAttr();
501 return baseAttr.isSubClassOf(className: "EnumAttr") &&
502 baseAttr.getDef().getValueAsString(FieldName: "assemblyFormat") ==
503 "`<` $value `>`";
504}
505
506/// Returns true if a stripped EnumAttr field needs brackets to disambiguate
507/// commas in an unquoted bit enum from commas separating `prop-dict` fields.
508static bool needsPropDictEnumBrackets(const NamedAttribute *attr) {
509 if (!shouldStripEnumAttrInPropDict(attr))
510 return false;
511 EnumInfo enumInfo(getEnumInfoRecord(attr: attr->attr.getBaseAttr()));
512 return enumInfo.isBitEnum() && enumInfo.getBitEnumSeparatorKind() ==
513 EnumInfo::BitEnumSeparatorKind::Comma;
514}
515
516/// Returns if we should format the given attribute as an SymbolNameAttr.
517static bool shouldFormatSymbolNameAttr(const NamedAttribute *attr) {
518 return attr->attr.getBaseAttr().getAttrDefName() == "SymbolNameAttr";
519}
520
521/// The code snippet used to get properties from the operation state.
522/// {0}: The C++ class name of the operation.
523const char *const getPropertiesCode =
524 "result.getOrAddProperties<{0}::Properties>()";
525
526/// The code snippet used to generate a parser call for an attribute.
527///
528/// {0}: The name of the attribute.
529/// {1}: The type for the attribute.
530const char *const attrParserCode = R"(
531 if (parser.parseCustomAttributeWithFallback({0}Attr, {1})) {{
532 return ::mlir::failure();
533 }
534)";
535
536/// The code snippet used to generate a parser call for an attribute.
537///
538/// {0}: The name of the attribute.
539/// {1}: The type for the attribute.
540const char *const genericAttrParserCode = R"(
541 if (parser.parseAttribute({0}Attr, {1}))
542 return ::mlir::failure();
543)";
544
545const char *const optionalAttrParserCode = R"(
546 ::mlir::OptionalParseResult parseResult{0}Attr =
547 parser.parseOptionalAttribute({0}Attr, {1});
548 if (parseResult{0}Attr.has_value() && failed(*parseResult{0}Attr))
549 return ::mlir::failure();
550 if (parseResult{0}Attr.has_value() && succeeded(*parseResult{0}Attr))
551)";
552
553/// The code snippet used to generate a parser call for a symbol name attribute.
554///
555/// {0}: The name of the attribute.
556const char *const symbolNameAttrParserCode = R"(
557 if (parser.parseSymbolName({0}Attr))
558 return ::mlir::failure();
559)";
560const char *const optionalSymbolNameAttrParserCode = R"(
561 // Parsing an optional symbol name doesn't fail, so no need to check the
562 // result.
563 (void)parser.parseOptionalSymbolName({0}Attr);
564)";
565
566/// The code snippet used to generate a parser call for an enum attribute.
567///
568/// {0}: The name of the attribute.
569/// {1}: The c++ namespace for the enum symbolize functions.
570/// {2}: The function to symbolize a string of the enum.
571/// {3}: The constant builder call to create an attribute of the enum type.
572/// {4}: The set of allowed enum keywords.
573/// {5}: The error message on failure when the enum isn't present.
574/// {6}: The attribute assignment expression
575const char *const enumAttrParserCode = R"(
576 {
577 ::llvm::StringRef attrStr;
578 ::mlir::NamedAttrList attrStorage;
579 auto loc = parser.getCurrentLocation();
580 if (parser.parseOptionalKeyword(&attrStr, {4})) {
581 ::mlir::StringAttr attrVal;
582 ::mlir::OptionalParseResult parseResult =
583 parser.parseOptionalAttribute(attrVal,
584 parser.getBuilder().getNoneType(),
585 "{0}", attrStorage);
586 if (parseResult.has_value()) {{
587 if (failed(*parseResult))
588 return ::mlir::failure();
589 attrStr = attrVal.getValue();
590 } else {
591 {5}
592 }
593 }
594 if (!attrStr.empty()) {
595 auto attrOptional = {1}::{2}(attrStr);
596 if (!attrOptional)
597 return parser.emitError(loc, "invalid ")
598 << "{0} attribute specification: \"" << attrStr << '"';;
599
600 {0}Attr = {3};
601 {6}
602 }
603 }
604)";
605
606/// The code snippet used to generate a parser call for an unquoted bit enum
607/// attribute.
608///
609/// {0}: The name of the attribute.
610/// {1}: The C++ namespace for the enum symbolize functions.
611/// {2}: The function to symbolize a string of the enum.
612/// {3}: The constant builder call to create an attribute of the enum type.
613/// {4}: The set of allowed enum keywords.
614/// {5}: The error message on failure when the enum isn't present.
615/// {6}: The attribute assignment expression.
616/// {7}: The C++ enum type.
617/// {8}: The code that parses the next case keyword into `attrStr`, breaking
618/// out of the loop when there is none.
619const char *const unquotedBitEnumAttrParserCode = R"(
620 {
621 ::llvm::StringRef attrStr;
622 auto loc = parser.getCurrentLocation();
623 if (parser.parseOptionalKeyword(&attrStr, {4})) {
624 {5}
625 } else {
626 {7} flags = {{};
627 while (true) {
628 auto flag = {1}::{2}(attrStr);
629 if (!flag)
630 return parser.emitError(loc, "invalid ")
631 << "{0} attribute specification: \"" << attrStr << '"';;
632 flags = flags | *flag;
633 {8}
634 }
635 auto attrOptional = ::std::optional<{7}>(flags);
636 {0}Attr = {3};
637 {6}
638 }
639 }
640)";
641
642/// The code snippet used to generate a parser call for a property.
643/// {0}: The name of the property
644/// {1}: The property access expression
645/// (result.getOrAddProperties<Op::Properties>()) {2}: The property's parser
646/// code with appropriate substitutions performed {3}: The description of the
647/// expected property for the error message.
648const char *const propertyParserCode = R"(
649 auto {0}PropLoc = parser.getCurrentLocation();
650 auto {0}PropParseResult = [&](auto& propStorage) -> ::mlir::ParseResult {{
651 {2}
652 return ::mlir::success();
653 }({1}.{0});
654 if (failed({0}PropParseResult)) {{
655 return parser.emitError({0}PropLoc, "invalid value for property {0}, expected {3}");
656 }
657)";
658
659/// The code snippet used to generate a parser call for a property.
660/// {0}: The name of the property
661/// {1}: The property access expression
662/// (result.getOrAddProperties<Op::Properties>()) {2}: The property's parser
663/// code with appropriate substitutions performed
664const char *const optionalPropertyParserCode = R"(
665 auto {0}PropParseResult = [&](auto& propStorage) -> ::mlir::OptionalParseResult {{
666 {2}
667 return ::mlir::success();
668 }({1}.{0});
669 if ({0}PropParseResult.has_value() && failed(*{0}PropParseResult)) {{
670 return ::mlir::failure();
671 }
672)";
673
674/// The code snippet used to generate a parser call for an operand.
675///
676/// {0}: The name of the operand.
677const char *const variadicOperandParserCode = R"(
678 {0}OperandsLoc = parser.getCurrentLocation();
679 if (parser.parseOperandList({0}Operands))
680 return ::mlir::failure();
681)";
682const char *const optionalOperandParserCode = R"(
683 {0}OperandsLoc = parser.getCurrentLocation();
684 if (::mlir::detail::parseOptionalOperandInto(parser, {0}Operands))
685 return ::mlir::failure();
686)";
687const char *const operandParserCode = R"(
688 {0}OperandsLoc = parser.getCurrentLocation();
689 if (parser.parseOperand({0}RawOperand))
690 return ::mlir::failure();
691)";
692/// The code snippet used to generate a parser call for a VariadicOfVariadic
693/// operand.
694///
695/// {0}: The name of the operand.
696/// {1}: The name of segment size attribute.
697const char *const variadicOfVariadicOperandParserCode = R"(
698 {
699 {0}OperandsLoc = parser.getCurrentLocation();
700 int32_t curSize = 0;
701 do {
702 if (parser.parseOptionalLParen())
703 break;
704 if (parser.parseOperandList({0}Operands) || parser.parseRParen())
705 return ::mlir::failure();
706 {0}OperandGroupSizes.push_back({0}Operands.size() - curSize);
707 curSize = {0}Operands.size();
708 } while (succeeded(parser.parseOptionalComma()));
709 }
710)";
711
712/// The code snippet used to generate a parser call for a type list.
713///
714/// {0}: The name for the type list.
715const char *const variadicOfVariadicTypeParserCode = R"(
716 do {
717 if (parser.parseOptionalLParen())
718 break;
719 if (parser.parseOptionalRParen() &&
720 (parser.parseTypeList({0}Types) || parser.parseRParen()))
721 return ::mlir::failure();
722 } while (succeeded(parser.parseOptionalComma()));
723)";
724const char *const variadicTypeParserCode = R"(
725 if (parser.parseTypeList({0}Types))
726 return ::mlir::failure();
727)";
728const char *const optionalTypeParserCode = R"(
729 if (::mlir::detail::parseOptionalTypeInto(parser, {0}Types))
730 return ::mlir::failure();
731)";
732const char *const typeParserCode = R"(
733 {
734 {0} type;
735 if (parser.parseCustomTypeWithFallback(type))
736 return ::mlir::failure();
737 {1}RawType = type;
738 }
739)";
740const char *const qualifiedTypeParserCode = R"(
741 if (parser.parseType({1}RawType))
742 return ::mlir::failure();
743)";
744
745/// The code snippet used to generate a parser call for a functional type.
746///
747/// {0}: The name for the input type list.
748/// {1}: The name for the result type list.
749const char *const functionalTypeParserCode = R"(
750 ::mlir::FunctionType {0}__{1}_functionType;
751 if (parser.parseType({0}__{1}_functionType))
752 return ::mlir::failure();
753 {0}Types = {0}__{1}_functionType.getInputs();
754 {1}Types = {0}__{1}_functionType.getResults();
755)";
756
757/// The code snippet used to generate a parser call to infer return types.
758///
759/// {0}: The operation class name
760const char *const inferReturnTypesParserCode = R"(
761 ::llvm::SmallVector<::mlir::Type> inferredReturnTypes;
762 if (::mlir::failed({0}::inferReturnTypes(parser.getContext(),
763 result.location, result.operands,
764 result.attributes.getDictionary(parser.getContext()),
765 result.getRawProperties(),
766 result.regions, inferredReturnTypes)))
767 return ::mlir::failure();
768 result.addTypes(inferredReturnTypes);
769)";
770
771/// The code snippet used to generate a parser call for a region list.
772///
773/// {0}: The name for the region list.
774static const char *regionListParserCode = R"(
775 {
776 std::unique_ptr<::mlir::Region> region;
777 auto firstRegionResult = parser.parseOptionalRegion(region);
778 if (firstRegionResult.has_value()) {
779 if (failed(*firstRegionResult))
780 return ::mlir::failure();
781 {0}Regions.emplace_back(std::move(region));
782
783 // Parse any trailing regions.
784 while (succeeded(parser.parseOptionalComma())) {
785 region = std::make_unique<::mlir::Region>();
786 if (parser.parseRegion(*region))
787 return ::mlir::failure();
788 {0}Regions.emplace_back(std::move(region));
789 }
790 }
791 }
792)";
793
794/// The code snippet used to ensure a list of regions have terminators.
795///
796/// {0}: The name of the region list.
797static const char *regionListEnsureTerminatorParserCode = R"(
798 for (auto &region : {0}Regions)
799 ensureTerminator(*region, parser.getBuilder(), result.location);
800)";
801
802/// The code snippet used to ensure a list of regions have a block.
803///
804/// {0}: The name of the region list.
805static const char *regionListEnsureSingleBlockParserCode = R"(
806 for (auto &region : {0}Regions)
807 if (region->empty()) region->emplaceBlock();
808)";
809
810/// The code snippet used to generate a parser call for an optional region.
811///
812/// {0}: The name of the region.
813static const char *optionalRegionParserCode = R"(
814 {
815 auto parseResult = parser.parseOptionalRegion(*{0}Region);
816 if (parseResult.has_value() && failed(*parseResult))
817 return ::mlir::failure();
818 }
819)";
820
821/// The code snippet used to generate a parser call for a region.
822///
823/// {0}: The name of the region.
824static const char *regionParserCode = R"(
825 if (parser.parseRegion(*{0}Region))
826 return ::mlir::failure();
827)";
828
829/// The code snippet used to ensure a region has a terminator.
830///
831/// {0}: The name of the region.
832static const char *regionEnsureTerminatorParserCode = R"(
833 ensureTerminator(*{0}Region, parser.getBuilder(), result.location);
834)";
835
836/// The code snippet used to ensure a region has a block.
837///
838/// {0}: The name of the region.
839static const char *regionEnsureSingleBlockParserCode = R"(
840 if ({0}Region->empty()) {0}Region->emplaceBlock();
841)";
842
843/// The code snippet used to generate a parser call for a successor list.
844///
845/// {0}: The name for the successor list.
846static const char *successorListParserCode = R"(
847 {
848 ::mlir::Block *succ;
849 auto firstSucc = parser.parseOptionalSuccessor(succ);
850 if (firstSucc.has_value()) {
851 if (failed(*firstSucc))
852 return ::mlir::failure();
853 {0}Successors.emplace_back(succ);
854
855 // Parse any trailing successors.
856 while (succeeded(parser.parseOptionalComma())) {
857 if (parser.parseSuccessor(succ))
858 return ::mlir::failure();
859 {0}Successors.emplace_back(succ);
860 }
861 }
862 }
863)";
864
865/// The code snippet used to generate a parser call for a successor.
866///
867/// {0}: The name of the successor.
868static const char *successorParserCode = R"(
869 if (parser.parseSuccessor({0}Successor))
870 return ::mlir::failure();
871)";
872
873/// The code snippet used to generate a parser for OIList
874///
875/// {0}: literal keyword corresponding to a case for oilist
876static const char *oilistParserCode = R"(
877 if ({0}Clause) {
878 return parser.emitError(parser.getNameLoc())
879 << "`{0}` clause can appear at most once in the expansion of the "
880 "oilist directive";
881 }
882 {0}Clause = true;
883)";
884
885namespace {
886/// The type of length for a given parse argument.
887enum class ArgumentLengthKind {
888 /// The argument is a variadic of a variadic, and may contain 0->N range
889 /// elements.
890 VariadicOfVariadic,
891 /// The argument is variadic, and may contain 0->N elements.
892 Variadic,
893 /// The argument is optional, and may contain 0 or 1 elements.
894 Optional,
895 /// The argument is a single element, i.e. always represents 1 element.
896 Single
897};
898} // namespace
899
900/// Get the length kind for the given constraint.
901static ArgumentLengthKind
902getArgumentLengthKind(const NamedTypeConstraint *var) {
903 if (var->isOptional())
904 return ArgumentLengthKind::Optional;
905 if (var->isVariadicOfVariadic())
906 return ArgumentLengthKind::VariadicOfVariadic;
907 if (var->isVariadic())
908 return ArgumentLengthKind::Variadic;
909 return ArgumentLengthKind::Single;
910}
911
912/// Get the name used for the type list for the given type directive operand.
913/// 'lengthKind' to the corresponding kind for the given argument.
914static StringRef getTypeListName(FormatElement *arg,
915 ArgumentLengthKind &lengthKind) {
916 if (auto *operand = dyn_cast<OperandVariable>(Val: arg)) {
917 lengthKind = getArgumentLengthKind(var: operand->getVar());
918 return operand->getVar()->name;
919 }
920 if (auto *result = dyn_cast<ResultVariable>(Val: arg)) {
921 lengthKind = getArgumentLengthKind(var: result->getVar());
922 return result->getVar()->name;
923 }
924 lengthKind = ArgumentLengthKind::Variadic;
925 if (isa<OperandsDirective>(Val: arg))
926 return "allOperand";
927 if (isa<ResultsDirective>(Val: arg))
928 return "allResult";
929 llvm_unreachable("unknown 'type' directive argument");
930}
931
932/// Generate the parser for a literal value.
933static void genLiteralParser(StringRef value, MethodBody &body) {
934 // Handle the case of a keyword/identifier.
935 if (value.front() == '_' || isalpha(value.front())) {
936 body << "Keyword(\"" << value << "\")";
937 return;
938 }
939 body << (StringRef)StringSwitch<StringRef>(value)
940 .Case(S: "->", Value: "Arrow()")
941 .Case(S: ":", Value: "Colon()")
942 .Case(S: ",", Value: "Comma()")
943 .Case(S: "=", Value: "Equal()")
944 .Case(S: "<", Value: "Less()")
945 .Case(S: ">", Value: "Greater()")
946 .Case(S: "{", Value: "LBrace()")
947 .Case(S: "}", Value: "RBrace()")
948 .Case(S: "(", Value: "LParen()")
949 .Case(S: ")", Value: "RParen()")
950 .Case(S: "[", Value: "LSquare()")
951 .Case(S: "]", Value: "RSquare()")
952 .Case(S: "?", Value: "Question()")
953 .Case(S: "+", Value: "Plus()")
954 .Case(S: "-", Value: "Minus()")
955 .Case(S: "*", Value: "Star()")
956 .Case(S: "...", Value: "Ellipsis()");
957}
958
959/// Generate the storage code required for parsing the given element.
960static void genElementParserStorage(FormatElement *element, const Operator &op,
961 MethodBody &body,
962 bool groupOperandStorage) {
963 if (auto *optional = dyn_cast<OptionalElement>(Val: element)) {
964 ArrayRef<FormatElement *> elements = optional->getThenElements();
965
966 // If the anchor is a unit attribute, it won't be parsed directly so elide
967 // it.
968 auto *anchor = dyn_cast<AttributeLikeVariable>(Val: optional->getAnchor());
969 FormatElement *elidedAnchorElement = nullptr;
970 if (anchor && anchor != elements.front() && anchor->isUnit())
971 elidedAnchorElement = anchor;
972 for (FormatElement *childElement : elements)
973 if (childElement != elidedAnchorElement)
974 genElementParserStorage(element: childElement, op, body, groupOperandStorage);
975 for (FormatElement *childElement : optional->getElseElements())
976 genElementParserStorage(element: childElement, op, body, groupOperandStorage);
977
978 } else if (auto *oilist = dyn_cast<OIListElement>(Val: element)) {
979 for (ArrayRef<FormatElement *> pelement : oilist->getParsingElements()) {
980 if (!oilist->getUnitVariableParsingElement(pelement))
981 for (FormatElement *element : pelement)
982 genElementParserStorage(element, op, body, groupOperandStorage);
983 }
984
985 } else if (auto *custom = dyn_cast<CustomDirective>(Val: element)) {
986 for (FormatElement *paramElement : custom->getElements())
987 genElementParserStorage(element: paramElement, op, body, groupOperandStorage);
988
989 } else if (isa<OperandsDirective>(Val: element)) {
990 body << " ::llvm::SmallVector<::mlir::OpAsmParser::UnresolvedOperand, 4> "
991 "allOperands;\n";
992
993 } else if (isa<RegionsDirective>(Val: element)) {
994 body << " ::llvm::SmallVector<std::unique_ptr<::mlir::Region>, 2> "
995 "fullRegions;\n";
996
997 } else if (isa<SuccessorsDirective>(Val: element)) {
998 body << " ::llvm::SmallVector<::mlir::Block *, 2> fullSuccessors;\n";
999
1000 } else if (auto *attr = dyn_cast<AttributeVariable>(Val: element)) {
1001 const NamedAttribute *var = attr->getVar();
1002 body << formatv(Fmt: " {0} {1}Attr;\n", Vals: var->attr.getStorageType(), Vals: var->name);
1003
1004 } else if (auto *operand = dyn_cast<OperandVariable>(Val: element)) {
1005 StringRef name = operand->getVar()->name;
1006 if (operand->getVar()->isVariableLength()) {
1007 if (groupOperandStorage) {
1008 unsigned index = 0;
1009 for (const NamedTypeConstraint &candidate : op.getOperands()) {
1010 if (&candidate == operand->getVar())
1011 break;
1012 if (candidate.isVariableLength())
1013 ++index;
1014 }
1015 body << " auto &" << name << "Operands = odsOperandVectors[" << index
1016 << "];\n";
1017 } else {
1018 body
1019 << " ::llvm::SmallVector<::mlir::OpAsmParser::UnresolvedOperand, 4> "
1020 << name << "Operands;\n";
1021 }
1022 if (operand->getVar()->isVariadicOfVariadic()) {
1023 body << " llvm::SmallVector<int32_t> " << name
1024 << "OperandGroupSizes;\n";
1025 }
1026 } else {
1027 body << " ::mlir::OpAsmParser::UnresolvedOperand " << name
1028 << "RawOperand{};\n"
1029 << " ::llvm::ArrayRef<::mlir::OpAsmParser::UnresolvedOperand> "
1030 << name << "Operands(&" << name << "RawOperand, 1);";
1031 }
1032 body << formatv(Fmt: " ::llvm::SMLoc {0}OperandsLoc;\n"
1033 " (void){0}OperandsLoc;\n",
1034 Vals&: name);
1035
1036 } else if (auto *region = dyn_cast<RegionVariable>(Val: element)) {
1037 StringRef name = region->getVar()->name;
1038 if (region->getVar()->isVariadic()) {
1039 body << formatv(
1040 Fmt: " ::llvm::SmallVector<std::unique_ptr<::mlir::Region>, 2> "
1041 "{0}Regions;\n",
1042 Vals&: name);
1043 } else {
1044 body << formatv(Fmt: " std::unique_ptr<::mlir::Region> {0}Region = "
1045 "std::make_unique<::mlir::Region>();\n",
1046 Vals&: name);
1047 }
1048
1049 } else if (auto *successor = dyn_cast<SuccessorVariable>(Val: element)) {
1050 StringRef name = successor->getVar()->name;
1051 if (successor->getVar()->isVariadic()) {
1052 body << formatv(Fmt: " ::llvm::SmallVector<::mlir::Block *, 2> "
1053 "{0}Successors;\n",
1054 Vals&: name);
1055 } else {
1056 body << formatv(Fmt: " ::mlir::Block *{0}Successor = nullptr;\n", Vals&: name);
1057 }
1058
1059 } else if (auto *dir = dyn_cast<TypeDirective>(Val: element)) {
1060 ArgumentLengthKind lengthKind;
1061 StringRef name = getTypeListName(arg: dir->getArg(), lengthKind);
1062 if (lengthKind != ArgumentLengthKind::Single)
1063 body << " ::llvm::SmallVector<::mlir::Type, 1> " << name << "Types;\n";
1064 else
1065 body
1066 << formatv(Fmt: " ::mlir::Type {0}RawType{{};\n", Vals&: name)
1067 << formatv(
1068 Fmt: " ::llvm::ArrayRef<::mlir::Type> {0}Types(&{0}RawType, 1);\n",
1069 Vals&: name);
1070 } else if (auto *dir = dyn_cast<FunctionalTypeDirective>(Val: element)) {
1071 ArgumentLengthKind ignored;
1072 body << " ::llvm::ArrayRef<::mlir::Type> "
1073 << getTypeListName(arg: dir->getInputs(), lengthKind&: ignored) << "Types;\n";
1074 body << " ::llvm::ArrayRef<::mlir::Type> "
1075 << getTypeListName(arg: dir->getResults(), lengthKind&: ignored) << "Types;\n";
1076 }
1077}
1078
1079/// Generate the parser for a parameter to a custom directive.
1080static void genCustomParameterParser(FormatElement *param, MethodBody &body,
1081 StringRef opCppClassName) {
1082 if (auto *attr = dyn_cast<AttributeVariable>(Val: param)) {
1083 body << attr->getVar()->name << "Attr";
1084 } else if (isa<AttrDictDirective>(Val: param)) {
1085 body << "result.attributes";
1086 } else if (isa<PropDictDirective>(Val: param)) {
1087 body << "result";
1088 } else if (auto *operand = dyn_cast<OperandVariable>(Val: param)) {
1089 StringRef name = operand->getVar()->name;
1090 ArgumentLengthKind lengthKind = getArgumentLengthKind(var: operand->getVar());
1091 if (lengthKind == ArgumentLengthKind::VariadicOfVariadic)
1092 body << formatv(Fmt: "{0}OperandGroups", Vals&: name);
1093 else if (lengthKind == ArgumentLengthKind::Variadic)
1094 body << formatv(Fmt: "{0}Operands", Vals&: name);
1095 else if (lengthKind == ArgumentLengthKind::Optional)
1096 body << formatv(Fmt: "{0}Operand", Vals&: name);
1097 else
1098 body << formatv(Fmt: "{0}RawOperand", Vals&: name);
1099
1100 } else if (auto *region = dyn_cast<RegionVariable>(Val: param)) {
1101 StringRef name = region->getVar()->name;
1102 if (region->getVar()->isVariadic())
1103 body << formatv(Fmt: "{0}Regions", Vals&: name);
1104 else
1105 body << formatv(Fmt: "*{0}Region", Vals&: name);
1106
1107 } else if (auto *successor = dyn_cast<SuccessorVariable>(Val: param)) {
1108 StringRef name = successor->getVar()->name;
1109 if (successor->getVar()->isVariadic())
1110 body << formatv(Fmt: "{0}Successors", Vals&: name);
1111 else
1112 body << formatv(Fmt: "{0}Successor", Vals&: name);
1113
1114 } else if (auto *dir = dyn_cast<RefDirective>(Val: param)) {
1115 genCustomParameterParser(param: dir->getArg(), body, opCppClassName);
1116
1117 } else if (auto *dir = dyn_cast<TypeDirective>(Val: param)) {
1118 ArgumentLengthKind lengthKind;
1119 StringRef listName = getTypeListName(arg: dir->getArg(), lengthKind);
1120 if (lengthKind == ArgumentLengthKind::VariadicOfVariadic)
1121 body << formatv(Fmt: "{0}TypeGroups", Vals&: listName);
1122 else if (lengthKind == ArgumentLengthKind::Variadic)
1123 body << formatv(Fmt: "{0}Types", Vals&: listName);
1124 else if (lengthKind == ArgumentLengthKind::Optional)
1125 body << formatv(Fmt: "{0}Type", Vals&: listName);
1126 else
1127 body << formatv(Fmt: "{0}RawType", Vals&: listName);
1128
1129 } else if (auto *string = dyn_cast<StringElement>(Val: param)) {
1130 FmtContext ctx;
1131 ctx.withBuilder(subst: "parser.getBuilder()");
1132 ctx.addSubst(placeholder: "_ctxt", subst: "parser.getContext()");
1133 body << tgfmt(fmt: string->getValue(), ctx: &ctx);
1134
1135 } else if (auto *property = dyn_cast<PropertyVariable>(Val: param)) {
1136 body << formatv(Fmt: getPropertiesCode, Vals&: opCppClassName) << "."
1137 << property->getVar()->name;
1138 } else {
1139 llvm_unreachable("unknown custom directive parameter");
1140 }
1141}
1142
1143/// Generate the parser for a custom directive.
1144static void genCustomDirectiveParser(CustomDirective *dir, MethodBody &body,
1145 StringRef opCppClassName,
1146 bool isOptional = false) {
1147 body << " {\n";
1148
1149 // Preprocess the directive variables.
1150 // * Add a local variable for optional operands and types. This provides a
1151 // better API to the user defined parser methods.
1152 // * Set the location of operand variables.
1153 for (FormatElement *param : dir->getElements()) {
1154 if (auto *operand = dyn_cast<OperandVariable>(Val: param)) {
1155 auto *var = operand->getVar();
1156 body << " " << var->name
1157 << "OperandsLoc = parser.getCurrentLocation();\n";
1158 if (var->isOptional()) {
1159 body << formatv(
1160 Fmt: " ::std::optional<::mlir::OpAsmParser::UnresolvedOperand> "
1161 "{0}Operand;\n",
1162 Vals: var->name);
1163 } else if (var->isVariadicOfVariadic()) {
1164 body << formatv(Fmt: " "
1165 "::llvm::SmallVector<::llvm::SmallVector<::mlir::"
1166 "OpAsmParser::UnresolvedOperand>> "
1167 "{0}OperandGroups;\n",
1168 Vals: var->name);
1169 }
1170 } else if (auto *dir = dyn_cast<TypeDirective>(Val: param)) {
1171 ArgumentLengthKind lengthKind;
1172 StringRef listName = getTypeListName(arg: dir->getArg(), lengthKind);
1173 if (lengthKind == ArgumentLengthKind::Optional) {
1174 body << formatv(Fmt: " ::mlir::Type {0}Type;\n", Vals&: listName);
1175 } else if (lengthKind == ArgumentLengthKind::VariadicOfVariadic) {
1176 body << formatv(
1177 Fmt: " ::llvm::SmallVector<llvm::SmallVector<::mlir::Type>> "
1178 "{0}TypeGroups;\n",
1179 Vals&: listName);
1180 }
1181 } else if (auto *dir = dyn_cast<RefDirective>(Val: param)) {
1182 FormatElement *input = dir->getArg();
1183 if (auto *operand = dyn_cast<OperandVariable>(Val: input)) {
1184 if (!operand->getVar()->isOptional())
1185 continue;
1186 body << formatv(
1187 Fmt: " {0} {1}Operand = {1}Operands.empty() ? {0}() : "
1188 "{1}Operands[0];\n",
1189 Vals: "::std::optional<::mlir::OpAsmParser::UnresolvedOperand>",
1190 Vals: operand->getVar()->name);
1191
1192 } else if (auto *type = dyn_cast<TypeDirective>(Val: input)) {
1193 ArgumentLengthKind lengthKind;
1194 StringRef listName = getTypeListName(arg: type->getArg(), lengthKind);
1195 if (lengthKind == ArgumentLengthKind::Optional) {
1196 body << formatv(Fmt: " ::mlir::Type {0}Type = {0}Types.empty() ? "
1197 "::mlir::Type() : {0}Types[0];\n",
1198 Vals&: listName);
1199 }
1200 }
1201 }
1202 }
1203
1204 body << " auto odsResult = parse" << dir->getName() << "(parser";
1205 for (FormatElement *param : dir->getElements()) {
1206 body << ", ";
1207 genCustomParameterParser(param, body, opCppClassName);
1208 }
1209 body << ");\n";
1210
1211 if (isOptional) {
1212 body << " if (!odsResult.has_value()) return {};\n"
1213 << " if (::mlir::failed(*odsResult)) return ::mlir::failure();\n";
1214 } else {
1215 body << " if (odsResult) return ::mlir::failure();\n";
1216 }
1217
1218 // After parsing, add handling for any of the optional constructs.
1219 for (FormatElement *param : dir->getElements()) {
1220 if (auto *attr = dyn_cast<AttributeVariable>(Val: param)) {
1221 const NamedAttribute *var = attr->getVar();
1222 if (var->attr.isOptional() || var->attr.hasDefaultValue())
1223 body << formatv(Fmt: " if ({0}Attr)\n ", Vals: var->name);
1224 std::string propAccess = formatv(Fmt: getPropertiesCode, Vals&: opCppClassName);
1225 body << formatv(Fmt: " {0}.{1} = {1}Attr;\n", Vals&: propAccess, Vals: var->name);
1226 } else if (auto *operand = dyn_cast<OperandVariable>(Val: param)) {
1227 const NamedTypeConstraint *var = operand->getVar();
1228 if (var->isOptional()) {
1229 body << formatv(Fmt: " if ({0}Operand.has_value())\n"
1230 " {0}Operands.push_back(*{0}Operand);\n",
1231 Vals: var->name);
1232 } else if (var->isVariadicOfVariadic()) {
1233 body << formatv(
1234 Fmt: " for (const auto &subRange : {0}OperandGroups) {{\n"
1235 " {0}Operands.append(subRange.begin(), subRange.end());\n"
1236 " {0}OperandGroupSizes.push_back(subRange.size());\n"
1237 " }\n",
1238 Vals: var->name);
1239 }
1240 } else if (auto *dir = dyn_cast<TypeDirective>(Val: param)) {
1241 ArgumentLengthKind lengthKind;
1242 StringRef listName = getTypeListName(arg: dir->getArg(), lengthKind);
1243 if (lengthKind == ArgumentLengthKind::Optional) {
1244 body << formatv(Fmt: " if ({0}Type)\n"
1245 " {0}Types.push_back({0}Type);\n",
1246 Vals&: listName);
1247 } else if (lengthKind == ArgumentLengthKind::VariadicOfVariadic) {
1248 body << formatv(
1249 Fmt: " for (const auto &subRange : {0}TypeGroups)\n"
1250 " {0}Types.append(subRange.begin(), subRange.end());\n",
1251 Vals&: listName);
1252 }
1253 }
1254 }
1255
1256 body << " }\n";
1257}
1258
1259/// Generate the parser for a enum attribute.
1260static void genEnumAttrParser(const NamedAttribute *var, MethodBody &body,
1261 FmtContext &attrTypeCtx, bool parseAsOptional,
1262 StringRef opCppClassName,
1263 bool formatAsEnumDirective,
1264 bool formatBitEnumAsUnquoted = false) {
1265 Attribute baseAttr = var->attr.getBaseAttr();
1266 EnumInfo enumInfo(getEnumInfoRecord(attr: baseAttr));
1267 std::vector<EnumCase> cases = enumInfo.getAllCases();
1268
1269 // Generate the code for building an attribute for this enum.
1270 std::string attrBuilderStr;
1271 {
1272 llvm::raw_string_ostream os(attrBuilderStr);
1273 os << tgfmt(fmt: baseAttr.getConstBuilderTemplate(), ctx: &attrTypeCtx,
1274 vals: "*attrOptional");
1275 }
1276
1277 // Build a string containing the cases that can be formatted as a keyword.
1278 std::string validCaseKeywordsStr;
1279 llvm::raw_string_ostream validCaseKeywordsOS(validCaseKeywordsStr);
1280 validCaseKeywordsOS << '{';
1281 bool isFirstKeyword = true;
1282 for (const EnumCase &attrCase : cases) {
1283 if (!canFormatStringAsKeyword(value: attrCase.getStr()))
1284 continue;
1285 if (!isFirstKeyword)
1286 validCaseKeywordsOS << ',';
1287 isFirstKeyword = false;
1288 validCaseKeywordsOS << '"' << attrCase.getStr() << '"';
1289 }
1290 validCaseKeywordsOS << '}';
1291
1292 // If the attribute is not optional, build an error message for the missing
1293 // attribute.
1294 std::string errorMessage;
1295 if (!parseAsOptional) {
1296 llvm::raw_string_ostream errorMessageOS(errorMessage);
1297 errorMessageOS
1298 << "return parser.emitError(loc, \"expected string or "
1299 "keyword containing one of the following enum values for attribute '"
1300 << var->name << "' [";
1301 llvm::interleaveComma(c: cases, os&: errorMessageOS, each_fn: [&](const auto &attrCase) {
1302 errorMessageOS << attrCase.getStr();
1303 });
1304 errorMessageOS << "]\");";
1305 }
1306 std::string attrAssignment;
1307 std::string propAccess = formatv(Fmt: getPropertiesCode, Vals&: opCppClassName);
1308 attrAssignment = formatv(Fmt: " {0}.{1} = {1}Attr;", Vals&: propAccess, Vals: var->name);
1309
1310 if (formatAsEnumDirective && enumInfo.isBitEnum() &&
1311 (formatBitEnumAsUnquoted || !enumInfo.printBitEnumQuoted())) {
1312 // With a space separator, the cases are a run of keywords;
1313 // otherwise each further case follows a separator token.
1314 std::string parseNextCase;
1315 if (enumInfo.getBitEnumSeparatorKind() ==
1316 EnumInfo::BitEnumSeparatorKind::Space) {
1317 parseNextCase =
1318 formatv(Fmt: "if (parser.parseOptionalKeyword(&attrStr, {0})) break;",
1319 Vals&: validCaseKeywordsStr);
1320 } else {
1321 parseNextCase = formatv(Fmt: "if (failed(parser.{0}())) break;\n"
1322 " if (parser.parseKeyword(&attrStr))\n"
1323 " return ::mlir::failure();",
1324 Vals: enumInfo.getBitEnumSeparatorParser());
1325 }
1326 std::string enumType =
1327 (enumInfo.getCppNamespace() + "::" + enumInfo.getEnumClassName()).str();
1328 body << formatv(Fmt: unquotedBitEnumAttrParserCode, Vals: var->name,
1329 Vals: enumInfo.getCppNamespace(),
1330 Vals: enumInfo.getStringToSymbolFnName(), Vals&: attrBuilderStr,
1331 Vals&: validCaseKeywordsStr, Vals&: errorMessage, Vals&: attrAssignment,
1332 Vals&: enumType, Vals&: parseNextCase);
1333 return;
1334 }
1335
1336 body << formatv(Fmt: enumAttrParserCode, Vals: var->name, Vals: enumInfo.getCppNamespace(),
1337 Vals: enumInfo.getStringToSymbolFnName(), Vals&: attrBuilderStr,
1338 Vals&: validCaseKeywordsStr, Vals&: errorMessage, Vals&: attrAssignment);
1339}
1340
1341// Generate the parser for a property.
1342static void genPropertyParser(PropertyVariable *propVar, MethodBody &body,
1343 StringRef opCppClassName,
1344 bool requireParse = true) {
1345 StringRef name = propVar->getVar()->name;
1346 const Property &prop = propVar->getVar()->prop;
1347 bool parseOptionally =
1348 prop.hasDefaultValue() && !requireParse && prop.hasOptionalParser();
1349 FmtContext fmtContext;
1350 fmtContext.addSubst(placeholder: "_parser", subst: "parser");
1351 fmtContext.addSubst(placeholder: "_ctxt", subst: "parser.getContext()");
1352 fmtContext.addSubst(placeholder: "_storage", subst: "propStorage");
1353
1354 std::string propAccess = formatv(Fmt: getPropertiesCode, Vals&: opCppClassName);
1355 if (parseOptionally) {
1356 body << formatv(Fmt: optionalPropertyParserCode, Vals&: name, Vals&: propAccess,
1357 Vals: tgfmt(fmt: prop.getOptionalParserCall(), ctx: &fmtContext));
1358 } else {
1359 body << formatv(Fmt: propertyParserCode, Vals&: name, Vals&: propAccess,
1360 Vals: tgfmt(fmt: prop.getParserCall(), ctx: &fmtContext),
1361 Vals: prop.getSummary());
1362 }
1363}
1364
1365// Generate the parser for an attribute.
1366static void genAttrParser(AttributeVariable *attr, MethodBody &body,
1367 FmtContext &attrTypeCtx, bool parseAsOptional,
1368 StringRef opCppClassName) {
1369 const NamedAttribute *var = attr->getVar();
1370
1371 // Check to see if we can parse this as an enum attribute.
1372 if (attr->shouldFormatAsEnum() || canFormatEnumAttr(attr: var))
1373 return genEnumAttrParser(var, body, attrTypeCtx, parseAsOptional,
1374 opCppClassName, formatAsEnumDirective: attr->shouldFormatAsEnum());
1375
1376 // Check to see if we should parse this as a symbol name attribute.
1377 if (shouldFormatSymbolNameAttr(attr: var)) {
1378 body << formatv(Fmt: parseAsOptional ? optionalSymbolNameAttrParserCode
1379 : symbolNameAttrParserCode,
1380 Vals: var->name);
1381 } else {
1382
1383 // If this attribute has a buildable type, use that when parsing the
1384 // attribute.
1385 std::string attrTypeStr;
1386 if (std::optional<StringRef> typeBuilder = attr->getTypeBuilder()) {
1387 llvm::raw_string_ostream os(attrTypeStr);
1388 os << tgfmt(fmt: *typeBuilder, ctx: &attrTypeCtx);
1389 } else {
1390 attrTypeStr = "::mlir::Type{}";
1391 }
1392 if (parseAsOptional) {
1393 body << formatv(Fmt: optionalAttrParserCode, Vals: var->name, Vals&: attrTypeStr);
1394 } else {
1395 if (attr->shouldBeQualified() ||
1396 var->attr.getStorageType() == "::mlir::Attribute")
1397 body << formatv(Fmt: genericAttrParserCode, Vals: var->name, Vals&: attrTypeStr);
1398 else
1399 body << formatv(Fmt: attrParserCode, Vals: var->name, Vals&: attrTypeStr);
1400 }
1401 }
1402 std::string propAccess = formatv(Fmt: getPropertiesCode, Vals&: opCppClassName);
1403 body << formatv(Fmt: " if ({0}Attr) {1}.{0} = {0}Attr;\n", Vals: var->name, Vals&: propAccess);
1404}
1405
1406// Generates the 'setPropertiesFromParsedAttr' used to set properties from a
1407// 'prop-dict' dictionary attr.
1408static void genParsedAttrPropertiesSetter(OperationFormat &fmt, Operator &op,
1409 OpClass &opClass) {
1410 // Not required unless 'prop-dict' is present.
1411 if (!fmt.hasPropDict)
1412 return;
1413
1414 SmallVector<MethodParameter> paramList;
1415 paramList.emplace_back(Args: "Properties &", Args: "prop");
1416 paramList.emplace_back(Args: "::mlir::Attribute", Args: "attr");
1417 paramList.emplace_back(Args: "::llvm::function_ref<::mlir::InFlightDiagnostic()>",
1418 Args: "emitError");
1419
1420 Method *method = opClass.addStaticMethod(retType: "::llvm::LogicalResult",
1421 name: "setPropertiesFromParsedAttr",
1422 args: std::move(paramList));
1423 MethodBody &body = method->body().indent();
1424
1425 body << R"decl(
1426::mlir::DictionaryAttr dict = ::llvm::dyn_cast<::mlir::DictionaryAttr>(attr);
1427if (!dict) {
1428 emitError() << "expected DictionaryAttr to set properties";
1429 return ::mlir::failure();
1430}
1431// keep track of used keys in the input dictionary to be able to error out
1432// if there are some unknown ones.
1433::mlir::DenseSet<::mlir::StringAttr> usedKeys;
1434::mlir::MLIRContext *ctx = dict.getContext();
1435(void)ctx;
1436)decl";
1437
1438 // `operandSegmentSizes`/`resultSegmentSizes` are trait-injected properties
1439 // not enumerated by `op.getProperties()`, so they need to be special-cased
1440 // here, mirroring `setPropertiesFromAttr` in OpDefinitionsGen.cpp. This is
1441 // only necessary when the format can't infer the sizes itself (bulk
1442 // `operands`/`type(results)` directives, or when there is no declarative
1443 // assemblyFormat at all -- e.g. `hasCustomAssemblyFormat`, where this
1444 // generated setter may still be reused by a hand-written parser that has
1445 // no other way to recover the sizes); when the format spells out each
1446 // variadic group individually, `genParserVariadicSegmentResolution` always
1447 // overwrites the property from the parsed operand/result groups, so the key
1448 // is left completely untouched here (same as any other property not
1449 // handled by this format).
1450 //
1451 // {0}: segment sizes property name
1452 const char *segmentSizesFromAttrFmt = R"decl(
1453auto {0}AttrName = ::mlir::StringAttr::get(ctx, "{0}");
1454usedKeys.insert({0}AttrName);
1455auto attr = dict.get({0}AttrName);
1456if (!attr) {{
1457 emitError() << "expected key entry for {0} in DictionaryAttr to set "
1458 "Properties.";
1459 return ::mlir::failure();
1460}
1461if (::mlir::failed(::mlir::convertFromAttribute(prop.{0}, attr, [&]() {{
1462 return emitError() << "for `{0}`: ";
1463 })))
1464 return ::mlir::failure();
1465)decl";
1466 bool hasNoDeclarativeFormat = !op.hasAssemblyFormat();
1467 if (op.getTrait(trait: "::mlir::OpTrait::AttrSizedOperandSegments") &&
1468 (hasNoDeclarativeFormat || fmt.allOperands)) {
1469 auto scope = body.scope(open: "{\n", close: "}\n", /*indent=*/true);
1470 body << formatv(Fmt: segmentSizesFromAttrFmt, Vals: "operandSegmentSizes");
1471 }
1472 if (op.getTrait(trait: "::mlir::OpTrait::AttrSizedResultSegments") &&
1473 (hasNoDeclarativeFormat || fmt.allResultTypes)) {
1474 auto scope = body.scope(open: "{\n", close: "}\n", /*indent=*/true);
1475 body << formatv(Fmt: segmentSizesFromAttrFmt, Vals: "resultSegmentSizes");
1476 }
1477
1478 // {0}: fromAttribute call
1479 // {1}: property name
1480 // {2}: isRequired
1481 const char *propFromAttrFmt = R"decl(
1482auto setFromAttr = [] (auto &propStorage, ::mlir::Attribute propAttr,
1483 ::llvm::function_ref<::mlir::InFlightDiagnostic()> emitError) -> ::mlir::LogicalResult {{
1484 {0};
1485};
1486auto {1}AttrName = ::mlir::StringAttr::get(ctx, "{1}");
1487usedKeys.insert({1}AttrName);
1488auto attr = dict.get({1}AttrName);
1489if (!attr && {2}) {{
1490 emitError() << "expected key entry for {1} in DictionaryAttr to set "
1491 "Properties.";
1492 return ::mlir::failure();
1493}
1494if (attr && ::mlir::failed(setFromAttr(prop.{1}, attr, [&]() {{
1495 return emitError() << "for `{1}`: ";
1496 })))
1497 return ::mlir::failure();
1498)decl";
1499
1500 // Generate the setter for any property not parsed elsewhere.
1501 for (const NamedProperty &namedProperty : op.getProperties()) {
1502 if (fmt.usedProperties.contains(key: &namedProperty))
1503 continue;
1504 if (fmt.inferredAttributes.contains(key: namedProperty.name))
1505 continue;
1506
1507 auto scope = body.scope(open: "{\n", close: "}\n", /*indent=*/true);
1508
1509 StringRef name = namedProperty.name;
1510 const Property &prop = namedProperty.prop;
1511 bool isRequired = !prop.hasDefaultValue();
1512 FmtContext fctx;
1513 body << formatv(Fmt: propFromAttrFmt,
1514 Vals: tgfmt(fmt: prop.getConvertFromAttributeCall(),
1515 ctx: &fctx.addSubst(placeholder: "_attr", subst: "propAttr")
1516 .addSubst(placeholder: "_storage", subst: "propStorage")
1517 .addSubst(placeholder: "_diag", subst: "emitError")),
1518 Vals&: name, Vals&: isRequired);
1519 }
1520
1521 // Generate the setter for any attribute not parsed elsewhere.
1522 for (const NamedAttribute &namedAttr : op.getAttributes()) {
1523 if (fmt.usedAttributes.contains(key: &namedAttr))
1524 continue;
1525 if (fmt.inferredAttributes.contains(key: namedAttr.name))
1526 continue;
1527
1528 const Attribute &attr = namedAttr.attr;
1529 // Derived attributes do not need to be parsed.
1530 if (attr.isDerivedAttr())
1531 continue;
1532
1533 auto scope = body.scope(open: "{\n", close: "}\n", /*indent=*/true);
1534
1535 // If the attribute has a default value or is optional, it does not need to
1536 // be present in the parsed dictionary attribute.
1537 bool isRequired = !attr.isOptional() && !attr.hasDefaultValue();
1538 body << formatv(Fmt: R"decl(
1539auto &propStorage = prop.{0};
1540auto {0}AttrName = ::mlir::StringAttr::get(ctx, "{0}");
1541auto attr = dict.get({0}AttrName);
1542usedKeys.insert({0}AttrName);
1543if (attr || /*isRequired=*/{1}) {{
1544 if (!attr) {{
1545 emitError() << "expected key entry for {0} in DictionaryAttr to set "
1546 "Properties.";
1547 return ::mlir::failure();
1548 }
1549 auto convertedAttr = ::llvm::dyn_cast<std::remove_reference_t<decltype(propStorage)>>(attr);
1550 if (convertedAttr) {{
1551 propStorage = convertedAttr;
1552 } else {{
1553 emitError() << "Invalid attribute `{0}` in property conversion: " << attr;
1554 return ::mlir::failure();
1555 }
1556}
1557)decl",
1558 Vals: namedAttr.name, Vals&: isRequired);
1559 }
1560 body << R"decl(
1561for (::mlir::NamedAttribute attr : dict) {
1562 if (!usedKeys.contains(attr.getName()))
1563 return emitError() << "unknown key '" << attr.getName() <<
1564 "' when parsing properties dictionary";
1565}
1566return ::mlir::success();
1567)decl";
1568}
1569
1570/// Generate the parser for the key-value spelling of `prop-dict`. The generic
1571/// DictionaryAttr spelling remains supported as a compatibility path.
1572static bool isPresenceOnlyUnitProp(const Property &property) {
1573 StringRef propertyDefName = property.getBaseProperty().getPropertyDefName();
1574 return (propertyDefName == "UnitProp" || propertyDefName == "UnitProperty") &&
1575 property.getDefaultValue() == "false";
1576}
1577
1578static void genKeyValuePropDictParser(OperationFormat &fmt, Operator &op,
1579 OpClass &opClass) {
1580 if (!fmt.hasPropDict)
1581 return;
1582
1583 SmallVector<MethodParameter> paramList;
1584 paramList.emplace_back(Args: "::mlir::OpAsmParser &", Args: "parser");
1585 paramList.emplace_back(Args: "::mlir::OperationState &", Args: "result");
1586
1587 Method *method = opClass.addStaticMethod(retType: "::mlir::ParseResult",
1588 name: "parsePropertiesFromKeyValueList",
1589 args: std::move(paramList));
1590 MethodBody &body = method->body().indent();
1591
1592 body << R"decl(
1593auto &prop = result.getOrAddProperties<Properties>();
1594(void)prop;
1595)decl";
1596
1597 bool parseOperandSegmentSizes =
1598 op.getTrait(trait: "::mlir::OpTrait::AttrSizedOperandSegments") &&
1599 fmt.allOperands;
1600 bool parseResultSegmentSizes =
1601 op.getTrait(trait: "::mlir::OpTrait::AttrSizedResultSegments") &&
1602 fmt.allResultTypes;
1603
1604 if (parseOperandSegmentSizes)
1605 body << "bool seen_operandSegmentSizes = false;\n";
1606 if (parseResultSegmentSizes)
1607 body << "bool seen_resultSegmentSizes = false;\n";
1608
1609 auto shouldParseProperty = [&](const NamedProperty &property) {
1610 return !fmt.usedProperties.contains(key: &property) &&
1611 !fmt.inferredAttributes.contains(key: property.name);
1612 };
1613 auto shouldParseAttribute = [&](const NamedAttribute &attribute) {
1614 return !attribute.attr.isDerivedAttr() &&
1615 !fmt.usedAttributes.contains(key: &attribute) &&
1616 !fmt.inferredAttributes.contains(key: attribute.name);
1617 };
1618
1619 for (const NamedProperty &property : op.getProperties())
1620 if (shouldParseProperty(property))
1621 body << "bool seen_" << property.name << " = false;\n";
1622 for (const NamedAttribute &attribute : op.getAttributes())
1623 if (shouldParseAttribute(attribute))
1624 body << "bool seen_" << attribute.name << " = false;\n";
1625
1626 body << R"decl(
1627if (succeeded(parser.parseOptionalLess())) {
1628 ::llvm::SMLoc dictionaryLoc = parser.getCurrentLocation();
1629 ::mlir::NamedAttrList propertyAttributes;
1630 if (parser.parseOptionalAttrDict(propertyAttributes))
1631 return ::mlir::failure();
1632 if (dictionaryLoc != parser.getCurrentLocation()) {
1633 if (parser.parseGreater())
1634 return ::mlir::failure();
1635 auto propertyDictionary =
1636 ::mlir::DictionaryAttr::get(parser.getContext(), propertyAttributes);
1637 return setPropertiesFromParsedAttr(prop, propertyDictionary, [&]() {
1638 return parser.emitError(dictionaryLoc)
1639 << "invalid properties " << propertyDictionary << ": ";
1640 });
1641 }
1642
1643 bool reachedEnd = succeeded(parser.parseOptionalGreater());
1644 while (!reachedEnd) {
1645 ::llvm::SMLoc keyLoc = parser.getCurrentLocation();
1646 ::llvm::StringRef key;
1647 if (parser.parseKeyword(&key))
1648 return ::mlir::failure();
1649)decl";
1650
1651 SmallVector<StringRef> unitKeys;
1652 for (const NamedProperty &property : op.getProperties())
1653 if (shouldParseProperty(property) && isPresenceOnlyUnitProp(property: property.prop))
1654 unitKeys.push_back(Elt: property.name);
1655 for (const NamedAttribute &attribute : op.getAttributes())
1656 if (shouldParseAttribute(attribute) &&
1657 attribute.attr.getBaseAttr().getAttrDefName() == "UnitAttr")
1658 unitKeys.push_back(Elt: attribute.name);
1659
1660 if (unitKeys.empty()) {
1661 body << " if (parser.parseEqual())\n";
1662 } else {
1663 body << " bool isUnitKey = ";
1664 for (auto [index, key] : llvm::enumerate(First&: unitKeys))
1665 body << (index == 0 ? "" : " || ") << "key == \"" << key << "\"";
1666 body << ";\n"
1667 << " if (!isUnitKey && parser.parseEqual())\n";
1668 }
1669 body << " return ::mlir::failure();\n";
1670
1671 bool isFirst = true;
1672 FmtContext attrTypeCtx;
1673 attrTypeCtx.withBuilder(subst: "parser.getBuilder()");
1674
1675 auto genSegmentSizesParser = [&](StringRef name) {
1676 body << (isFirst ? " if" : " else if") << " (!seen_" << name
1677 << " && key == \"" << name << "\") {\n"
1678 << " seen_" << name << " = true;\n"
1679 << R"decl(
1680 ::llvm::SmallVector<int32_t> parsedSegmentSizes;
1681 if (parser.parseCommaSeparatedList(
1682 ::mlir::AsmParser::Delimiter::Square, [&]() {
1683 int32_t size;
1684 if (parser.parseInteger(size))
1685 return ::mlir::failure();
1686 parsedSegmentSizes.push_back(size);
1687 return ::mlir::success();
1688 }))
1689 return ::mlir::failure();
1690)decl"
1691 << " if (parsedSegmentSizes.size() != prop." << name
1692 << ".size())\n"
1693 << " return parser.emitError(keyLoc, \"expected "
1694 << (name == "operandSegmentSizes" ? op.getNumOperands()
1695 : op.getNumResults())
1696 << " entries for " << name << "\");\n"
1697 << " ::llvm::copy(parsedSegmentSizes, prop." << name
1698 << ".begin());\n"
1699 << " }\n";
1700 isFirst = false;
1701 };
1702
1703 if (parseOperandSegmentSizes)
1704 genSegmentSizesParser("operandSegmentSizes");
1705 if (parseResultSegmentSizes)
1706 genSegmentSizesParser("resultSegmentSizes");
1707
1708 for (const NamedProperty &property : op.getProperties()) {
1709 if (!shouldParseProperty(property))
1710 continue;
1711 bool isUnitProp = isPresenceOnlyUnitProp(property: property.prop);
1712 body << (isFirst ? " if" : " else if") << " (!seen_" << property.name
1713 << " && key == \"" << property.name << "\") {\n"
1714 << " seen_" << property.name << " = true;\n";
1715 if (isUnitProp) {
1716 PropertyVariable propertyVariable(&property);
1717 body << " if (succeeded(parser.parseOptionalEqual())) {\n";
1718 genPropertyParser(propVar: &propertyVariable, body&: body.indent().indent(),
1719 opCppClassName: fmt.opCppClassName);
1720 body.unindent() << " } else {\n"
1721 << " prop." << property.name << " = true;\n"
1722 << " }\n";
1723 } else if (!property.prop.usesDefaultParser()) {
1724 PropertyVariable propertyVariable(&property);
1725 genPropertyParser(propVar: &propertyVariable, body&: body.indent(), opCppClassName: fmt.opCppClassName);
1726 } else {
1727 FmtContext fctx;
1728 fctx.addSubst(placeholder: "_attr", subst: "propertyAttr");
1729 fctx.addSubst(placeholder: "_storage", subst: "propStorage");
1730 fctx.addSubst(placeholder: "_diag", subst: "emitError");
1731 body.indent() << R"decl(
1732auto parseResult = ::mlir::detail::parsePropertyWithFallback(
1733 parser, prop.)decl"
1734 << property.name << R"decl(,
1735 [&](auto &propStorage,
1736 ::mlir::Attribute propertyAttr) -> ::mlir::LogicalResult {
1737 auto emitError = [&]() {
1738 return parser.emitError(parser.getCurrentLocation())
1739 << "invalid value for property " << key << ": ";
1740 };
1741)decl";
1742 body << tgfmt(fmt: property.prop.getConvertFromAttributeCall(), ctx: &fctx)
1743 << ";\n";
1744 body << "});\n"
1745 << "if (failed(parseResult))\n"
1746 << " return ::mlir::failure();\n";
1747 body.unindent();
1748 }
1749 body.unindent() << " }\n";
1750 isFirst = false;
1751 }
1752 for (const NamedAttribute &attribute : op.getAttributes()) {
1753 if (!shouldParseAttribute(attribute))
1754 continue;
1755 AttributeVariable attributeVariable(&attribute);
1756 bool isUnitAttr =
1757 attribute.attr.getBaseAttr().getAttrDefName() == "UnitAttr";
1758 body << (isFirst ? " if" : " else if") << " (!seen_" << attribute.name
1759 << " && key == \"" << attribute.name << "\") {\n"
1760 << " seen_" << attribute.name << " = true;\n";
1761 if (isUnitAttr) {
1762 body << " if (succeeded(parser.parseOptionalEqual())) {\n"
1763 << " " << attribute.attr.getStorageType() << " "
1764 << attribute.name << "Attr;\n";
1765 genAttrParser(attr: &attributeVariable, body&: body.indent().indent(), attrTypeCtx,
1766 /*parseAsOptional=*/false, opCppClassName: fmt.opCppClassName);
1767 body.unindent() << " } else {\n"
1768 << " prop." << attribute.name
1769 << " = parser.getBuilder().getUnitAttr();\n"
1770 << " }\n";
1771 } else {
1772 body << " " << attribute.attr.getStorageType() << " "
1773 << attribute.name << "Attr;\n";
1774 if (shouldStripEnumAttrInPropDict(attr: &attribute)) {
1775 bool useBrackets = needsPropDictEnumBrackets(attr: &attribute);
1776 if (useBrackets)
1777 body << " if (parser.parseLSquare())\n"
1778 " return ::mlir::failure();\n";
1779 genEnumAttrParser(var: &attribute, body&: body.indent(), attrTypeCtx,
1780 /*parseAsOptional=*/false, opCppClassName: fmt.opCppClassName,
1781 /*formatAsEnumDirective=*/true,
1782 /*formatBitEnumAsUnquoted=*/true);
1783 if (useBrackets)
1784 body << " if (parser.parseRSquare())\n"
1785 " return ::mlir::failure();\n";
1786 } else {
1787 genAttrParser(attr: &attributeVariable, body&: body.indent(), attrTypeCtx,
1788 /*parseAsOptional=*/false, opCppClassName: fmt.opCppClassName);
1789 }
1790 }
1791 body.unindent() << " }\n";
1792 isFirst = false;
1793 }
1794
1795 if (isFirst) {
1796 body << R"decl(
1797 return parser.emitError(keyLoc,
1798 "unknown property in properties dictionary: ")
1799 << key;
1800)decl";
1801 } else {
1802 body << R"decl(
1803 else {
1804 return parser.emitError(
1805 keyLoc,
1806 "duplicate or unknown property in properties dictionary: ")
1807 << key;
1808 }
1809)decl";
1810 }
1811
1812 body << R"decl(
1813 reachedEnd = succeeded(parser.parseOptionalGreater());
1814 if (!reachedEnd && parser.parseComma())
1815 return ::mlir::failure();
1816 }
1817}
1818)decl";
1819
1820 if (parseOperandSegmentSizes)
1821 body << "if (!seen_operandSegmentSizes)\n"
1822 " return ::mlir::emitError(result.location, \"properties "
1823 "dictionary is missing required property: "
1824 "operandSegmentSizes\");\n";
1825 if (parseResultSegmentSizes)
1826 body << "if (!seen_resultSegmentSizes)\n"
1827 " return ::mlir::emitError(result.location, \"properties "
1828 "dictionary is missing required property: "
1829 "resultSegmentSizes\");\n";
1830
1831 for (const NamedProperty &property : op.getProperties()) {
1832 if (shouldParseProperty(property) && !property.prop.hasDefaultValue())
1833 body << "if (!seen_" << property.name
1834 << ")\n return ::mlir::emitError(result.location, "
1835 "\"properties dictionary is missing required property: "
1836 << property.name << "\");\n";
1837 }
1838 for (const NamedAttribute &attribute : op.getAttributes()) {
1839 if (shouldParseAttribute(attribute) && !attribute.attr.isOptional() &&
1840 !attribute.attr.hasDefaultValue())
1841 body << "if (!seen_" << attribute.name
1842 << ")\n return ::mlir::emitError(result.location, "
1843 "\"properties dictionary is missing required attribute: "
1844 << attribute.name << "\");\n";
1845 }
1846 body << "return ::mlir::success();\n";
1847}
1848
1849void OperationFormat::genParser(Operator &op, OpClass &opClass) {
1850 SmallVector<MethodParameter> paramList;
1851 paramList.emplace_back(Args: "::mlir::OpAsmParser &", Args: "parser");
1852 paramList.emplace_back(Args: "::mlir::OperationState &", Args: "result");
1853
1854 auto *method = opClass.addStaticMethod(retType: "::mlir::ParseResult", name: "parse",
1855 args: std::move(paramList));
1856 auto &body = method->body();
1857
1858 // Generate variables to store the operands and type within the format. This
1859 // allows for referencing these variables in the presence of optional
1860 // groupings.
1861 unsigned numVariableLengthOperands = llvm::count_if(
1862 Range: op.getOperands(), P: [](const NamedTypeConstraint &operand) {
1863 return operand.isVariableLength();
1864 });
1865 bool groupOperandStorage = !allOperands && numVariableLengthOperands > 1;
1866 if (groupOperandStorage)
1867 body << " ::mlir::detail::OperandParserStorage<"
1868 << numVariableLengthOperands << "> odsOperandVectors;\n";
1869 for (FormatElement *element : elements)
1870 genElementParserStorage(element, op, body, groupOperandStorage);
1871
1872 // A format context used when parsing attributes with buildable types.
1873 FmtContext attrTypeCtx;
1874 attrTypeCtx.withBuilder(subst: "parser.getBuilder()");
1875
1876 // Generate parsers for each of the elements.
1877 for (FormatElement *element : elements)
1878 genElementParser(element, body, attrTypeCtx);
1879
1880 // Generate the code to resolve the operand/result types and successors now
1881 // that they have been parsed.
1882 genParserRegionResolution(op, body);
1883 genParserSuccessorResolution(op, body);
1884 genParserVariadicSegmentResolution(op, body);
1885 genParserTypeResolution(op, body);
1886
1887 body << " return ::mlir::success();\n";
1888
1889 genParsedAttrPropertiesSetter(fmt&: *this, op, opClass);
1890 genKeyValuePropDictParser(fmt&: *this, op, opClass);
1891}
1892
1893void OperationFormat::genElementParser(FormatElement *element, MethodBody &body,
1894 FmtContext &attrTypeCtx,
1895 GenContext genCtx) {
1896 std::string propAccess = formatv(Fmt: getPropertiesCode, Vals&: opCppClassName);
1897 /// Optional Group.
1898 if (auto *optional = dyn_cast<OptionalElement>(Val: element)) {
1899 auto genElementParsers = [&](FormatElement *firstElement,
1900 ArrayRef<FormatElement *> elements,
1901 bool thenGroup) {
1902 // If the anchor is a unit attribute, we don't need to print it. When
1903 // parsing, we will add this attribute if this group is present.
1904 FormatElement *elidedAnchorElement = nullptr;
1905 auto *anchorVar = dyn_cast<AttributeLikeVariable>(Val: optional->getAnchor());
1906 if (anchorVar && anchorVar != firstElement && anchorVar->isUnit()) {
1907 elidedAnchorElement = anchorVar;
1908
1909 if (!thenGroup == optional->isInverted()) {
1910 // Add the anchor unit attribute or property to the operation state
1911 // or set the property to true.
1912 if (isa<PropertyVariable>(Val: anchorVar)) {
1913 body << formatv(Fmt: " {0}.{1} = true;", Vals&: propAccess,
1914 Vals: anchorVar->getName());
1915 } else {
1916 body << formatv(Fmt: " {0}.{1} = parser.getBuilder().getUnitAttr();",
1917 Vals&: propAccess, Vals: anchorVar->getName());
1918 }
1919 }
1920 }
1921
1922 // Generate the remaining then-elements or all else-elements after the
1923 // guard has selected a branch. Optional attributes must be parsed as
1924 // required here so that an incomplete group is rejected.
1925 for (FormatElement *childElement : elements)
1926 if (childElement != elidedAnchorElement)
1927 genElementParser(element: childElement, body, attrTypeCtx,
1928 genCtx: GenContext::Optional);
1929 };
1930
1931 ArrayRef<FormatElement *> thenElements =
1932 optional->getThenElements(/*parseable=*/true);
1933
1934 // Generate a special optional parser for the first element to gate the
1935 // parsing of the rest of the elements.
1936 FormatElement *firstElement = thenElements.front();
1937 if (auto *attrVar = dyn_cast<AttributeVariable>(Val: firstElement)) {
1938 genAttrParser(attr: attrVar, body, attrTypeCtx, /*parseAsOptional=*/true,
1939 opCppClassName);
1940 body << " if (" << attrVar->getVar()->name << "Attr) {\n";
1941 } else if (auto *propVar = dyn_cast<PropertyVariable>(Val: firstElement)) {
1942 genPropertyParser(propVar, body, opCppClassName, /*requireParse=*/false);
1943 body << formatv(Fmt: "if ({0}PropParseResult.has_value() && "
1944 "succeeded(*{0}PropParseResult)) ",
1945 Vals: propVar->getVar()->name)
1946 << " {\n";
1947 } else if (auto *literal = dyn_cast<LiteralElement>(Val: firstElement)) {
1948 body << " if (::mlir::succeeded(parser.parseOptional";
1949 genLiteralParser(value: literal->getSpelling(), body);
1950 body << ")) {\n";
1951 } else if (auto *opVar = dyn_cast<OperandVariable>(Val: firstElement)) {
1952 genElementParser(element: opVar, body, attrTypeCtx);
1953 body << " if (!" << opVar->getVar()->name << "Operands.empty()) {\n";
1954 } else if (auto *regionVar = dyn_cast<RegionVariable>(Val: firstElement)) {
1955 const NamedRegion *region = regionVar->getVar();
1956 if (region->isVariadic()) {
1957 genElementParser(element: regionVar, body, attrTypeCtx);
1958 body << " if (!" << region->name << "Regions.empty()) {\n";
1959 } else {
1960 body << formatv(Fmt: optionalRegionParserCode, Vals: region->name);
1961 body << " if (!" << region->name << "Region->empty()) {\n ";
1962 if (hasImplicitTermTrait)
1963 body << formatv(Fmt: regionEnsureTerminatorParserCode, Vals: region->name);
1964 else if (hasSingleBlockTrait)
1965 body << formatv(Fmt: regionEnsureSingleBlockParserCode, Vals: region->name);
1966 }
1967 } else if (auto *custom = dyn_cast<CustomDirective>(Val: firstElement)) {
1968 body << " if (auto optResult = [&]() -> ::mlir::OptionalParseResult {\n";
1969 genCustomDirectiveParser(dir: custom, body, opCppClassName,
1970 /*isOptional=*/true);
1971 body << " return ::mlir::success();\n"
1972 << " }(); optResult.has_value() && ::mlir::failed(*optResult)) {\n"
1973 << " return ::mlir::failure();\n"
1974 << " } else if (optResult.has_value()) {\n";
1975 }
1976
1977 genElementParsers(firstElement, thenElements.drop_front(),
1978 /*thenGroup=*/true);
1979 body << " }";
1980
1981 // Generate the else elements.
1982 auto elseElements = optional->getElseElements();
1983 if (!elseElements.empty()) {
1984 body << " else {\n";
1985 ArrayRef<FormatElement *> elseElements =
1986 optional->getElseElements(/*parseable=*/true);
1987 genElementParsers(elseElements.front(), elseElements,
1988 /*thenGroup=*/false);
1989 body << " }";
1990 }
1991 body << "\n";
1992
1993 /// OIList Directive
1994 } else if (OIListElement *oilist = dyn_cast<OIListElement>(Val: element)) {
1995 if (oilist->getSeparator()) {
1996 body << " {\n";
1997 body.indent();
1998 }
1999
2000 for (LiteralElement *le : oilist->getLiteralElements())
2001 body << " bool " << le->getSpelling() << "Clause = false;\n";
2002 if (oilist->getSeparator())
2003 body << " bool oilistClauseParsed = false;\n";
2004
2005 // Generate the parsing loop
2006 body << " while(true) {\n";
2007 if (LiteralElement *separator = oilist->getSeparator()) {
2008 body << " auto oilistSeparatorLoc = parser.getCurrentLocation();\n";
2009 body << " if (oilistClauseParsed) {\n";
2010 body << " if (failed(parser.parseOptional";
2011 genLiteralParser(value: separator->getSpelling(), body);
2012 body << ")) {\n";
2013 body << " if (";
2014 llvm::interleave(
2015 c: oilist->getLiteralElements(),
2016 each_fn: [&](LiteralElement *literal) {
2017 body << "succeeded(parser.parseOptional";
2018 genLiteralParser(value: literal->getSpelling(), body);
2019 body << ")";
2020 },
2021 between_fn: [&] { body << " || "; });
2022 body << ")\n";
2023 body << " return parser.emitError(oilistSeparatorLoc,\n"
2024 " \"expected '"
2025 << separator->getSpelling() << "' between oilist clauses\");\n";
2026 body << " break;\n";
2027 body << " }\n";
2028 body << " }\n";
2029 }
2030 for (auto clause : oilist->getClauses()) {
2031 LiteralElement *lelement = std::get<0>(t&: clause);
2032 ArrayRef<FormatElement *> pelement = std::get<1>(t&: clause);
2033 body << "if (succeeded(parser.parseOptional";
2034 genLiteralParser(value: lelement->getSpelling(), body);
2035 body << ")) {\n";
2036 StringRef lelementName = lelement->getSpelling();
2037 body << formatv(Fmt: oilistParserCode, Vals&: lelementName);
2038 if (oilist->getSeparator())
2039 body << " oilistClauseParsed = true;\n";
2040 if (AttributeLikeVariable *unitVarElem =
2041 oilist->getUnitVariableParsingElement(pelement)) {
2042 if (isa<PropertyVariable>(Val: unitVarElem)) {
2043 body << formatv(Fmt: " {0}.{1} = true;", Vals&: propAccess,
2044 Vals: unitVarElem->getName());
2045 } else {
2046 body << formatv(Fmt: " {0}.{1} = parser.getBuilder().getUnitAttr();",
2047 Vals&: propAccess, Vals: unitVarElem->getName());
2048 }
2049 } else {
2050 for (FormatElement *el : pelement)
2051 genElementParser(element: el, body, attrTypeCtx, genCtx: GenContext::Optional);
2052 }
2053 body << " } else ";
2054 }
2055 body << " {\n";
2056 if (oilist->getSeparator()) {
2057 body << " if (oilistClauseParsed)\n";
2058 body << " return parser.emitError(oilistSeparatorLoc,\n"
2059 " \"expected oilist clause after separator\");\n";
2060 }
2061 body << " break;\n";
2062 body << " }\n";
2063 body << "}\n";
2064 if (oilist->getSeparator())
2065 body.unindent() << " }\n";
2066
2067 /// Literals.
2068 } else if (LiteralElement *literal = dyn_cast<LiteralElement>(Val: element)) {
2069 body << " if (parser.parse";
2070 genLiteralParser(value: literal->getSpelling(), body);
2071 body << ")\n return ::mlir::failure();\n";
2072
2073 /// Whitespaces.
2074 } else if (isa<WhitespaceElement>(Val: element)) {
2075 // Nothing to parse.
2076
2077 /// Arguments.
2078 } else if (auto *attr = dyn_cast<AttributeVariable>(Val: element)) {
2079 bool parseAsOptional =
2080 (genCtx == GenContext::Normal && attr->getVar()->attr.isOptional());
2081 genAttrParser(attr, body, attrTypeCtx, parseAsOptional, opCppClassName);
2082 } else if (auto *prop = dyn_cast<PropertyVariable>(Val: element)) {
2083 genPropertyParser(propVar: prop, body, opCppClassName);
2084
2085 } else if (auto *operand = dyn_cast<OperandVariable>(Val: element)) {
2086 ArgumentLengthKind lengthKind = getArgumentLengthKind(var: operand->getVar());
2087 StringRef name = operand->getVar()->name;
2088 if (lengthKind == ArgumentLengthKind::VariadicOfVariadic)
2089 body << formatv(Fmt: variadicOfVariadicOperandParserCode, Vals&: name);
2090 else if (lengthKind == ArgumentLengthKind::Variadic)
2091 body << formatv(Fmt: variadicOperandParserCode, Vals&: name);
2092 else if (lengthKind == ArgumentLengthKind::Optional)
2093 body << formatv(Fmt: optionalOperandParserCode, Vals&: name);
2094 else
2095 body << formatv(Fmt: operandParserCode, Vals&: name);
2096
2097 } else if (auto *region = dyn_cast<RegionVariable>(Val: element)) {
2098 bool isVariadic = region->getVar()->isVariadic();
2099 body << formatv(Fmt: isVariadic ? regionListParserCode : regionParserCode,
2100 Vals: region->getVar()->name);
2101 if (hasImplicitTermTrait)
2102 body << formatv(Fmt: isVariadic ? regionListEnsureTerminatorParserCode
2103 : regionEnsureTerminatorParserCode,
2104 Vals: region->getVar()->name);
2105 else if (hasSingleBlockTrait)
2106 body << formatv(Fmt: isVariadic ? regionListEnsureSingleBlockParserCode
2107 : regionEnsureSingleBlockParserCode,
2108 Vals: region->getVar()->name);
2109
2110 } else if (auto *successor = dyn_cast<SuccessorVariable>(Val: element)) {
2111 bool isVariadic = successor->getVar()->isVariadic();
2112 body << formatv(Fmt: isVariadic ? successorListParserCode : successorParserCode,
2113 Vals: successor->getVar()->name);
2114
2115 /// Directives.
2116 } else if (auto *attrDict = dyn_cast<AttrDictDirective>(Val: element)) {
2117 body.indent() << "{\n";
2118 body.indent() << "auto loc = parser.getCurrentLocation();(void)loc;\n"
2119 << "if (parser.parseOptionalAttrDict"
2120 << (attrDict->isWithKeyword() ? "WithKeyword" : "")
2121 << "(result.attributes))\n"
2122 << " return ::mlir::failure();\n";
2123 if (!useStrictPropertiesInAssemblyFormat) {
2124 body << "if (failed(verifyInherentAttrs(result.name, result.attributes, "
2125 "[&]() {\n"
2126 << " return parser.emitError(loc) << \"'\" << "
2127 "result.name.getStringRef() << \"' op \";\n"
2128 << " })))\n"
2129 << " return ::mlir::failure();\n";
2130 } else {
2131 for (StringRef name : inherentAttrNames) {
2132 body << "if (result.attributes.get(\"" << name << "\"))\n"
2133 << " return parser.emitError(loc, \"inherent attribute '" << name
2134 << "' cannot be parsed from attr-dict when strict properties in "
2135 "assembly format is enabled\");\n";
2136 }
2137 }
2138 body.unindent() << "}\n";
2139 body.unindent();
2140 } else if (isa<PropDictDirective>(Val: element)) {
2141 body << " if (parseProperties(parser, result))\n"
2142 << " return ::mlir::failure();\n";
2143 } else if (auto *customDir = dyn_cast<CustomDirective>(Val: element)) {
2144 genCustomDirectiveParser(dir: customDir, body, opCppClassName);
2145 } else if (isa<OperandsDirective>(Val: element)) {
2146 body << " [[maybe_unused]] ::llvm::SMLoc allOperandLoc ="
2147 << " parser.getCurrentLocation();\n"
2148 << " if (parser.parseOperandList(allOperands))\n"
2149 << " return ::mlir::failure();\n";
2150
2151 } else if (isa<RegionsDirective>(Val: element)) {
2152 body << formatv(Fmt: regionListParserCode, Vals: "full");
2153 if (hasImplicitTermTrait)
2154 body << formatv(Fmt: regionListEnsureTerminatorParserCode, Vals: "full");
2155 else if (hasSingleBlockTrait)
2156 body << formatv(Fmt: regionListEnsureSingleBlockParserCode, Vals: "full");
2157
2158 } else if (isa<SuccessorsDirective>(Val: element)) {
2159 body << formatv(Fmt: successorListParserCode, Vals: "full");
2160
2161 } else if (auto *dir = dyn_cast<TypeDirective>(Val: element)) {
2162 ArgumentLengthKind lengthKind;
2163 StringRef listName = getTypeListName(arg: dir->getArg(), lengthKind);
2164 if (lengthKind == ArgumentLengthKind::VariadicOfVariadic) {
2165 body << formatv(Fmt: variadicOfVariadicTypeParserCode, Vals&: listName);
2166 } else if (lengthKind == ArgumentLengthKind::Variadic) {
2167 body << formatv(Fmt: variadicTypeParserCode, Vals&: listName);
2168 } else if (lengthKind == ArgumentLengthKind::Optional) {
2169 body << formatv(Fmt: optionalTypeParserCode, Vals&: listName);
2170 } else {
2171 const char *parserCode =
2172 dir->shouldBeQualified() ? qualifiedTypeParserCode : typeParserCode;
2173 TypeSwitch<FormatElement *>(dir->getArg())
2174 .Case<OperandVariable, ResultVariable>(caseFn: [&](auto operand) {
2175 body << formatv(false, parserCode,
2176 operand->getVar()->constraint.getCppType(),
2177 listName);
2178 })
2179 .Default(defaultFn: [&](auto operand) {
2180 body << formatv(Validate: false, Fmt: parserCode, Vals: "::mlir::Type", Vals&: listName);
2181 });
2182 }
2183 } else if (auto *dir = dyn_cast<FunctionalTypeDirective>(Val: element)) {
2184 ArgumentLengthKind ignored;
2185 body << formatv(Fmt: functionalTypeParserCode,
2186 Vals: getTypeListName(arg: dir->getInputs(), lengthKind&: ignored),
2187 Vals: getTypeListName(arg: dir->getResults(), lengthKind&: ignored));
2188 } else {
2189 llvm_unreachable("unknown format element");
2190 }
2191}
2192
2193void OperationFormat::genParserTypeResolution(Operator &op, MethodBody &body) {
2194 // If any of type resolutions use transformed variables, make sure that the
2195 // types of those variables are resolved.
2196 SmallPtrSet<const NamedTypeConstraint *, 8> verifiedVariables;
2197 FmtContext verifierFCtx;
2198 for (TypeResolution &resolver :
2199 llvm::concat<TypeResolution>(Ranges&: resultTypes, Ranges&: operandTypes)) {
2200 std::optional<StringRef> transformer = resolver.getVarTransformer();
2201 if (!transformer)
2202 continue;
2203 // Ensure that we don't verify the same variables twice.
2204 const NamedTypeConstraint *variable = resolver.getVariable();
2205 if (!variable || !verifiedVariables.insert(Ptr: variable).second)
2206 continue;
2207
2208 auto constraint = variable->constraint;
2209 body << " for (::mlir::Type type : " << variable->name << "Types) {\n"
2210 << " (void)type;\n"
2211 << " if (!("
2212 << tgfmt(fmt: constraint.getConditionTemplate(),
2213 ctx: &verifierFCtx.withSelf(subst: "type"))
2214 << ")) {\n"
2215 << formatv(Fmt: " return parser.emitError(parser.getNameLoc()) << "
2216 "\"'{0}' must be {1}, but got \" << type;\n",
2217 Vals: variable->name, Vals: constraint.getSummary())
2218 << " }\n"
2219 << " }\n";
2220 }
2221
2222 // Initialize the set of buildable types.
2223 if (!buildableTypes.empty()) {
2224 FmtContext typeBuilderCtx;
2225 typeBuilderCtx.withBuilder(subst: "parser.getBuilder()");
2226 for (auto &it : buildableTypes)
2227 body << " ::mlir::Type odsBuildableType" << it.second << " = "
2228 << tgfmt(fmt: it.first, ctx: &typeBuilderCtx) << ";\n";
2229 }
2230
2231 // Emit the code necessary for a type resolver.
2232 auto emitTypeResolver = [&](TypeResolution &resolver, StringRef curVar) {
2233 if (std::optional<int> val = resolver.getBuilderIdx()) {
2234 body << "odsBuildableType" << *val;
2235 } else if (const NamedTypeConstraint *var = resolver.getVariable()) {
2236 if (std::optional<StringRef> tform = resolver.getVarTransformer()) {
2237 FmtContext fmtContext;
2238 fmtContext.addSubst(placeholder: "_ctxt", subst: "parser.getContext()");
2239 if (var->isVariadic())
2240 fmtContext.withSelf(subst: var->name + "Types");
2241 else
2242 fmtContext.withSelf(subst: var->name + "Types[0]");
2243 body << tgfmt(fmt: *tform, ctx: &fmtContext);
2244 } else {
2245 body << var->name << "Types";
2246 if (!var->isVariadic())
2247 body << "[0]";
2248 }
2249 } else if (const NamedAttribute *attr = resolver.getAttribute()) {
2250 if (std::optional<StringRef> tform = resolver.getVarTransformer())
2251 body << tgfmt(fmt: *tform,
2252 ctx: &FmtContext().withSelf(subst: attr->name + "Attr.getType()"));
2253 else
2254 body << attr->name << "Attr.getType()";
2255 } else {
2256 body << curVar << "Types";
2257 }
2258 };
2259
2260 // Resolve each of the result types.
2261 if (!infersResultTypes) {
2262 if (allResultTypes) {
2263 body << " result.addTypes(allResultTypes);\n";
2264 } else {
2265 for (unsigned i = 0, e = op.getNumResults(); i != e; ++i) {
2266 body << " result.addTypes(";
2267 emitTypeResolver(resultTypes[i], op.getResultName(index: i));
2268 body << ");\n";
2269 }
2270 }
2271 }
2272
2273 // Emit the operand type resolutions.
2274 genParserOperandTypeResolution(op, body, emitTypeResolver);
2275
2276 // Handle return type inference once all operands have been resolved
2277 if (infersResultTypes)
2278 body << formatv(Fmt: inferReturnTypesParserCode, Vals: op.getCppClassName());
2279}
2280
2281void OperationFormat::genParserOperandTypeResolution(
2282 Operator &op, MethodBody &body,
2283 function_ref<void(TypeResolution &, StringRef)> emitTypeResolver) {
2284 // Fixed-length parser variables are represented as ArrayRefs to scalar
2285 // storage. Coverity does not track the explicit length and reports the
2286 // resolveOperands calls as ARRAY_VS_SINGLETON.
2287 auto emitArrayVsSingletonSuppression = [&] {
2288 body << " // coverity[ARRAY_VS_SINGLETON]\n";
2289 };
2290
2291 // Early exit if there are no operands.
2292 if (op.getNumOperands() == 0)
2293 return;
2294
2295 // Handle the case where all operand types are grouped together with
2296 // "types(operands)".
2297 if (allOperandTypes) {
2298 // If `operands` was specified, use the full operand list directly.
2299 if (allOperands) {
2300 emitArrayVsSingletonSuppression();
2301 body << " if (parser.resolveOperands(allOperands, allOperandTypes, "
2302 "allOperandLoc, result.operands))\n"
2303 " return ::mlir::failure();\n";
2304 return;
2305 }
2306
2307 // Otherwise, use llvm::concat to merge the disjoint operand lists together.
2308 // llvm::concat does not allow the case of a single range, so guard it here.
2309 emitArrayVsSingletonSuppression();
2310 body << " if (parser.resolveOperands(";
2311 if (op.getNumOperands() > 1) {
2312 body << "::llvm::concat<const ::mlir::OpAsmParser::UnresolvedOperand>(";
2313 llvm::interleaveComma(c: op.getOperands(), os&: body, each_fn: [&](auto &operand) {
2314 body << operand.name << "Operands";
2315 });
2316 body << ")";
2317 } else {
2318 body << op.operand_begin()->name << "Operands";
2319 }
2320 body << ", allOperandTypes, parser.getNameLoc(), result.operands))\n"
2321 << " return ::mlir::failure();\n";
2322 return;
2323 }
2324
2325 // Handle the case where all operands are grouped together with "operands".
2326 if (allOperands) {
2327 emitArrayVsSingletonSuppression();
2328 body << " if (parser.resolveOperands(allOperands, ";
2329
2330 // Group all of the operand types together to perform the resolution all at
2331 // once. Use llvm::concat to perform the merge. llvm::concat does not allow
2332 // the case of a single range, so guard it here.
2333 if (op.getNumOperands() > 1) {
2334 body << "::llvm::concat<const ::mlir::Type>(";
2335 llvm::interleaveComma(
2336 c: llvm::seq<int>(Begin: 0, End: op.getNumOperands()), os&: body, each_fn: [&](int i) {
2337 body << "::llvm::ArrayRef<::mlir::Type>(";
2338 emitTypeResolver(operandTypes[i], op.getOperand(index: i).name);
2339 body << ")";
2340 });
2341 body << ")";
2342 } else {
2343 emitTypeResolver(operandTypes.front(), op.getOperand(index: 0).name);
2344 }
2345
2346 body << ", allOperandLoc, result.operands))\n return "
2347 "::mlir::failure();\n";
2348 return;
2349 }
2350
2351 // The final case is the one where each of the operands types are resolved
2352 // separately.
2353 for (unsigned i = 0, e = op.getNumOperands(); i != e; ++i) {
2354 NamedTypeConstraint &operand = op.getOperand(index: i);
2355 TypeResolution &operandType = operandTypes[i];
2356 // Inferred type resolution may access another optional variable's empty
2357 // type vector. Directly parsed type ranges are safe and must always be
2358 // resolved so that operand/type cardinality is validated.
2359 bool guardOptionalOperand =
2360 operand.isOptional() && !operandType.isDirectlyParsed();
2361 if (guardOptionalOperand)
2362 body << " if (!" << operand.name << "Operands.empty()) {\n";
2363 emitArrayVsSingletonSuppression();
2364 body << " if (parser.resolveOperands(" << operand.name << "Operands, ";
2365
2366 // Resolve the type of this operand.
2367 emitTypeResolver(operandType, operand.name);
2368
2369 body << ", " << operand.name
2370 << "OperandsLoc, result.operands))\n return ::mlir::failure();\n";
2371 if (guardOptionalOperand)
2372 body << " }\n";
2373 }
2374}
2375
2376void OperationFormat::genParserRegionResolution(Operator &op,
2377 MethodBody &body) {
2378 // Check for the case where all regions were parsed.
2379 bool hasAllRegions = llvm::any_of(
2380 Range&: elements, P: [](FormatElement *elt) { return isa<RegionsDirective>(Val: elt); });
2381 if (hasAllRegions) {
2382 body << " result.addRegions(fullRegions);\n";
2383 return;
2384 }
2385
2386 // Otherwise, handle each region individually.
2387 for (const NamedRegion &region : op.getRegions()) {
2388 if (region.isVariadic())
2389 body << " result.addRegions(" << region.name << "Regions);\n";
2390 else
2391 body << " result.addRegion(std::move(" << region.name << "Region));\n";
2392 }
2393}
2394
2395void OperationFormat::genParserSuccessorResolution(Operator &op,
2396 MethodBody &body) {
2397 // Check for the case where all successors were parsed.
2398 bool hasAllSuccessors = llvm::any_of(Range&: elements, P: [](FormatElement *elt) {
2399 return isa<SuccessorsDirective>(Val: elt);
2400 });
2401 if (hasAllSuccessors) {
2402 body << " result.addSuccessors(fullSuccessors);\n";
2403 return;
2404 }
2405
2406 // Otherwise, handle each successor individually.
2407 for (const NamedSuccessor &successor : op.getSuccessors()) {
2408 if (successor.isVariadic())
2409 body << " result.addSuccessors(" << successor.name << "Successors);\n";
2410 else
2411 body << " result.addSuccessors(" << successor.name << "Successor);\n";
2412 }
2413}
2414
2415void OperationFormat::genParserVariadicSegmentResolution(Operator &op,
2416 MethodBody &body) {
2417 std::string propAccess = formatv(Fmt: getPropertiesCode, Vals: op.getCppClassName());
2418 if (!allOperands) {
2419 if (op.getTrait(trait: "::mlir::OpTrait::AttrSizedOperandSegments")) {
2420 auto interleaveFn = [&](const NamedTypeConstraint &operand) {
2421 // If the operand is variadic emit the parsed size.
2422 if (operand.isVariableLength())
2423 body << "static_cast<int32_t>(" << operand.name << "Operands.size())";
2424 else
2425 body << "1";
2426 };
2427 body << "::llvm::copy(::llvm::ArrayRef<int32_t>({";
2428 llvm::interleaveComma(c: op.getOperands(), os&: body, each_fn: interleaveFn);
2429 body << "}), " << propAccess << ".operandSegmentSizes.begin());\n";
2430 }
2431 for (const NamedTypeConstraint &operand : op.getOperands()) {
2432 if (!operand.isVariadicOfVariadic())
2433 continue;
2434 body << formatv(
2435 Fmt: " {0}.{1} = "
2436 "parser.getBuilder().getDenseI32ArrayAttr({2}OperandGroupSizes);\n",
2437 Vals&: propAccess, Vals: operand.constraint.getVariadicOfVariadicSegmentSizeAttr(),
2438 Vals: operand.name);
2439 }
2440 }
2441
2442 if (!allResultTypes &&
2443 op.getTrait(trait: "::mlir::OpTrait::AttrSizedResultSegments")) {
2444 auto interleaveFn = [&](const NamedTypeConstraint &result) {
2445 // If the result is variadic emit the parsed size.
2446 if (result.isVariableLength())
2447 body << "static_cast<int32_t>(" << result.name << "Types.size())";
2448 else
2449 body << "1";
2450 };
2451 body << "::llvm::copy(::llvm::ArrayRef<int32_t>({";
2452 llvm::interleaveComma(c: op.getResults(), os&: body, each_fn: interleaveFn);
2453 body << "}), " << propAccess << ".resultSegmentSizes.begin());\n";
2454 }
2455}
2456
2457//===----------------------------------------------------------------------===//
2458// PrinterGen
2459//===----------------------------------------------------------------------===//
2460
2461/// The code snippet used to generate a printer call for a region of an
2462// operation that has the SingleBlockImplicitTerminator trait.
2463///
2464/// {0}: The name of the region.
2465static const char *regionSingleBlockImplicitTerminatorPrinterCode = R"(
2466 {
2467 bool printTerminator = true;
2468 if (auto *term = {0}.empty() ? nullptr : {0}.begin()->getTerminator()) {{
2469 ::mlir::NamedAttrList termAttrs(term->getRawDictionaryAttrs());
2470 term->getName().walkInherentAttrs(
2471 term, [&](::llvm::StringRef name, ::mlir::Attribute &attr) {{
2472 termAttrs.append(name, attr);
2473 });
2474 printTerminator = !termAttrs.empty() ||
2475 term->getNumOperands() != 0 ||
2476 term->getNumResults() != 0;
2477 }
2478 _odsPrinter.printRegion({0}, /*printEntryBlockArgs=*/true,
2479 /*printBlockTerminators=*/printTerminator);
2480 }
2481)";
2482
2483/// The code snippet used to generate a printer call for an enum that has cases
2484/// that can't be represented with a keyword.
2485///
2486/// {0}: The name of the enum attribute.
2487/// {1}: The name of the enum attributes symbolToString function.
2488static const char *enumAttrBeginPrinterCode = R"(
2489 {
2490 auto caseValue = {0};
2491 auto caseValueStr = {1}(caseValue);
2492)";
2493
2494/// Generate a check that an optional or default-valued attribute or property
2495/// has a non-default value. For these purposes, the default value of an
2496/// optional attribute is its presence, even if the attribute itself has a
2497/// default value.
2498static void genNonDefaultValueCheck(MethodBody &body, const Operator &op,
2499 AttributeVariable &attrElement) {
2500 Attribute attr = attrElement.getVar()->attr;
2501 std::string getter = op.getGetterName(name: attrElement.getVar()->name);
2502 bool optionalAndDefault = attr.isOptional() && attr.hasDefaultValue();
2503 if (optionalAndDefault)
2504 body << "(";
2505 if (attr.isOptional())
2506 body << getter << "Attr()";
2507 if (optionalAndDefault)
2508 body << " && ";
2509 if (attr.hasDefaultValue()) {
2510 FmtContext fctx;
2511 fctx.withBuilder(subst: "::mlir::OpBuilder((*this)->getContext())");
2512 body << getter << "Attr() != "
2513 << tgfmt(fmt: attr.getConstBuilderTemplate(), ctx: &fctx,
2514 vals: tgfmt(fmt: attr.getDefaultValue(), ctx: &fctx));
2515 }
2516 if (optionalAndDefault)
2517 body << ")";
2518}
2519
2520static void genNonDefaultValueCheck(MethodBody &body, const Operator &op,
2521 PropertyVariable &propElement) {
2522 FmtContext fctx;
2523 fctx.withBuilder(subst: "::mlir::OpBuilder((*this)->getContext())");
2524 body << op.getGetterName(name: propElement.getVar()->name) << "() != "
2525 << tgfmt(fmt: propElement.getVar()->prop.getDefaultValue(), ctx: &fctx);
2526}
2527
2528/// Elide the variadic segment size attributes if necessary.
2529/// This pushes elided attribute names in `elidedStorage`.
2530static void genVariadicSegmentElision(OperationFormat &fmt, Operator &op,
2531 MethodBody &body,
2532 const char *elidedStorage) {
2533 if (!fmt.allOperands &&
2534 op.getTrait(trait: "::mlir::OpTrait::AttrSizedOperandSegments"))
2535 body << " " << elidedStorage << ".push_back(\"operandSegmentSizes\");\n";
2536 if (!fmt.allResultTypes &&
2537 op.getTrait(trait: "::mlir::OpTrait::AttrSizedResultSegments"))
2538 body << " " << elidedStorage << ".push_back(\"resultSegmentSizes\");\n";
2539}
2540
2541static void genEnumAttrPrinter(const NamedAttribute *var, const Operator &op,
2542 MethodBody &body, StringRef valueExpression,
2543 bool formatAsEnumDirective = false,
2544 bool formatBitEnumAsUnquoted = false);
2545
2546/// Generate the key-value printer used by the default `prop-dict` printer.
2547static void genKeyValuePropDictPrinter(OperationFormat &fmt, Operator &op,
2548 OpClass &opClass) {
2549 if (!fmt.hasPropDict || op.hasCustomPropertiesPrinter())
2550 return;
2551
2552 bool hasPrintableField =
2553 !op.getProperties().empty() ||
2554 llvm::any_of(
2555 Range: op.getAttributes(),
2556 P: [](const auto &attr) { return !attr.attr.isDerivedAttr(); }) ||
2557 (op.getTrait(trait: "::mlir::OpTrait::AttrSizedOperandSegments") &&
2558 fmt.allOperands) ||
2559 (op.getTrait(trait: "::mlir::OpTrait::AttrSizedResultSegments") &&
2560 fmt.allResultTypes);
2561 if (!hasPrintableField)
2562 return;
2563
2564 SmallVector<MethodParameter> paramList;
2565 paramList.emplace_back(Args: "::mlir::MLIRContext *", Args: "_odsContext");
2566 paramList.emplace_back(Args: "::mlir::OpAsmPrinter &", Args: "_odsPrinter");
2567 paramList.emplace_back(Args: "const Properties &", Args: "prop");
2568 paramList.emplace_back(Args: "::mlir::ArrayRef<::llvm::StringRef>", Args: "elidedProps");
2569 Method *method = opClass.addStaticMethod(
2570 retType: "void", name: "_odsPrintPropertiesAsKeyValueList", args: std::move(paramList));
2571 MethodBody &body = method->body().indent();
2572
2573 body << R"decl(
2574bool first = true;
2575auto printKey = [&](::llvm::StringRef name, bool printValue) {
2576 _odsPrinter << (first ? " <" : ", ") << name;
2577 if (printValue)
2578 _odsPrinter << " = ";
2579 first = false;
2580};
2581auto shouldPrint = [&](::llvm::StringRef name) {
2582 return !::llvm::is_contained(elidedProps, name);
2583};
2584)decl";
2585
2586 auto genSegmentSizesPrinter = [&](StringRef name) {
2587 body << "if (shouldPrint(\"" << name << "\")) {\n"
2588 << " printKey(\"" << name << "\", /*printValue=*/true);\n"
2589 << " _odsPrinter << \"[\";\n"
2590 << " ::llvm::interleaveComma(prop." << name << ", _odsPrinter);\n"
2591 << " _odsPrinter << \"]\";\n"
2592 << "}\n";
2593 };
2594 if (op.getTrait(trait: "::mlir::OpTrait::AttrSizedOperandSegments") &&
2595 fmt.allOperands)
2596 genSegmentSizesPrinter("operandSegmentSizes");
2597 if (op.getTrait(trait: "::mlir::OpTrait::AttrSizedResultSegments") &&
2598 fmt.allResultTypes)
2599 genSegmentSizesPrinter("resultSegmentSizes");
2600
2601 for (const NamedProperty &namedProperty : op.getProperties()) {
2602 const Property &property = namedProperty.prop;
2603 bool isUnitProp = isPresenceOnlyUnitProp(property);
2604 body << "if (shouldPrint(\"" << namedProperty.name << "\")) {\n"
2605 << " printKey(\"" << namedProperty.name << "\", /*printValue=*/"
2606 << (isUnitProp ? "false" : "true") << ");\n";
2607 FmtContext printerContext;
2608 printerContext.addSubst(placeholder: "_printer", subst: "_odsPrinter");
2609 printerContext.addSubst(placeholder: "_ctxt", subst: "_odsContext");
2610 printerContext.addSubst(placeholder: "_storage", subst: "prop." + namedProperty.name);
2611 if (isUnitProp) {
2612 // Unit properties are represented by the presence of their key.
2613 } else if (property.usesDefaultParser()) {
2614 body << " if constexpr (::mlir::detail::HasKeyValueFieldParser<"
2615 "std::remove_cv_t<std::remove_reference_t<decltype(prop."
2616 << namedProperty.name << ")>>>::value) {\n"
2617 << " " << tgfmt(fmt: property.getPrinterCall(), ctx: &printerContext)
2618 << ";\n"
2619 << " } else {\n"
2620 << " auto propertyAttr = [&]() -> ::mlir::Attribute {\n";
2621 FmtContext conversionContext;
2622 conversionContext.addSubst(placeholder: "_ctxt", subst: "_odsContext");
2623 conversionContext.addSubst(placeholder: "_storage", subst: "prop." + namedProperty.name);
2624 body << tgfmt(fmt: property.getConvertToAttributeCall(), ctx: &conversionContext)
2625 << "\n"
2626 << " }();\n"
2627 << " _odsPrinter.printAttribute(propertyAttr);\n"
2628 << " }\n";
2629 } else {
2630 body << " " << tgfmt(fmt: property.getPrinterCall(), ctx: &printerContext)
2631 << ";\n";
2632 }
2633 body << "}\n";
2634 }
2635
2636 for (const NamedAttribute &namedAttr : op.getAttributes()) {
2637 if (namedAttr.attr.isDerivedAttr())
2638 continue;
2639 StringRef name = namedAttr.name;
2640 AttributeVariable attrVariable(&namedAttr);
2641 bool isUnitAttr =
2642 namedAttr.attr.getBaseAttr().getAttrDefName() == "UnitAttr";
2643 body << "if (shouldPrint(\"" << name << "\")";
2644 if (namedAttr.attr.isOptional() || namedAttr.attr.hasDefaultValue())
2645 body << " && prop." << name;
2646 body << ") {\n"
2647 << " printKey(\"" << name << "\", /*printValue=*/"
2648 << (isUnitAttr ? "false" : "true") << ");\n";
2649
2650 if (isUnitAttr) {
2651 // Unit attributes are represented by the presence of their key.
2652 } else if (shouldStripEnumAttrInPropDict(attr: &namedAttr)) {
2653 bool useBrackets = needsPropDictEnumBrackets(attr: &namedAttr);
2654 if (useBrackets)
2655 body << " _odsPrinter << \"[\";\n";
2656 FmtContext conversionContext;
2657 conversionContext.withSelf(subst: "prop." + name);
2658 std::string valueExpression = std::string(tgfmt(
2659 fmt: namedAttr.attr.getConvertFromStorageCall(), ctx: &conversionContext));
2660 genEnumAttrPrinter(var: &namedAttr, op, body, valueExpression,
2661 /*formatAsEnumDirective=*/true,
2662 /*formatBitEnumAsUnquoted=*/true);
2663 if (useBrackets)
2664 body << " _odsPrinter << \"]\";\n";
2665 } else if (canFormatEnumAttr(attr: &namedAttr)) {
2666 FmtContext conversionContext;
2667 conversionContext.withSelf(subst: "prop." + name);
2668 std::string valueExpression = std::string(tgfmt(
2669 fmt: namedAttr.attr.getConvertFromStorageCall(), ctx: &conversionContext));
2670 genEnumAttrPrinter(var: &namedAttr, op, body, valueExpression);
2671 } else if (shouldFormatSymbolNameAttr(attr: &namedAttr)) {
2672 body << " _odsPrinter.printSymbolName(prop." << name
2673 << ".getValue());\n";
2674 } else {
2675 if (attrVariable.getTypeBuilder())
2676 body << " _odsPrinter.printAttributeWithoutType(prop." << name
2677 << ");\n";
2678 else if (attrVariable.shouldBeQualified() ||
2679 namedAttr.attr.getStorageType() == "::mlir::Attribute")
2680 body << " _odsPrinter.printAttribute(prop." << name << ");\n";
2681 else
2682 body << " _odsPrinter.printStrippedAttrOrType(prop." << name << ");\n";
2683 }
2684 body << "}\n";
2685 }
2686 body << "if (!first)\n"
2687 " _odsPrinter << \">\";\n";
2688}
2689
2690/// Generate the printer for the 'prop-dict' directive.
2691static void genPropDictPrinter(OperationFormat &fmt, Operator &op,
2692 MethodBody &body) {
2693 body << " ::llvm::SmallVector<::llvm::StringRef, 2> elidedProps;\n";
2694
2695 genVariadicSegmentElision(fmt, op, body, elidedStorage: "elidedProps");
2696
2697 for (const NamedProperty *namedProperty : fmt.usedProperties)
2698 body << " elidedProps.push_back(\"" << namedProperty->name << "\");\n";
2699 for (StringRef key : fmt.inferredAttributes.keys())
2700 body << " elidedProps.push_back(\"" << key << "\");\n";
2701 for (const NamedAttribute *namedAttr : fmt.usedAttributes)
2702 body << " elidedProps.push_back(\"" << namedAttr->name << "\");\n";
2703
2704 // Add code to check attributes for equality with their default values.
2705 // Default-valued attributes will not be printed when their value matches the
2706 // default.
2707 for (const NamedAttribute &namedAttr : op.getAttributes()) {
2708 if (fmt.usedAttributes.contains(key: &namedAttr))
2709 continue;
2710 const Attribute &attr = namedAttr.attr;
2711 if (!attr.isDerivedAttr() && attr.hasDefaultValue()) {
2712 const StringRef &name = namedAttr.name;
2713 FmtContext fctx;
2714 fctx.withBuilder(subst: "odsBuilder");
2715 std::string defaultValue =
2716 std::string(tgfmt(fmt: attr.getConstBuilderTemplate(), ctx: &fctx,
2717 vals: tgfmt(fmt: attr.getDefaultValue(), ctx: &fctx)));
2718 body << " {\n";
2719 body << " ::mlir::Builder odsBuilder((*this)->getContext());\n";
2720 body << " ::mlir::Attribute attr = " << op.getGetterName(name)
2721 << "Attr();\n";
2722 body << " if(attr && (attr == " << defaultValue << "))\n";
2723 body << " elidedProps.push_back(\"" << name << "\");\n";
2724 body << " }\n";
2725 }
2726 }
2727 // Similarly, elide default-valued properties.
2728 for (const NamedProperty &prop : op.getProperties()) {
2729 if (prop.prop.hasDefaultValue()) {
2730 FmtContext fctx;
2731 fctx.withBuilder(subst: "odsBuilder");
2732 body << " if (" << op.getGetterName(name: prop.name)
2733 << "() == " << tgfmt(fmt: prop.prop.getDefaultValue(), ctx: &fctx) << ") {";
2734 body << " elidedProps.push_back(\"" << prop.name << "\");\n";
2735 body << " }\n";
2736 }
2737 }
2738
2739 // The `printProperties` method is responsible for printing out a leading
2740 // space so that empty `prop-dict`s don't produce stray whitespace.
2741 body << " printProperties((*this)->getContext(), _odsPrinter, "
2742 "getProperties(), elidedProps);\n";
2743}
2744
2745/// Generate the printer for the 'attr-dict' directive.
2746static void genAttrDictPrinter(OperationFormat &fmt, Operator &op,
2747 MethodBody &body, bool withKeyword) {
2748 // TODO: Remove the non-strict path when strict properties in assembly
2749 // formats are always enabled.
2750 if (fmt.useStrictPropertiesInAssemblyFormat) {
2751 // Inherent attributes are printed by their bindings or prop-dict.
2752 body << " _odsPrinter.printOptionalAttrDict"
2753 << (withKeyword ? "WithKeyword" : "")
2754 << "((*this)->getDiscardableAttrDictionary().getValue());\n";
2755 return;
2756 }
2757
2758 SmallVector<StringRef> fixedElidedAttrs;
2759 if (!fmt.allOperands &&
2760 op.getTrait(trait: "::mlir::OpTrait::AttrSizedOperandSegments"))
2761 fixedElidedAttrs.push_back(Elt: "operandSegmentSizes");
2762 if (!fmt.allResultTypes &&
2763 op.getTrait(trait: "::mlir::OpTrait::AttrSizedResultSegments"))
2764 fixedElidedAttrs.push_back(Elt: "resultSegmentSizes");
2765 for (StringRef key : fmt.inferredAttributes.keys())
2766 fixedElidedAttrs.push_back(Elt: key);
2767 for (const NamedAttribute *attr : fmt.usedAttributes)
2768 fixedElidedAttrs.push_back(Elt: attr->name);
2769
2770 bool hasConditionalElision =
2771 llvm::any_of(Range: op.getAttributes(), P: [&](const NamedAttribute &namedAttr) {
2772 return !fmt.usedAttributes.contains(key: &namedAttr) &&
2773 !namedAttr.attr.isDerivedAttr() &&
2774 namedAttr.attr.hasDefaultValue();
2775 });
2776 if (hasConditionalElision) {
2777 body << " ::llvm::SmallVector<::llvm::StringRef, 2> elidedAttrs = {";
2778 llvm::interleaveComma(c: fixedElidedAttrs, os&: body, each_fn: [&](StringRef name) {
2779 body << "\"" << name << "\"";
2780 });
2781 body << "};\n";
2782 } else if (fixedElidedAttrs.empty()) {
2783 body << " ::llvm::ArrayRef<::llvm::StringRef> elidedAttrs;\n";
2784 } else {
2785 body << " static constexpr ::llvm::StringRef elidedAttrs[] = {";
2786 llvm::interleaveComma(c: fixedElidedAttrs, os&: body, each_fn: [&](StringRef name) {
2787 body << "\"" << name << "\"";
2788 });
2789 body << "};\n";
2790 }
2791
2792 // Add code to check attributes for equality with their default values.
2793 // Default-valued attributes will not be printed when their value matches the
2794 // default.
2795 for (const NamedAttribute &namedAttr : op.getAttributes()) {
2796 if (fmt.usedAttributes.contains(key: &namedAttr))
2797 continue;
2798 const Attribute &attr = namedAttr.attr;
2799 if (!attr.isDerivedAttr() && attr.hasDefaultValue()) {
2800 const StringRef &name = namedAttr.name;
2801 FmtContext fctx;
2802 fctx.withBuilder(subst: "odsBuilder");
2803 std::string defaultValue =
2804 std::string(tgfmt(fmt: attr.getConstBuilderTemplate(), ctx: &fctx,
2805 vals: tgfmt(fmt: attr.getDefaultValue(), ctx: &fctx)));
2806 body << " {\n";
2807 body << " ::mlir::Builder odsBuilder((*this)->getContext());\n";
2808 body << " ::mlir::Attribute attr = " << op.getGetterName(name)
2809 << "Attr();\n";
2810 body << " if(attr && (attr == " << defaultValue << "))\n";
2811 body << " elidedAttrs.push_back(\"" << name << "\");\n";
2812 body << " }\n";
2813 }
2814 }
2815 if (fmt.hasPropDict)
2816 body << " _odsPrinter.printOptionalAttrDict"
2817 << (withKeyword ? "WithKeyword" : "")
2818 << "(llvm::to_vector((*this)->getDiscardableAttrDictionary().getValue("
2819 ")), elidedAttrs);\n";
2820 else {
2821 body << " ::mlir::NamedAttrList _odsAttrs("
2822 "(*this)->getRawDictionaryAttrs());\n"
2823 " (*this)->getName().walkInherentAttrs(*this, "
2824 "[&](::llvm::StringRef name, ::mlir::Attribute &attr) {\n"
2825 " _odsAttrs.append(name, attr);\n"
2826 " });\n"
2827 " _odsPrinter.printOptionalAttrDict"
2828 << (withKeyword ? "WithKeyword" : "")
2829 << "(_odsAttrs.getDictionary((*this)->getContext()).getValue(), "
2830 "elidedAttrs);\n";
2831 }
2832}
2833
2834/// Generate the printer for a literal value. `shouldEmitSpace` is true if a
2835/// space should be emitted before this element. `lastWasPunctuation` is true if
2836/// the previous element was a punctuation literal.
2837static void genLiteralPrinter(StringRef value, MethodBody &body,
2838 bool &shouldEmitSpace, bool &lastWasPunctuation) {
2839 body << " _odsPrinter << \"";
2840
2841 // Don't insert a space for certain punctuation.
2842 if (shouldEmitSpace && shouldEmitSpaceBefore(value, lastWasPunctuation))
2843 body << ' ';
2844 body << value << "\";\n";
2845
2846 // Insert a space after certain literals.
2847 shouldEmitSpace =
2848 value.size() != 1 || !StringRef("<({[").contains(C: value.front());
2849 lastWasPunctuation = value.front() != '_' && !isalpha(value.front());
2850}
2851
2852/// Generate the printer for a space. `shouldEmitSpace` and `lastWasPunctuation`
2853/// are set to false.
2854static void genSpacePrinter(bool value, MethodBody &body, bool &shouldEmitSpace,
2855 bool &lastWasPunctuation) {
2856 if (value) {
2857 body << " _odsPrinter << ' ';\n";
2858 lastWasPunctuation = false;
2859 } else {
2860 lastWasPunctuation = true;
2861 }
2862 shouldEmitSpace = false;
2863}
2864
2865/// Generate the printer for a custom directive parameter.
2866static void genCustomDirectiveParameterPrinter(FormatElement *element,
2867 const Operator &op,
2868 MethodBody &body) {
2869 if (auto *attr = dyn_cast<AttributeVariable>(Val: element)) {
2870 body << op.getGetterName(name: attr->getVar()->name) << "Attr()";
2871
2872 } else if (isa<AttrDictDirective>(Val: element)) {
2873 body << "[&]() { ::mlir::NamedAttrList attrs("
2874 "getOperation()->getRawDictionaryAttrs()); "
2875 "getOperation()->getName().walkInherentAttrs(getOperation(), "
2876 "[&](::llvm::StringRef name, ::mlir::Attribute &attr) { "
2877 "attrs.append(name, attr); }); return attrs.getDictionary("
2878 "getOperation()->getContext()); }()";
2879
2880 } else if (isa<PropDictDirective>(Val: element)) {
2881 body << "getProperties()";
2882
2883 } else if (auto *operand = dyn_cast<OperandVariable>(Val: element)) {
2884 body << op.getGetterName(name: operand->getVar()->name) << "()";
2885
2886 } else if (auto *region = dyn_cast<RegionVariable>(Val: element)) {
2887 body << op.getGetterName(name: region->getVar()->name) << "()";
2888
2889 } else if (auto *successor = dyn_cast<SuccessorVariable>(Val: element)) {
2890 body << op.getGetterName(name: successor->getVar()->name) << "()";
2891
2892 } else if (auto *dir = dyn_cast<RefDirective>(Val: element)) {
2893 genCustomDirectiveParameterPrinter(element: dir->getArg(), op, body);
2894
2895 } else if (auto *dir = dyn_cast<TypeDirective>(Val: element)) {
2896 auto *typeOperand = dir->getArg();
2897 auto *operand = dyn_cast<OperandVariable>(Val: typeOperand);
2898 auto *var = operand ? operand->getVar()
2899 : cast<ResultVariable>(Val: typeOperand)->getVar();
2900 std::string name = op.getGetterName(name: var->name);
2901 if (var->isVariadic())
2902 body << name << "().getTypes()";
2903 else if (var->isOptional())
2904 body << formatv(Fmt: "({0}() ? {0}().getType() : ::mlir::Type())", Vals&: name);
2905 else
2906 body << name << "().getType()";
2907
2908 } else if (auto *string = dyn_cast<StringElement>(Val: element)) {
2909 FmtContext ctx;
2910 ctx.withBuilder(subst: "::mlir::Builder(getContext())");
2911 ctx.addSubst(placeholder: "_ctxt", subst: "getContext()");
2912 body << tgfmt(fmt: string->getValue(), ctx: &ctx);
2913
2914 } else if (auto *property = dyn_cast<PropertyVariable>(Val: element)) {
2915 FmtContext ctx;
2916 const NamedProperty *namedProperty = property->getVar();
2917 ctx.addSubst(placeholder: "_storage", subst: "getProperties()." + namedProperty->name);
2918 body << tgfmt(fmt: namedProperty->prop.getConvertFromStorageCall(), ctx: &ctx);
2919 } else {
2920 llvm_unreachable("unknown custom directive parameter");
2921 }
2922}
2923
2924/// Generate the printer for a custom directive.
2925static void genCustomDirectivePrinter(CustomDirective *customDir,
2926 const Operator &op, MethodBody &body) {
2927 body << " print" << customDir->getName() << "(_odsPrinter, *this";
2928 for (FormatElement *param : customDir->getElements()) {
2929 body << ", ";
2930 genCustomDirectiveParameterPrinter(element: param, op, body);
2931 }
2932 body << ");\n";
2933}
2934
2935/// Generate the printer for a region with the given variable name.
2936static void genRegionPrinter(const Twine &regionName, MethodBody &body,
2937 bool hasImplicitTermTrait) {
2938 if (hasImplicitTermTrait)
2939 body << formatv(Fmt: regionSingleBlockImplicitTerminatorPrinterCode, Vals: regionName);
2940 else
2941 body << " _odsPrinter.printRegion(" << regionName << ");\n";
2942}
2943static void genVariadicRegionPrinter(const Twine &regionListName,
2944 MethodBody &body,
2945 bool hasImplicitTermTrait) {
2946 body << " llvm::interleaveComma(" << regionListName
2947 << ", _odsPrinter, [&](::mlir::Region &region) {\n ";
2948 genRegionPrinter(regionName: "region", body, hasImplicitTermTrait);
2949 body << " });\n";
2950}
2951
2952/// Generate the C++ for an operand to a (*-)type directive.
2953static MethodBody &genTypeOperandPrinter(FormatElement *arg, const Operator &op,
2954 MethodBody &body,
2955 bool useArrayRef = true) {
2956 if (isa<OperandsDirective>(Val: arg))
2957 return body << "getOperation()->getOperandTypes()";
2958 if (isa<ResultsDirective>(Val: arg))
2959 return body << "getOperation()->getResultTypes()";
2960 auto *operand = dyn_cast<OperandVariable>(Val: arg);
2961 auto *var = operand ? operand->getVar() : cast<ResultVariable>(Val: arg)->getVar();
2962 if (var->isVariadicOfVariadic())
2963 return body << formatv(Fmt: "{0}().join().getTypes()",
2964 Vals: op.getGetterName(name: var->name));
2965 if (var->isVariadic())
2966 return body << op.getGetterName(name: var->name) << "().getTypes()";
2967 if (var->isOptional())
2968 return body << formatv(
2969 Fmt: "({0}() ? ::llvm::ArrayRef<::mlir::Type>({0}().getType()) : "
2970 "::llvm::ArrayRef<::mlir::Type>())",
2971 Vals: op.getGetterName(name: var->name));
2972 if (useArrayRef)
2973 return body << "::llvm::ArrayRef<::mlir::Type>("
2974 << op.getGetterName(name: var->name) << "().getType())";
2975 return body << op.getGetterName(name: var->name) << "().getType()";
2976}
2977
2978/// Generate the printer for an enum attribute.
2979static void genEnumAttrPrinter(const NamedAttribute *var, const Operator &op,
2980 MethodBody &body, StringRef valueExpression,
2981 bool formatAsEnumDirective,
2982 bool formatBitEnumAsUnquoted) {
2983 Attribute baseAttr = var->attr.getBaseAttr();
2984 const EnumInfo enumInfo(getEnumInfoRecord(attr: baseAttr));
2985 bool dereferenceGetter =
2986 var->attr.isOptional() && !var->attr.hasDefaultValue();
2987
2988 std::string caseValue = valueExpression.empty()
2989 ? op.getGetterName(name: var->name) + "()"
2990 : valueExpression.str();
2991 if (dereferenceGetter)
2992 caseValue = "*(" + caseValue + ")";
2993 body << formatv(Fmt: enumAttrBeginPrinterCode, Vals&: caseValue,
2994 Vals: enumInfo.getSymbolToStringFnName());
2995
2996 if (formatAsEnumDirective && enumInfo.isBitEnum() &&
2997 (formatBitEnumAsUnquoted || !enumInfo.printBitEnumQuoted())) {
2998 body << " _odsPrinter << caseValueStr;\n"
2999 " }\n";
3000 return;
3001 }
3002
3003 std::vector<EnumCase> cases = enumInfo.getAllCases();
3004
3005 // Get a string containing all of the cases that can't be represented with a
3006 // keyword.
3007 BitVector nonKeywordCases(cases.size());
3008 for (auto it : llvm::enumerate(First&: cases)) {
3009 if (!canFormatStringAsKeyword(value: it.value().getStr()))
3010 nonKeywordCases.set(it.index());
3011 }
3012
3013 // Otherwise if this is a bit enum attribute, don't allow cases that may
3014 // overlap with other cases. For simplicity sake, only allow cases with a
3015 // single bit value.
3016 if (enumInfo.isBitEnum()) {
3017 for (auto it : llvm::enumerate(First&: cases)) {
3018 int64_t value = it.value().getValue();
3019 if (value < 0 || !llvm::isPowerOf2_64(Value: value))
3020 nonKeywordCases.set(it.index());
3021 }
3022 }
3023
3024 // If there are any cases that can't be used with a keyword, switch on the
3025 // case value to determine when to print in the string form.
3026 if (nonKeywordCases.any()) {
3027 body << " switch (caseValue) {\n";
3028 StringRef cppNamespace = enumInfo.getCppNamespace();
3029 StringRef enumName = enumInfo.getEnumClassName();
3030 for (auto it : llvm::enumerate(First&: cases)) {
3031 if (nonKeywordCases.test(Idx: it.index()))
3032 continue;
3033 StringRef symbol = it.value().getSymbol();
3034 body << formatv(Fmt: " case {0}::{1}::{2}:\n", Vals&: cppNamespace, Vals&: enumName,
3035 Vals: llvm::isDigit(C: symbol.front()) ? ("_" + symbol) : symbol);
3036 }
3037 body << " _odsPrinter << caseValueStr;\n"
3038 " break;\n"
3039 " default:\n"
3040 " _odsPrinter << '\"' << caseValueStr << '\"';\n"
3041 " break;\n"
3042 " }\n"
3043 " }\n";
3044 return;
3045 }
3046
3047 body << " _odsPrinter << caseValueStr;\n"
3048 " }\n";
3049}
3050
3051/// Generate the check for the anchor of an optional group.
3052static void genOptionalGroupPrinterAnchor(FormatElement *anchor,
3053 const Operator &op,
3054 MethodBody &body) {
3055 TypeSwitch<FormatElement *>(anchor)
3056 .Case<OperandVariable, ResultVariable>(caseFn: [&](auto *element) {
3057 const NamedTypeConstraint *var = element->getVar();
3058 std::string name = op.getGetterName(name: var->name);
3059 if (var->isOptional())
3060 body << name << "()";
3061 else if (var->isVariadic())
3062 body << "!" << name << "().empty()";
3063 })
3064 .Case(caseFn: [&](RegionVariable *element) {
3065 const NamedRegion *var = element->getVar();
3066 std::string name = op.getGetterName(name: var->name);
3067 // TODO: Add a check for optional regions here when ODS supports it.
3068 body << "!" << name << "().empty()";
3069 })
3070 .Case(caseFn: [&](TypeDirective *element) {
3071 genOptionalGroupPrinterAnchor(anchor: element->getArg(), op, body);
3072 })
3073 .Case(caseFn: [&](FunctionalTypeDirective *element) {
3074 genOptionalGroupPrinterAnchor(anchor: element->getInputs(), op, body);
3075 })
3076 .Case(caseFn: [&](AttributeVariable *element) {
3077 // Consider a default-valued attribute as present if it's not the
3078 // default value and an optional one present if it is set.
3079 genNonDefaultValueCheck(body, op, attrElement&: *element);
3080 })
3081 .Case(caseFn: [&](PropertyVariable *element) {
3082 genNonDefaultValueCheck(body, op, propElement&: *element);
3083 })
3084 .Case(caseFn: [&](CustomDirective *ele) {
3085 body << '(';
3086 llvm::interleave(
3087 c: ele->getElements(), os&: body,
3088 each_fn: [&](FormatElement *child) {
3089 body << '(';
3090 genOptionalGroupPrinterAnchor(anchor: child, op, body);
3091 body << ')';
3092 },
3093 separator: " || ");
3094 body << ')';
3095 });
3096}
3097
3098static void collect(FormatElement *element,
3099 SmallVectorImpl<VariableElement *> &variables) {
3100 TypeSwitch<FormatElement *>(element)
3101 .Case(caseFn: [&](VariableElement *var) { variables.emplace_back(Args&: var); })
3102 .Case(caseFn: [&](CustomDirective *ele) {
3103 for (FormatElement *arg : ele->getElements())
3104 collect(element: arg, variables);
3105 })
3106 .Case(caseFn: [&](OptionalElement *ele) {
3107 for (FormatElement *arg : ele->getThenElements())
3108 collect(element: arg, variables);
3109 for (FormatElement *arg : ele->getElseElements())
3110 collect(element: arg, variables);
3111 })
3112 .Case(caseFn: [&](FunctionalTypeDirective *funcType) {
3113 collect(element: funcType->getInputs(), variables);
3114 collect(element: funcType->getResults(), variables);
3115 })
3116 .Case(caseFn: [&](OIListElement *oilist) {
3117 for (ArrayRef<FormatElement *> arg : oilist->getParsingElements())
3118 for (FormatElement *arg : arg)
3119 collect(element: arg, variables);
3120 });
3121}
3122
3123void OperationFormat::genElementPrinter(FormatElement *element,
3124 MethodBody &body, Operator &op,
3125 bool &shouldEmitSpace,
3126 bool &lastWasPunctuation) {
3127 if (LiteralElement *literal = dyn_cast<LiteralElement>(Val: element))
3128 return genLiteralPrinter(value: literal->getSpelling(), body, shouldEmitSpace,
3129 lastWasPunctuation);
3130
3131 // Emit a whitespace element.
3132 if (auto *space = dyn_cast<WhitespaceElement>(Val: element)) {
3133 if (space->getValue() == "\\n") {
3134 body << " _odsPrinter.printNewline();\n";
3135 } else {
3136 genSpacePrinter(value: !space->getValue().empty(), body, shouldEmitSpace,
3137 lastWasPunctuation);
3138 }
3139 return;
3140 }
3141
3142 // Emit an optional group.
3143 if (OptionalElement *optional = dyn_cast<OptionalElement>(Val: element)) {
3144 // Emit the check for the presence of the anchor element.
3145 FormatElement *anchor = optional->getAnchor();
3146 body << " if (";
3147 if (optional->isInverted())
3148 body << "!";
3149 genOptionalGroupPrinterAnchor(anchor, op, body);
3150 body << ") {\n";
3151 body.indent();
3152
3153 // If the anchor is a unit attribute, we don't need to print it. When
3154 // parsing, we will add this attribute if this group is present.
3155 ArrayRef<FormatElement *> thenElements = optional->getThenElements();
3156 ArrayRef<FormatElement *> elseElements = optional->getElseElements();
3157 FormatElement *elidedAnchorElement = nullptr;
3158 auto *anchorAttr = dyn_cast<AttributeLikeVariable>(Val: anchor);
3159 if (anchorAttr && anchorAttr != thenElements.front() &&
3160 (elseElements.empty() || anchorAttr != elseElements.front()) &&
3161 anchorAttr->isUnit()) {
3162 elidedAnchorElement = anchorAttr;
3163 }
3164 auto genElementPrinters = [&](ArrayRef<FormatElement *> elements) {
3165 for (FormatElement *childElement : elements) {
3166 if (childElement != elidedAnchorElement) {
3167 genElementPrinter(element: childElement, body, op, shouldEmitSpace,
3168 lastWasPunctuation);
3169 }
3170 }
3171 };
3172
3173 // Emit each of the elements.
3174 genElementPrinters(thenElements);
3175 body << "}";
3176
3177 // Emit each of the else elements.
3178 if (!elseElements.empty()) {
3179 body << " else {\n";
3180 genElementPrinters(elseElements);
3181 body << "}";
3182 }
3183
3184 body.unindent() << "\n";
3185 return;
3186 }
3187
3188 // Emit the OIList
3189 if (auto *oilist = dyn_cast<OIListElement>(Val: element)) {
3190 if (oilist->getSeparator()) {
3191 body << " {\n";
3192 body.indent();
3193 body << " bool oilistClausePrinted = false;\n";
3194 }
3195 for (auto clause : oilist->getClauses()) {
3196 LiteralElement *lelement = std::get<0>(t&: clause);
3197 ArrayRef<FormatElement *> pelement = std::get<1>(t&: clause);
3198
3199 SmallVector<VariableElement *> vars;
3200 for (FormatElement *el : pelement)
3201 collect(element: el, variables&: vars);
3202 body << " if (false";
3203 for (VariableElement *var : vars) {
3204 TypeSwitch<FormatElement *>(var)
3205 .Case(caseFn: [&](AttributeVariable *attrEle) {
3206 body << " || (";
3207 genNonDefaultValueCheck(body, op, attrElement&: *attrEle);
3208 body << ")";
3209 })
3210 .Case(caseFn: [&](PropertyVariable *propEle) {
3211 body << " || (";
3212 genNonDefaultValueCheck(body, op, propElement&: *propEle);
3213 body << ")";
3214 })
3215 .Case(caseFn: [&](OperandVariable *ele) {
3216 if (ele->getVar()->isVariadic()) {
3217 body << " || " << op.getGetterName(name: ele->getVar()->name)
3218 << "().size()";
3219 } else {
3220 body << " || " << op.getGetterName(name: ele->getVar()->name) << "()";
3221 }
3222 })
3223 .Case(caseFn: [&](ResultVariable *ele) {
3224 if (ele->getVar()->isVariadic()) {
3225 body << " || " << op.getGetterName(name: ele->getVar()->name)
3226 << "().size()";
3227 } else {
3228 body << " || " << op.getGetterName(name: ele->getVar()->name) << "()";
3229 }
3230 })
3231 .Case(caseFn: [&](RegionVariable *reg) {
3232 body << " || " << op.getGetterName(name: reg->getVar()->name) << "()";
3233 });
3234 }
3235
3236 body << ") {\n";
3237 if (LiteralElement *separator = oilist->getSeparator()) {
3238 body << " if (oilistClausePrinted) {\n";
3239 genLiteralPrinter(value: separator->getSpelling(), body, shouldEmitSpace,
3240 lastWasPunctuation);
3241 body << " }\n";
3242 body << " oilistClausePrinted = true;\n";
3243 }
3244 genLiteralPrinter(value: lelement->getSpelling(), body, shouldEmitSpace,
3245 lastWasPunctuation);
3246 if (oilist->getUnitVariableParsingElement(pelement) == nullptr) {
3247 for (FormatElement *element : pelement)
3248 genElementPrinter(element, body, op, shouldEmitSpace,
3249 lastWasPunctuation);
3250 }
3251 body << " }\n";
3252 }
3253 if (oilist->getSeparator())
3254 body.unindent() << " }\n";
3255 return;
3256 }
3257
3258 // Emit the attribute dictionary.
3259 if (auto *attrDict = dyn_cast<AttrDictDirective>(Val: element)) {
3260 genAttrDictPrinter(fmt&: *this, op, body, withKeyword: attrDict->isWithKeyword());
3261 lastWasPunctuation = false;
3262 return;
3263 }
3264
3265 // Emit the property dictionary.
3266 if (isa<PropDictDirective>(Val: element)) {
3267 genPropDictPrinter(fmt&: *this, op, body);
3268 lastWasPunctuation = false;
3269 return;
3270 }
3271
3272 // Optionally insert a space before the next element. The AttrDict printer
3273 // already adds a space as necessary.
3274 if (shouldEmitSpace || !lastWasPunctuation)
3275 body << " _odsPrinter << ' ';\n";
3276 lastWasPunctuation = false;
3277 shouldEmitSpace = true;
3278
3279 if (auto *attr = dyn_cast<AttributeVariable>(Val: element)) {
3280 const NamedAttribute *var = attr->getVar();
3281
3282 // If we are formatting as an enum, symbolize the attribute as a string.
3283 if (attr->shouldFormatAsEnum() || canFormatEnumAttr(attr: var))
3284 return genEnumAttrPrinter(var, op, body, /*valueExpression=*/{},
3285 formatAsEnumDirective: attr->shouldFormatAsEnum());
3286
3287 // If we are formatting as a symbol name, handle it as a symbol name.
3288 if (shouldFormatSymbolNameAttr(attr: var)) {
3289 body << " _odsPrinter.printSymbolName(" << op.getGetterName(name: var->name)
3290 << "Attr().getValue());\n";
3291 return;
3292 }
3293
3294 // Elide the attribute type if it is buildable.
3295 if (attr->getTypeBuilder())
3296 body << " _odsPrinter.printAttributeWithoutType("
3297 << op.getGetterName(name: var->name) << "Attr());\n";
3298 else if (attr->shouldBeQualified() ||
3299 var->attr.getStorageType() == "::mlir::Attribute")
3300 body << " _odsPrinter.printAttribute(" << op.getGetterName(name: var->name)
3301 << "Attr());\n";
3302 else
3303 body << "_odsPrinter.printStrippedAttrOrType("
3304 << op.getGetterName(name: var->name) << "Attr());\n";
3305 } else if (auto *property = dyn_cast<PropertyVariable>(Val: element)) {
3306 const NamedProperty *var = property->getVar();
3307 FmtContext fmtContext;
3308 fmtContext.addSubst(placeholder: "_printer", subst: "_odsPrinter");
3309 fmtContext.addSubst(placeholder: "_ctxt", subst: "getContext()");
3310 fmtContext.addSubst(placeholder: "_storage", subst: "getProperties()." + var->name);
3311 body << tgfmt(fmt: var->prop.getPrinterCall(), ctx: &fmtContext) << ";\n";
3312 } else if (auto *operand = dyn_cast<OperandVariable>(Val: element)) {
3313 if (operand->getVar()->isVariadicOfVariadic()) {
3314 body << " ::llvm::interleaveComma("
3315 << op.getGetterName(name: operand->getVar()->name)
3316 << "(), _odsPrinter, [&](const auto &operands) { _odsPrinter << "
3317 "\"(\" << operands << "
3318 "\")\"; });\n";
3319
3320 } else if (operand->getVar()->isOptional()) {
3321 body << " if (::mlir::Value value = "
3322 << op.getGetterName(name: operand->getVar()->name) << "())\n"
3323 << " _odsPrinter << value;\n";
3324 } else {
3325 body << " _odsPrinter << " << op.getGetterName(name: operand->getVar()->name)
3326 << "();\n";
3327 }
3328 } else if (auto *region = dyn_cast<RegionVariable>(Val: element)) {
3329 const NamedRegion *var = region->getVar();
3330 std::string name = op.getGetterName(name: var->name);
3331 if (var->isVariadic()) {
3332 genVariadicRegionPrinter(regionListName: name + "()", body, hasImplicitTermTrait);
3333 } else {
3334 genRegionPrinter(regionName: name + "()", body, hasImplicitTermTrait);
3335 }
3336 } else if (auto *successor = dyn_cast<SuccessorVariable>(Val: element)) {
3337 const NamedSuccessor *var = successor->getVar();
3338 std::string name = op.getGetterName(name: var->name);
3339 if (var->isVariadic())
3340 body << " ::llvm::interleaveComma(" << name << "(), _odsPrinter);\n";
3341 else
3342 body << " _odsPrinter << " << name << "();\n";
3343 } else if (auto *dir = dyn_cast<CustomDirective>(Val: element)) {
3344 genCustomDirectivePrinter(customDir: dir, op, body);
3345 } else if (isa<OperandsDirective>(Val: element)) {
3346 body << " _odsPrinter << getOperation()->getOperands();\n";
3347 } else if (isa<RegionsDirective>(Val: element)) {
3348 genVariadicRegionPrinter(regionListName: "getOperation()->getRegions()", body,
3349 hasImplicitTermTrait);
3350 } else if (isa<SuccessorsDirective>(Val: element)) {
3351 body << " ::llvm::interleaveComma(getOperation()->getSuccessors(), "
3352 "_odsPrinter);\n";
3353 } else if (auto *dir = dyn_cast<TypeDirective>(Val: element)) {
3354 if (auto *operand = dyn_cast<OperandVariable>(Val: dir->getArg())) {
3355 if (operand->getVar()->isVariadicOfVariadic()) {
3356 body << formatv(
3357 Fmt: " ::llvm::interleaveComma({0}().getTypes(), _odsPrinter, "
3358 "[&](::mlir::TypeRange types) {{ _odsPrinter << \"(\" << "
3359 "types << \")\"; });\n",
3360 Vals: op.getGetterName(name: operand->getVar()->name));
3361 return;
3362 }
3363 }
3364 const NamedTypeConstraint *var = nullptr;
3365 {
3366 if (auto *operand = dyn_cast<OperandVariable>(Val: dir->getArg()))
3367 var = operand->getVar();
3368 else if (auto *operand = dyn_cast<ResultVariable>(Val: dir->getArg()))
3369 var = operand->getVar();
3370 }
3371 if (var && !var->isVariadicOfVariadic() && !var->isVariadic() &&
3372 !var->isOptional()) {
3373 StringRef cppType = var->constraint.getCppType();
3374 if (dir->shouldBeQualified()) {
3375 body << " _odsPrinter << " << op.getGetterName(name: var->name)
3376 << "().getType();\n";
3377 return;
3378 }
3379 body << " {\n"
3380 << " auto type = " << op.getGetterName(name: var->name)
3381 << "().getType();\n"
3382 << " if (auto validType = ::llvm::dyn_cast<" << cppType
3383 << ">(type))\n"
3384 << " _odsPrinter.printStrippedAttrOrType(validType);\n"
3385 << " else\n"
3386 << " _odsPrinter << type;\n"
3387 << " }\n";
3388 return;
3389 }
3390 body << " _odsPrinter << ";
3391 genTypeOperandPrinter(arg: dir->getArg(), op, body, /*useArrayRef=*/false)
3392 << ";\n";
3393 } else if (auto *dir = dyn_cast<FunctionalTypeDirective>(Val: element)) {
3394 body << " _odsPrinter.printFunctionalType(";
3395 genTypeOperandPrinter(arg: dir->getInputs(), op, body) << ", ";
3396 genTypeOperandPrinter(arg: dir->getResults(), op, body) << ");\n";
3397 } else {
3398 llvm_unreachable("unknown format element");
3399 }
3400}
3401
3402void OperationFormat::genPrinter(Operator &op, OpClass &opClass) {
3403 // Printing is not performance sensitive. LLVM_ATTRIBUTE_MINSIZE reduces
3404 // binary size and compiler work for printers generated for every operation.
3405 auto *method = opClass.addMethod(
3406 retType: "LLVM_ATTRIBUTE_MINSIZE void", name: "print",
3407 args: MethodParameter("::mlir::OpAsmPrinter &", "_odsPrinter"));
3408 auto &body = method->body();
3409
3410 // Flags for if we should emit a space, and if the last element was
3411 // punctuation.
3412 bool shouldEmitSpace = true, lastWasPunctuation = false;
3413 for (FormatElement *element : elements)
3414 genElementPrinter(element, body, op, shouldEmitSpace, lastWasPunctuation);
3415
3416 genKeyValuePropDictPrinter(fmt&: *this, op, opClass);
3417}
3418
3419//===----------------------------------------------------------------------===//
3420// OpFormatParser
3421//===----------------------------------------------------------------------===//
3422
3423/// Function to find an element within the given range that has the same name as
3424/// 'name'.
3425template <typename RangeT>
3426static auto findArg(RangeT &&range, StringRef name) {
3427 auto it = llvm::find_if(range, [=](auto &arg) { return arg.name == name; });
3428 return it != range.end() ? &*it : nullptr;
3429}
3430
3431namespace {
3432/// This class implements a parser for an instance of an operation assembly
3433/// format.
3434class OpFormatParser : public FormatParser {
3435public:
3436 OpFormatParser(llvm::SourceMgr &mgr, OperationFormat &format, Operator &op)
3437 : FormatParser(mgr, op.getLoc()[0]), fmt(format), op(op),
3438 seenOperandTypes(op.getNumOperands()),
3439 seenResultTypes(op.getNumResults()) {}
3440
3441protected:
3442 /// Verify the format elements.
3443 LogicalResult verify(SMLoc loc, ArrayRef<FormatElement *> elements) override;
3444 /// Verify the arguments to a custom directive.
3445 LogicalResult
3446 verifyCustomDirectiveArguments(SMLoc loc,
3447 ArrayRef<FormatElement *> arguments) override;
3448 /// Verify the elements of an optional group.
3449 LogicalResult verifyOptionalGroupElements(SMLoc loc,
3450 ArrayRef<FormatElement *> elements,
3451 FormatElement *anchor) override;
3452 LogicalResult verifyOptionalGroupElement(SMLoc loc, FormatElement *element,
3453 bool isAnchor);
3454
3455 LogicalResult markQualified(SMLoc loc, FormatElement *element) override;
3456
3457 /// Parse an operation variable.
3458 FailureOr<FormatElement *> parseVariableImpl(SMLoc loc, StringRef name,
3459 Context ctx) override;
3460 /// Parse an operation format directive.
3461 FailureOr<FormatElement *>
3462 parseDirectiveImpl(SMLoc loc, FormatToken::Kind kind, Context ctx) override;
3463
3464private:
3465 /// This struct represents a type resolution instance. It includes a specific
3466 /// type as well as an optional transformer to apply to that type in order to
3467 /// properly resolve the type of a variable.
3468 struct TypeResolutionInstance {
3469 ConstArgument resolver;
3470 std::optional<StringRef> transformer;
3471 };
3472
3473 /// Verify the state of operation attributes within the format.
3474 LogicalResult verifyAttributes(SMLoc loc, ArrayRef<FormatElement *> elements);
3475
3476 /// Verify that attributes elements aren't followed by colon literals.
3477 LogicalResult verifyAttributeColonType(SMLoc loc,
3478 ArrayRef<FormatElement *> elements);
3479 /// Verify that the attribute dictionary directive isn't followed by a region.
3480 LogicalResult verifyAttrDictRegion(SMLoc loc,
3481 ArrayRef<FormatElement *> elements);
3482 /// Verify that an unquoted bit enum isn't followed by an indistinguishable
3483 /// separator literal.
3484 LogicalResult verifyEnumAdjacentLiterals(SMLoc loc,
3485 ArrayRef<FormatElement *> elements);
3486
3487 /// Verify the state of operation operands within the format.
3488 LogicalResult
3489 verifyOperands(SMLoc loc,
3490 StringMap<TypeResolutionInstance> &variableTyResolver);
3491
3492 /// Verify the state of operation regions within the format.
3493 LogicalResult verifyRegions(SMLoc loc);
3494
3495 /// Verify the state of operation results within the format.
3496 LogicalResult
3497 verifyResults(SMLoc loc,
3498 StringMap<TypeResolutionInstance> &variableTyResolver);
3499
3500 /// Verify the state of operation successors within the format.
3501 LogicalResult verifySuccessors(SMLoc loc);
3502
3503 LogicalResult verifyOIListElements(SMLoc loc,
3504 ArrayRef<FormatElement *> elements);
3505
3506 /// Given the values of an `AllTypesMatch` trait, check for inferable type
3507 /// resolution.
3508 void handleAllTypesMatchConstraint(
3509 ArrayRef<StringRef> values,
3510 StringMap<TypeResolutionInstance> &variableTyResolver);
3511 /// Check for inferable type resolution given all operands, and or results,
3512 /// have the same type. If 'includeResults' is true, the results also have the
3513 /// same type as all of the operands.
3514 void handleSameTypesConstraint(
3515 StringMap<TypeResolutionInstance> &variableTyResolver,
3516 bool includeResults);
3517 /// Check for inferable type resolution based on another operand, result, or
3518 /// attribute.
3519 void handleTypesMatchConstraint(
3520 StringMap<TypeResolutionInstance> &variableTyResolver, const Record &def);
3521
3522 /// Check for inferable type resolution based on
3523 /// `ShapedTypeMatchesElementCountAndTypes` constraint.
3524 void handleShapedTypeMatchesElementCountAndTypesConstraint(
3525 StringMap<TypeResolutionInstance> &variableTyResolver, const Record &def);
3526
3527 /// Returns an argument or attribute with the given name that has been seen
3528 /// within the format.
3529 ConstArgument findSeenArg(StringRef name);
3530
3531 /// Parse the various different directives.
3532 FailureOr<FormatElement *> parsePropDictDirective(SMLoc loc, Context context);
3533 FailureOr<FormatElement *> parseAttrDictDirective(SMLoc loc, Context context,
3534 bool withKeyword);
3535 FailureOr<FormatElement *> parseEnumDirective(SMLoc loc, Context context);
3536 FailureOr<FormatElement *> parseFunctionalTypeDirective(SMLoc loc,
3537 Context context);
3538 FailureOr<FormatElement *> parseOIListDirective(SMLoc loc, Context context);
3539 LogicalResult verifyOIListParsingElement(FormatElement *element, SMLoc loc);
3540 FailureOr<FormatElement *> parseOperandsDirective(SMLoc loc, Context context);
3541 FailureOr<FormatElement *> parseRegionsDirective(SMLoc loc, Context context);
3542 FailureOr<FormatElement *> parseResultsDirective(SMLoc loc, Context context);
3543 FailureOr<FormatElement *> parseSuccessorsDirective(SMLoc loc,
3544 Context context);
3545 FailureOr<FormatElement *> parseTypeDirective(SMLoc loc, Context context);
3546 FailureOr<FormatElement *> parseTypeDirectiveOperand(SMLoc loc,
3547 bool isRefChild = false);
3548
3549 //===--------------------------------------------------------------------===//
3550 // Fields
3551 //===--------------------------------------------------------------------===//
3552
3553 OperationFormat &fmt;
3554 Operator &op;
3555
3556 // The following are various bits of format state used for verification
3557 // during parsing.
3558 bool hasAttrDict = false;
3559 bool hasPropDict = false;
3560 bool hasAllRegions = false, hasAllSuccessors = false;
3561 bool canInferResultTypes = false;
3562 llvm::SmallBitVector seenOperandTypes, seenResultTypes;
3563 llvm::SmallSetVector<const NamedAttribute *, 8> seenAttrs;
3564 llvm::DenseSet<const NamedTypeConstraint *> seenOperands;
3565 llvm::DenseSet<const NamedRegion *> seenRegions;
3566 llvm::DenseSet<const NamedSuccessor *> seenSuccessors;
3567 llvm::SmallSetVector<const NamedProperty *, 8> seenProperties;
3568};
3569} // namespace
3570
3571LogicalResult OpFormatParser::verify(SMLoc loc,
3572 ArrayRef<FormatElement *> elements) {
3573 // Check that the attribute dictionary is in the format.
3574 if (!hasAttrDict)
3575 return emitError(loc, msg: "'attr-dict' directive not found in "
3576 "custom assembly format");
3577
3578 // Check for any type traits that we can use for inferring types.
3579 StringMap<TypeResolutionInstance> variableTyResolver;
3580 for (const Trait &trait : op.getTraits()) {
3581 const Record &def = trait.getDef();
3582 if (def.isSubClassOf(Name: "AllTypesMatch")) {
3583 handleAllTypesMatchConstraint(values: def.getValueAsListOfStrings(FieldName: "values"),
3584 variableTyResolver);
3585 } else if (def.getName() == "SameTypeOperands") {
3586 handleSameTypesConstraint(variableTyResolver, /*includeResults=*/false);
3587 } else if (def.getName() == "SameOperandsAndResultType") {
3588 handleSameTypesConstraint(variableTyResolver, /*includeResults=*/true);
3589 } else if (def.isSubClassOf(Name: "TypesMatchWith")) {
3590 handleTypesMatchConstraint(variableTyResolver, def);
3591 } else if (def.isSubClassOf(Name: "ShapedTypeMatchesElementCountAndTypes")) {
3592 handleShapedTypeMatchesElementCountAndTypesConstraint(variableTyResolver,
3593 def);
3594 } else if (!op.allResultTypesKnown()) {
3595 // This doesn't check the name directly to handle
3596 // DeclareOpInterfaceMethods<InferTypeOpInterface>
3597 // and the like.
3598 // TODO: Add hasCppInterface check.
3599 if (auto name = def.getValueAsOptionalString(FieldName: "cppInterfaceName")) {
3600 if (*name == "InferTypeOpInterface" &&
3601 def.getValueAsString(FieldName: "cppNamespace") == "::mlir")
3602 canInferResultTypes = true;
3603 }
3604 }
3605 }
3606
3607 // Verify the state of the various operation components.
3608 if (failed(Result: verifyAttributes(loc, elements)) ||
3609 failed(Result: verifyResults(loc, variableTyResolver)) ||
3610 failed(Result: verifyOperands(loc, variableTyResolver)) ||
3611 failed(Result: verifyRegions(loc)) || failed(Result: verifySuccessors(loc)) ||
3612 failed(Result: verifyEnumAdjacentLiterals(loc, elements)) ||
3613 failed(Result: verifyOIListElements(loc, elements)))
3614 return failure();
3615
3616 if (fmt.useStrictPropertiesInAssemblyFormat && !hasPropDict) {
3617 auto emitMissingError = [&](StringRef kind,
3618 StringRef name) -> LogicalResult {
3619 return emitError(loc,
3620 msg: llvm::Twine("strict properties in assembly format "
3621 "requires prop-dict unless all inherent "
3622 "attributes and properties are bound in "
3623 "the custom assembly format; "
3624 "missing ") +
3625 kind + " '" + name + "'");
3626 };
3627 for (const NamedAttribute &attr : op.getAttributes()) {
3628 if (attr.attr.isDerivedAttr())
3629 continue;
3630 if (fmt.inferredAttributes.contains(key: attr.name))
3631 continue;
3632 if (!seenAttrs.count(key: &attr))
3633 return emitMissingError("attribute", attr.name);
3634 }
3635 for (const NamedProperty &prop : op.getProperties()) {
3636 if (!seenProperties.count(key: &prop))
3637 return emitMissingError("property", prop.name);
3638 }
3639 }
3640
3641 // Collect the set of used attributes in the format.
3642 fmt.usedAttributes = std::move(seenAttrs);
3643 fmt.usedProperties = std::move(seenProperties);
3644
3645 // Set whether prop-dict is used in the format
3646 fmt.hasPropDict = hasPropDict;
3647 return success();
3648}
3649
3650LogicalResult
3651OpFormatParser::verifyAttributes(SMLoc loc,
3652 ArrayRef<FormatElement *> elements) {
3653 // Check that there are no `:` literals after an attribute without a constant
3654 // type. The attribute grammar contains an optional trailing colon type, which
3655 // can lead to unexpected and generally unintended behavior. Given that, it is
3656 // better to just error out here instead.
3657 if (failed(Result: verifyAttributeColonType(loc, elements)))
3658 return failure();
3659 // Check that there are no region variables following an attribute dicitonary.
3660 // Both start with `{` and so the optional attribute dictionary can cause
3661 // format ambiguities.
3662 if (failed(Result: verifyAttrDictRegion(loc, elements)))
3663 return failure();
3664
3665 // Check for VariadicOfVariadic variables. The segment attribute of those
3666 // variables will be infered.
3667 for (const NamedTypeConstraint *var : seenOperands) {
3668 if (var->constraint.isVariadicOfVariadic()) {
3669 fmt.inferredAttributes.insert(
3670 key: var->constraint.getVariadicOfVariadicSegmentSizeAttr());
3671 }
3672 }
3673
3674 // Check that optional attributes are not used directly (i.e. outside of an
3675 // optional group or oilist). Printing an absent optional attribute passes a
3676 // null Attribute to the printer, which leads to crashes in alias
3677 // initialisation. OIList elements require optional attributes by design, so
3678 // attributes nested inside them are not checked here.
3679 for (FormatElement *element : elements) {
3680 if (auto *attrVar = dyn_cast<AttributeVariable>(Val: element)) {
3681 const NamedAttribute *var = attrVar->getVar();
3682 if (var->attr.isOptional()) {
3683 return emitErrorAndNote(
3684 loc,
3685 msg: "optional attribute '" + var->name +
3686 "' cannot be used outside of an optional group",
3687 note: "to conditionally print the attribute, use '($" + var->name +
3688 "^)?'");
3689 }
3690 }
3691 }
3692
3693 return success();
3694}
3695
3696/// Returns whether the single format element is optionally parsed.
3697static bool isOptionallyParsed(FormatElement *el) {
3698 if (auto *attrVar = dyn_cast<AttributeVariable>(Val: el)) {
3699 Attribute attr = attrVar->getVar()->attr;
3700 return attr.isOptional() || attr.hasDefaultValue();
3701 }
3702 if (auto *propVar = dyn_cast<PropertyVariable>(Val: el)) {
3703 const Property &prop = propVar->getVar()->prop;
3704 return prop.hasDefaultValue() && prop.hasOptionalParser();
3705 }
3706 if (auto *operandVar = dyn_cast<OperandVariable>(Val: el)) {
3707 const NamedTypeConstraint *operand = operandVar->getVar();
3708 return operand->isOptional() || operand->isVariadic() ||
3709 operand->isVariadicOfVariadic();
3710 }
3711 if (auto *successorVar = dyn_cast<SuccessorVariable>(Val: el))
3712 return successorVar->getVar()->isVariadic();
3713 if (auto *regionVar = dyn_cast<RegionVariable>(Val: el))
3714 return regionVar->getVar()->isVariadic();
3715 return isa<WhitespaceElement, AttrDictDirective>(Val: el);
3716}
3717
3718/// Scan the given range of elements from the start for an invalid format
3719/// element that satisfies `isInvalid`, skipping any optionally-parsed elements.
3720/// If an optional group is encountered, this function recurses into the 'then'
3721/// and 'else' elements to check if they are invalid. Returns `success` if the
3722/// range is known to be valid or `std::nullopt` if scanning reached the end.
3723///
3724/// Since the guard element of an optional group is required, this function
3725/// accepts an optional element pointer to mark it as required.
3726static std::optional<LogicalResult> checkRangeForElement(
3727 FormatElement *base,
3728 function_ref<bool(FormatElement *, FormatElement *)> isInvalid,
3729 iterator_range<ArrayRef<FormatElement *>::iterator> elementRange,
3730 FormatElement *optionalGuard = nullptr) {
3731 for (FormatElement *element : elementRange) {
3732 // If we encounter an invalid element, return an error.
3733 if (isInvalid(base, element))
3734 return failure();
3735
3736 // Recurse on optional groups.
3737 if (auto *optional = dyn_cast<OptionalElement>(Val: element)) {
3738 if (std::optional<LogicalResult> result = checkRangeForElement(
3739 base, isInvalid, elementRange: optional->getThenElements(),
3740 // The optional group guard is required for the group.
3741 optionalGuard: optional->getThenElements().front()))
3742 if (failed(Result: *result))
3743 return failure();
3744 if (std::optional<LogicalResult> result = checkRangeForElement(
3745 base, isInvalid, elementRange: optional->getElseElements()))
3746 if (failed(Result: *result))
3747 return failure();
3748 // Skip the optional group.
3749 continue;
3750 }
3751
3752 // Skip optionally parsed elements.
3753 if (element != optionalGuard && isOptionallyParsed(el: element))
3754 continue;
3755
3756 // We found a closing element that is valid.
3757 return success();
3758 }
3759 // Return std::nullopt to indicate that we reached the end.
3760 return std::nullopt;
3761}
3762
3763/// For the given elements, check whether any attributes are followed by a colon
3764/// literal, resulting in an ambiguous assembly format. Returns a non-null
3765/// attribute if verification of said attribute reached the end of the range.
3766/// Returns null if all attribute elements are verified.
3767static FailureOr<FormatElement *> verifyAdjacentElements(
3768 function_ref<bool(FormatElement *)> isBase,
3769 function_ref<bool(FormatElement *, FormatElement *)> isInvalid,
3770 ArrayRef<FormatElement *> elements) {
3771 for (auto *it = elements.begin(), *e = elements.end(); it != e; ++it) {
3772 // The current attribute being verified.
3773 FormatElement *base;
3774
3775 if (isBase(*it)) {
3776 base = *it;
3777 } else if (auto *optional = dyn_cast<OptionalElement>(Val: *it)) {
3778 // Recurse on optional groups.
3779 FailureOr<FormatElement *> thenResult = verifyAdjacentElements(
3780 isBase, isInvalid, elements: optional->getThenElements());
3781 if (failed(Result: thenResult))
3782 return failure();
3783 FailureOr<FormatElement *> elseResult = verifyAdjacentElements(
3784 isBase, isInvalid, elements: optional->getElseElements());
3785 if (failed(Result: elseResult))
3786 return failure();
3787 // If either optional group has an unverified attribute, save it.
3788 // Otherwise, move on to the next element.
3789 if (!(base = *thenResult) && !(base = *elseResult))
3790 continue;
3791 } else {
3792 continue;
3793 }
3794
3795 // Verify subsequent elements for potential ambiguities.
3796 if (std::optional<LogicalResult> result =
3797 checkRangeForElement(base, isInvalid, elementRange: {std::next(x: it), e})) {
3798 if (failed(Result: *result))
3799 return failure();
3800 } else {
3801 // Since we reached the end, return the attribute as unverified.
3802 return base;
3803 }
3804 }
3805 // All attribute elements are known to be verified.
3806 return nullptr;
3807}
3808
3809LogicalResult
3810OpFormatParser::verifyAttributeColonType(SMLoc loc,
3811 ArrayRef<FormatElement *> elements) {
3812 auto isBase = [](FormatElement *el) {
3813 auto *attr = dyn_cast<AttributeVariable>(Val: el);
3814 if (!attr)
3815 return false;
3816 // Check only attributes without type builders or that are known to call
3817 // the generic attribute parser.
3818 return !attr->getTypeBuilder() &&
3819 (attr->shouldBeQualified() ||
3820 attr->getVar()->attr.getStorageType() == "::mlir::Attribute");
3821 };
3822 auto isInvalid = [&](FormatElement *base, FormatElement *el) {
3823 auto *literal = dyn_cast<LiteralElement>(Val: el);
3824 if (!literal || literal->getSpelling() != ":")
3825 return false;
3826 // If we encounter `:`, the range is known to be invalid.
3827 (void)emitError(
3828 loc, msg: formatv(Fmt: "format ambiguity caused by `:` literal found after "
3829 "attribute `{0}` which does not have a buildable type",
3830 Vals: cast<AttributeVariable>(Val: base)->getVar()->name));
3831 return true;
3832 };
3833 return verifyAdjacentElements(isBase, isInvalid, elements);
3834}
3835
3836LogicalResult
3837OpFormatParser::verifyAttrDictRegion(SMLoc loc,
3838 ArrayRef<FormatElement *> elements) {
3839 auto isBase = [](FormatElement *el) {
3840 if (auto *attrDict = dyn_cast<AttrDictDirective>(Val: el))
3841 return !attrDict->isWithKeyword();
3842 return false;
3843 };
3844 auto isInvalid = [&](FormatElement *base, FormatElement *el) {
3845 auto *region = dyn_cast<RegionVariable>(Val: el);
3846 if (!region)
3847 return false;
3848 (void)emitErrorAndNote(
3849 loc,
3850 msg: formatv(Fmt: "format ambiguity caused by `attr-dict` directive "
3851 "followed by region `{0}`",
3852 Vals: region->getVar()->name),
3853 note: "try using `attr-dict-with-keyword` instead");
3854 return true;
3855 };
3856 return verifyAdjacentElements(isBase, isInvalid, elements);
3857}
3858
3859LogicalResult OpFormatParser::verifyOperands(
3860 SMLoc loc, StringMap<TypeResolutionInstance> &variableTyResolver) {
3861 // Check that all of the operands are within the format, and their types can
3862 // be inferred.
3863 auto &buildableTypes = fmt.buildableTypes;
3864 for (unsigned i = 0, e = op.getNumOperands(); i != e; ++i) {
3865 NamedTypeConstraint &operand = op.getOperand(index: i);
3866
3867 // Check that the operand itself is in the format.
3868 if (!fmt.allOperands && !seenOperands.count(V: &operand)) {
3869 return emitErrorAndNote(loc,
3870 msg: "operand #" + Twine(i) + ", named '" +
3871 operand.name + "', not found",
3872 note: "suggest adding a '$" + operand.name +
3873 "' directive to the custom assembly format");
3874 }
3875
3876 // Check that the operand type is in the format, or that it can be inferred.
3877 if (fmt.allOperandTypes || seenOperandTypes.test(Idx: i))
3878 continue;
3879
3880 // Check to see if we can infer this type from another variable.
3881 auto varResolverIt = variableTyResolver.find(Key: op.getOperand(index: i).name);
3882 if (varResolverIt != variableTyResolver.end()) {
3883 TypeResolutionInstance &resolver = varResolverIt->second;
3884 fmt.operandTypes[i].setResolver(arg: resolver.resolver, transformer: resolver.transformer);
3885 continue;
3886 }
3887
3888 // Similarly to results, allow a custom builder for resolving the type if
3889 // we aren't using the 'operands' directive.
3890 std::optional<StringRef> builder = operand.constraint.getBuilderCall();
3891 if (!builder || (fmt.allOperands && operand.isVariableLength())) {
3892 return emitErrorAndNote(
3893 loc,
3894 msg: "type of operand #" + Twine(i) + ", named '" + operand.name +
3895 "', is not buildable and a buildable type cannot be inferred",
3896 note: "suggest adding a type constraint to the operation or adding a "
3897 "'type($" +
3898 operand.name + ")' directive to the " + "custom assembly format");
3899 }
3900 auto it = buildableTypes.insert(KV: {*builder, buildableTypes.size()});
3901 fmt.operandTypes[i].setBuilderIdx(it.first->second);
3902 }
3903 return success();
3904}
3905
3906LogicalResult OpFormatParser::verifyRegions(SMLoc loc) {
3907 // Check that all of the regions are within the format.
3908 if (hasAllRegions)
3909 return success();
3910
3911 for (unsigned i = 0, e = op.getNumRegions(); i != e; ++i) {
3912 const NamedRegion &region = op.getRegion(index: i);
3913 if (!seenRegions.count(V: &region)) {
3914 return emitErrorAndNote(loc,
3915 msg: "region #" + Twine(i) + ", named '" +
3916 region.name + "', not found",
3917 note: "suggest adding a '$" + region.name +
3918 "' directive to the custom assembly format");
3919 }
3920 }
3921 return success();
3922}
3923
3924LogicalResult OpFormatParser::verifyResults(
3925 SMLoc loc, StringMap<TypeResolutionInstance> &variableTyResolver) {
3926 // If we format all of the types together, there is nothing to check.
3927 if (fmt.allResultTypes)
3928 return success();
3929
3930 // If no result types are specified and we can infer them, infer all result
3931 // types
3932 if (op.getNumResults() > 0 && seenResultTypes.count() == 0 &&
3933 canInferResultTypes) {
3934 fmt.infersResultTypes = true;
3935 return success();
3936 }
3937
3938 // Check that all of the result types can be inferred.
3939 auto &buildableTypes = fmt.buildableTypes;
3940 for (unsigned i = 0, e = op.getNumResults(); i != e; ++i) {
3941 if (seenResultTypes.test(Idx: i))
3942 continue;
3943
3944 // Check to see if we can infer this type from another variable.
3945 auto varResolverIt = variableTyResolver.find(Key: op.getResultName(index: i));
3946 if (varResolverIt != variableTyResolver.end()) {
3947 TypeResolutionInstance resolver = varResolverIt->second;
3948 fmt.resultTypes[i].setResolver(arg: resolver.resolver, transformer: resolver.transformer);
3949 continue;
3950 }
3951
3952 // If the result is not variable length, allow for the case where the type
3953 // has a builder that we can use.
3954 NamedTypeConstraint &result = op.getResult(index: i);
3955 std::optional<StringRef> builder = result.constraint.getBuilderCall();
3956 if (!builder || result.isVariableLength()) {
3957 return emitErrorAndNote(
3958 loc,
3959 msg: "type of result #" + Twine(i) + ", named '" + result.name +
3960 "', is not buildable and a buildable type cannot be inferred",
3961 note: "suggest adding a type constraint to the operation or adding a "
3962 "'type($" +
3963 result.name + ")' directive to the " + "custom assembly format");
3964 }
3965 // Note in the format that this result uses the custom builder.
3966 auto it = buildableTypes.insert(KV: {*builder, buildableTypes.size()});
3967 fmt.resultTypes[i].setBuilderIdx(it.first->second);
3968 }
3969 return success();
3970}
3971
3972LogicalResult OpFormatParser::verifySuccessors(SMLoc loc) {
3973 // Check that all of the successors are within the format.
3974 if (hasAllSuccessors)
3975 return success();
3976
3977 for (unsigned i = 0, e = op.getNumSuccessors(); i != e; ++i) {
3978 const NamedSuccessor &successor = op.getSuccessor(index: i);
3979 if (!seenSuccessors.count(V: &successor)) {
3980 return emitErrorAndNote(loc,
3981 msg: "successor #" + Twine(i) + ", named '" +
3982 successor.name + "', not found",
3983 note: "suggest adding a '$" + successor.name +
3984 "' directive to the custom assembly format");
3985 }
3986 }
3987 return success();
3988}
3989
3990LogicalResult
3991OpFormatParser::verifyEnumAdjacentLiterals(SMLoc loc,
3992 ArrayRef<FormatElement *> elements) {
3993 for (auto [index, element] : llvm::enumerate(First&: elements)) {
3994 auto *attr = dyn_cast<AttributeVariable>(Val: element);
3995 if (!attr || !attr->shouldFormatAsEnum())
3996 continue;
3997
3998 Attribute baseAttr = attr->getVar()->attr.getBaseAttr();
3999 EnumInfo enumInfo(getEnumInfoRecord(attr: baseAttr));
4000 if (!enumInfo.isNewStyleBitEnum())
4001 continue;
4002
4003 auto remaining = elements.drop_front(N: index + 1);
4004 auto next = llvm::find_if_not(Range&: remaining, P: llvm::IsaPred<WhitespaceElement>);
4005 if (next == remaining.end())
4006 continue;
4007
4008 auto *literal = dyn_cast<LiteralElement>(Val: *next);
4009 if (!literal)
4010 continue;
4011
4012 StringRef separator = enumInfo.getBitEnumSeparator().trim();
4013 if (literal->getSpelling() == separator) {
4014 return emitError(loc, msg: "unquoted bit enum cannot be followed by its '" +
4015 separator + "' separator literal");
4016 }
4017
4018 // With a space separator, the enum parser would take a following
4019 // case literal as part of the enum.
4020 if (enumInfo.getBitEnumSeparatorKind() ==
4021 EnumInfo::BitEnumSeparatorKind::Space &&
4022 llvm::any_of(Range: enumInfo.getAllCases(), P: [&](const EnumCase &enumCase) {
4023 return enumCase.getStr() == literal->getSpelling();
4024 })) {
4025 return emitError(loc, msg: "space-separated bit enum cannot be followed by "
4026 "its '" +
4027 literal->getSpelling() + "' case literal");
4028 }
4029 }
4030 return success();
4031}
4032
4033LogicalResult
4034OpFormatParser::verifyOIListElements(SMLoc loc,
4035 ArrayRef<FormatElement *> elements) {
4036 // Check for ambiguous literals in and around oilist elements.
4037 SmallVector<StringRef> prohibitedLiterals;
4038 for (FormatElement *it : elements) {
4039 if (auto *oilist = dyn_cast<OIListElement>(Val: it)) {
4040 if (LiteralElement *separator = oilist->getSeparator()) {
4041 for (LiteralElement *literal : oilist->getLiteralElements()) {
4042 if (literal->getSpelling() == separator->getSpelling()) {
4043 return emitError(
4044 loc, msg: "format ambiguity because " + separator->getSpelling() +
4045 " is used as both an oilist separator and clause "
4046 "keyword.");
4047 }
4048 }
4049 }
4050 if (!prohibitedLiterals.empty()) {
4051 // We just saw an oilist element in last iteration. Literals should not
4052 // match.
4053 for (LiteralElement *literal : oilist->getLiteralElements()) {
4054 if (find(Range&: prohibitedLiterals, Val: literal->getSpelling()) !=
4055 prohibitedLiterals.end()) {
4056 return emitError(
4057 loc, msg: "format ambiguity because " + literal->getSpelling() +
4058 " is used in two adjacent oilist elements.");
4059 }
4060 }
4061 }
4062 for (LiteralElement *literal : oilist->getLiteralElements())
4063 prohibitedLiterals.push_back(Elt: literal->getSpelling());
4064 if (LiteralElement *separator = oilist->getSeparator())
4065 prohibitedLiterals.push_back(Elt: separator->getSpelling());
4066 } else if (auto *literal = dyn_cast<LiteralElement>(Val: it)) {
4067 if (find(Range&: prohibitedLiterals, Val: literal->getSpelling()) !=
4068 prohibitedLiterals.end()) {
4069 return emitError(
4070 loc,
4071 msg: "format ambiguity because " + literal->getSpelling() +
4072 " is used both in oilist element and the adjacent literal.");
4073 }
4074 prohibitedLiterals.clear();
4075 } else {
4076 prohibitedLiterals.clear();
4077 }
4078 }
4079 return success();
4080}
4081
4082void OpFormatParser::handleAllTypesMatchConstraint(
4083 ArrayRef<StringRef> values,
4084 StringMap<TypeResolutionInstance> &variableTyResolver) {
4085 for (unsigned i = 0, e = values.size(); i != e; ++i) {
4086 // Check to see if this value matches a resolved operand or result type.
4087 ConstArgument arg = findSeenArg(name: values[i]);
4088 if (!arg)
4089 continue;
4090
4091 // Mark this value as the type resolver for the other variables.
4092 for (unsigned j = 0; j != i; ++j)
4093 variableTyResolver[values[j]] = {.resolver: arg, .transformer: std::nullopt};
4094 for (unsigned j = i + 1; j != e; ++j)
4095 variableTyResolver[values[j]] = {.resolver: arg, .transformer: std::nullopt};
4096 }
4097}
4098
4099void OpFormatParser::handleSameTypesConstraint(
4100 StringMap<TypeResolutionInstance> &variableTyResolver,
4101 bool includeResults) {
4102 const NamedTypeConstraint *resolver = nullptr;
4103 int resolvedIt = -1;
4104
4105 // Check to see if there is an operand or result to use for the resolution.
4106 if ((resolvedIt = seenOperandTypes.find_first()) != -1)
4107 resolver = &op.getOperand(index: resolvedIt);
4108 else if (includeResults && (resolvedIt = seenResultTypes.find_first()) != -1)
4109 resolver = &op.getResult(index: resolvedIt);
4110 else
4111 return;
4112
4113 // Set the resolvers for each operand and result.
4114 for (unsigned i = 0, e = op.getNumOperands(); i != e; ++i)
4115 if (!seenOperandTypes.test(Idx: i))
4116 variableTyResolver[op.getOperand(index: i).name] = {.resolver: resolver, .transformer: std::nullopt};
4117 if (includeResults) {
4118 for (unsigned i = 0, e = op.getNumResults(); i != e; ++i)
4119 if (!seenResultTypes.test(Idx: i))
4120 variableTyResolver[op.getResultName(index: i)] = {.resolver: resolver, .transformer: std::nullopt};
4121 }
4122}
4123
4124void OpFormatParser::handleTypesMatchConstraint(
4125 StringMap<TypeResolutionInstance> &variableTyResolver, const Record &def) {
4126 StringRef lhsName = def.getValueAsString(FieldName: "lhs");
4127 StringRef rhsName = def.getValueAsString(FieldName: "rhs");
4128 StringRef transformer = def.getValueAsString(FieldName: "transformer");
4129 if (ConstArgument arg = findSeenArg(name: lhsName))
4130 variableTyResolver[rhsName] = {.resolver: arg, .transformer: transformer};
4131}
4132
4133void OpFormatParser::handleShapedTypeMatchesElementCountAndTypesConstraint(
4134 StringMap<TypeResolutionInstance> &variableTyResolver, const Record &def) {
4135 StringRef shapedArg = def.getValueAsString(FieldName: "shaped");
4136 StringRef elementsArg = def.getValueAsString(FieldName: "elements");
4137
4138 // Check if the 'shaped' argument is seen, then we can infer the 'elements'
4139 // types.
4140 if (ConstArgument arg = findSeenArg(name: shapedArg)) {
4141 variableTyResolver[elementsArg] = {
4142 .resolver: arg, .transformer: "::llvm::SmallVector<::mlir::Type>(::llvm::cast<::mlir::"
4143 "ShapedType>($_self).getNumElements(), "
4144 "::llvm::cast<::mlir::ShapedType>($_self).getElementType())"};
4145 }
4146
4147 // Type inference in the opposite direction is not possible as the actual
4148 // shaped type can't be inferred from the variadic elements.
4149}
4150
4151ConstArgument OpFormatParser::findSeenArg(StringRef name) {
4152 if (const NamedTypeConstraint *arg = findArg(range: op.getOperands(), name))
4153 return seenOperandTypes.test(Idx: arg - op.operand_begin()) ? arg : nullptr;
4154 if (const NamedTypeConstraint *arg = findArg(range: op.getResults(), name))
4155 return seenResultTypes.test(Idx: arg - op.result_begin()) ? arg : nullptr;
4156 if (const NamedAttribute *attr = findArg(range: op.getAttributes(), name))
4157 return seenAttrs.count(key: attr) ? attr : nullptr;
4158 return nullptr;
4159}
4160
4161FailureOr<FormatElement *>
4162OpFormatParser::parseVariableImpl(SMLoc loc, StringRef name, Context ctx) {
4163 // Check that the parsed argument is something actually registered on the op.
4164 // Attributes
4165 if (const NamedAttribute *attr = findArg(range: op.getAttributes(), name)) {
4166 if (ctx == TypeDirectiveContext)
4167 return emitError(
4168 loc, msg: "attributes cannot be used as children to a `type` directive");
4169 if (ctx == RefDirectiveContext) {
4170 if (!seenAttrs.count(key: attr))
4171 return emitError(loc, msg: "attribute '" + name +
4172 "' must be bound before it is referenced");
4173 } else if (!seenAttrs.insert(X: attr)) {
4174 return emitError(loc, msg: "attribute '" + name + "' is already bound");
4175 }
4176
4177 return create<AttributeVariable>(args&: attr);
4178 }
4179
4180 if (const NamedProperty *property = findArg(range: op.getProperties(), name)) {
4181 if (ctx == TypeDirectiveContext)
4182 return emitError(
4183 loc, msg: "properties cannot be used as children to a `type` directive");
4184 if (ctx == RefDirectiveContext) {
4185 if (!seenProperties.count(key: property))
4186 return emitError(loc, msg: "property '" + name +
4187 "' must be bound before it is referenced");
4188 } else {
4189 if (!seenProperties.insert(X: property))
4190 return emitError(loc, msg: "property '" + name + "' is already bound");
4191 }
4192
4193 return create<PropertyVariable>(args&: property);
4194 }
4195
4196 // Operands
4197 if (const NamedTypeConstraint *operand = findArg(range: op.getOperands(), name)) {
4198 if (ctx == TopLevelContext || ctx == CustomDirectiveContext) {
4199 if (fmt.allOperands || !seenOperands.insert(V: operand).second)
4200 return emitError(loc, msg: "operand '" + name + "' is already bound");
4201 } else if (ctx == RefDirectiveContext && !seenOperands.count(V: operand)) {
4202 return emitError(loc, msg: "operand '" + name +
4203 "' must be bound before it is referenced");
4204 }
4205 return create<OperandVariable>(args&: operand);
4206 }
4207 // Regions
4208 if (const NamedRegion *region = findArg(range: op.getRegions(), name)) {
4209 if (ctx == TopLevelContext || ctx == CustomDirectiveContext) {
4210 if (hasAllRegions || !seenRegions.insert(V: region).second)
4211 return emitError(loc, msg: "region '" + name + "' is already bound");
4212 } else if (ctx == RefDirectiveContext) {
4213 if (!seenRegions.count(V: region))
4214 return emitError(loc, msg: "region '" + name +
4215 "' must be bound before it is referenced");
4216 } else {
4217 return emitError(loc, msg: "regions can only be used at the top level "
4218 "or in a ref directive");
4219 }
4220 return create<RegionVariable>(args&: region);
4221 }
4222 // Results.
4223 if (const auto *result = findArg(range: op.getResults(), name)) {
4224 if (ctx != TypeDirectiveContext)
4225 return emitError(loc, msg: "result variables can can only be used as a child "
4226 "to a 'type' directive");
4227 return create<ResultVariable>(args&: result);
4228 }
4229 // Successors.
4230 if (const auto *successor = findArg(range: op.getSuccessors(), name)) {
4231 if (ctx == TopLevelContext || ctx == CustomDirectiveContext) {
4232 if (hasAllSuccessors || !seenSuccessors.insert(V: successor).second)
4233 return emitError(loc, msg: "successor '" + name + "' is already bound");
4234 } else if (ctx == RefDirectiveContext) {
4235 if (!seenSuccessors.count(V: successor))
4236 return emitError(loc, msg: "successor '" + name +
4237 "' must be bound before it is referenced");
4238 } else {
4239 return emitError(loc, msg: "successors can only be used at the top level "
4240 "or in a ref directive");
4241 }
4242
4243 return create<SuccessorVariable>(args&: successor);
4244 }
4245 return emitError(loc, msg: "expected variable to refer to an argument, region, "
4246 "result, or successor");
4247}
4248
4249FailureOr<FormatElement *>
4250OpFormatParser::parseDirectiveImpl(SMLoc loc, FormatToken::Kind kind,
4251 Context ctx) {
4252 switch (kind) {
4253 case FormatToken::kw_prop_dict:
4254 return parsePropDictDirective(loc, context: ctx);
4255 case FormatToken::kw_attr_dict:
4256 return parseAttrDictDirective(loc, context: ctx,
4257 /*withKeyword=*/false);
4258 case FormatToken::kw_attr_dict_w_keyword:
4259 return parseAttrDictDirective(loc, context: ctx,
4260 /*withKeyword=*/true);
4261 case FormatToken::kw_enum:
4262 return parseEnumDirective(loc, context: ctx);
4263 case FormatToken::kw_functional_type:
4264 return parseFunctionalTypeDirective(loc, context: ctx);
4265 case FormatToken::kw_operands:
4266 return parseOperandsDirective(loc, context: ctx);
4267 case FormatToken::kw_regions:
4268 return parseRegionsDirective(loc, context: ctx);
4269 case FormatToken::kw_results:
4270 return parseResultsDirective(loc, context: ctx);
4271 case FormatToken::kw_successors:
4272 return parseSuccessorsDirective(loc, context: ctx);
4273 case FormatToken::kw_type:
4274 return parseTypeDirective(loc, context: ctx);
4275 case FormatToken::kw_oilist:
4276 return parseOIListDirective(loc, context: ctx);
4277
4278 default:
4279 return emitError(loc, msg: "unsupported directive kind");
4280 }
4281}
4282
4283FailureOr<FormatElement *> OpFormatParser::parseEnumDirective(SMLoc loc,
4284 Context context) {
4285 if (context != TopLevelContext)
4286 return emitError(loc, msg: "'enum' directive can only be used at the top level");
4287
4288 FailureOr<FormatElement *> element;
4289 if (failed(Result: parseToken(kind: FormatToken::l_paren,
4290 msg: "expected '(' before argument list")) ||
4291 failed(Result: element = parseElement(ctx: context)) ||
4292 failed(
4293 Result: parseToken(kind: FormatToken::r_paren, msg: "expected ')' after argument list")))
4294 return failure();
4295
4296 auto *attr = dyn_cast<AttributeVariable>(Val: *element);
4297 if (!attr)
4298 return emitError(loc, msg: "'enum' directive expects an enum attribute");
4299
4300 Attribute baseAttr = attr->getVar()->attr.getBaseAttr();
4301 if (!baseAttr.isEnumAttr())
4302 return emitError(loc, msg: "'enum' directive expects an enum attribute");
4303
4304 EnumInfo enumInfo(getEnumInfoRecord(attr: baseAttr));
4305 if (enumInfo.getUnderlyingType().empty() ||
4306 baseAttr.getConstBuilderTemplate().empty()) {
4307 return emitError(
4308 loc, msg: "'enum' directive requires an enum attribute with an underlying "
4309 "type and a constant builder");
4310 }
4311
4312 if (enumInfo.isBitEnum() &&
4313 llvm::none_of(Range: enumInfo.getAllCases(), P: [](const EnumCase &attrCase) {
4314 return attrCase.getValue() == 0;
4315 })) {
4316 return emitError(loc, msg: "'enum' directive requires a bit enum to define a "
4317 "zero-valued case");
4318 }
4319
4320 if (attr->shouldBeQualified())
4321 return emitError(loc,
4322 msg: "'enum' and 'qualified' directives cannot be combined");
4323 attr->setShouldFormatAsEnum();
4324 return attr;
4325}
4326
4327FailureOr<FormatElement *>
4328OpFormatParser::parseAttrDictDirective(SMLoc loc, Context context,
4329 bool withKeyword) {
4330 if (context == TypeDirectiveContext)
4331 return emitError(loc, msg: "'attr-dict' directive can only be used as a "
4332 "top-level directive");
4333
4334 if (context == RefDirectiveContext) {
4335 if (!hasAttrDict)
4336 return emitError(loc, msg: "'ref' of 'attr-dict' is not bound by a prior "
4337 "'attr-dict' directive");
4338
4339 // Otherwise, this is a top-level context.
4340 } else {
4341 if (hasAttrDict)
4342 return emitError(loc, msg: "'attr-dict' directive has already been seen");
4343 hasAttrDict = true;
4344 }
4345
4346 return create<AttrDictDirective>(args&: withKeyword);
4347}
4348
4349FailureOr<FormatElement *>
4350OpFormatParser::parsePropDictDirective(SMLoc loc, Context context) {
4351 if (context == TypeDirectiveContext)
4352 return emitError(loc, msg: "'prop-dict' directive can only be used as a "
4353 "top-level directive");
4354
4355 if (context == RefDirectiveContext)
4356 llvm::report_fatal_error(reason: "'ref' of 'prop-dict' unsupported");
4357 // Otherwise, this is a top-level context.
4358
4359 if (hasPropDict)
4360 return emitError(loc, msg: "'prop-dict' directive has already been seen");
4361 hasPropDict = true;
4362
4363 return create<PropDictDirective>();
4364}
4365
4366LogicalResult OpFormatParser::verifyCustomDirectiveArguments(
4367 SMLoc loc, ArrayRef<FormatElement *> arguments) {
4368 for (FormatElement *argument : arguments) {
4369 if (!isa<AttrDictDirective, PropDictDirective, AttributeVariable,
4370 OperandVariable, PropertyVariable, RefDirective, RegionVariable,
4371 SuccessorVariable, StringElement, TypeDirective>(Val: argument)) {
4372 // TODO: FormatElement should have location info attached.
4373 return emitError(loc, msg: "only variables and types may be used as "
4374 "parameters to a custom directive");
4375 }
4376 if (auto *type = dyn_cast<TypeDirective>(Val: argument)) {
4377 if (!isa<OperandVariable, ResultVariable>(Val: type->getArg())) {
4378 return emitError(loc, msg: "type directives within a custom directive may "
4379 "only refer to variables");
4380 }
4381 }
4382 }
4383 return success();
4384}
4385
4386FailureOr<FormatElement *>
4387OpFormatParser::parseFunctionalTypeDirective(SMLoc loc, Context context) {
4388 if (context != TopLevelContext)
4389 return emitError(
4390 loc, msg: "'functional-type' is only valid as a top-level directive");
4391
4392 // Parse the main operand.
4393 FailureOr<FormatElement *> inputs, results;
4394 if (failed(Result: parseToken(kind: FormatToken::l_paren,
4395 msg: "expected '(' before argument list")) ||
4396 failed(Result: inputs = parseTypeDirectiveOperand(loc)) ||
4397 failed(Result: parseToken(kind: FormatToken::comma,
4398 msg: "expected ',' after inputs argument")) ||
4399 failed(Result: results = parseTypeDirectiveOperand(loc)) ||
4400 failed(
4401 Result: parseToken(kind: FormatToken::r_paren, msg: "expected ')' after argument list")))
4402 return failure();
4403 return create<FunctionalTypeDirective>(args&: *inputs, args&: *results);
4404}
4405
4406FailureOr<FormatElement *>
4407OpFormatParser::parseOperandsDirective(SMLoc loc, Context context) {
4408 if (context == RefDirectiveContext) {
4409 if (!fmt.allOperands)
4410 return emitError(loc, msg: "'ref' of 'operands' is not bound by a prior "
4411 "'operands' directive");
4412
4413 } else if (context == TopLevelContext || context == CustomDirectiveContext) {
4414 if (fmt.allOperands || !seenOperands.empty())
4415 return emitError(loc, msg: "'operands' directive creates overlap in format");
4416 fmt.allOperands = true;
4417 }
4418 return create<OperandsDirective>();
4419}
4420
4421FailureOr<FormatElement *>
4422OpFormatParser::parseRegionsDirective(SMLoc loc, Context context) {
4423 if (context == TypeDirectiveContext)
4424 return emitError(loc, msg: "'regions' is only valid as a top-level directive");
4425 if (context == RefDirectiveContext) {
4426 if (!hasAllRegions)
4427 return emitError(loc, msg: "'ref' of 'regions' is not bound by a prior "
4428 "'regions' directive");
4429
4430 // Otherwise, this is a TopLevel directive.
4431 } else {
4432 if (hasAllRegions || !seenRegions.empty())
4433 return emitError(loc, msg: "'regions' directive creates overlap in format");
4434 hasAllRegions = true;
4435 }
4436 return create<RegionsDirective>();
4437}
4438
4439FailureOr<FormatElement *>
4440OpFormatParser::parseResultsDirective(SMLoc loc, Context context) {
4441 if (context != TypeDirectiveContext)
4442 return emitError(loc, msg: "'results' directive can can only be used as a child "
4443 "to a 'type' directive");
4444 return create<ResultsDirective>();
4445}
4446
4447FailureOr<FormatElement *>
4448OpFormatParser::parseSuccessorsDirective(SMLoc loc, Context context) {
4449 if (context == TypeDirectiveContext)
4450 return emitError(loc,
4451 msg: "'successors' is only valid as a top-level directive");
4452 if (context == RefDirectiveContext) {
4453 if (!hasAllSuccessors)
4454 return emitError(loc, msg: "'ref' of 'successors' is not bound by a prior "
4455 "'successors' directive");
4456
4457 // Otherwise, this is a TopLevel directive.
4458 } else {
4459 if (hasAllSuccessors || !seenSuccessors.empty())
4460 return emitError(loc, msg: "'successors' directive creates overlap in format");
4461 hasAllSuccessors = true;
4462 }
4463 return create<SuccessorsDirective>();
4464}
4465
4466FailureOr<FormatElement *>
4467OpFormatParser::parseOIListDirective(SMLoc loc, Context context) {
4468 LiteralElement *separator = nullptr;
4469 if (peekToken().is(kind: FormatToken::less)) {
4470 consumeToken();
4471 SMLoc separatorLoc = peekToken().getLoc();
4472 FailureOr<FormatElement *> separatorElement = parseLiteral(ctx: context);
4473 if (failed(Result: separatorElement))
4474 return failure();
4475 separator = dyn_cast<LiteralElement>(Val: *separatorElement);
4476 if (!separator)
4477 return emitError(loc: separatorLoc,
4478 msg: "oilist separator must be a non-whitespace literal");
4479 if (failed(Result: parseToken(kind: FormatToken::greater,
4480 msg: "expected '>' after oilist separator")))
4481 return failure();
4482 }
4483 if (failed(Result: parseToken(kind: FormatToken::l_paren,
4484 msg: "expected '(' before oilist argument list")))
4485 return failure();
4486 std::vector<FormatElement *> literalElements;
4487 std::vector<std::vector<FormatElement *>> parsingElements;
4488 do {
4489 FailureOr<FormatElement *> lelement = parseLiteral(ctx: context);
4490 if (failed(Result: lelement))
4491 return failure();
4492 literalElements.push_back(x: *lelement);
4493 parsingElements.emplace_back();
4494 std::vector<FormatElement *> &currParsingElements = parsingElements.back();
4495 while (peekToken().getKind() != FormatToken::pipe &&
4496 peekToken().getKind() != FormatToken::r_paren) {
4497 FailureOr<FormatElement *> pelement = parseElement(ctx: context);
4498 if (failed(Result: pelement) ||
4499 failed(Result: verifyOIListParsingElement(element: *pelement, loc)))
4500 return failure();
4501 currParsingElements.push_back(x: *pelement);
4502 }
4503 if (peekToken().getKind() == FormatToken::pipe) {
4504 consumeToken();
4505 continue;
4506 }
4507 if (peekToken().getKind() == FormatToken::r_paren) {
4508 consumeToken();
4509 break;
4510 }
4511 } while (true);
4512
4513 return create<OIListElement>(args&: separator, args: std::move(literalElements),
4514 args: std::move(parsingElements));
4515}
4516
4517LogicalResult OpFormatParser::verifyOIListParsingElement(FormatElement *element,
4518 SMLoc loc) {
4519 SmallVector<VariableElement *> vars;
4520 collect(element, variables&: vars);
4521 for (VariableElement *elem : vars) {
4522 LogicalResult res =
4523 TypeSwitch<FormatElement *, LogicalResult>(elem)
4524 // Only optional attributes can be within an oilist parsing group.
4525 .Case(caseFn: [&](AttributeVariable *attrEle) {
4526 if (!attrEle->getVar()->attr.isOptional() &&
4527 !attrEle->getVar()->attr.hasDefaultValue())
4528 return emitError(loc, msg: "only optional attributes can be used in "
4529 "an oilist parsing group");
4530 return success();
4531 })
4532 // Only optional properties can be within an oilist parsing group.
4533 .Case(caseFn: [&](PropertyVariable *propEle) {
4534 if (!propEle->getVar()->prop.hasDefaultValue())
4535 return emitError(
4536 loc,
4537 msg: "only default-valued or optional properties can be used in "
4538 "an olist parsing group");
4539 return success();
4540 })
4541 // Only optional-like(i.e. variadic) operands can be within an
4542 // oilist parsing group.
4543 .Case(caseFn: [&](OperandVariable *ele) {
4544 if (!ele->getVar()->isVariableLength())
4545 return emitError(loc, msg: "only variable length operands can be "
4546 "used within an oilist parsing group");
4547 return success();
4548 })
4549 // Only optional-like(i.e. variadic) results can be within an oilist
4550 // parsing group.
4551 .Case(caseFn: [&](ResultVariable *ele) {
4552 if (!ele->getVar()->isVariableLength())
4553 return emitError(loc, msg: "only variable length results can be "
4554 "used within an oilist parsing group");
4555 return success();
4556 })
4557 .Case(caseFn: [&](RegionVariable *) { return success(); })
4558 .Default(defaultFn: [&](FormatElement *) {
4559 return emitError(loc,
4560 msg: "only literals, types, and variables can be "
4561 "used within an oilist group");
4562 });
4563 if (failed(Result: res))
4564 return failure();
4565 }
4566 return success();
4567}
4568
4569FailureOr<FormatElement *> OpFormatParser::parseTypeDirective(SMLoc loc,
4570 Context context) {
4571 if (context == TypeDirectiveContext)
4572 return emitError(loc, msg: "'type' cannot be used as a child of another `type`");
4573
4574 bool isRefChild = context == RefDirectiveContext;
4575 FailureOr<FormatElement *> operand;
4576 if (failed(Result: parseToken(kind: FormatToken::l_paren,
4577 msg: "expected '(' before argument list")) ||
4578 failed(Result: operand = parseTypeDirectiveOperand(loc, isRefChild)) ||
4579 failed(
4580 Result: parseToken(kind: FormatToken::r_paren, msg: "expected ')' after argument list")))
4581 return failure();
4582
4583 return create<TypeDirective>(args&: *operand);
4584}
4585
4586LogicalResult OpFormatParser::markQualified(SMLoc loc, FormatElement *element) {
4587 return TypeSwitch<FormatElement *, LogicalResult>(element)
4588 .Case(caseFn: [&](AttributeVariable *element) {
4589 if (element->shouldFormatAsEnum())
4590 return emitError(
4591 loc, msg: "'enum' and 'qualified' directives cannot be combined");
4592 element->setShouldBeQualified();
4593 return success();
4594 })
4595 .Case<TypeDirective>(caseFn: [](auto *element) {
4596 element->setShouldBeQualified();
4597 return success();
4598 })
4599 .Default(defaultFn: [&](auto *element) {
4600 return this->emitError(
4601 loc,
4602 msg: "'qualified' directive expects an attribute or a `type` directive");
4603 });
4604}
4605
4606FailureOr<FormatElement *>
4607OpFormatParser::parseTypeDirectiveOperand(SMLoc loc, bool isRefChild) {
4608 FailureOr<FormatElement *> result = parseElement(ctx: TypeDirectiveContext);
4609 if (failed(Result: result))
4610 return failure();
4611
4612 FormatElement *element = *result;
4613 if (isa<LiteralElement>(Val: element))
4614 return emitError(
4615 loc, msg: "'type' directive operand expects variable or directive operand");
4616
4617 if (auto *var = dyn_cast<OperandVariable>(Val: element)) {
4618 unsigned opIdx = var->getVar() - op.operand_begin();
4619 if (!isRefChild && (fmt.allOperandTypes || seenOperandTypes.test(Idx: opIdx)))
4620 return emitError(loc, msg: "'type' of '" + var->getVar()->name +
4621 "' is already bound");
4622 if (isRefChild && !(fmt.allOperandTypes || seenOperandTypes.test(Idx: opIdx)))
4623 return emitError(loc, msg: "'ref' of 'type($" + var->getVar()->name +
4624 ")' is not bound by a prior 'type' directive");
4625 seenOperandTypes.set(opIdx);
4626 } else if (auto *var = dyn_cast<ResultVariable>(Val: element)) {
4627 unsigned resIdx = var->getVar() - op.result_begin();
4628 if (!isRefChild && (fmt.allResultTypes || seenResultTypes.test(Idx: resIdx)))
4629 return emitError(loc, msg: "'type' of '" + var->getVar()->name +
4630 "' is already bound");
4631 if (isRefChild && !(fmt.allResultTypes || seenResultTypes.test(Idx: resIdx)))
4632 return emitError(loc, msg: "'ref' of 'type($" + var->getVar()->name +
4633 ")' is not bound by a prior 'type' directive");
4634 seenResultTypes.set(resIdx);
4635 } else if (isa<OperandsDirective>(Val: &*element)) {
4636 if (!isRefChild && (fmt.allOperandTypes || seenOperandTypes.any()))
4637 return emitError(loc, msg: "'operands' 'type' is already bound");
4638 if (isRefChild && !fmt.allOperandTypes)
4639 return emitError(loc, msg: "'ref' of 'type(operands)' is not bound by a prior "
4640 "'type' directive");
4641 fmt.allOperandTypes = true;
4642 } else if (isa<ResultsDirective>(Val: &*element)) {
4643 if (!isRefChild && (fmt.allResultTypes || seenResultTypes.any()))
4644 return emitError(loc, msg: "'results' 'type' is already bound");
4645 if (isRefChild && !fmt.allResultTypes)
4646 return emitError(loc, msg: "'ref' of 'type(results)' is not bound by a prior "
4647 "'type' directive");
4648 fmt.allResultTypes = true;
4649 } else {
4650 return emitError(loc, msg: "invalid argument to 'type' directive");
4651 }
4652 return element;
4653}
4654
4655LogicalResult OpFormatParser::verifyOptionalGroupElements(
4656 SMLoc loc, ArrayRef<FormatElement *> elements, FormatElement *anchor) {
4657 if (failed(Result: verifyEnumAdjacentLiterals(loc, elements)))
4658 return failure();
4659 for (FormatElement *element : elements) {
4660 if (failed(Result: verifyOptionalGroupElement(loc, element, isAnchor: element == anchor)))
4661 return failure();
4662 }
4663 return success();
4664}
4665
4666LogicalResult OpFormatParser::verifyOptionalGroupElement(SMLoc loc,
4667 FormatElement *element,
4668 bool isAnchor) {
4669 return TypeSwitch<FormatElement *, LogicalResult>(element)
4670 // All attributes can be within the optional group, but only optional
4671 // attributes can be the anchor.
4672 .Case(caseFn: [&](AttributeVariable *attrEle) {
4673 Attribute attr = attrEle->getVar()->attr;
4674 if (isAnchor && !(attr.isOptional() || attr.hasDefaultValue()))
4675 return emitError(loc, msg: "only optional or default-valued attributes "
4676 "can be used to anchor an optional group");
4677 return success();
4678 })
4679 // All properties can be within the optional group, but only optional
4680 // properties can be the anchor.
4681 .Case(caseFn: [&](PropertyVariable *propEle) {
4682 Property prop = propEle->getVar()->prop;
4683 if (isAnchor && !(prop.hasDefaultValue() && prop.hasOptionalParser()))
4684 return emitError(loc, msg: "only properties with default values "
4685 "that can be optionally parsed (have the `let "
4686 "optionalParser = ...` field defined) "
4687 "can be used to anchor an optional group");
4688 return success();
4689 })
4690 // Only optional-like(i.e. variadic) operands can be within an optional
4691 // group.
4692 .Case(caseFn: [&](OperandVariable *ele) {
4693 if (!ele->getVar()->isVariableLength())
4694 return emitError(loc, msg: "only variable length operands can be used "
4695 "within an optional group");
4696 return success();
4697 })
4698 // Only optional-like(i.e. variadic) results can be within an optional
4699 // group.
4700 .Case(caseFn: [&](ResultVariable *ele) {
4701 if (!ele->getVar()->isVariableLength())
4702 return emitError(loc, msg: "only variable length results can be used "
4703 "within an optional group");
4704 return success();
4705 })
4706 .Case(caseFn: [&](RegionVariable *) {
4707 // TODO: When ODS has proper support for marking "optional" regions, add
4708 // a check here.
4709 return success();
4710 })
4711 .Case(caseFn: [&](TypeDirective *ele) {
4712 return verifyOptionalGroupElement(loc, element: ele->getArg(),
4713 /*isAnchor=*/false);
4714 })
4715 .Case(caseFn: [&](FunctionalTypeDirective *ele) {
4716 if (failed(Result: verifyOptionalGroupElement(loc, element: ele->getInputs(),
4717 /*isAnchor=*/false)))
4718 return failure();
4719 return verifyOptionalGroupElement(loc, element: ele->getResults(),
4720 /*isAnchor=*/false);
4721 })
4722 .Case(caseFn: [&](CustomDirective *ele) {
4723 if (!isAnchor)
4724 return success();
4725 // Verify each child as being valid in an optional group. They are all
4726 // potential anchors if the custom directive was marked as one.
4727 for (FormatElement *child : ele->getElements()) {
4728 if (isa<RefDirective>(Val: child))
4729 continue;
4730 if (failed(Result: verifyOptionalGroupElement(loc, element: child, /*isAnchor=*/true)))
4731 return failure();
4732 }
4733 return success();
4734 })
4735 // Literals, whitespace, and custom directives may be used, but they can't
4736 // anchor the group.
4737 .Case<LiteralElement, WhitespaceElement, OptionalElement>(
4738 caseFn: [&](FormatElement *) {
4739 if (isAnchor)
4740 return emitError(loc, msg: "only variables and types can be used "
4741 "to anchor an optional group");
4742 return success();
4743 })
4744 .Default(defaultFn: [&](FormatElement *) {
4745 return emitError(loc, msg: "only literals, types, and variables can be "
4746 "used within an optional group");
4747 });
4748}
4749
4750//===----------------------------------------------------------------------===//
4751// Interface
4752//===----------------------------------------------------------------------===//
4753
4754void mlir::tblgen::generateOpFormat(const Operator &constOp, OpClass &opClass) {
4755 // TODO: Operator doesn't expose all necessary functionality via
4756 // the const interface.
4757 Operator &op = const_cast<Operator &>(constOp);
4758 if (!op.hasAssemblyFormat()) {
4759 // We still need to generate the parsed attribute properties setter for
4760 // allowing it to be reused in custom assembly implementations.
4761 OperationFormat format(op);
4762 format.hasPropDict = true;
4763 genParsedAttrPropertiesSetter(fmt&: format, op, opClass);
4764 return;
4765 }
4766
4767 // Parse the format description.
4768 llvm::SourceMgr mgr;
4769 mgr.AddNewSourceBuffer(
4770 F: llvm::MemoryBuffer::getMemBuffer(InputData: op.getAssemblyFormat()), IncludeLoc: SMLoc());
4771 OperationFormat format(op);
4772 OpFormatParser parser(mgr, format, op);
4773 FailureOr<std::vector<FormatElement *>> elements = parser.parse();
4774 if (failed(Result: elements)) {
4775 // Exit the process if format errors are treated as fatal.
4776 if (formatErrorIsFatal) {
4777 // Invoke the interrupt handlers to run the file cleanup handlers.
4778 llvm::sys::RunInterruptHandlers();
4779 std::exit(status: 1);
4780 }
4781 return;
4782 }
4783 format.elements = std::move(*elements);
4784
4785 // Generate the printer and parser based on the parsed format.
4786 format.genParser(op, opClass);
4787 format.genPrinter(op, opClass);
4788}
4789