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 
9 #include "mlir/Dialect/Async/IR/Async.h"
10 
11 #include "mlir/IR/DialectImplementation.h"
12 #include "llvm/ADT/TypeSwitch.h"
13 
14 using namespace mlir;
15 using namespace mlir::async;
16 
17 #include "mlir/Dialect/Async/IR/AsyncOpsDialect.cpp.inc"
18 
19 constexpr StringRef AsyncDialect::kAllowedToBlockAttrName;
20 
21 void AsyncDialect::initialize() {
22   addOperations<
23 #define GET_OP_LIST
24 #include "mlir/Dialect/Async/IR/AsyncOps.cpp.inc"
25       >();
26   addTypes<
27 #define GET_TYPEDEF_LIST
28 #include "mlir/Dialect/Async/IR/AsyncOpsTypes.cpp.inc"
29       >();
30 }
31 
32 //===----------------------------------------------------------------------===//
33 // YieldOp
34 //===----------------------------------------------------------------------===//
35 
36 static LogicalResult verify(YieldOp op) {
37   // Get the underlying value types from async values returned from the
38   // parent `async.execute` operation.
39   auto executeOp = op->getParentOfType<ExecuteOp>();
40   auto types = llvm::map_range(executeOp.results(), [](const OpResult &result) {
41     return result.getType().cast<ValueType>().getValueType();
42   });
43 
44   if (op.getOperandTypes() != types)
45     return op.emitOpError("operand types do not match the types returned from "
46                           "the parent ExecuteOp");
47 
48   return success();
49 }
50 
51 MutableOperandRange
52 YieldOp::getMutableSuccessorOperands(Optional<unsigned> index) {
53   assert(!index.hasValue());
54   return operandsMutable();
55 }
56 
57 //===----------------------------------------------------------------------===//
58 /// ExecuteOp
59 //===----------------------------------------------------------------------===//
60 
61 constexpr char kOperandSegmentSizesAttr[] = "operand_segment_sizes";
62 
63 OperandRange ExecuteOp::getSuccessorEntryOperands(unsigned index) {
64   assert(index == 0 && "invalid region index");
65   return operands();
66 }
67 
68 void ExecuteOp::getSuccessorRegions(Optional<unsigned> index,
69                                     ArrayRef<Attribute>,
70                                     SmallVectorImpl<RegionSuccessor> &regions) {
71   // The `body` region branch back to the parent operation.
72   if (index.hasValue()) {
73     assert(*index == 0 && "invalid region index");
74     regions.push_back(RegionSuccessor(results()));
75     return;
76   }
77 
78   // Otherwise the successor is the body region.
79   regions.push_back(RegionSuccessor(&body(), body().getArguments()));
80 }
81 
82 void ExecuteOp::build(OpBuilder &builder, OperationState &result,
83                       TypeRange resultTypes, ValueRange dependencies,
84                       ValueRange operands, BodyBuilderFn bodyBuilder) {
85 
86   result.addOperands(dependencies);
87   result.addOperands(operands);
88 
89   // Add derived `operand_segment_sizes` attribute based on parsed operands.
90   int32_t numDependencies = dependencies.size();
91   int32_t numOperands = operands.size();
92   auto operandSegmentSizes = DenseIntElementsAttr::get(
93       VectorType::get({2}, builder.getIntegerType(32)),
94       {numDependencies, numOperands});
95   result.addAttribute(kOperandSegmentSizesAttr, operandSegmentSizes);
96 
97   // First result is always a token, and then `resultTypes` wrapped into
98   // `async.value`.
99   result.addTypes({TokenType::get(result.getContext())});
100   for (Type type : resultTypes)
101     result.addTypes(ValueType::get(type));
102 
103   // Add a body region with block arguments as unwrapped async value operands.
104   Region *bodyRegion = result.addRegion();
105   bodyRegion->push_back(new Block);
106   Block &bodyBlock = bodyRegion->front();
107   for (Value operand : operands) {
108     auto valueType = operand.getType().dyn_cast<ValueType>();
109     bodyBlock.addArgument(valueType ? valueType.getValueType()
110                                     : operand.getType(),
111                           operand.getLoc());
112   }
113 
114   // Create the default terminator if the builder is not provided and if the
115   // expected result is empty. Otherwise, leave this to the caller
116   // because we don't know which values to return from the execute op.
117   if (resultTypes.empty() && !bodyBuilder) {
118     OpBuilder::InsertionGuard guard(builder);
119     builder.setInsertionPointToStart(&bodyBlock);
120     builder.create<async::YieldOp>(result.location, ValueRange());
121   } else if (bodyBuilder) {
122     OpBuilder::InsertionGuard guard(builder);
123     builder.setInsertionPointToStart(&bodyBlock);
124     bodyBuilder(builder, result.location, bodyBlock.getArguments());
125   }
126 }
127 
128 static void print(OpAsmPrinter &p, ExecuteOp op) {
129   // [%tokens,...]
130   if (!op.dependencies().empty())
131     p << " [" << op.dependencies() << "]";
132 
133   // (%value as %unwrapped: !async.value<!arg.type>, ...)
134   if (!op.operands().empty()) {
135     p << " (";
136     Block *entry = op.body().empty() ? nullptr : &op.body().front();
137     llvm::interleaveComma(op.operands(), p, [&, n = 0](Value operand) mutable {
138       Value argument = entry ? entry->getArgument(n++) : Value();
139       p << operand << " as " << argument << ": " << operand.getType();
140     });
141     p << ")";
142   }
143 
144   // -> (!async.value<!return.type>, ...)
145   p.printOptionalArrowTypeList(llvm::drop_begin(op.getResultTypes()));
146   p.printOptionalAttrDictWithKeyword(op->getAttrs(),
147                                      {kOperandSegmentSizesAttr});
148   p << ' ';
149   p.printRegion(op.body(), /*printEntryBlockArgs=*/false);
150 }
151 
152 static ParseResult parseExecuteOp(OpAsmParser &parser, OperationState &result) {
153   MLIRContext *ctx = result.getContext();
154 
155   // Sizes of parsed variadic operands, will be updated below after parsing.
156   int32_t numDependencies = 0;
157 
158   auto tokenTy = TokenType::get(ctx);
159 
160   // Parse dependency tokens.
161   if (succeeded(parser.parseOptionalLSquare())) {
162     SmallVector<OpAsmParser::OperandType, 4> tokenArgs;
163     if (parser.parseOperandList(tokenArgs) ||
164         parser.resolveOperands(tokenArgs, tokenTy, result.operands) ||
165         parser.parseRSquare())
166       return failure();
167 
168     numDependencies = tokenArgs.size();
169   }
170 
171   // Parse async value operands (%value as %unwrapped : !async.value<!type>).
172   SmallVector<OpAsmParser::OperandType, 4> valueArgs;
173   SmallVector<OpAsmParser::OperandType, 4> unwrappedArgs;
174   SmallVector<Type, 4> valueTypes;
175   SmallVector<Type, 4> unwrappedTypes;
176 
177   // Parse a single instance of `%value as %unwrapped : !async.value<!type>`.
178   auto parseAsyncValueArg = [&]() -> ParseResult {
179     if (parser.parseOperand(valueArgs.emplace_back()) ||
180         parser.parseKeyword("as") ||
181         parser.parseOperand(unwrappedArgs.emplace_back()) ||
182         parser.parseColonType(valueTypes.emplace_back()))
183       return failure();
184 
185     auto valueTy = valueTypes.back().dyn_cast<ValueType>();
186     unwrappedTypes.emplace_back(valueTy ? valueTy.getValueType() : Type());
187 
188     return success();
189   };
190 
191   auto argsLoc = parser.getCurrentLocation();
192   if (parser.parseCommaSeparatedList(OpAsmParser::Delimiter::OptionalParen,
193                                      parseAsyncValueArg) ||
194       parser.resolveOperands(valueArgs, valueTypes, argsLoc, result.operands))
195     return failure();
196 
197   int32_t numOperands = valueArgs.size();
198 
199   // Add derived `operand_segment_sizes` attribute based on parsed operands.
200   auto operandSegmentSizes = DenseIntElementsAttr::get(
201       VectorType::get({2}, parser.getBuilder().getI32Type()),
202       {numDependencies, numOperands});
203   result.addAttribute(kOperandSegmentSizesAttr, operandSegmentSizes);
204 
205   // Parse the types of results returned from the async execute op.
206   SmallVector<Type, 4> resultTypes;
207   if (parser.parseOptionalArrowTypeList(resultTypes))
208     return failure();
209 
210   // Async execute first result is always a completion token.
211   parser.addTypeToList(tokenTy, result.types);
212   parser.addTypesToList(resultTypes, result.types);
213 
214   // Parse operation attributes.
215   NamedAttrList attrs;
216   if (parser.parseOptionalAttrDictWithKeyword(attrs))
217     return failure();
218   result.addAttributes(attrs);
219 
220   // Parse asynchronous region.
221   Region *body = result.addRegion();
222   if (parser.parseRegion(*body, /*arguments=*/{unwrappedArgs},
223                          /*argTypes=*/{unwrappedTypes},
224                          /*argLocations=*/{},
225                          /*enableNameShadowing=*/false))
226     return failure();
227 
228   return success();
229 }
230 
231 static LogicalResult verify(ExecuteOp op) {
232   // Unwrap async.execute value operands types.
233   auto unwrappedTypes = llvm::map_range(op.operands(), [](Value operand) {
234     return operand.getType().cast<ValueType>().getValueType();
235   });
236 
237   // Verify that unwrapped argument types matches the body region arguments.
238   if (op.body().getArgumentTypes() != unwrappedTypes)
239     return op.emitOpError("async body region argument types do not match the "
240                           "execute operation arguments types");
241 
242   return success();
243 }
244 
245 //===----------------------------------------------------------------------===//
246 /// CreateGroupOp
247 //===----------------------------------------------------------------------===//
248 
249 LogicalResult CreateGroupOp::canonicalize(CreateGroupOp op,
250                                           PatternRewriter &rewriter) {
251   // Find all `await_all` users of the group.
252   llvm::SmallVector<AwaitAllOp> awaitAllUsers;
253 
254   auto isAwaitAll = [&](Operation *op) -> bool {
255     if (AwaitAllOp awaitAll = dyn_cast<AwaitAllOp>(op)) {
256       awaitAllUsers.push_back(awaitAll);
257       return true;
258     }
259     return false;
260   };
261 
262   // Check if all users of the group are `await_all` operations.
263   if (!llvm::all_of(op->getUsers(), isAwaitAll))
264     return failure();
265 
266   // If group is only awaited without adding anything to it, we can safely erase
267   // the create operation and all users.
268   for (AwaitAllOp awaitAll : awaitAllUsers)
269     rewriter.eraseOp(awaitAll);
270   rewriter.eraseOp(op);
271 
272   return success();
273 }
274 
275 //===----------------------------------------------------------------------===//
276 /// AwaitOp
277 //===----------------------------------------------------------------------===//
278 
279 void AwaitOp::build(OpBuilder &builder, OperationState &result, Value operand,
280                     ArrayRef<NamedAttribute> attrs) {
281   result.addOperands({operand});
282   result.attributes.append(attrs.begin(), attrs.end());
283 
284   // Add unwrapped async.value type to the returned values types.
285   if (auto valueType = operand.getType().dyn_cast<ValueType>())
286     result.addTypes(valueType.getValueType());
287 }
288 
289 static ParseResult parseAwaitResultType(OpAsmParser &parser, Type &operandType,
290                                         Type &resultType) {
291   if (parser.parseType(operandType))
292     return failure();
293 
294   // Add unwrapped async.value type to the returned values types.
295   if (auto valueType = operandType.dyn_cast<ValueType>())
296     resultType = valueType.getValueType();
297 
298   return success();
299 }
300 
301 static void printAwaitResultType(OpAsmPrinter &p, Operation *op,
302                                  Type operandType, Type resultType) {
303   p << operandType;
304 }
305 
306 static LogicalResult verify(AwaitOp op) {
307   Type argType = op.operand().getType();
308 
309   // Awaiting on a token does not have any results.
310   if (argType.isa<TokenType>() && !op.getResultTypes().empty())
311     return op.emitOpError("awaiting on a token must have empty result");
312 
313   // Awaiting on a value unwraps the async value type.
314   if (auto value = argType.dyn_cast<ValueType>()) {
315     if (*op.getResultType() != value.getValueType())
316       return op.emitOpError()
317              << "result type " << *op.getResultType()
318              << " does not match async value type " << value.getValueType();
319   }
320 
321   return success();
322 }
323 
324 //===----------------------------------------------------------------------===//
325 // TableGen'd op method definitions
326 //===----------------------------------------------------------------------===//
327 
328 #define GET_OP_CLASSES
329 #include "mlir/Dialect/Async/IR/AsyncOps.cpp.inc"
330 
331 //===----------------------------------------------------------------------===//
332 // TableGen'd type method definitions
333 //===----------------------------------------------------------------------===//
334 
335 #define GET_TYPEDEF_CLASSES
336 #include "mlir/Dialect/Async/IR/AsyncOpsTypes.cpp.inc"
337 
338 void ValueType::print(AsmPrinter &printer) const {
339   printer << "<";
340   printer.printType(getValueType());
341   printer << '>';
342 }
343 
344 Type ValueType::parse(mlir::AsmParser &parser) {
345   Type ty;
346   if (parser.parseLess() || parser.parseType(ty) || parser.parseGreater()) {
347     parser.emitError(parser.getNameLoc(), "failed to parse async value type");
348     return Type();
349   }
350   return ValueType::get(ty);
351 }
352