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