clang 24.0.0git
CIRGenCoroutine.cpp
Go to the documentation of this file.
1//===----- CGCoroutine.cpp - Emit CIR Code for C++ coroutines -------------===//
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// This contains code dealing with C++ code generation of coroutines.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CIRGenFunction.h"
14#include "mlir/Support/LLVM.h"
15#include "clang/AST/StmtCXX.h"
20
21using namespace clang;
22using namespace clang::CIRGen;
23
25 // What is the current await expression kind and how many
26 // await/yield expressions were encountered so far.
27 // These are used to generate pretty labels for await expressions in LLVM IR.
28 cir::AwaitKind currentAwaitKind = cir::AwaitKind::Init;
29 // Stores the __builtin_coro_id emitted in the function so that we can supply
30 // it as the first argument to other builtins.
31 cir::CoroIdOp coroId = nullptr;
32
33 // Stores the result of __builtin_coro_begin call.
34 mlir::Value coroBegin = nullptr;
35
36 // How many co_return statements are in the coroutine. Used to decide whether
37 // we need to add co_return; equivalent at the end of the user authored body.
38 unsigned coreturnCount = 0;
39
40 // The promise type's 'unhandled_exception' handler, if it defines one.
42
43 // Stores the last emitted coro.free for the deallocate expressions, we use it
44 // to wrap dealloc code with if(auto mem = coro.free) dealloc(mem).
45 cir::CoroFreeOp lastCoroFree = nullptr;
46
47 // A temporary bool alloca that stores whether 'await_resume' threw an
48 // exception. If it did, 'true' is stored in this variable, and the coroutine
49 // body must be skipped. If the promise type does not define an exception
50 // handler, this is null.
52
53 // If coro.id came from the builtin, remember the expression to give better
54 // diagnostic. If CoroIdExpr is nullptr, the coro.id was created by
55 // EmitCoroutineBody.
56 CallExpr const *coroIdExpr = nullptr;
57};
58
59// Defining these here allows to keep CGCoroData private to this file.
62
63namespace {
64// FIXME: both GetParamRef and ParamReferenceReplacerRAII are good template
65// candidates to be shared among LLVM / CIR codegen.
66
67// Hunts for the parameter reference in the parameter copy/move declaration.
68struct GetParamRef : public StmtVisitor<GetParamRef> {
69public:
70 DeclRefExpr *expr = nullptr;
71 GetParamRef() {}
72 void VisitDeclRefExpr(DeclRefExpr *e) {
73 assert(expr == nullptr && "multilple declref in param move");
74 expr = e;
75 }
76 void VisitStmt(Stmt *s) {
77 for (Stmt *c : s->children()) {
78 if (c)
79 Visit(c);
80 }
81 }
82};
83
84// This class replaces references to parameters to their copies by changing
85// the addresses in CGF.LocalDeclMap and restoring back the original values in
86// its destructor.
87struct ParamReferenceReplacerRAII {
88 CIRGenFunction::DeclMapTy savedLocals;
89 CIRGenFunction::DeclMapTy &localDeclMap;
90
91 ParamReferenceReplacerRAII(CIRGenFunction::DeclMapTy &localDeclMap)
92 : localDeclMap(localDeclMap) {}
93
94 void addCopy(const DeclStmt *pm) {
95 // Figure out what param it refers to.
96
97 assert(pm->isSingleDecl());
98 const VarDecl *vd = static_cast<const VarDecl *>(pm->getSingleDecl());
99 const Expr *initExpr = vd->getInit();
100 GetParamRef visitor;
101 visitor.Visit(const_cast<Expr *>(initExpr));
102 assert(visitor.expr);
103 DeclRefExpr *dreOrig = visitor.expr;
104 auto *pd = dreOrig->getDecl();
105
106 auto it = localDeclMap.find(pd);
107 assert(it != localDeclMap.end() && "parameter is not found");
108 savedLocals.insert({pd, it->second});
109
110 auto copyIt = localDeclMap.find(vd);
111 assert(copyIt != localDeclMap.end() && "parameter copy is not found");
112 it->second = copyIt->getSecond();
113 }
114
115 ~ParamReferenceReplacerRAII() {
116 for (auto &&savedLocal : savedLocals) {
117 localDeclMap.insert({savedLocal.first, savedLocal.second});
118 }
119 }
120};
121} // namespace
122
124 if (curCoro.data && curCoro.data->coroBegin) {
125 return RValue::get(curCoro.data->coroBegin);
126 }
127 cgm.errorNYI("NYI");
128 return RValue();
129}
130
133 cir::CoroIdOp coroId,
134 CallExpr const *coroIdExpr = nullptr) {
135
136 if (curCoro.data) {
137 if (curCoro.data->coroIdExpr)
138 cgf.cgm.error(coroIdExpr->getBeginLoc(),
139 "only one __builtin_coro_id can be used in a function");
140 else if (coroIdExpr)
141 cgf.cgm.error(coroIdExpr->getBeginLoc(),
142 "__builtin_coro_id shall not be used in a C++ coroutine");
143 else
144 llvm_unreachable("EmitCoroutineBodyStatement called twice?");
145
146 return;
147 }
148
149 curCoro.data = std::make_unique<CGCoroData>();
150 curCoro.data->coroId = coroId;
151 curCoro.data->coroIdExpr = coroIdExpr;
152}
153
154static mlir::LogicalResult
156 Stmt *body,
157 const CIRGenFunction::LexicalScope *currLexScope) {
158 {
159 // Destroy the body's local variables, and the temporaries they extend, when
160 // the body ends, before the fall-through handler, the implicit
161 // `co_return;`, calls return_void(). The body stays in the current lexical
162 // scope so that a co_return at its top level is recorded in currLexScope.
164 if (cgf.emitStmt(body, /*useCurrentScope=*/true).failed())
165 return mlir::failure();
166 }
167
168 // Note that classic codegen checks CanFallthrough by looking into the
169 // availability of the insert block which is kinda brittle and unintuitive,
170 // seems to be related with how landing pads are handled.
171 //
172 // CIRGen handles this by checking pre-existing co_returns in the current
173 // scope instead.
174
175 // From LLVM IR Gen: const bool CanFallthrough = Builder.GetInsertBlock();
176 const bool canFallthrough = !currLexScope->hasCoreturn();
177 if (canFallthrough)
178 if (Stmt *onFallthrough = s.getFallthroughHandler())
179 if (cgf.emitStmt(onFallthrough, /*useCurrentScope=*/true).failed())
180 return mlir::failure();
181
182 return mlir::success();
183}
184
186 mlir::Location loc = getLoc(e->getBeginLoc());
187
189 for (const Expr *arg : e->arguments())
190 args.push_back(emitScalarExpr(arg));
191
192 auto coroId = cir::CoroIdOp::create(cgm.getBuilder(), loc, args);
193 createCoroData(*this, curCoro, coroId, e);
194 return coroId;
195}
196
198 mlir::Location loc = getLoc(e->getBeginLoc());
199 if (!curCoro.data || !curCoro.data->coroId) {
200 cgm.error(e->getBeginLoc(), "this builtin expect that __builtin_coro_id has"
201 " been used earlier in this function");
202 return {};
203 }
204
205 return cir::CoroAllocOp::create(
206 cgm.getBuilder(), loc,
207 mlir::ValueRange{curCoro.data->coroId.getResult()});
208}
209
211
212 mlir::Location loc = getLoc(e->getBeginLoc());
213 if (!curCoro.data || !curCoro.data->coroId) {
214 cgm.error(e->getBeginLoc(), "this builtin expect that __builtin_coro_id has"
215 " been used earlier in this function");
216 return {};
217 }
219 args.push_back(curCoro.data->coroId.getResult());
220 for (const Expr *arg : e->arguments())
221 args.push_back(emitScalarExpr(arg));
222
223 auto coroBegin = cir::CoroBeginOp::create(cgm.getBuilder(), loc, args);
224 curCoro.data->coroBegin = coroBegin;
225 return coroBegin;
226}
227
229
230 mlir::Location loc = getLoc(e->getBeginLoc());
231 CIRGenBuilderTy &builder = cgm.getBuilder();
233 for (const Expr *arg : e->arguments())
234 args.push_back(emitScalarExpr(arg));
235 args.push_back(cir::TokenNoneOp::create(builder, loc));
236 return cir::CoroEndOp::create(builder, loc, {cgm.voidTy}, args);
237}
238
240 mlir::Location loc = getLoc(e->getBeginLoc());
241
242 if (!curCoro.data || !curCoro.data->coroId) {
243 cgm.error(e->getBeginLoc(), "this builtin expect that __builtin_coro_id has"
244 " been used earlier in this function");
245 return {};
246 }
247
248 auto coroFree =
249 cir::CoroFreeOp::create(cgm.getBuilder(), loc,
250 mlir::ValueRange{curCoro.data->coroId.getResult(),
251 curCoro.data->coroBegin});
252
253 curCoro.data->lastCoroFree = coroFree;
254 return coroFree;
255}
256
258 mlir::Location loc = getLoc(e->getBeginLoc());
259 return cir::CoroSizeOp::create(cgm.getBuilder(), loc,
260 convertType(e->getType()));
261}
262
264 mlir::Location loc = getLoc(e->getBeginLoc());
265 return cir::CoroAlignOp::create(cgm.getBuilder(), loc,
266 convertType(e->getType()));
267}
268
269cir::CoroPromiseOp
271 mlir::Location loc = getLoc(e->getBeginLoc());
272
274 for (const Expr *arg : e->arguments())
275 args.push_back(emitScalarExpr(arg));
276
277 auto coroPromise = cir::CoroPromiseOp::create(cgm.getBuilder(), loc, args);
278 return coroPromise;
279}
280
282 mlir::Location loc = getLoc(e->getBeginLoc());
283 return cir::CoroDoneOp::create(cgm.getBuilder(), loc,
284 emitScalarExpr(e->getArg(0)));
285}
286
288 mlir::Location loc = getLoc(e->getBeginLoc());
289 return cir::CoroResumeOp::create(cgm.getBuilder(), loc,
290 emitScalarExpr(e->getArg(0)));
291}
292
293cir::CoroDestroyOp
295 mlir::Location loc = getLoc(e->getBeginLoc());
296 return cir::CoroDestroyOp::create(cgm.getBuilder(), loc,
297 emitScalarExpr(e->getArg(0)));
298}
299
301 mlir::Location loc = getLoc(e->getBeginLoc());
302 return cir::CoroNoopOp::create(cgm.getBuilder(), loc);
303}
304
305cir::CoroSuspendOp
307 mlir::Location loc = getLoc(e->getBeginLoc());
309 args.push_back(cir::TokenNoneOp::create(builder, loc));
310 args.push_back(emitScalarExpr(e->getArg(0)));
311
312 return cir::CoroSuspendOp::create(cgm.getBuilder(), loc, args);
313}
314
315static mlir::LogicalResult
317
318 CXXCatchStmt catchStmt(s.getBeginLoc(), /*exDecl=*/nullptr,
319 cgf.curCoro.data->exceptionHandler);
320 auto *tryStmt = CXXTryStmt::Create(cgf.getContext(), s.getBeginLoc(),
321 s.getBody(), &catchStmt);
322 struct handlerEmitter final : CIRGenFunction::cxxTryBodyEmitter {
323 const CoroutineBodyStmt &s;
324
325 handlerEmitter(const CoroutineBodyStmt &s) : s(s) /*, scope(scope)*/ {}
326 mlir::LogicalResult operator()(CIRGenFunction &cgf) override {
327 return emitBodyAndFallthrough(cgf, s, s.getBody(), cgf.curLexScope);
328 }
329 ~handlerEmitter() override = default;
330 } emitter{s};
331
332 mlir::LogicalResult res = cgf.emitCXXTryStmt(*tryStmt, emitter);
333
334 return res;
335}
336
337mlir::LogicalResult
339 mlir::Location openCurlyLoc = getLoc(s.getBeginLoc());
340 cir::ConstantOp nullPtrCst = builder.getNullPtr(voidPtrTy, openCurlyLoc);
341
342 auto fn = mlir::cast<cir::FuncOp>(curFn);
343 fn.setCoroutine(true);
344 const TargetInfo &ti = cgm.getASTContext().getTargetInfo();
345 unsigned newAlign = ti.getNewAlign() / ti.getCharWidth();
346
347 cir::CoroIdOp coroId = cir::CoroIdOp::create(
348 cgm.getBuilder(), openCurlyLoc,
349 mlir::ValueRange{builder.getUInt32(newAlign, openCurlyLoc), nullPtrCst,
350 nullPtrCst, nullPtrCst});
351 createCoroData(*this, curCoro, coroId);
352
353 // Backend is allowed to elide memory allocations, to help it, emit
354 // auto mem = coro.alloc() ? 0 : ... allocation code ...;
355 cir::CoroAllocOp coroAlloc = cir::CoroAllocOp::create(
356 cgm.getBuilder(), openCurlyLoc,
357 mlir::ValueRange{curCoro.data->coroId.getResult()});
358
359 // Initialize address of coroutine frame to null
360 CanQualType astVoidPtrTy = cgm.getASTContext().VoidPtrTy;
361 mlir::Type allocaTy = convertTypeForMem(astVoidPtrTy);
362 Address coroFrame =
363 createTempAlloca(allocaTy, getContext().getTypeAlignInChars(astVoidPtrTy),
364 openCurlyLoc, "__coro_frame_addr",
365 /*ArraySize=*/nullptr);
366
367 mlir::Value storeAddr = coroFrame.getPointer();
368 builder.CIRBaseBuilderTy::createStore(openCurlyLoc, nullPtrCst, storeAddr);
369 mlir::LogicalResult res = mlir::success();
370 cir::IfOp::create(
371 builder, openCurlyLoc, coroAlloc.getResult(),
372 /*withElseRegion=*/false,
373 /*thenBuilder=*/[&](mlir::OpBuilder &b, mlir::Location loc) {
374 mlir::Value allocatedPtr = emitScalarExpr(s.getAllocate());
375 builder.CIRBaseBuilderTy::createStore(loc, allocatedPtr, storeAddr);
376 // Handle allocation failure if 'ReturnStmtOnAllocFailure' was provided.
377 if (Stmt *retOnAllocFailure = s.getReturnStmtOnAllocFailure()) {
378 mlir::Value isPtrNull = builder.createPtrIsNull(allocatedPtr);
379 assert(!cir::MissingFeatures::emitCondLikelihoodViaExpectIntrinsic());
380 cir::IfOp::create(builder, loc, isPtrNull, /*withElseRegion=*/false,
381 [&](mlir::OpBuilder &b, mlir::Location loc) {
382 res = emitStmt(retOnAllocFailure,
383 /*useCurrentScope=*/true);
384 cir::UnreachableOp::create(builder, loc);
385 });
386 }
387 cir::YieldOp::create(builder, loc);
388 });
389
390 if (res.failed())
391 return res;
392
393 curCoro.data->coroBegin = cir::CoroBeginOp::create(
394 cgm.getBuilder(), openCurlyLoc,
395 mlir::ValueRange{
396 curCoro.data->coroId.getResult(),
397 cir::LoadOp::create(builder, openCurlyLoc, allocaTy, storeAddr)});
398
399 {
401 ParamReferenceReplacerRAII paramReplacer(localDeclMap);
402
403 // Create mapping between parameters and copy-params for coroutine
404 // function.
405 llvm::ArrayRef<const Stmt *> paramMoves = s.getParamMoves();
406 assert((paramMoves.size() == 0 || (paramMoves.size() == fnArgs.size())) &&
407 "ParamMoves and FnArgs should be the same size for coroutine "
408 "function");
409 // For zipping the arg map into debug info.
411
412 // Create parameter copies. We do it before creating a promise, since an
413 // evolution of coroutine TS may allow promise constructor to observe
414 // parameter copies.
416 for (auto *pm : paramMoves) {
417 if (emitStmt(pm, /*useCurrentScope=*/true).failed())
418 return mlir::failure();
419 paramReplacer.addCopy(cast<DeclStmt>(pm));
420 }
421
422 // Builds `initial_suspend`.
423 auto initialSuspendBuilder = [&]() -> mlir::LogicalResult {
424 if (emitStmt(s.getPromiseDeclStmt(), /*useCurrentScope=*/true).failed())
425 return mlir::failure();
426 // returnValue should be valid as long as the coroutine's return type
427 // is not void. The assertion could help us to reduce the check later.
428 assert(returnValue.isValid() == (bool)s.getReturnStmt());
429 // Now we have the promise, initialize the GRO.
430 // We need to emit `get_return_object` first. According to:
431 // [dcl.fct.def.coroutine]p7
432 // The call to get_return_­object is sequenced before the call to
433 // initial_suspend and is invoked at most once.
434 //
435 // So we couldn't emit return value when we emit return statment,
436 // otherwise the call to get_return_object wouldn't be in front
437 // of initial_suspend.
438 if (returnValue.isValid())
439 emitAnyExprToMem(s.getReturnValue(), returnValue,
440 s.getReturnValue()->getType().getQualifiers(),
441 /*isInit*/ true);
442
443 curCoro.data->currentAwaitKind = cir::AwaitKind::Init;
444 curCoro.data->exceptionHandler = s.getExceptionHandler();
445
446 if (emitStmt(s.getInitSuspendStmt(), /*useCurrentScope=*/true).failed())
447 return mlir::failure();
448
449 cir::YieldOp::create(builder, openCurlyLoc);
450 return mlir::success();
451 };
452
453 // Builds `body`: the user-written coroutine code, including its
454 // implicit `try { ... } catch (...) { unhandled_exception(); }`.
455 auto bodyBuilder = [&]() -> mlir::LogicalResult {
456 curCoro.data->currentAwaitKind = cir::AwaitKind::User;
457
458 if (curCoro.data->exceptionHandler) {
459 // This bit of code is supposed to do:
460 //
461 // if (await-resume-didnt-throw-exception) {
462 // try {
463 // coroutine-body
464 // } catch (...) {
465 // unhandled_exception();
466 // }
467 // }
468 //
469 // IF resume couldn't have thrown an exception(await_resume is
470 // noexcept), we skip the 'if'.
471 //
472 // Note that we've reversed the condition of the 'if' from classic
473 // codegen so that we don't need an 'else' block.
474 if (curCoro.data->resumeEHVar.isValid()) {
475 mlir::Value shouldSkip = builder.createFlagLoad(
476 openCurlyLoc, curCoro.data->resumeEHVar.getPointer());
477 mlir::LogicalResult res = mlir::success();
478 cir::IfOp::create(builder, openCurlyLoc, shouldSkip,
479 /*withElseRegion=*/false,
480 [&](mlir::OpBuilder &b, mlir::Location loc) {
481 res = coroutineBodyExceptionHelper(*this, s);
482 builder.createYield(openCurlyLoc);
483 });
484
485 if (res.failed())
486 return mlir::failure();
487
488 } else if (coroutineBodyExceptionHelper(*this, s).failed()) {
489 return mlir::failure();
490 }
491 } else if (emitBodyAndFallthrough(*this, s, s.getBody(), curLexScope)
492 .failed()) {
493 return mlir::failure();
494 }
495
496 return mlir::success();
497 };
498
499 // Builds `final_suspend`: only emitted at all if the body can actually
500 // reach it (an explicit co_return, or falling off the end).
501 auto finalSuspendBuilder = [&]() -> mlir::LogicalResult {
502 // Note that LLVM checks CanFallthrough by looking into the availability
503 // of the insert block which is kinda brittle and unintuitive, seems to be
504 // related with how landing pads are handled.
505 //
506 // CIRGen handles this by checking pre-existing co_returns in the current
507 // scope instead.
508 //
509 // From LLVM IR Gen: const bool CanFallthrough = Builder.GetInsertBlock();
510 const bool canFallthrough = curLexScope->hasCoreturn();
511 const bool hasCoreturns = curCoro.data->coreturnCount > 0;
512 if (canFallthrough || hasCoreturns) {
513 curCoro.data->currentAwaitKind = cir::AwaitKind::Final;
514 if (emitStmt(s.getFinalSuspendStmt(), /*useCurrentScope=*/true)
515 .failed())
516 return mlir::failure();
517 }
518 cir::YieldOp::create(builder, openCurlyLoc);
519 return mlir::success();
520 };
521
522 // Emit "if (coro.free(CoroId, CoroBegin)) Deallocate;"
523 auto destroyBuilder = [&]() -> mlir::LogicalResult {
524 Stmt *deallocate = s.getDeallocate();
525 if (emitStmt(deallocate, /*useCurrentScope=*/true).failed()) {
526 cgm.error(deallocate->getBeginLoc(),
527 "failed to emit coroutine deallocation expression");
528 return mlir::failure();
529 }
530
531 cir::CoroFreeOp coroFree = curCoro.data->lastCoroFree;
532
533 if (!coroFree) {
534 cgm.error(deallocate->getBeginLoc(),
535 "Deallocation expression does not refer to coro.free");
536 return mlir::failure();
537 }
538 {
539 mlir::OpBuilder::InsertionGuard guard(builder);
540 builder.setInsertionPointAfter(coroFree);
541 mlir::Value isPtrNotNull =
542 builder.createPtrIsNotNull(coroFree.getResult());
543
544 llvm::SmallVector<mlir::Operation *> opsToMove;
545 mlir::Block *block = builder.getInsertionBlock();
546 mlir::Block::iterator it(isPtrNotNull.getDefiningOp());
547
548 for (++it; it != block->end(); ++it)
549 opsToMove.push_back(&*it);
550
551 auto ifOp = cir::IfOp::create(
552 builder, getLoc(deallocate->getSourceRange()), isPtrNotNull,
553 /*withElseRegion*/ false,
554 [&](mlir::OpBuilder &builder, mlir::Location loc) {
555 cir::YieldOp::create(builder, loc);
556 });
557
558 mlir::Operation *yieldOp = ifOp.getThenRegion().back().getTerminator();
559 for (auto *op : opsToMove)
560 op->moveBefore(yieldOp);
561 }
562
563 cir::YieldOp::create(builder, openCurlyLoc);
564 return mlir::success();
565 };
566
567 // Builds `exit`: coro.end(/*unwind*/ false) followed by the actual return
568 // to the caller.
569 auto exitBuilder = [&]() {
570 cir::ConstantOp nullHandler =
571 builder.getNullPtr(builder.getVoidPtrTy(), openCurlyLoc);
572 cir::ConstantOp noUnwind = builder.getBool(false, openCurlyLoc);
573 auto tkNone = cir::TokenNoneOp::create(builder, openCurlyLoc);
574 cir::CoroEndOp::create(builder, openCurlyLoc, nullHandler, noUnwind,
575 tkNone);
576
577 if (auto *ret = cast_or_null<ReturnStmt>(s.getReturnStmt())) {
578 // Since we already emitted the return value above, so we shouldn't
579 // emit it again here.
580 Expr *previousRetValue = ret->getRetValue();
581 ret->setRetValue(nullptr);
582 if (emitStmt(ret, /*useCurrentScope=*/true).failed())
583 return mlir::failure();
584 mlir::Block *block = builder.getInsertionBlock();
585 // emitReturnStmt() always creates a new insertion block after emitting
586 // the return. That block is unreachable in this case, so erase it.
587 block->erase();
588 // Set the return value back. The code generator, as the AST
589 // **Consumer**, shouldn't change the AST.
590 ret->setRetValue(previousRetValue);
591 } else {
592 cir::ReturnOp::create(builder, openCurlyLoc);
593 }
594
595 return mlir::success();
596 };
597
598 cir::CoroutineOp coro = cir::CoroutineOp::create(
599 builder, openCurlyLoc,
600 /*initialSuspendBuilder=*/
601 [&](mlir::OpBuilder &b, mlir::Location loc) {
602 if (initialSuspendBuilder().failed())
603 res = mlir::failure();
604 },
605 /*bodyBuilder=*/
606 [&](mlir::OpBuilder &b, mlir::Location loc) {
607 if (bodyBuilder().failed())
608 res = mlir::failure();
609 },
610 /*finalSuspendBuilder=*/
611 [&](mlir::OpBuilder &b, mlir::Location loc) {
612 if (finalSuspendBuilder().failed())
613 res = mlir::failure();
614 },
615 /*destroyBuilder=*/
616 [&](mlir::OpBuilder &b, mlir::Location loc) {
617 if (destroyBuilder().failed())
618 res = mlir::failure();
619 },
620 /*exitBuilder=*/
621 [&](mlir::OpBuilder &b, mlir::Location loc) {
622 if (exitBuilder().failed())
623 res = mlir::failure();
624 });
625
626 if (coro && !coro.getBody().empty()) {
627 mlir::Block &lastBlock = coro.getBody().back();
628 mlir::Block *prevBlock = lastBlock.getPrevNode();
629 if (lastBlock.empty() && lastBlock.hasNoPredecessors() && prevBlock &&
630 !prevBlock->empty() && isa<cir::CoReturnOp>(prevBlock->back())) {
631 lastBlock.erase();
632 } else if (!lastBlock.mightHaveTerminator()) {
633 mlir::OpBuilder::InsertionGuard guard(builder);
634 builder.setInsertionPointToEnd(&lastBlock);
635 cir::YieldOp::create(builder, openCurlyLoc);
636 }
637 }
638 }
639
640 return res;
641}
642
643static bool functionCanThrow(const FunctionDecl *d) {
644 const auto *proto = d->getType()->getAs<FunctionProtoType>();
645 if (!proto)
646 return true;
647 return !isNoexceptExceptionSpec(proto->getExceptionSpecType()) ||
648 proto->canThrow() != CT_Cannot;
649}
650
651static bool stmtCanThrow(const Stmt *s) {
652 if (const auto *ce = dyn_cast<CallExpr>(s)) {
653 const FunctionDecl *callee = ce->getDirectCallee();
654 if (!callee || functionCanThrow(callee))
655 return true;
656 }
657
658 // The destructor call of a bound temporary is not among the children.
659 if (const auto *te = dyn_cast<CXXBindTemporaryExpr>(s))
660 if (functionCanThrow(te->getTemporary()->getDestructor()))
661 return true;
662
663 return llvm::any_of(s->children(), [](const Stmt *child) {
664 return child && stmtCanThrow(child);
665 });
666}
667
668// Given a suspend expression which roughly looks like:
669//
670// auto && x = CommonExpr();
671// if (!x.await_ready()) {
672// x.await_suspend(...); (*)
673// }
674// x.await_resume();
675//
676// where the result of the entire expression is the result of x.await_resume()
677//
678// (*) If x.await_suspend return type is bool, it allows to veto a suspend:
679// if (x.await_suspend(...))
680// llvm_coro_suspend();
681//
682// This is more higher level than LLVM codegen, for that one see llvm's
683// docs/Coroutines.md for more details.
684namespace {
685struct LValueOrRValue {
686 LValue lv;
687 RValue rv;
688};
689} // namespace
690
691static bool isResumeExprInTryCatch(const CGCoroData &coro, cir::AwaitKind kind,
692 const CoroutineSuspendExpr &s) {
693 return coro.exceptionHandler && kind == cir::AwaitKind::Init &&
695}
696
697static LValueOrRValue
699 CoroutineSuspendExpr const &s, cir::AwaitKind kind,
700 AggValueSlot aggSlot, bool ignoreResult,
701 mlir::Block *scopeParentBlock,
702 mlir::Value &tmpResumeRValAddr, bool forLValue) {
703 [[maybe_unused]] mlir::LogicalResult awaitBuild = mlir::success();
704 LValueOrRValue awaitRes;
705
708 CIRGenBuilderTy &builder = cgf.getBuilder();
709
710 // Exception handling requires additional IR. We avoid generating it when
711 // neither the await_resume() call nor the destruction of its result can
712 // throw.
713 const bool resumeInTry = isResumeExprInTryCatch(coro, kind, s);
714
715 // If the await_resume() result needs a destructor, take over its
716 // destruction, unless the destination owns it. The try/catch path destroys
717 // the result itself.
718 const CXXBindTemporaryExpr *resultBind = nullptr;
719 if (!resumeInTry && !aggSlot.isExternallyDestructed())
720 resultBind = dyn_cast<CXXBindTemporaryExpr>(s.getResumeExpr());
721 if (resultBind) {
722 // Emit the result into a slot created outside of the cir.await, so that it
723 // is still available after it.
724 if (aggSlot.isIgnored())
725 aggSlot = cgf.createAggTemp(resultBind->getType(),
726 cgf.getLoc(resultBind->getSourceRange()),
727 "agg.tmp.ensured");
728 // Don't push the destructor from within the resume region, where its
729 // cir.cleanup.scope would capture the region's terminator.
730 aggSlot.setExternallyDestructed();
731 }
732
733 [[maybe_unused]] cir::AwaitOp awaitOp = cir::AwaitOp::create(
734 builder, cgf.getLoc(s.getSourceRange()), kind,
735 /*readyBuilder=*/
736 [&](mlir::OpBuilder &b, mlir::Location loc) {
737 Expr *condExpr = s.getReadyExpr()->IgnoreParens();
738 builder.createCondition(cgf.evaluateExprAsBool(condExpr));
739 },
740 /*suspendBuilder=*/
741 [&](mlir::OpBuilder &b, mlir::Location loc) {
742 // Note that differently from LLVM codegen we do not emit coro.save
743 // and coro.suspend here, that should be done as part of lowering this
744 // to LLVM dialect (or some other MLIR dialect)
745
746 switch (s.getSuspendReturnType()) {
747 case CoroutineSuspendExpr::SuspendReturnType::SuspendBool: {
748 mlir::Value suspendRet = cgf.evaluateExprAsBool(s.getSuspendExpr());
749 // Veto suspension if requested by bool returning await_suspend.
750 cir::CoroSuspendPoint::create(builder, loc, suspendRet);
751 break;
752 }
753 case CoroutineSuspendExpr::SuspendReturnType::SuspendVoid:
754 cgf.emitScalarExpr(s.getSuspendExpr());
755 // Signals the parent that execution flows to next region.
756 cir::CoroSuspendPoint::create(builder, loc);
757 break;
758 case CoroutineSuspendExpr::SuspendReturnType::SuspendHandle:
759 cgf.cgm.errorNYI(s.getSourceRange(),
760 "await_suspend returning handle");
761 cir::CoroSuspendPoint::create(builder, loc);
762 break;
763 }
764 },
765 /*resumeBuilder=*/
766 [&](mlir::OpBuilder &b, mlir::Location loc) {
767 if (resumeInTry) {
768 // we are basically just emitting:
769 // resumeEh = false;
770 // try {
771 // resumeExpr();
772 // resumeEh = true;
773 // } catch(...) {
774 // exceptionHandler();
775 // }
776 // Note the values of resumeEh are reversed from classic codegen,
777 // simply so we can use an 'IfOp' without a 'else' later.
778 ASTContext &ctx = cgf.getContext();
779 SourceLocation resumeLoc = s.getResumeExpr()->getExprLoc();
780 mlir::Location mlirLoc = cgf.getLoc(resumeLoc);
781 coro.resumeEHVar = cgf.createTempAlloca(
782 builder.getBoolTy(), ctx.getTypeAlignInChars(ctx.BoolTy), mlirLoc,
783 "resume.eh");
784 builder.createFlagStore(mlirLoc, false,
785 coro.resumeEHVar.getPointer());
786
787 CXXCatchStmt catchStmt(resumeLoc,
788 /*exDecl=*/nullptr, coro.exceptionHandler);
789 auto *tryBody =
790 CompoundStmt::Create(ctx, s.getResumeExpr(), FPOptionsOverride(),
791 resumeLoc, resumeLoc);
792 CXXTryStmt *tryStmt =
793 CXXTryStmt::Create(ctx, resumeLoc, tryBody, &catchStmt);
794
795 struct resumeEmitter final : CIRGenFunction::cxxTryBodyEmitter {
796 const CXXTryStmt &tryStmt;
797 mlir::Location loc;
798 mlir::Value resumeEHVar;
799 resumeEmitter(const CXXTryStmt &tryStmt, mlir::Location loc,
800 Address resumeEHVar)
801 : tryStmt(tryStmt), loc(loc),
802 resumeEHVar(resumeEHVar.getPointer()) {}
803
804 mlir::LogicalResult operator()(CIRGenFunction &cgf) override {
805 CIRGenFunction::RunCleanupsScope resumeCleanups(cgf);
806 mlir::LogicalResult res =
807 cgf.emitStmt(tryStmt.getTryBlock(), /*useCurrentScope=*/true);
808 resumeCleanups.forceCleanup();
809 cgf.getBuilder().createFlagStore(loc, true, resumeEHVar);
810 return res;
811 }
812
813 ~resumeEmitter() override = default;
814 } emitter{*tryStmt, mlirLoc, coro.resumeEHVar};
815
816 awaitBuild = cgf.emitCXXTryStmt(*tryStmt, emitter);
817 // We are not supposed to obtain the value from init suspend
818 // await_resume().
819 awaitRes.rv = RValue::getIgnored();
820 } else if (forLValue) {
821 // FIXME(cir): the alloca for the resume expr should be placed in the
822 // enclosing cir.scope instead.
823 awaitRes.lv = cgf.emitLValue(s.getResumeExpr());
824 } else {
825 awaitRes.rv =
826 cgf.emitAnyExpr(s.getResumeExpr(), aggSlot, ignoreResult);
827 if (!awaitRes.rv.isIgnored()) {
828 RValue rv = awaitRes.rv;
829 if (rv.isScalar() || rv.isComplex()) {
830 mlir::Value value =
831 rv.isScalar() ? rv.getValue() : rv.getComplexValue();
832 tmpResumeRValAddr = cgf.emitAlloca(
833 "__coawait_resume_rval", value.getType(), loc,
835 builder.getBestAllocaInsertPoint(scopeParentBlock));
836 // Store the rvalue so we can reload it before the promise call.
837 builder.CIRBaseBuilderTy::createStore(loc, value,
838 tmpResumeRValAddr);
839 } else {
840 assert(rv.isAggregate() && "unexpected rvalue kind");
841 }
842 }
843 }
844
845 // Returns control back to parent.
846 cir::YieldOp::create(builder, loc);
847 });
848
849 // Push the destructor right after the cir.await, where the result starts to
850 // exist, and not around it: destroying the coroutine at the suspend point
851 // would destroy the not yet constructed result. The cleanup runs at the end
852 // of the full-expression.
853 if (resultBind)
854 cgf.emitCXXTemporary(resultBind->getTemporary(), resultBind->getType(),
855 aggSlot.getAddress());
856
857 assert(awaitBuild.succeeded() && "Should know how to codegen");
858 return awaitRes;
859}
860
862 const CoroutineSuspendExpr &e,
863 cir::AwaitKind kind, AggValueSlot aggSlot,
864 bool ignoreResult) {
865 RValue rval;
866 mlir::Location scopeLoc = cgf.getLoc(e.getSourceRange());
867
868 // Since we model suspend / resume as an inner region, we must store
869 // resume scalar results in a tmp alloca, and load it after we build the
870 // suspend expression. An alternative way to do this would be to make
871 // every region return a value when promise.return_value() is used, but
872 // it's a bit awkward given that resume is the only region that actually
873 // returns a value.
874 mlir::Block *currEntryBlock = cgf.curLexScope->getEntryBlock();
875 [[maybe_unused]] mlir::Value tmpResumeRValAddr;
876
877 // No need to explicitly wrap this into a scope since the AST already uses a
878 // ExprWithCleanups, which will wrap this into a cir.scope anyways.
879 rval = emitSuspendExpression(cgf, *cgf.curCoro.data, e, kind, aggSlot,
880 ignoreResult, currEntryBlock, tmpResumeRValAddr,
881 /*forLValue*/ false)
882 .rv;
883
884 if (ignoreResult || rval.isIgnored())
885 return rval;
886
887 if (rval.isScalar()) {
888 rval = RValue::get(cir::LoadOp::create(cgf.getBuilder(), scopeLoc,
889 rval.getValue().getType(),
890 tmpResumeRValAddr));
891 } else if (rval.isAggregate()) {
892 return rval;
893 } else { // complex
894 rval = RValue::getComplex(cir::LoadOp::create(
895 cgf.getBuilder(), scopeLoc, rval.getComplexValue().getType(),
896 tmpResumeRValAddr));
897 }
898 return rval;
899}
900
902 AggValueSlot aggSlot,
903 bool ignoreResult) {
904 return emitSuspendExpr(*this, e, curCoro.data->currentAwaitKind, aggSlot,
905 ignoreResult);
906}
907
909 AggValueSlot aggSlot,
910 bool ignoreResult) {
911 return emitSuspendExpr(*this, e, cir::AwaitKind::Yield, aggSlot,
912 ignoreResult);
913}
914
915mlir::LogicalResult CIRGenFunction::emitCoreturnStmt(CoreturnStmt const &s) {
916 ++curCoro.data->coreturnCount;
917
918 const Expr *rv = s.getOperand();
919 if (rv && rv->getType()->isVoidType() && !isa<InitListExpr>(rv)) {
920 // Make sure to evaluate the non initlist expression of a co_return
921 // with a void expression for side effects.
922 RunCleanupsScope cleanupScope(*this);
923 emitIgnoredExpr(rv);
924 }
925
926 if (emitStmt(s.getPromiseCall(), /*useCurrentScope=*/true).failed())
927 return mlir::failure();
928 mlir::Location loc = getLoc(s.getSourceRange());
929 cir::CoReturnOp::create(builder, loc);
930 curLexScope->markCoreturnEmitted();
931
932 // Statements after a co_return may stil be reachable through a label.
933 // Continue codegen.
934 builder.createBlock(builder.getBlock()->getParent());
935 return mlir::success();
936}
static void createCoroData(CIRGenFunction &cgf, CIRGenFunction::CGCoroInfo &curCoro, cir::CoroIdOp coroId, CallExpr const *coroIdExpr=nullptr)
static LValueOrRValue emitSuspendExpression(CIRGenFunction &cgf, CGCoroData &coro, CoroutineSuspendExpr const &s, cir::AwaitKind kind, AggValueSlot aggSlot, bool ignoreResult, mlir::Block *scopeParentBlock, mlir::Value &tmpResumeRValAddr, bool forLValue)
static bool stmtCanThrow(const Stmt *s)
static RValue emitSuspendExpr(CIRGenFunction &cgf, const CoroutineSuspendExpr &e, cir::AwaitKind kind, AggValueSlot aggSlot, bool ignoreResult)
static bool functionCanThrow(const FunctionDecl *d)
static bool isResumeExprInTryCatch(const CGCoroData &coro, cir::AwaitKind kind, const CoroutineSuspendExpr &s)
static mlir::LogicalResult coroutineBodyExceptionHelper(CIRGenFunction &cgf, const CoroutineBodyStmt &s)
static mlir::LogicalResult emitBodyAndFallthrough(CIRGenFunction &cgf, const CoroutineBodyStmt &s, Stmt *body, const CIRGenFunction::LexicalScope *currLexScope)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
cir::StoreOp createFlagStore(mlir::Location loc, bool val, mlir::Value dst)
cir::YieldOp createYield(mlir::Location loc, mlir::ValueRange value={})
Create a yield operation.
cir::LoadOp createFlagLoad(mlir::Location loc, mlir::Value addr)
Emit a load from an boolean flag variable.
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
CanQualType BoolTy
mlir::Value getPointer() const
Definition Address.h:98
static Address invalid()
Definition Address.h:76
bool isValid() const
Definition Address.h:77
An aggregate value slot.
IsDestructed_t isExternallyDestructed() const
void setExternallyDestructed(bool destructed=true)
An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
Enters a new scope for capturing cleanups, all of which will be executed once the scope is exited.
mlir::Type convertType(clang::QualType t)
mlir::LogicalResult emitCoreturnStmt(const CoreturnStmt &s)
cir::AllocaOp createTempAlloca(mlir::Type ty, mlir::Location loc, const Twine &name="tmp", mlir::Value arraySize=nullptr, bool insertIntoFnEntryBlock=false)
This creates an alloca and inserts it into the entry block if ArraySize is nullptr,...
cir::CoroAllocOp emitCoroAllocBuiltinCall(const CallExpr *e)
llvm::DenseMap< const clang::Decl *, Address > DeclMapTy
LValue emitLValue(const clang::Expr *e)
Emit code to compute a designator that specifies the location of the expression.
cir::CoroNoopOp emitCoroNoopBuiltinCall(const CallExpr *e)
cir::CoroSuspendOp emitCoroSuspendBuiltinCall(const CallExpr *e)
mlir::Location getLoc(clang::SourceLocation srcLoc)
Helpers to convert Clang's SourceLocation to a MLIR Location.
cir::CoroBeginOp emitCoroBeginBuiltinCall(const CallExpr *e)
void emitAnyExprToMem(const Expr *e, Address location, Qualifiers quals, bool isInitializer)
Emits the code necessary to evaluate an arbitrary expression into the given memory location.
RValue emitCoyieldExpr(const CoyieldExpr &e, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
cir::CoroFreeOp emitCoroFreeBuiltin(const CallExpr *e)
mlir::Operation * curFn
The current function or global initializer that is generated code for.
llvm::SmallVector< const ParmVarDecl * > fnArgs
Save Parameter Decl for coroutine.
AggValueSlot createAggTemp(QualType ty, mlir::Location loc, const Twine &name="tmp", Address *alloca=nullptr)
Create a temporary memory object for the given aggregate type.
mlir::Type convertTypeForMem(QualType t)
mlir::Value emitAlloca(llvm::StringRef name, mlir::Type ty, mlir::Location loc, clang::CharUnits alignment, bool insertIntoFnEntryBlock, mlir::Value arraySize=nullptr)
mlir::LogicalResult emitCXXTryStmt(const clang::CXXTryStmt &s, cxxTryBodyEmitter &bodyCallback, bool isFnTryBlock=false)
cir::CoroPromiseOp emitCoroPromiseBuiltinCall(const CallExpr *e)
Address returnValue
The temporary alloca to hold the return value.
cir::CoroDestroyOp emitCoroDestroyBuiltinCall(const CallExpr *e)
cir::CoroEndOp emitCoroEndBuiltinCall(const CallExpr *e)
void emitCXXTemporary(const CXXTemporary *temporary, QualType tempType, Address ptr)
Emits all the code to cause the given temporary to be cleaned up.
mlir::Value emitScalarExpr(const clang::Expr *e, bool ignoreResultAssign=false)
Emit the computation of the specified expression of scalar type.
CIRGenBuilderTy & getBuilder()
DeclMapTy localDeclMap
This keeps track of the CIR allocas or globals for local C declarations.
RValue emitCoawaitExpr(const CoawaitExpr &e, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
RValue emitAnyExpr(const clang::Expr *e, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
Emit code to compute the specified expression which can have any type.
cir::CoroSizeOp emitCoroSizeBuiltinCall(const CallExpr *e)
cir::CoroDoneOp emitCoroDoneBuiltinCall(const CallExpr *e)
cir::CoroResumeOp emitCoroResumeBuiltinCall(const CallExpr *e)
cir::CoroAlignOp emitCoroAlignBuiltinCall(const CallExpr *e)
cir::CoroIdOp emitCoroIDBuiltinCall(const CallExpr *e)
clang::ASTContext & getContext() const
mlir::LogicalResult emitCoroutineBody(const CoroutineBodyStmt &s)
mlir::LogicalResult emitStmt(const clang::Stmt *s, bool useCurrentScope, llvm::ArrayRef< const Attr * > attrs={})
void emitIgnoredExpr(const clang::Expr *e)
Emit code to compute the specified expression, ignoring the result.
CIRGenBuilderTy & getBuilder()
void error(SourceLocation loc, llvm::StringRef error)
Emit a general error that something can't be done.
This trivial value class is used to represent the result of an expression that is evaluated.
Definition CIRGenValue.h:33
bool isAggregate() const
Definition CIRGenValue.h:51
static RValue get(mlir::Value v)
Definition CIRGenValue.h:83
static RValue getComplex(mlir::Value v)
Definition CIRGenValue.h:91
bool isComplex() const
Definition CIRGenValue.h:50
mlir::Value getValue() const
Return the value of this scalar value.
Definition CIRGenValue.h:57
bool isScalar() const
Definition CIRGenValue.h:49
bool isIgnored() const
Definition CIRGenValue.h:52
mlir::Value getComplexValue() const
Return the value of this complex value.
Definition CIRGenValue.h:63
static RValue getIgnored()
Definition CIRGenValue.h:78
Represents binding an expression to a temporary.
Definition ExprCXX.h:1498
CXXCatchStmt - This represents a C++ catch block.
Definition StmtCXX.h:29
static CXXTryStmt * Create(const ASTContext &C, SourceLocation tryLoc, CompoundStmt *tryBlock, ArrayRef< Stmt * > handlers)
Definition StmtCXX.cpp:26
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2991
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3195
SourceLocation getBeginLoc() const
Definition Expr.h:3325
arg_range arguments()
Definition Expr.h:3243
static CharUnits One()
Construct a CharUnits quantity of one.
Definition CharUnits.h:55
Represents a 'co_await' expression.
Definition ExprCXX.h:5423
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt * > Stmts, FPOptionsOverride FPFeatures, SourceLocation LB, SourceLocation RB)
Definition Stmt.cpp:399
Represents a 'co_return' statement in the C++ Coroutines TS.
Definition StmtCXX.h:474
Expr * getOperand() const
Retrieve the operand of the 'co_return' statement.
Definition StmtCXX.h:498
Expr * getPromiseCall() const
Retrieve the promise call that results from this 'co_return' statement.
Definition StmtCXX.h:503
Represents the body of a coroutine.
Definition StmtCXX.h:321
CompoundStmt * getBody() const
Retrieve the body of the coroutine as written.
Definition StmtCXX.h:381
Stmt * getFallthroughHandler() const
Definition StmtCXX.h:402
SourceLocation getBeginLoc() const LLVM_READONLY
Definition StmtCXX.h:428
Represents an expression that might suspend coroutine execution; either a co_await or co_yield expres...
Definition ExprCXX.h:5309
Expr * getResumeExpr() const
Definition ExprCXX.h:5373
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition ExprCXX.h:5363
Represents a 'co_yield' expression.
Definition ExprCXX.h:5504
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1294
ValueDecl * getDecl()
Definition Expr.h:1362
bool isSingleDecl() const
isSingleDecl - This method returns true if this DeclStmt refers to a single Decl.
Definition Stmt.h:1656
const Decl * getSingleDecl() const
Definition Stmt.h:1658
This represents one expression.
Definition Expr.h:113
QualType getType() const
Definition Expr.h:145
Represents a function declaration or definition.
Definition Decl.h:2059
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5416
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Stmt - This represents one statement.
Definition Stmt.h:85
child_range children()
Definition Stmt.cpp:304
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
Exposes information about the current target.
Definition TargetInfo.h:228
unsigned getNewAlign() const
Return the largest alignment for which a suitably-sized allocation with 'operator new(size_t)' is gua...
Definition TargetInfo.h:762
unsigned getCharWidth() const
Definition TargetInfo.h:528
bool isVoidType() const
Definition TypeBase.h:9068
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9299
QualType getType() const
Definition Decl.h:724
const Expr * getInit() const
Definition Decl.h:1392
Defines the clang::TargetInfo interface.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isNoexceptExceptionSpec(ExceptionSpecificationType ESpecType)
U cast(CodeGen::Address addr)
Definition Address.h:327
static bool coroOutsideFrameMD()
static bool generateDebugInfo()
std::unique_ptr< CGCoroData > data
Represents a scope, including function bodies, compound statements, and the substatements of if/while...
cir::PointerType voidPtrTy
void* in address space 0