MLIR 24.0.0git
IRDL.cpp
Go to the documentation of this file.
1//===- IRDL.cpp - IRDL dialect ----------------------------------*- C++ -*-===//
2//
3// This file is licensed 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
11#include "mlir/IR/Builders.h"
13#include "mlir/IR/Diagnostics.h"
18#include "mlir/IR/Operation.h"
19#include "mlir/Support/LLVM.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SetOperations.h"
22#include "llvm/ADT/StringExtras.h"
23#include "llvm/ADT/TypeSwitch.h"
24#include "llvm/Support/Casting.h"
25
26using namespace mlir;
27using namespace mlir::irdl;
28
29//===----------------------------------------------------------------------===//
30// IRDL dialect.
31//===----------------------------------------------------------------------===//
32
33#include "mlir/Dialect/IRDL/IR/IRDL.cpp.inc"
34
35#include "mlir/Dialect/IRDL/IR/IRDLDialect.cpp.inc"
36
37//===----------------------------------------------------------------------===//
38// Parsing/Printing/Verifying
39//===----------------------------------------------------------------------===//
40
41/// Parse a region, and add a single block if the region is empty.
42/// If no region is parsed, create a new region with a single empty block.
43static ParseResult parseSingleBlockRegion(OpAsmParser &p, Region &region) {
44 auto regionParseRes = p.parseOptionalRegion(region);
45 if (regionParseRes.has_value() && failed(regionParseRes.value()))
46 return failure();
47
48 // If the region is empty, add a single empty block.
49 if (region.empty())
50 region.push_back(new Block());
51
52 return success();
53}
54
56 Region &region) {
57 if (!region.getBlocks().front().empty())
58 p.printRegion(region);
59}
60static llvm::LogicalResult isValidName(llvm::StringRef in, mlir::Operation *loc,
61 const Twine &label) {
62 if (in.empty())
63 return loc->emitError("name of ") << label << " is empty";
64
65 char prev = '_'; // treat the initial as _ to eliminate leading underscores
66 for (const auto &elem : in) {
67 if (elem == '_') {
68 if (prev == '_')
69 return loc->emitError("name of ")
70 << label << " should not contain leading or double underscores";
71 } else {
72 if (elem == '.') {
73 if (prev == '.')
74 return loc->emitError("empty namespace not allowed");
75 } else {
76 if (!isalnum(elem))
77 return loc->emitError("name of ")
78 << label
79 << " must contain only lowercase letters, digits and "
80 "underscores";
81
82 if (llvm::isUpper(elem))
83 return loc->emitError("name of ")
84 << label << " should not contain uppercase letters";
85 }
86 }
87
88 prev = elem;
89 }
90
91 return success();
92}
93
94LogicalResult DialectOp::verify() {
95 if (!Dialect::isValidNamespace(getName()))
96 return emitOpError("invalid dialect name");
97 if (failed(isValidName(getSymName(), getOperation(), "dialect")))
98 return failure();
99
100 return success();
101}
102
103LogicalResult OperationOp::verify() {
104 return isValidName(getSymName(), getOperation(), "operation");
105}
106
107LogicalResult TypeOp::verify() {
108 auto symName = getSymName();
109 if (!symName.empty() && symName.front() == '!')
110 symName = symName.substr(1);
111 return isValidName(symName, getOperation(), "type");
112}
113
114LogicalResult AttributeOp::verify() {
115 auto symName = getSymName();
116 if (!symName.empty() && symName.front() == '#')
117 symName = symName.substr(1);
118 return isValidName(symName, getOperation(), "attribute");
119}
120
121LogicalResult OperationOp::verifyRegions() {
122 // Stores pairs of value kinds and the list of names of values of this kind in
123 // the operation.
125
126 auto insertNames = [&](StringRef kind, ArrayAttr names) {
127 llvm::SmallDenseSet<StringRef> nameSet;
128 nameSet.reserve(names.size());
129 for (auto name : names)
130 nameSet.insert(llvm::cast<StringAttr>(name).getValue());
131 valueNames.emplace_back(kind, std::move(nameSet));
132 };
133
134 for (Operation &op : getBody().getOps()) {
136 .Case([&](OperandsOp op) { insertNames("operands", op.getNames()); })
137 .Case([&](ResultsOp op) { insertNames("results", op.getNames()); })
138 .Case([&](RegionsOp op) { insertNames("regions", op.getNames()); });
139 }
140
141 // Verify that no two operand, result or region share the same name.
142 // The absence of duplicates within each value kind is checked by the
143 // associated operation's verifier.
144 for (size_t i : llvm::seq(valueNames.size())) {
145 for (size_t j : llvm::seq(i + 1, valueNames.size())) {
146 auto [lhs, lhsSet] = valueNames[i];
147 auto &[rhs, rhsSet] = valueNames[j];
148 llvm::set_intersect(lhsSet, rhsSet);
149 if (!lhsSet.empty())
150 return emitOpError("contains a value named '")
151 << *lhsSet.begin() << "' for both its " << lhs << " and " << rhs;
152 }
153 }
154
155 return success();
156}
157
158static LogicalResult verifyNames(Operation *op, StringRef kindName,
159 ArrayAttr names, size_t numOperands) {
160 if (numOperands != names.size())
161 return op->emitOpError()
162 << "the number of " << kindName
163 << "s and their names must be "
164 "the same, but got "
165 << numOperands << " and " << names.size() << " respectively";
166
168 for (auto [i, name] : llvm::enumerate(names)) {
169 StringRef nameRef = llvm::cast<StringAttr>(name).getValue();
170
171 if (failed(isValidName(nameRef, op, Twine(kindName) + " #" + Twine(i))))
172 return failure();
173
174 if (nameMap.contains(nameRef))
175 return op->emitOpError() << "name of " << kindName << " #" << i
176 << " is a duplicate of the name of " << kindName
177 << " #" << nameMap[nameRef];
178 nameMap.insert({nameRef, i});
179 }
180
181 return success();
182}
183
184LogicalResult ParametersOp::verify() {
185 return verifyNames(*this, "parameter", getNames(), getNumOperands());
186}
187
188template <typename ValueListOp>
189static LogicalResult verifyOperandsResultsCommon(ValueListOp op,
190 StringRef kindName) {
191 size_t numVariadicities = op.getVariadicity().size();
192 size_t numOperands = op.getNumOperands();
193
194 if (numOperands != numVariadicities)
195 return op.emitOpError()
196 << "the number of " << kindName
197 << "s and their variadicities must be "
198 "the same, but got "
199 << numOperands << " and " << numVariadicities << " respectively";
200
201 return verifyNames(op, kindName, op.getNames(), numOperands);
202}
203
204LogicalResult OperandsOp::verify() {
205 return verifyOperandsResultsCommon(*this, "operand");
206}
207
208LogicalResult ResultsOp::verify() {
209 return verifyOperandsResultsCommon(*this, "result");
210}
211
212LogicalResult AttributesOp::verify() {
213 size_t namesSize = getAttributeValueNames().size();
214 size_t valuesSize = getAttributeValues().size();
215
216 if (namesSize != valuesSize)
217 return emitOpError()
218 << "the number of attribute names and their constraints must be "
219 "the same but got "
220 << namesSize << " and " << valuesSize << " respectively";
221
222 return success();
223}
224
225LogicalResult BaseOp::verify() {
226 std::optional<StringRef> baseName = getBaseName();
227 std::optional<SymbolRefAttr> baseRef = getBaseRef();
228 if (baseName.has_value() == baseRef.has_value())
229 return emitOpError() << "the base type or attribute should be specified by "
230 "either a name or a reference";
231
232 if (baseName &&
233 (baseName->empty() || ((*baseName)[0] != '!' && (*baseName)[0] != '#')))
234 return emitOpError() << "the base type or attribute name should start with "
235 "'!' or '#'";
236
237 return success();
238}
239
240/// Finds whether the provided symbol is an IRDL type or attribute definition.
241/// The source operation must be within a DialectOp.
242static LogicalResult
244 Operation *source, SymbolRefAttr symbol) {
245 Operation *targetOp =
246 irdl::lookupSymbolNearDialect(symbolTable, source, symbol);
247
248 if (!targetOp)
249 return source->emitOpError() << "symbol '" << symbol << "' not found";
250
251 if (!isa<TypeOp, AttributeOp>(targetOp))
252 return source->emitOpError() << "symbol '" << symbol
253 << "' does not refer to a type or attribute "
254 "definition (refers to '"
255 << targetOp->getName() << "')";
256
257 return success();
258}
259
260LogicalResult BaseOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
261 std::optional<SymbolRefAttr> baseRef = getBaseRef();
262 if (!baseRef)
263 return success();
264
265 return checkSymbolIsTypeOrAttribute(symbolTable, *this, *baseRef);
266}
267
268LogicalResult
269ParametricOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
270 std::optional<SymbolRefAttr> baseRef = getBaseType();
271 if (!baseRef)
272 return success();
273
274 return checkSymbolIsTypeOrAttribute(symbolTable, *this, *baseRef);
275}
276
277/// Parse a value with its variadicity first. By default, the variadicity is
278/// single.
279///
280/// value-with-variadicity ::= ("single" | "optional" | "variadic")? ssa-value
281static ParseResult
284 VariadicityAttr &variadicityAttr) {
285 MLIRContext *ctx = p.getBuilder().getContext();
286
287 // Parse the variadicity, if present
288 if (p.parseOptionalKeyword("single").succeeded()) {
289 variadicityAttr = VariadicityAttr::get(ctx, Variadicity::single);
290 } else if (p.parseOptionalKeyword("optional").succeeded()) {
291 variadicityAttr = VariadicityAttr::get(ctx, Variadicity::optional);
292 } else if (p.parseOptionalKeyword("variadic").succeeded()) {
293 variadicityAttr = VariadicityAttr::get(ctx, Variadicity::variadic);
294 } else {
295 variadicityAttr = VariadicityAttr::get(ctx, Variadicity::single);
296 }
297
298 // Parse the value
299 if (p.parseOperand(operand))
300 return failure();
301 return success();
302}
303
304static ParseResult parseNamedValueListImpl(
306 ArrayAttr &valueNamesAttr, VariadicityArrayAttr *variadicityAttr) {
307 Builder &builder = p.getBuilder();
308 MLIRContext *ctx = builder.getContext();
309 SmallVector<Attribute> valueNames;
310 SmallVector<VariadicityAttr> variadicities;
311
312 // Parse a single value with its variadicity
313 auto parseOne = [&] {
314 StringRef name;
316 VariadicityAttr variadicity;
317 if (p.parseKeyword(&name) || p.parseColon())
318 return failure();
319
320 if (variadicityAttr) {
321 if (parseValueWithVariadicity(p, operand, variadicity))
322 return failure();
323 variadicities.push_back(variadicity);
324 } else {
325 if (p.parseOperand(operand))
326 return failure();
327 }
328
329 valueNames.push_back(StringAttr::get(ctx, name));
330 operands.push_back(operand);
331 return success();
332 };
333
335 return failure();
336 valueNamesAttr = ArrayAttr::get(ctx, valueNames);
337 if (variadicityAttr)
338 *variadicityAttr = VariadicityArrayAttr::get(ctx, variadicities);
339 return success();
340}
341
342/// Parse a list of named values.
343///
344/// values ::=
345/// `(` (named-value (`,` named-value)*)? `)`
346/// named-value := bare-id `:` ssa-value
347static ParseResult
350 ArrayAttr &valueNamesAttr) {
351 return parseNamedValueListImpl(p, operands, valueNamesAttr, nullptr);
352}
353
354/// Parse a list of named values with their variadicities first. By default, the
355/// variadicity is single.
356///
357/// values-with-variadicity ::=
358/// `(` (value-with-variadicity (`,` value-with-variadicity)*)? `)`
359/// value-with-variadicity
360/// ::= bare-id `:` ("single" | "optional" | "variadic")? ssa-value
363 ArrayAttr &valueNamesAttr, VariadicityArrayAttr &variadicityAttr) {
364 return parseNamedValueListImpl(p, operands, valueNamesAttr, &variadicityAttr);
365}
366
368 OperandRange operands,
369 ArrayAttr valueNamesAttr,
370 VariadicityArrayAttr variadicityAttr) {
371 p << "(";
372 interleaveComma(llvm::seq<int>(0, operands.size()), p, [&](int i) {
373 p << llvm::cast<StringAttr>(valueNamesAttr[i]).getValue() << ": ";
374 if (variadicityAttr) {
375 Variadicity variadicity = variadicityAttr[i].getValue();
376 if (variadicity != Variadicity::single) {
377 p << stringifyVariadicity(variadicity) << " ";
378 }
379 }
380 p << operands[i];
381 });
382 p << ")";
383}
384
385/// Print a list of named values.
386///
387/// values ::=
388/// `(` (named-value (`,` named-value)*)? `)`
389/// named-value := bare-id `:` ssa-value
391 OperandRange operands,
392 ArrayAttr valueNamesAttr) {
393 printNamedValueListImpl(p, op, operands, valueNamesAttr, nullptr);
394}
395
396/// Print a list of named values with their variadicities first. By default, the
397/// variadicity is single.
398///
399/// values-with-variadicity ::=
400/// `(` (value-with-variadicity (`,` value-with-variadicity)*)? `)`
401/// value-with-variadicity ::=
402/// bare-id `:` ("single" | "optional" | "variadic")? ssa-value
404 OpAsmPrinter &p, Operation *op, OperandRange operands,
405 ArrayAttr valueNamesAttr, VariadicityArrayAttr variadicityAttr) {
406 printNamedValueListImpl(p, op, operands, valueNamesAttr, variadicityAttr);
407}
408
409static ParseResult
412 ArrayAttr &attrNamesAttr) {
413 Builder &builder = p.getBuilder();
414 SmallVector<Attribute> attrNames;
415 if (succeeded(p.parseOptionalLBrace())) {
416 auto parseOperands = [&]() {
417 if (p.parseAttribute(attrNames.emplace_back()) || p.parseEqual() ||
418 p.parseOperand(attrOperands.emplace_back()))
419 return failure();
420 return success();
421 };
422 if (p.parseCommaSeparatedList(parseOperands) || p.parseRBrace())
423 return failure();
424 }
425 attrNamesAttr = builder.getArrayAttr(attrNames);
426 return success();
427}
428
429static void printAttributesOp(OpAsmPrinter &p, AttributesOp op,
430 OperandRange attrArgs, ArrayAttr attrNames) {
431 if (attrNames.empty())
432 return;
433 p << "{";
434 interleaveComma(llvm::seq<int>(0, attrNames.size()), p,
435 [&](int i) { p << attrNames[i] << " = " << attrArgs[i]; });
436 p << '}';
437}
438
439LogicalResult RegionOp::verify() {
440 if (IntegerAttr numberOfBlocks = getNumberOfBlocksAttr())
441 if (int64_t number = numberOfBlocks.getInt(); number <= 0) {
442 return emitOpError("the number of blocks is expected to be >= 1 but got ")
443 << number;
444 }
445 return success();
446}
447
448LogicalResult RegionsOp::verify() {
449 return verifyNames(*this, "region", getNames(), getNumOperands());
450}
451
452#include "mlir/Dialect/IRDL/IR/IRDLInterfaces.cpp.inc"
453
454#define GET_TYPEDEF_CLASSES
455#include "mlir/Dialect/IRDL/IR/IRDLTypesGen.cpp.inc"
456
457#include "mlir/Dialect/IRDL/IR/IRDLEnums.cpp.inc"
458
459#define GET_ATTRDEF_CLASSES
460#include "mlir/Dialect/IRDL/IR/IRDLAttributes.cpp.inc"
461
462#define GET_OP_CLASSES
463#include "mlir/Dialect/IRDL/IR/IRDLOps.cpp.inc"
return success()
static LogicalResult verifyNames(Operation *op, StringRef kindName, ArrayAttr names, size_t numOperands)
Definition IRDL.cpp:158
static ParseResult parseValueWithVariadicity(OpAsmParser &p, OpAsmParser::UnresolvedOperand &operand, VariadicityAttr &variadicityAttr)
Parse a value with its variadicity first.
Definition IRDL.cpp:282
static void printAttributesOp(OpAsmPrinter &p, AttributesOp op, OperandRange attrArgs, ArrayAttr attrNames)
Definition IRDL.cpp:429
static llvm::LogicalResult isValidName(llvm::StringRef in, mlir::Operation *loc, const Twine &label)
Definition IRDL.cpp:60
static LogicalResult checkSymbolIsTypeOrAttribute(SymbolTableCollection &symbolTable, Operation *source, SymbolRefAttr symbol)
Finds whether the provided symbol is an IRDL type or attribute definition.
Definition IRDL.cpp:243
static LogicalResult verifyOperandsResultsCommon(ValueListOp op, StringRef kindName)
Definition IRDL.cpp:189
static ParseResult parseSingleBlockRegion(OpAsmParser &p, Region &region)
Parse a region, and add a single block if the region is empty.
Definition IRDL.cpp:43
static ParseResult parseAttributesOp(OpAsmParser &p, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &attrOperands, ArrayAttr &attrNamesAttr)
Definition IRDL.cpp:410
static void printNamedValueList(OpAsmPrinter &p, Operation *op, OperandRange operands, ArrayAttr valueNamesAttr)
Print a list of named values.
Definition IRDL.cpp:390
static void printNamedValueListWithVariadicity(OpAsmPrinter &p, Operation *op, OperandRange operands, ArrayAttr valueNamesAttr, VariadicityArrayAttr variadicityAttr)
Print a list of named values with their variadicities first.
Definition IRDL.cpp:403
static ParseResult parseNamedValueList(OpAsmParser &p, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &operands, ArrayAttr &valueNamesAttr)
Parse a list of named values.
Definition IRDL.cpp:348
static ParseResult parseNamedValueListImpl(OpAsmParser &p, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &operands, ArrayAttr &valueNamesAttr, VariadicityArrayAttr *variadicityAttr)
Definition IRDL.cpp:304
static void printNamedValueListImpl(OpAsmPrinter &p, Operation *op, OperandRange operands, ArrayAttr valueNamesAttr, VariadicityArrayAttr variadicityAttr)
Definition IRDL.cpp:367
static ParseResult parseNamedValueListWithVariadicity(OpAsmParser &p, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &operands, ArrayAttr &valueNamesAttr, VariadicityArrayAttr &variadicityAttr)
Parse a list of named values with their variadicities first.
Definition IRDL.cpp:361
static void printSingleBlockRegion(OpAsmPrinter &p, Operation *op, Region &region)
Definition IRDL.cpp:55
ArrayAttr()
@ Paren
Parens surrounding zero or more operands.
virtual Builder & getBuilder() const =0
Return a builder which provides useful access to MLIRContext, global objects like types and attribute...
virtual ParseResult parseCommaSeparatedList(Delimiter delimiter, function_ref< ParseResult()> parseElementFn, StringRef contextMessage=StringRef())=0
Parse a list of comma-separated items with an optional delimiter.
virtual ParseResult parseOptionalKeyword(StringRef keyword)=0
Parse the given keyword if present.
virtual ParseResult parseRBrace()=0
Parse a } token.
virtual ParseResult parseEqual()=0
Parse a = token.
virtual ParseResult parseColon()=0
Parse a : token.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
virtual ParseResult parseAttribute(Attribute &result, Type type={})=0
Parse an arbitrary attribute of a given type and return it in result.
virtual ParseResult parseOptionalLBrace()=0
Parse a { token if present.
This class is a general helper class for creating context-global objects like types,...
Definition Builders.h:51
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
Definition Builders.cpp:275
MLIRContext * getContext() const
Definition Builders.h:56
static bool isValidNamespace(StringRef str)
Utility function that returns if the given string is a valid dialect namespace.
Definition Dialect.cpp:95
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
virtual OptionalParseResult parseOptionalRegion(Region &region, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region if present.
virtual ParseResult parseOperand(UnresolvedOperand &result, bool allowResultNumber=true)=0
Parse a single SSA value operand name along with a result number if allowResultNumber is true.
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
virtual void printRegion(Region &blocks, bool printEntryBlockArgs=true, bool printBlockTerminators=true, bool printEmptyBlock=false)=0
Prints a region.
This class implements the operand iterators for the Operation class.
Definition ValueRange.h:44
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
OperationName getName()
The name of an operation is the key identifier for it.
Definition Operation.h:115
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
void push_back(Block *block)
Definition Region.h:61
bool empty()
Definition Region.h:60
BlockListType & getBlocks()
Definition Region.h:45
This class represents a collection of SymbolTables.
Operation * lookupSymbolNearDialect(SymbolTableCollection &symbolTable, Operation *source, SymbolRefAttr symbol)
Looks up a symbol from the symbol table containing the source operation's dialect definition operatio...
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
Include the generated interface declarations.
llvm::TypeSwitch< T, ResultT > TypeSwitch
Definition LLVM.h:147
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123
This is the representation of an operand reference.
Eliminates variable at the specified position using Fourier-Motzkin variable elimination.