MLIR 24.0.0git
Async.cpp
Go to the documentation of this file.
1//===- Async.cpp - MLIR Async Operations ----------------------------------===//
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
10
12
13using namespace mlir;
14using namespace mlir::async;
15
16#include "mlir/Dialect/Async/IR/AsyncOpsDialect.cpp.inc"
17
18//===----------------------------------------------------------------------===//
19/// ExecuteOp
20//===----------------------------------------------------------------------===//
21
22constexpr char kOperandSegmentSizesAttr[] = "operandSegmentSizes";
23
24OperandRange ExecuteOp::getEntrySuccessorOperands(RegionSuccessor successor) {
25 assert(successor.getSuccessor() == &getBodyRegion() &&
26 "invalid region index");
27 return getBodyOperands();
28}
29
30bool ExecuteOp::areTypesCompatible(Type lhs, Type rhs) {
31 const auto getValueOrTokenType = [](Type type) {
32 if (auto value = llvm::dyn_cast<ValueType>(type))
33 return value.getValueType();
34 return type;
35 };
36 return getValueOrTokenType(lhs) == getValueOrTokenType(rhs);
37}
38
39void ExecuteOp::getSuccessorRegions(RegionBranchPoint point,
41 // The `body` region branch back to the parent operation.
42 if (!point.isParent() &&
43 point.getTerminatorPredecessorOrNull()->getParentRegion() ==
44 &getBodyRegion()) {
45 regions.push_back(RegionSuccessor(getOperation()));
46 return;
47 }
48
49 // Otherwise the successor is the body region.
50 regions.push_back(RegionSuccessor(&getBodyRegion()));
51}
52
53ValueRange ExecuteOp::getSuccessorInputs(RegionSuccessor successor) {
54 return successor.isOperation() ? ValueRange(getBodyResults())
55 : ValueRange(getBodyRegion().getArguments());
56}
57
58void ExecuteOp::build(OpBuilder &builder, OperationState &result,
59 TypeRange resultTypes, ValueRange dependencies,
60 ValueRange operands, BodyBuilderFn bodyBuilder) {
61 OpBuilder::InsertionGuard guard(builder);
62 result.addOperands(dependencies);
63 result.addOperands(operands);
64
65 // Add derived `operandSegmentSizes` attribute based on parsed operands.
66 int32_t numDependencies = dependencies.size();
67 int32_t numOperands = operands.size();
68 auto operandSegmentSizes =
69 builder.getDenseI32ArrayAttr({numDependencies, numOperands});
70 result.addAttribute(kOperandSegmentSizesAttr, operandSegmentSizes);
71
72 // First result is always a token, and then `resultTypes` wrapped into
73 // `async.value`.
74 result.addTypes({async::TokenType::get(result.getContext())});
75 for (Type type : resultTypes)
76 result.addTypes(ValueType::get(type));
77
78 // Add a body region with block arguments as unwrapped async value operands.
79 Region *bodyRegion = result.addRegion();
80 Block *bodyBlock = builder.createBlock(bodyRegion);
81 for (Value operand : operands) {
82 auto valueType = llvm::dyn_cast<ValueType>(operand.getType());
83 bodyBlock->addArgument(valueType ? valueType.getValueType()
84 : operand.getType(),
85 operand.getLoc());
86 }
87
88 // Create the default terminator if the builder is not provided and if the
89 // expected result is empty. Otherwise, leave this to the caller
90 // because we don't know which values to return from the execute op.
91 if (resultTypes.empty() && !bodyBuilder) {
92 async::YieldOp::create(builder, result.location, ValueRange());
93 } else if (bodyBuilder) {
94 bodyBuilder(builder, result.location, bodyBlock->getArguments());
95 }
96}
97
98void ExecuteOp::print(OpAsmPrinter &p) {
99 // [%tokens,...]
100 if (!getDependencies().empty())
101 p << " [" << getDependencies() << "]";
102
103 // (%value as %unwrapped: !async.value<!arg.type>, ...)
104 if (!getBodyOperands().empty()) {
105 p << " (";
106 Block *entry = getBodyRegion().empty() ? nullptr : &getBodyRegion().front();
107 llvm::interleaveComma(
108 getBodyOperands(), p, [&, n = 0](Value operand) mutable {
109 Value argument = entry ? entry->getArgument(n++) : Value();
110 p << operand << " as " << argument << ": " << operand.getType();
111 });
112 p << ")";
113 }
114
115 // -> (!async.value<!return.type>, ...)
116 p.printOptionalArrowTypeList(llvm::drop_begin(getResultTypes()));
118 (*this)->getDiscardableAttrDictionary().getValue(),
119 {kOperandSegmentSizesAttr});
120 p << ' ';
121 p.printRegion(getBodyRegion(), /*printEntryBlockArgs=*/false);
122}
123
124ParseResult ExecuteOp::parse(OpAsmParser &parser, OperationState &result) {
125 MLIRContext *ctx = result.getContext();
126
127 // Sizes of parsed variadic operands, will be updated below after parsing.
128 int32_t numDependencies = 0;
129
130 auto tokenTy = async::TokenType::get(ctx);
131
132 // Parse dependency tokens.
133 if (succeeded(parser.parseOptionalLSquare())) {
135 if (parser.parseOperandList(tokenArgs) ||
136 parser.resolveOperands(tokenArgs, tokenTy, result.operands) ||
137 parser.parseRSquare())
138 return failure();
139
140 numDependencies = tokenArgs.size();
141 }
142
143 // Parse async value operands (%value as %unwrapped : !async.value<!type>).
146 SmallVector<Type, 4> valueTypes;
147
148 // Parse a single instance of `%value as %unwrapped : !async.value<!type>`.
149 auto parseAsyncValueArg = [&]() -> ParseResult {
150 if (parser.parseOperand(valueArgs.emplace_back()) ||
151 parser.parseKeyword("as") ||
152 parser.parseArgument(unwrappedArgs.emplace_back()) ||
153 parser.parseColonType(valueTypes.emplace_back()))
154 return failure();
155
156 auto valueTy = llvm::dyn_cast<ValueType>(valueTypes.back());
157 unwrappedArgs.back().type = valueTy ? valueTy.getValueType() : Type();
158 return success();
159 };
160
161 auto argsLoc = parser.getCurrentLocation();
163 parseAsyncValueArg) ||
164 parser.resolveOperands(valueArgs, valueTypes, argsLoc, result.operands))
165 return failure();
166
167 int32_t numOperands = valueArgs.size();
168
169 // Add derived `operandSegmentSizes` attribute based on parsed operands.
170 auto operandSegmentSizes =
171 parser.getBuilder().getDenseI32ArrayAttr({numDependencies, numOperands});
172 result.addAttribute(kOperandSegmentSizesAttr, operandSegmentSizes);
173
174 // Parse the types of results returned from the async execute op.
175 SmallVector<Type, 4> resultTypes;
176 NamedAttrList attrs;
177 if (parser.parseOptionalArrowTypeList(resultTypes) ||
178 // Async execute first result is always a completion token.
179 parser.addTypeToList(tokenTy, result.types) ||
180 parser.addTypesToList(resultTypes, result.types) ||
181 // Parse operation attributes.
183 return failure();
184
185 result.addAttributes(attrs);
186
187 // Parse asynchronous region.
188 Region *body = result.addRegion();
189 return parser.parseRegion(*body, /*arguments=*/unwrappedArgs);
190}
191
192LogicalResult ExecuteOp::verifyRegions() {
193 // Unwrap async.execute value operands types.
194 auto unwrappedTypes = llvm::map_range(getBodyOperands(), [](Value operand) {
195 return llvm::cast<ValueType>(operand.getType()).getValueType();
196 });
197
198 // Verify that unwrapped argument types matches the body region arguments.
199 if (getBodyRegion().getArgumentTypes() != unwrappedTypes)
200 return emitOpError("async body region argument types do not match the "
201 "execute operation arguments types");
202
203 return success();
204}
205
206//===----------------------------------------------------------------------===//
207/// CreateGroupOp
208//===----------------------------------------------------------------------===//
209
210LogicalResult CreateGroupOp::canonicalize(CreateGroupOp op,
211 PatternRewriter &rewriter) {
212 // Find all `await_all` users of the group.
213 llvm::SmallVector<AwaitAllOp> awaitAllUsers;
214
215 auto isAwaitAll = [&](Operation *op) -> bool {
216 if (AwaitAllOp awaitAll = dyn_cast<AwaitAllOp>(op)) {
217 awaitAllUsers.push_back(awaitAll);
218 return true;
219 }
220 return false;
221 };
222
223 // Check if all users of the group are `await_all` operations.
224 if (!llvm::all_of(op->getUsers(), isAwaitAll))
225 return failure();
226
227 // If group is only awaited without adding anything to it, we can safely erase
228 // the create operation and all users.
229 for (AwaitAllOp awaitAll : awaitAllUsers)
230 rewriter.eraseOp(awaitAll);
231 rewriter.eraseOp(op);
232
233 return success();
234}
235
236//===----------------------------------------------------------------------===//
237/// AwaitOp
238//===----------------------------------------------------------------------===//
239
240void AwaitOp::build(OpBuilder &builder, OperationState &result, Value operand,
242 result.addOperands({operand});
243 result.attributes.append(attrs.begin(), attrs.end());
244
245 // Add unwrapped async.value type to the returned values types.
246 if (auto valueType = llvm::dyn_cast<ValueType>(operand.getType()))
247 result.addTypes(valueType.getValueType());
248}
249
250static ParseResult parseAwaitResultType(OpAsmParser &parser, Type &operandType,
251 Type &resultType) {
252 if (parser.parseType(operandType))
253 return failure();
254
255 // Add unwrapped async.value type to the returned values types.
256 if (auto valueType = llvm::dyn_cast<ValueType>(operandType))
257 resultType = valueType.getValueType();
258
259 return success();
260}
261
263 Type operandType, Type resultType) {
264 p << operandType;
265}
266
267LogicalResult AwaitOp::verify() {
268 Type argType = getOperand().getType();
269
270 // Awaiting on a token does not have any results.
271 if (llvm::isa<async::TokenType>(argType) && !getResultTypes().empty())
272 return emitOpError("awaiting on a token must have empty result");
273
274 // Awaiting on a value unwraps the async value type.
275 if (auto value = llvm::dyn_cast<ValueType>(argType)) {
276 if (*getResultType() != value.getValueType())
277 return emitOpError() << "result type " << *getResultType()
278 << " does not match async value type "
279 << value.getValueType();
280 }
281
282 return success();
283}
284
285//===----------------------------------------------------------------------===//
286// FuncOp
287//===----------------------------------------------------------------------===//
288
289void FuncOp::build(OpBuilder &builder, OperationState &state, StringRef name,
290 FunctionType type, ArrayRef<NamedAttribute> attrs,
291 ArrayRef<DictionaryAttr> argAttrs) {
292 state.getOrAddProperties<Properties>().sym_name = builder.getStringAttr(name);
293 state.addAttribute(getFunctionTypeAttrName(state.name), TypeAttr::get(type));
294
295 state.attributes.append(attrs.begin(), attrs.end());
296 state.addRegion();
297
298 if (argAttrs.empty())
299 return;
300 assert(type.getNumInputs() == argAttrs.size());
302 builder, state, argAttrs, /*resultAttrs=*/{},
303 getArgAttrsAttrName(state.name), getResAttrsAttrName(state.name));
304}
305
306ParseResult FuncOp::parse(OpAsmParser &parser, OperationState &result) {
307 auto buildFuncType =
308 [](Builder &builder, ArrayRef<Type> argTypes, ArrayRef<Type> results,
310 std::string &) { return builder.getFunctionType(argTypes, results); };
311
313 parser, result, /*allowVariadic=*/false,
314 getFunctionTypeAttrName(result.name), buildFuncType,
315 getArgAttrsAttrName(result.name), getResAttrsAttrName(result.name));
316}
317
318void FuncOp::print(OpAsmPrinter &p) {
320 p, *this, /*isVariadic=*/false, getFunctionTypeAttrName(),
321 getArgAttrsAttrName(), getResAttrsAttrName());
322}
323
324/// Check that the result type of async.func is not void and must be
325/// some async token or async values.
326LogicalResult FuncOp::verify() {
327 auto resultTypes = getResultTypes();
328 if (resultTypes.empty())
329 return emitOpError()
330 << "result is expected to be at least of size 1, but got "
331 << resultTypes.size();
332
333 for (unsigned i = 0, e = resultTypes.size(); i != e; ++i) {
334 auto type = resultTypes[i];
335 if (!llvm::isa<async::TokenType>(type) && !llvm::isa<ValueType>(type))
336 return emitOpError() << "result type must be async value type or async "
337 "token type, but got "
338 << type;
339 // We only allow AsyncToken appear as the first return value
340 if (llvm::isa<async::TokenType>(type) && i != 0) {
341 return emitOpError()
342 << " results' (optional) async token type is expected "
343 "to appear as the 1st return value, but got "
344 << i + 1;
345 }
346 }
347
348 return success();
349}
350
351//===----------------------------------------------------------------------===//
352/// CallOp
353//===----------------------------------------------------------------------===//
354
355LogicalResult CallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
356 // Check that the callee attribute was specified.
357 auto fnAttr = getCalleeAttr();
358 if (!fnAttr)
359 return emitOpError("requires a 'callee' symbol reference attribute");
360 FuncOp fn = symbolTable.lookupNearestSymbolFrom<FuncOp>(*this, fnAttr);
361 if (!fn)
362 return emitOpError() << "'" << fnAttr.getValue()
363 << "' does not reference a valid async function";
364
365 // Verify that the operand and result types match the callee.
367}
368
369FunctionType CallOp::getCalleeType() {
370 return FunctionType::get(getContext(), getOperandTypes(), getResultTypes());
371}
372
373//===----------------------------------------------------------------------===//
374/// ReturnOp
375//===----------------------------------------------------------------------===//
376
377LogicalResult ReturnOp::verify() {
378 auto funcOp = (*this)->getParentOfType<FuncOp>();
379 ArrayRef<Type> resultTypes = funcOp.isStateful()
380 ? funcOp.getResultTypes().drop_front()
381 : funcOp.getResultTypes();
382 // Get the underlying value types from async types returned from the
383 // parent `async.func` operation.
384 auto types = llvm::map_range(resultTypes, [](const Type &result) {
385 return llvm::cast<ValueType>(result).getValueType();
386 });
387
388 if (getOperandTypes() != types)
389 return emitOpError("operand types do not match the types returned from "
390 "the parent FuncOp");
391
392 return success();
393}
394
395//===----------------------------------------------------------------------===//
396// TableGen'd op method definitions
397//===----------------------------------------------------------------------===//
398
399#define GET_OP_CLASSES
400#include "mlir/Dialect/Async/IR/AsyncOps.cpp.inc"
401
402//===----------------------------------------------------------------------===//
403// TableGen'd type method definitions
404//===----------------------------------------------------------------------===//
405
406#define GET_TYPEDEF_CLASSES
407#include "mlir/Dialect/Async/IR/AsyncOpsTypes.cpp.inc"
408
409void ValueType::print(AsmPrinter &printer) const {
410 printer << "<";
411 printer.printType(getValueType());
412 printer << '>';
413}
414
415Type ValueType::parse(mlir::AsmParser &parser) {
416 Type ty;
417 if (parser.parseLess() || parser.parseType(ty) || parser.parseGreater()) {
418 parser.emitError(parser.getNameLoc(), "failed to parse async value type");
419 return Type();
420 }
421 return ValueType::get(ty);
422}
return success()
static ParseResult parseAwaitResultType(OpAsmParser &parser, Type &operandType, Type &resultType)
Definition Async.cpp:250
constexpr char kOperandSegmentSizesAttr[]
ExecuteOp.
Definition Async.cpp:22
static void printAwaitResultType(OpAsmPrinter &p, Operation *op, Type operandType, Type resultType)
Definition Async.cpp:262
b getContext())
static Type getValueType(Attribute attr)
Definition SPIRVOps.cpp:846
This base class exposes generic asm parser hooks, usable across the various derived parsers.
@ OptionalParen
Parens supporting zero or more operands, or nothing.
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 InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
virtual ParseResult parseRSquare()=0
Parse a ] token.
ParseResult addTypeToList(Type type, SmallVectorImpl< Type > &result)
Add the specified type to the end of the specified type list and return success.
virtual ParseResult parseLess()=0
Parse a '<' token.
virtual ParseResult parseOptionalAttrDictWithKeyword(NamedAttrList &result)=0
Parse a named dictionary into 'result' if the attributes keyword is present.
virtual ParseResult parseColonType(Type &result)=0
Parse a colon followed by a type.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
ParseResult addTypesToList(ArrayRef< Type > types, SmallVectorImpl< Type > &result)
Add the specified types to the end of the specified type list and return success.
virtual SMLoc getNameLoc() const =0
Return the location of the original name token.
virtual ParseResult parseGreater()=0
Parse a '>' token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
virtual ParseResult parseOptionalArrowTypeList(SmallVectorImpl< Type > &result)=0
Parse an optional arrow followed by a type list.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
virtual ParseResult parseOptionalLSquare()=0
Parse a [ token if present.
This base class exposes generic asm printer hooks, usable across the various derived printers.
virtual void printType(Type type)
void printOptionalArrowTypeList(TypeRange &&types)
Print an optional arrow followed by a type list.
Block represents an ordered list of Operations.
Definition Block.h:34
bool empty()
Definition Block.h:173
BlockArgument getArgument(unsigned i)
Definition Block.h:154
BlockArgument addArgument(Type type, Location loc)
Add one value to the argument list.
Definition Block.cpp:158
BlockArgListType getArguments()
Definition Block.h:112
This class is a general helper class for creating context-global objects like types,...
Definition Builders.h:51
DenseI32ArrayAttr getDenseI32ArrayAttr(ArrayRef< int32_t > values)
Definition Builders.cpp:171
FunctionType getFunctionType(TypeRange inputs, TypeRange results)
Definition Builders.cpp:84
StringAttr getStringAttr(const Twine &bytes)
Definition Builders.cpp:271
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
NamedAttrList is array of NamedAttributes that tracks whether it is sorted and does some basic work t...
void append(StringRef name, Attribute attr)
Add an attribute with the specified name.
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
virtual ParseResult parseRegion(Region &region, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region.
virtual ParseResult parseArgument(Argument &result, bool allowType=false, bool allowAttrs=false)=0
Parse a single argument with the following syntax:
ParseResult resolveOperands(Operands &&operands, Type type, SmallVectorImpl< Value > &result)
Resolve a list of operands to SSA values, emitting an error on failure, or appending the results to t...
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.
virtual ParseResult parseOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None, bool allowResultNumber=true, int requiredOperandCount=-1)=0
Parse zero or more SSA comma-separated operand references with a specified surrounding delimiter,...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
virtual void printOptionalAttrDictWithKeyword(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary prefixed with 'attribute...
virtual void printRegion(Region &blocks, bool printEntryBlockArgs=true, bool printBlockTerminators=true, bool printEmptyBlock=false)=0
Prints a region.
RAII guard to reset the insertion point of the builder when destroyed.
Definition Builders.h:351
This class helps build Operations.
Definition Builders.h:210
Block * createBlock(Region *parent, Region::iterator insertPt={}, TypeRange argTypes={}, ArrayRef< Location > locs={})
Add new block with 'argTypes' arguments and set the insertion point to the end of it.
Definition Builders.cpp:439
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
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
This class represents a point being branched from in the methods of the RegionBranchOpInterface.
bool isParent() const
Returns true if branching from the parent op.
RegionBranchTerminatorOpInterface getTerminatorPredecessorOrNull() const
Returns the terminator if branching from a region.
This class represents a successor of a region.
Region * getSuccessor() const
Return the given region successor.
bool isOperation() const
Return true if the successor is an operation.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
This class represents a collection of SymbolTables.
virtual Operation * lookupNearestSymbolFrom(Operation *from, StringAttr symbol)
Returns the operation registered with the given symbol name within the closest parent operation of,...
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:40
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
A named class for passing around the variadic flag.
LogicalResult verifyCallOpInterface(CallOpInterface call, TypeRange argumentTypes, TypeRange resultTypes)
Verify that the forwarded operands and results of call are in a 1:1 relationship with the given argum...
void addArgAndResultAttrs(Builder &builder, OperationState &result, ArrayRef< DictionaryAttr > argAttrs, ArrayRef< DictionaryAttr > resultAttrs, StringAttr argAttrsName, StringAttr resAttrsName)
Adds argument and result attributes, provided as argAttrs and resultAttrs arguments,...
void printFunctionOp(OpAsmPrinter &p, FunctionOpInterface op, bool isVariadic, StringRef typeAttrName, StringAttr argAttrsName, StringAttr resAttrsName)
Printer implementation for function-like operations.
ParseResult parseFunctionOp(OpAsmParser &parser, OperationState &result, bool allowVariadic, StringAttr typeAttrName, FuncTypeBuilder funcTypeBuilder, StringAttr argAttrsName, StringAttr resAttrsName)
Parser implementation for function-like operations.
Include the generated interface declarations.
This represents an operation in an abstracted form, suitable for use with the builder APIs.
T & getOrAddProperties()
Get (or create) the properties of the provided type to be set on the operation on creation.
void addAttribute(StringRef name, Attribute attr)
Add an attribute with the specified name.
Region * addRegion()
Create a region that should be attached to the operation.