1//===----- CGCoroutine.cpp - Emit LLVM 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 "CGCleanup.h"
14#include "CGDebugInfo.h"
15#include "CodeGenFunction.h"
16#include "clang/AST/StmtCXX.h"
17#include "clang/AST/StmtVisitor.h"
18#include "llvm/ADT/ScopeExit.h"
19
20using namespace clang;
21using namespace CodeGen;
22
23using llvm::Value;
24using llvm::BasicBlock;
25
26namespace {
27enum class AwaitKind { Init, Normal, Yield, Final };
28static constexpr llvm::StringLiteral AwaitKindStr[] = {"init", "await", "yield",
29 "final"};
30}
31
32struct clang::CodeGen::CGCoroData {
33 // What is the current await expression kind and how many
34 // await/yield expressions were encountered so far.
35 // These are used to generate pretty labels for await expressions in LLVM IR.
36 AwaitKind CurrentAwaitKind = AwaitKind::Init;
37 unsigned AwaitNum = 0;
38 unsigned YieldNum = 0;
39
40 // How many co_return statements are in the coroutine. Used to decide whether
41 // we need to add co_return; equivalent at the end of the user authored body.
42 unsigned CoreturnCount = 0;
43
44 // A branch to this block is emitted when coroutine needs to suspend.
45 llvm::BasicBlock *SuspendBB = nullptr;
46 // A branch to this block after final.cleanup or final.ready
47 llvm::BasicBlock *FinalExit = nullptr;
48
49 // The promise type's 'unhandled_exception' handler, if it defines one.
50 Stmt *ExceptionHandler = nullptr;
51
52 // A temporary i1 alloca that stores whether 'await_resume' threw an
53 // exception. If it did, 'true' is stored in this variable, and the coroutine
54 // body must be skipped. If the promise type does not define an exception
55 // handler, this is null.
56 llvm::Value *ResumeEHVar = nullptr;
57
58 // Stores the jump destination just before the coroutine memory is freed.
59 // This is the destination that every suspend point jumps to for the cleanup
60 // branch.
61 CodeGenFunction::JumpDest CleanupJD;
62
63 // Stores the jump destination just before the final suspend. The co_return
64 // statements jumps to this point after calling return_xxx promise member.
65 CodeGenFunction::JumpDest FinalJD;
66
67 // Stores the llvm.coro.id emitted in the function so that we can supply it
68 // as the first argument to coro.begin, coro.alloc and coro.free intrinsics.
69 // Note: llvm.coro.id returns a token that cannot be directly expressed in a
70 // builtin.
71 llvm::CallInst *CoroId = nullptr;
72
73 // Stores the llvm.coro.begin emitted in the function so that we can replace
74 // all coro.frame intrinsics with direct SSA value of coro.begin that returns
75 // the address of the coroutine frame of the current coroutine.
76 llvm::CallInst *CoroBegin = nullptr;
77
78 // Stores the last emitted coro.free for the deallocate expressions, we use it
79 // to wrap dealloc code with if(auto mem = coro.free) dealloc(mem).
80 llvm::CallInst *LastCoroFree = nullptr;
81
82 // If coro.id came from the builtin, remember the expression to give better
83 // diagnostic. If CoroIdExpr is nullptr, the coro.id was created by
84 // EmitCoroutineBody.
85 CallExpr const *CoroIdExpr = nullptr;
86};
87
88// Defining these here allows to keep CGCoroData private to this file.
89clang::CodeGen::CodeGenFunction::CGCoroInfo::CGCoroInfo() {}
90CodeGenFunction::CGCoroInfo::~CGCoroInfo() {}
91
92static void createCoroData(CodeGenFunction &CGF,
93 CodeGenFunction::CGCoroInfo &CurCoro,
94 llvm::CallInst *CoroId,
95 CallExpr const *CoroIdExpr = nullptr) {
96 if (CurCoro.Data) {
97 if (CurCoro.Data->CoroIdExpr)
98 CGF.CGM.Error(loc: CoroIdExpr->getBeginLoc(),
99 error: "only one __builtin_coro_id can be used in a function");
100 else if (CoroIdExpr)
101 CGF.CGM.Error(loc: CoroIdExpr->getBeginLoc(),
102 error: "__builtin_coro_id shall not be used in a C++ coroutine");
103 else
104 llvm_unreachable("EmitCoroutineBodyStatement called twice?");
105
106 return;
107 }
108
109 CurCoro.Data = std::make_unique<CGCoroData>();
110 CurCoro.Data->CoroId = CoroId;
111 CurCoro.Data->CoroIdExpr = CoroIdExpr;
112}
113
114// Synthesize a pretty name for a suspend point.
115static SmallString<32> buildSuspendPrefixStr(CGCoroData &Coro, AwaitKind Kind) {
116 unsigned No = 0;
117 switch (Kind) {
118 case AwaitKind::Init:
119 case AwaitKind::Final:
120 break;
121 case AwaitKind::Normal:
122 No = ++Coro.AwaitNum;
123 break;
124 case AwaitKind::Yield:
125 No = ++Coro.YieldNum;
126 break;
127 }
128 SmallString<32> Prefix(AwaitKindStr[static_cast<unsigned>(Kind)]);
129 if (No > 1) {
130 Twine(No).toVector(Out&: Prefix);
131 }
132 return Prefix;
133}
134
135// Check if function can throw based on prototype noexcept, also works for
136// destructors which are implicitly noexcept but can be marked noexcept(false).
137static bool FunctionCanThrow(const FunctionDecl *D) {
138 const auto *Proto = D->getType()->getAs<FunctionProtoType>();
139 if (!Proto) {
140 // Function proto is not found, we conservatively assume throwing.
141 return true;
142 }
143 return !isNoexceptExceptionSpec(ESpecType: Proto->getExceptionSpecType()) ||
144 Proto->canThrow() != CT_Cannot;
145}
146
147static bool StmtCanThrow(const Stmt *S) {
148 if (const auto *CE = dyn_cast<CallExpr>(Val: S)) {
149 const auto *Callee = CE->getDirectCallee();
150 if (!Callee)
151 // We don't have direct callee. Conservatively assume throwing.
152 return true;
153
154 if (FunctionCanThrow(D: Callee))
155 return true;
156
157 // Fall through to visit the children.
158 }
159
160 if (const auto *TE = dyn_cast<CXXBindTemporaryExpr>(Val: S)) {
161 // Special handling of CXXBindTemporaryExpr here as calling of Dtor of the
162 // temporary is not part of `children()` as covered in the fall through.
163 // We need to mark entire statement as throwing if the destructor of the
164 // temporary throws.
165 const auto *Dtor = TE->getTemporary()->getDestructor();
166 if (FunctionCanThrow(D: Dtor))
167 return true;
168
169 // Fall through to visit the children.
170 }
171
172 for (const auto *child : S->children())
173 if (StmtCanThrow(S: child))
174 return true;
175
176 return false;
177}
178
179// Emit suspend expression which roughly looks like:
180//
181// auto && x = CommonExpr();
182// if (!x.await_ready()) {
183// llvm_coro_save();
184// llvm_coro_await_suspend(&x, frame, wrapper) (*) (**)
185// llvm_coro_suspend(); (***)
186// }
187// x.await_resume();
188//
189// where the result of the entire expression is the result of x.await_resume()
190//
191// (*) llvm_coro_await_suspend_{void, bool, handle} is lowered to
192// wrapper(&x, frame) when it's certain not to interfere with
193// coroutine transform. await_suspend expression is
194// asynchronous to the coroutine body and not all analyses
195// and transformations can handle it correctly at the moment.
196//
197// Wrapper function encapsulates x.await_suspend(...) call and looks like:
198//
199// auto __await_suspend_wrapper(auto& awaiter, void* frame) {
200// std::coroutine_handle<> handle(frame);
201// return awaiter.await_suspend(handle);
202// }
203//
204// (**) If x.await_suspend return type is bool, it allows to veto a suspend:
205// if (x.await_suspend(...))
206// llvm_coro_suspend();
207//
208// (***) llvm_coro_suspend() encodes three possible continuations as
209// a switch instruction:
210//
211// %where-to = call i8 @llvm.coro.suspend(...)
212// switch i8 %where-to, label %coro.ret [ ; jump to epilogue to suspend
213// i8 0, label %yield.ready ; go here when resumed
214// i8 1, label %yield.cleanup ; go here when destroyed
215// ]
216//
217// See llvm's docs/Coroutines.md for more details.
218//
219namespace {
220 struct LValueOrRValue {
221 LValue LV;
222 RValue RV;
223 };
224}
225static LValueOrRValue emitSuspendExpression(CodeGenFunction &CGF, CGCoroData &Coro,
226 CoroutineSuspendExpr const &S,
227 AwaitKind Kind, AggValueSlot aggSlot,
228 bool ignoreResult, bool forLValue) {
229 auto *E = S.getCommonExpr();
230
231 auto CommonBinder =
232 CodeGenFunction::OpaqueValueMappingData::bind(CGF, ov: S.getOpaqueValue(), e: E);
233 llvm::scope_exit UnbindCommonOnExit([&] { CommonBinder.unbind(CGF); });
234
235 auto Prefix = buildSuspendPrefixStr(Coro, Kind);
236 BasicBlock *ReadyBlock = CGF.createBasicBlock(name: Prefix + Twine(".ready"));
237 BasicBlock *SuspendBlock = CGF.createBasicBlock(name: Prefix + Twine(".suspend"));
238 BasicBlock *CleanupBlock = CGF.createBasicBlock(name: Prefix + Twine(".cleanup"));
239
240 // If expression is ready, no need to suspend.
241 CGF.EmitBranchOnBoolExpr(Cond: S.getReadyExpr(), TrueBlock: ReadyBlock, FalseBlock: SuspendBlock, TrueCount: 0);
242
243 // Otherwise, emit suspend logic.
244 CGF.EmitBlock(BB: SuspendBlock);
245
246 auto &Builder = CGF.Builder;
247 llvm::Function *CoroSave = CGF.CGM.getIntrinsic(IID: llvm::Intrinsic::coro_save);
248 auto *NullPtr = llvm::ConstantPointerNull::get(T: CGF.CGM.Int8PtrTy);
249 auto *SaveCall = Builder.CreateCall(Callee: CoroSave, Args: {NullPtr});
250
251 auto SuspendWrapper = CodeGenFunction(CGF.CGM).generateAwaitSuspendWrapper(
252 CoroName: CGF.CurFn->getName(), SuspendPointName: Prefix, S);
253
254 CGF.CurCoro.InSuspendBlock = true;
255
256 assert(CGF.CurCoro.Data && CGF.CurCoro.Data->CoroBegin &&
257 "expected to be called in coroutine context");
258
259 SmallVector<llvm::Value *, 3> SuspendIntrinsicCallArgs;
260 SuspendIntrinsicCallArgs.push_back(
261 Elt: CGF.getOrCreateOpaqueLValueMapping(e: S.getOpaqueValue()).getPointer(CGF));
262
263 SuspendIntrinsicCallArgs.push_back(Elt: CGF.CurCoro.Data->CoroBegin);
264 SuspendIntrinsicCallArgs.push_back(Elt: SuspendWrapper);
265
266 const auto SuspendReturnType = S.getSuspendReturnType();
267 llvm::Intrinsic::ID AwaitSuspendIID;
268
269 switch (SuspendReturnType) {
270 case CoroutineSuspendExpr::SuspendReturnType::SuspendVoid:
271 AwaitSuspendIID = llvm::Intrinsic::coro_await_suspend_void;
272 break;
273 case CoroutineSuspendExpr::SuspendReturnType::SuspendBool:
274 AwaitSuspendIID = llvm::Intrinsic::coro_await_suspend_bool;
275 break;
276 case CoroutineSuspendExpr::SuspendReturnType::SuspendHandle:
277 AwaitSuspendIID = llvm::Intrinsic::coro_await_suspend_handle;
278 break;
279 }
280
281 llvm::Function *AwaitSuspendIntrinsic = CGF.CGM.getIntrinsic(IID: AwaitSuspendIID);
282
283 // SuspendHandle might throw since it also resumes the returned handle.
284 const bool AwaitSuspendCanThrow =
285 SuspendReturnType ==
286 CoroutineSuspendExpr::SuspendReturnType::SuspendHandle ||
287 StmtCanThrow(S: S.getSuspendExpr());
288
289 llvm::CallBase *SuspendRet = nullptr;
290 // FIXME: add call attributes?
291 if (AwaitSuspendCanThrow)
292 SuspendRet =
293 CGF.EmitCallOrInvoke(Callee: AwaitSuspendIntrinsic, Args: SuspendIntrinsicCallArgs);
294 else
295 SuspendRet = CGF.EmitNounwindRuntimeCall(callee: AwaitSuspendIntrinsic,
296 args: SuspendIntrinsicCallArgs);
297
298 assert(SuspendRet);
299 CGF.CurCoro.InSuspendBlock = false;
300
301 switch (SuspendReturnType) {
302 case CoroutineSuspendExpr::SuspendReturnType::SuspendVoid:
303 assert(SuspendRet->getType()->isVoidTy());
304 break;
305 case CoroutineSuspendExpr::SuspendReturnType::SuspendBool: {
306 assert(SuspendRet->getType()->isIntegerTy());
307
308 // Veto suspension if requested by bool returning await_suspend.
309 BasicBlock *RealSuspendBlock =
310 CGF.createBasicBlock(name: Prefix + Twine(".suspend.bool"));
311 CGF.Builder.CreateCondBr(Cond: SuspendRet, True: RealSuspendBlock, False: ReadyBlock);
312 CGF.EmitBlock(BB: RealSuspendBlock);
313 break;
314 }
315 case CoroutineSuspendExpr::SuspendReturnType::SuspendHandle: {
316 assert(SuspendRet->getType()->isVoidTy());
317 break;
318 }
319 }
320
321 // Emit the suspend point.
322 const bool IsFinalSuspend = (Kind == AwaitKind::Final);
323 llvm::Function *CoroSuspend =
324 CGF.CGM.getIntrinsic(IID: llvm::Intrinsic::coro_suspend);
325 auto *SuspendResult = Builder.CreateCall(
326 Callee: CoroSuspend, Args: {SaveCall, Builder.getInt1(V: IsFinalSuspend)});
327
328 // Create a switch capturing three possible continuations.
329 auto *Switch = Builder.CreateSwitch(V: SuspendResult, Dest: Coro.SuspendBB, NumCases: 2);
330 Switch->addCase(OnVal: Builder.getInt8(C: 0), Dest: ReadyBlock);
331 Switch->addCase(OnVal: Builder.getInt8(C: 1), Dest: CleanupBlock);
332
333 // Emit cleanup for this suspend point.
334 CGF.EmitBlock(BB: CleanupBlock);
335 CGF.EmitBranchThroughCleanup(Dest: Coro.CleanupJD);
336 if (IsFinalSuspend)
337 Coro.FinalExit = CleanupBlock->getSingleSuccessor();
338
339 // Emit await_resume expression.
340 CGF.EmitBlock(BB: ReadyBlock);
341
342 // Exception handling requires additional IR. If the 'await_resume' function
343 // is marked as 'noexcept', we avoid generating this additional IR.
344 CXXTryStmt *TryStmt = nullptr;
345 if (Coro.ExceptionHandler && Kind == AwaitKind::Init &&
346 StmtCanThrow(S: S.getResumeExpr())) {
347 Coro.ResumeEHVar =
348 CGF.CreateTempAlloca(Ty: Builder.getInt1Ty(), Name: Prefix + Twine("resume.eh"));
349 Builder.CreateFlagStore(Value: true, Addr: Coro.ResumeEHVar);
350
351 auto Loc = S.getResumeExpr()->getExprLoc();
352 auto *Catch = new (CGF.getContext())
353 CXXCatchStmt(Loc, /*exDecl=*/nullptr, Coro.ExceptionHandler);
354 auto *TryBody = CompoundStmt::Create(C: CGF.getContext(), Stmts: S.getResumeExpr(),
355 FPFeatures: FPOptionsOverride(), LB: Loc, RB: Loc);
356 TryStmt = CXXTryStmt::Create(C: CGF.getContext(), tryLoc: Loc, tryBlock: TryBody, handlers: Catch);
357 CGF.EnterCXXTryStmt(S: *TryStmt);
358 CGF.EmitStmt(S: TryBody);
359 // We don't use EmitCXXTryStmt here. We need to store to ResumeEHVar that
360 // doesn't exist in the body.
361 Builder.CreateFlagStore(Value: false, Addr: Coro.ResumeEHVar);
362 CGF.ExitCXXTryStmt(S: *TryStmt);
363 LValueOrRValue Res;
364 // We are not supposed to obtain the value from init suspend await_resume().
365 Res.RV = RValue::getIgnored();
366 return Res;
367 }
368
369 LValueOrRValue Res;
370 if (forLValue)
371 Res.LV = CGF.EmitLValue(E: S.getResumeExpr());
372 else
373 Res.RV = CGF.EmitAnyExpr(E: S.getResumeExpr(), aggSlot, ignoreResult);
374
375 return Res;
376}
377
378RValue CodeGenFunction::EmitCoawaitExpr(const CoawaitExpr &E,
379 AggValueSlot aggSlot,
380 bool ignoreResult) {
381 return emitSuspendExpression(CGF&: *this, Coro&: *CurCoro.Data, S: E,
382 Kind: CurCoro.Data->CurrentAwaitKind, aggSlot,
383 ignoreResult, /*forLValue*/false).RV;
384}
385RValue CodeGenFunction::EmitCoyieldExpr(const CoyieldExpr &E,
386 AggValueSlot aggSlot,
387 bool ignoreResult) {
388 return emitSuspendExpression(CGF&: *this, Coro&: *CurCoro.Data, S: E, Kind: AwaitKind::Yield,
389 aggSlot, ignoreResult, /*forLValue*/false).RV;
390}
391
392void CodeGenFunction::EmitCoreturnStmt(CoreturnStmt const &S) {
393 ++CurCoro.Data->CoreturnCount;
394 const Expr *RV = S.getOperand();
395 if (RV && RV->getType()->isVoidType() && !isa<InitListExpr>(Val: RV)) {
396 // Make sure to evaluate the non initlist expression of a co_return
397 // with a void expression for side effects.
398 RunCleanupsScope cleanupScope(*this);
399 EmitIgnoredExpr(E: RV);
400 }
401 EmitStmt(S: S.getPromiseCall());
402 EmitBranchThroughCleanup(Dest: CurCoro.Data->FinalJD);
403}
404
405
406#ifndef NDEBUG
407static QualType getCoroutineSuspendExprReturnType(const ASTContext &Ctx,
408 const CoroutineSuspendExpr *E) {
409 const auto *RE = E->getResumeExpr();
410 // Is it possible for RE to be a CXXBindTemporaryExpr wrapping
411 // a MemberCallExpr?
412 assert(isa<CallExpr>(RE) && "unexpected suspend expression type");
413 return cast<CallExpr>(RE)->getCallReturnType(Ctx);
414}
415#endif
416
417llvm::Function *
418CodeGenFunction::generateAwaitSuspendWrapper(Twine const &CoroName,
419 Twine const &SuspendPointName,
420 CoroutineSuspendExpr const &S) {
421 std::string FuncName =
422 (CoroName + ".__await_suspend_wrapper__" + SuspendPointName).str();
423
424 ASTContext &C = getContext();
425
426 auto *AwaiterDecl =
427 ImplicitParamDecl::Create(C, T: C.VoidPtrTy, ParamKind: ImplicitParamKind::Other);
428 auto *FrameDecl =
429 ImplicitParamDecl::Create(C, T: C.VoidPtrTy, ParamKind: ImplicitParamKind::Other);
430 QualType ReturnTy = S.getSuspendExpr()->getType();
431
432 FunctionArgList args{AwaiterDecl, FrameDecl};
433 const CGFunctionInfo &FI =
434 CGM.getTypes().arrangeBuiltinFunctionDeclaration(resultType: ReturnTy, args);
435
436 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(Info: FI);
437
438 llvm::Function *Fn = llvm::Function::Create(
439 Ty: LTy, Linkage: llvm::GlobalValue::InternalLinkage, N: FuncName, M: &CGM.getModule());
440
441 Fn->addParamAttr(ArgNo: 0, Kind: llvm::Attribute::AttrKind::NonNull);
442 Fn->addParamAttr(ArgNo: 0, Kind: llvm::Attribute::AttrKind::NoUndef);
443
444 Fn->addParamAttr(ArgNo: 1, Kind: llvm::Attribute::AttrKind::NoUndef);
445
446 Fn->setMustProgress();
447 Fn->addFnAttr(Kind: llvm::Attribute::AttrKind::AlwaysInline);
448 Fn->addFnAttr(Kind: "sample-profile-suffix-elision-policy", Val: "selected");
449
450 StartFunction(GD: GlobalDecl(), RetTy: ReturnTy, Fn, FnInfo: FI, Args: args);
451
452 // FIXME: add TBAA metadata to the loads
453 llvm::Value *AwaiterPtr = Builder.CreateLoad(Addr: GetAddrOfLocalVar(VD: AwaiterDecl));
454 auto AwaiterLValue =
455 MakeNaturalAlignAddrLValue(V: AwaiterPtr, T: AwaiterDecl->getType());
456
457 CurAwaitSuspendWrapper.FramePtr =
458 Builder.CreateLoad(Addr: GetAddrOfLocalVar(VD: FrameDecl));
459
460 auto AwaiterBinder = CodeGenFunction::OpaqueValueMappingData::bind(
461 CGF&: *this, ov: S.getOpaqueValue(), lv: AwaiterLValue);
462
463 auto *SuspendRet = EmitScalarExpr(E: S.getSuspendExpr());
464
465 llvm::scope_exit UnbindCommonOnExit([&] { AwaiterBinder.unbind(CGF&: *this); });
466 if (SuspendRet != nullptr) {
467 Fn->addRetAttr(Kind: llvm::Attribute::AttrKind::NoUndef);
468 Builder.CreateStore(Val: SuspendRet, Addr: ReturnValue);
469 }
470
471 CurAwaitSuspendWrapper.FramePtr = nullptr;
472 FinishFunction();
473 return Fn;
474}
475
476LValue
477CodeGenFunction::EmitCoawaitLValue(const CoawaitExpr *E) {
478 assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
479 "Can't have a scalar return unless the return type is a "
480 "reference type!");
481 return emitSuspendExpression(CGF&: *this, Coro&: *CurCoro.Data, S: *E,
482 Kind: CurCoro.Data->CurrentAwaitKind, aggSlot: AggValueSlot::ignored(),
483 /*ignoreResult*/false, /*forLValue*/true).LV;
484}
485
486LValue
487CodeGenFunction::EmitCoyieldLValue(const CoyieldExpr *E) {
488 assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
489 "Can't have a scalar return unless the return type is a "
490 "reference type!");
491 return emitSuspendExpression(CGF&: *this, Coro&: *CurCoro.Data, S: *E,
492 Kind: AwaitKind::Yield, aggSlot: AggValueSlot::ignored(),
493 /*ignoreResult*/false, /*forLValue*/true).LV;
494}
495
496// Hunts for the parameter reference in the parameter copy/move declaration.
497namespace {
498struct GetParamRef : public StmtVisitor<GetParamRef> {
499public:
500 DeclRefExpr *Expr = nullptr;
501 GetParamRef() {}
502 void VisitDeclRefExpr(DeclRefExpr *E) {
503 assert(Expr == nullptr && "multilple declref in param move");
504 Expr = E;
505 }
506 void VisitStmt(Stmt *S) {
507 for (auto *C : S->children()) {
508 if (C)
509 Visit(S: C);
510 }
511 }
512};
513}
514
515// This class replaces references to parameters to their copies by changing
516// the addresses in CGF.LocalDeclMap and restoring back the original values in
517// its destructor.
518
519namespace {
520 struct ParamReferenceReplacerRAII {
521 CodeGenFunction::DeclMapTy SavedLocals;
522 CodeGenFunction::DeclMapTy& LocalDeclMap;
523
524 ParamReferenceReplacerRAII(CodeGenFunction::DeclMapTy &LocalDeclMap)
525 : LocalDeclMap(LocalDeclMap) {}
526
527 void addCopy(DeclStmt const *PM) {
528 // Figure out what param it refers to.
529
530 assert(PM->isSingleDecl());
531 VarDecl const*VD = static_cast<VarDecl const*>(PM->getSingleDecl());
532 Expr const *InitExpr = VD->getInit();
533 GetParamRef Visitor;
534 Visitor.Visit(S: const_cast<Expr*>(InitExpr));
535 assert(Visitor.Expr);
536 DeclRefExpr *DREOrig = Visitor.Expr;
537 auto *PD = DREOrig->getDecl();
538
539 auto it = LocalDeclMap.find(Val: PD);
540 assert(it != LocalDeclMap.end() && "parameter is not found");
541 SavedLocals.insert(KV: { PD, it->second });
542
543 auto copyIt = LocalDeclMap.find(Val: VD);
544 assert(copyIt != LocalDeclMap.end() && "parameter copy is not found");
545 it->second = copyIt->getSecond();
546 }
547
548 ~ParamReferenceReplacerRAII() {
549 for (auto&& SavedLocal : SavedLocals) {
550 LocalDeclMap.insert(KV: {SavedLocal.first, SavedLocal.second});
551 }
552 }
553 };
554}
555
556// For WinEH exception representation backend needs to know what funclet coro.end
557// belongs to. That information is passed in a funclet bundle.
558static SmallVector<llvm::OperandBundleDef, 1>
559getBundlesForCoroEnd(CodeGenFunction &CGF) {
560 SmallVector<llvm::OperandBundleDef, 1> BundleList;
561
562 if (llvm::Instruction *EHPad = CGF.CurrentFuncletPad)
563 BundleList.emplace_back(Args: "funclet", Args&: EHPad);
564
565 return BundleList;
566}
567
568namespace {
569// We will insert coro.end to cut any of the destructors for objects that
570// do not need to be destroyed once the coroutine is resumed.
571// See llvm/docs/Coroutines.md for more details about coro.end.
572struct CallCoroEnd final : public EHScopeStack::Cleanup {
573 void Emit(CodeGenFunction &CGF, Flags flags) override {
574 auto &CGM = CGF.CGM;
575 auto *NullPtr = llvm::ConstantPointerNull::get(T: CGF.Int8PtrTy);
576 llvm::Function *CoroEndFn = CGM.getIntrinsic(IID: llvm::Intrinsic::coro_end);
577 // See if we have a funclet bundle to associate coro.end with. (WinEH)
578 auto Bundles = getBundlesForCoroEnd(CGF);
579 CGF.Builder.CreateCall(
580 Callee: CoroEndFn,
581 Args: {NullPtr, CGF.Builder.getTrue(),
582 llvm::ConstantTokenNone::get(Context&: CoroEndFn->getContext())},
583 OpBundles: Bundles);
584 if (Bundles.empty()) {
585 // Otherwise, (landingpad model), create a conditional branch that leads
586 // either to a cleanup block or a block with EH resume instruction.
587 auto *ResumeBB = CGF.getEHResumeBlock(/*isCleanup=*/true);
588 auto *CleanupContBB = CGF.createBasicBlock(name: "cleanup.cont");
589 auto *CoroIsInRampFn = CGM.getIntrinsic(IID: llvm::Intrinsic::coro_is_in_ramp);
590 auto *CoroIsInRamp = CGF.Builder.CreateCall(Callee: CoroIsInRampFn);
591 CGF.Builder.CreateCondBr(Cond: CoroIsInRamp, True: CleanupContBB, False: ResumeBB);
592 CGF.EmitBlock(BB: CleanupContBB);
593 }
594 }
595};
596}
597
598namespace {
599// Make sure to call coro.delete on scope exit.
600struct CallCoroDelete final : public EHScopeStack::Cleanup {
601 Stmt *Deallocate;
602
603 // Emit "if (coro.free(CoroId, CoroBegin)) Deallocate;"
604
605 // Note: That deallocation will be emitted twice: once for a normal exit and
606 // once for exceptional exit. This usage is safe because Deallocate does not
607 // contain any declarations. The SubStmtBuilder::makeNewAndDeleteExpr()
608 // builds a single call to a deallocation function which is safe to emit
609 // multiple times.
610 void Emit(CodeGenFunction &CGF, Flags) override {
611 // Remember the current point, as we are going to emit deallocation code
612 // first to get to coro.free instruction that is an argument to a delete
613 // call.
614 BasicBlock *SaveInsertBlock = CGF.Builder.GetInsertBlock();
615
616 auto *FreeBB = CGF.createBasicBlock(name: "coro.free");
617 CGF.EmitBlock(BB: FreeBB);
618 CGF.EmitStmt(S: Deallocate);
619
620 auto *AfterFreeBB = CGF.createBasicBlock(name: "after.coro.free");
621 CGF.EmitBlock(BB: AfterFreeBB);
622
623 // We should have captured coro.free from the emission of deallocate.
624 auto *CoroFree = CGF.CurCoro.Data->LastCoroFree;
625 if (!CoroFree) {
626 CGF.CGM.Error(loc: Deallocate->getBeginLoc(),
627 error: "Deallocation expressoin does not refer to coro.free");
628 return;
629 }
630
631 // Get back to the block we were originally and move coro.free there.
632 auto *InsertPt = SaveInsertBlock->getTerminator();
633 CoroFree->moveBefore(InsertPos: InsertPt->getIterator());
634 CGF.Builder.SetInsertPoint(InsertPt);
635
636 // Add if (auto *mem = coro.free) Deallocate;
637 auto *NullPtr = llvm::ConstantPointerNull::get(T: CGF.Int8PtrTy);
638 auto *Cond = CGF.Builder.CreateICmpNE(LHS: CoroFree, RHS: NullPtr);
639 CGF.Builder.CreateCondBr(Cond, True: FreeBB, False: AfterFreeBB);
640
641 // No longer need old terminator.
642 InsertPt->eraseFromParent();
643 CGF.Builder.SetInsertPoint(AfterFreeBB);
644
645 auto *CoroDeadFn = CGF.CGM.getIntrinsic(IID: llvm::Intrinsic::coro_dead);
646 CGF.Builder.CreateCall(Callee: CoroDeadFn, Args: {CGF.CurCoro.Data->CoroBegin});
647 }
648 explicit CallCoroDelete(Stmt *DeallocStmt) : Deallocate(DeallocStmt) {}
649};
650}
651
652namespace {
653struct GetReturnObjectManager {
654 CodeGenFunction &CGF;
655 CGBuilderTy &Builder;
656 const CoroutineBodyStmt &S;
657 // When true, performs RVO for the return object.
658 bool DirectEmit = false;
659
660 Address GroActiveFlag;
661 CodeGenFunction::AutoVarEmission GroEmission;
662 std::unique_ptr<CodeGenFunction::RunCleanupsScope> GroScope;
663
664 GetReturnObjectManager(CodeGenFunction &CGF, const CoroutineBodyStmt &S)
665 : CGF(CGF), Builder(CGF.Builder), S(S), GroActiveFlag(Address::invalid()),
666 GroEmission(CodeGenFunction::AutoVarEmission::invalid()) {
667 // The call to get_­return_­object is sequenced before the call to
668 // initial_­suspend and is invoked at most once, but there are caveats
669 // regarding on whether the prvalue result object may be initialized
670 // directly/eager or delayed, depending on the types involved.
671 //
672 // More info at https://github.com/cplusplus/papers/issues/1414
673 //
674 // The general cases:
675 // 1. Same type of get_return_object and coroutine return type (direct
676 // emission):
677 // - Constructed in the return slot.
678 // 2. Different types (delayed emission):
679 // - Constructed temporary object prior to initial suspend initialized with
680 // a call to get_return_object()
681 // - When coroutine needs to to return to the caller and needs to construct
682 // return value for the coroutine it is initialized with expiring value of
683 // the temporary obtained above.
684 //
685 // Direct emission for void returning coroutines or GROs.
686 DirectEmit = [&]() {
687 auto *RVI = S.getReturnValueInit();
688 assert(RVI && "expected RVI");
689 auto GroType = RVI->getType();
690 return CGF.getContext().hasSameType(T1: GroType, T2: CGF.FnRetTy);
691 }();
692 }
693
694 // The gro variable has to outlive coroutine frame and coroutine promise, but,
695 // it can only be initialized after coroutine promise was created. Thus,
696 // EmitGroActive emits a flag and sets it to false. Later when coroutine
697 // promise is available we initialize the gro and set the flag indicating that
698 // the cleanup is now active.
699 void EmitGroActive() {
700 if (DirectEmit)
701 return;
702
703 auto *GroDeclStmt = dyn_cast_or_null<DeclStmt>(Val: S.getResultDecl());
704 if (!GroDeclStmt) {
705 // If get_return_object returns void, no need to do an alloca.
706 return;
707 }
708
709 // Set GRO flag that it is not initialized yet
710 GroActiveFlag = CGF.CreateTempAlloca(Ty: Builder.getInt1Ty(), align: CharUnits::One(),
711 Name: "gro.active");
712 Builder.CreateStore(Val: Builder.getFalse(), Addr: GroActiveFlag);
713 }
714
715 void EmitGroAlloca() {
716 if (DirectEmit)
717 return;
718
719 auto *GroDeclStmt = dyn_cast_or_null<DeclStmt>(Val: S.getResultDecl());
720 if (!GroDeclStmt) {
721 // If get_return_object returns void, no need to do an alloca.
722 return;
723 }
724
725 auto *GroVarDecl = cast<VarDecl>(Val: GroDeclStmt->getSingleDecl());
726
727 GroEmission = CGF.EmitAutoVarAlloca(var: *GroVarDecl);
728
729 if (!GroVarDecl->isNRVOVariable()) {
730 // NRVO variables don't have allocas and won't have the same issue.
731 auto *GroAlloca = dyn_cast_or_null<llvm::AllocaInst>(
732 Val: GroEmission.getOriginalAllocatedAddress().getPointer());
733 assert(GroAlloca && "expected alloca to be emitted");
734 GroAlloca->setMetadata(KindID: llvm::LLVMContext::MD_coro_outside_frame,
735 Node: llvm::MDNode::get(Context&: CGF.CGM.getLLVMContext(), MDs: {}));
736 }
737
738 GroScope = std::make_unique<CodeGenFunction::RunCleanupsScope>(args&: CGF);
739 // Remember the top of EHStack before emitting the cleanup.
740 auto old_top = CGF.EHStack.stable_begin();
741 CGF.EmitAutoVarCleanups(emission: GroEmission);
742 auto top = CGF.EHStack.stable_begin();
743
744 // Make the cleanup conditional on gro.active
745 for (auto b = CGF.EHStack.find(sp: top), e = CGF.EHStack.find(sp: old_top); b != e;
746 b++) {
747 if (auto *Cleanup = dyn_cast<EHCleanupScope>(Val: &*b)) {
748 assert(!Cleanup->hasActiveFlag() && "cleanup already has active flag?");
749 Cleanup->setActiveFlag(GroActiveFlag);
750 Cleanup->setTestFlagInEHCleanup();
751 Cleanup->setTestFlagInNormalCleanup();
752 }
753 }
754 }
755
756 Address EmitDirectReturnObjectCleanup() {
757 if (!DirectEmit || !CGF.ReturnValue.isValid())
758 return Address::invalid();
759
760 QualType RetTy = CGF.FnRetTy;
761 QualType::DestructionKind DtorKind = RetTy.isDestructedType();
762 if (DtorKind == QualType::DK_none || !CGF.needsEHCleanup(kind: DtorKind))
763 return Address::invalid();
764
765 Address ActiveFlag = CGF.CreateTempAlloca(
766 Ty: Builder.getInt1Ty(), align: CharUnits::One(), Name: "coro.result.active");
767 Builder.CreateStore(Val: Builder.getFalse(), Addr: ActiveFlag);
768
769 auto OldTop = CGF.EHStack.stable_begin();
770 CGF.pushDestroy(kind: EHCleanup, addr: CGF.ReturnValue, type: RetTy,
771 destroyer: CGF.getDestroyer(destructionKind: DtorKind),
772 /*useEHCleanupForArray*/ true);
773 auto Top = CGF.EHStack.stable_begin();
774
775 for (auto B = CGF.EHStack.find(sp: Top), E = CGF.EHStack.find(sp: OldTop); B != E;
776 ++B) {
777 if (auto *Cleanup = dyn_cast<EHCleanupScope>(Val: &*B)) {
778 assert(!Cleanup->hasActiveFlag() && "cleanup already has active flag?");
779 Cleanup->setActiveFlag(ActiveFlag);
780 Cleanup->setTestFlagInEHCleanup();
781 }
782 }
783 return ActiveFlag;
784 }
785
786 void EmitGroInit() {
787 if (DirectEmit) {
788 // ReturnValue should be valid as long as the coroutine's return type
789 // is not void. The assertion could help us to reduce the check later.
790 assert(CGF.ReturnValue.isValid() == (bool)S.getReturnStmt());
791 // Now we have the promise, initialize the GRO.
792 // We need to emit `get_return_object` first. According to:
793 // [dcl.fct.def.coroutine]p7
794 // The call to get_return_­object is sequenced before the call to
795 // initial_suspend and is invoked at most once.
796 //
797 // So we couldn't emit return value when we emit return statment,
798 // otherwise the call to get_return_object wouldn't be in front
799 // of initial_suspend.
800 if (CGF.ReturnValue.isValid()) {
801 auto ActiveFlag = EmitDirectReturnObjectCleanup();
802 CGF.EmitAnyExprToMem(E: S.getReturnValue(), Location: CGF.ReturnValue,
803 Quals: S.getReturnValue()->getType().getQualifiers(),
804 /*IsInit*/ IsInitializer: true);
805 if (ActiveFlag.isValid())
806 Builder.CreateStore(Val: Builder.getTrue(), Addr: ActiveFlag);
807 }
808 return;
809 }
810
811 if (!GroActiveFlag.isValid()) {
812 // No Gro variable was allocated. Simply emit the call to
813 // get_return_object.
814 CGF.EmitStmt(S: S.getResultDecl());
815 return;
816 }
817
818 CGF.EmitAutoVarInit(emission: GroEmission);
819 Builder.CreateStore(Val: Builder.getTrue(), Addr: GroActiveFlag);
820 }
821 // The GRO returns either when it is first suspended or when it completes
822 // without ever being suspended. The EmitGroConv function evaluates these
823 // conditions and perform the conversion if needed.
824 //
825 // Before EmitGroConv():
826 // final.exit:
827 // switch i32 %cleanup.dest, label %destroy [
828 // i32 0, label %after.ready
829 // ]
830 //
831 // after.ready:
832 // ; (empty)
833 //
834 // After EmitGroConv():
835 // final.exit:
836 // switch i32 %cleanup.dest, label %destroy [
837 // i32 0, label %pre.gro.conv
838 // ]
839 //
840 // pre.gro.conv:
841 // %IsFinalExit = phi i1 [ false, %any.suspend ], [ true, %final.exit ]
842 // %InRamp = call i1 @llvm.coro.is_in_ramp()
843 // br i1 %InRamp, label %gro.conv, label %after.gro.conv
844 //
845 // gro.conv:
846 // ; GRO conversion
847 // br label %after.gro.conv
848 //
849 // after.gro.conv:
850 // br i1 %IsFinalExit, label %after.ready, label %coro.ret
851 void EmitGroConv(BasicBlock *RetBB) {
852 auto *AfterReadyBB = Builder.GetInsertBlock();
853 Builder.ClearInsertionPoint();
854
855 auto *PreConvBB = CGF.CurCoro.Data->SuspendBB;
856 CGF.EmitBlock(BB: PreConvBB);
857 // If final.exit exists, redirect it to PreConvBB
858 llvm::PHINode *IsFinalExit = nullptr;
859 if (BasicBlock *FinalExit = CGF.CurCoro.Data->FinalExit) {
860 assert(AfterReadyBB &&
861 AfterReadyBB->getSinglePredecessor() == FinalExit &&
862 "Expect fallthrough from final.exit block");
863 AfterReadyBB->replaceAllUsesWith(V: PreConvBB);
864 PreConvBB->moveBefore(MovePos: AfterReadyBB);
865
866 // If true, coroutine completes and should be destroyed after conversion
867 IsFinalExit =
868 Builder.CreatePHI(Ty: Builder.getInt1Ty(), NumReservedValues: llvm::pred_size(BB: PreConvBB));
869 for (auto *Pred : llvm::predecessors(BB: PreConvBB)) {
870 auto *V = (Pred == FinalExit) ? Builder.getTrue() : Builder.getFalse();
871 IsFinalExit->addIncoming(V, BB: Pred);
872 }
873 }
874 auto *InRampFn = CGF.CGM.getIntrinsic(IID: llvm::Intrinsic::coro_is_in_ramp);
875 auto *InRamp = Builder.CreateCall(Callee: InRampFn, Args: {}, Name: "InRamp");
876 auto *ConvBB = CGF.createBasicBlock(name: "gro.conv");
877 auto *AfterConvBB = CGF.createBasicBlock(name: "after.gro.conv");
878 Builder.CreateCondBr(Cond: InRamp, True: ConvBB, False: AfterConvBB);
879
880 CGF.EmitBlock(BB: ConvBB);
881 CGF.EmitAnyExprToMem(E: S.getReturnValue(), Location: CGF.ReturnValue,
882 Quals: S.getReturnValue()->getType().getQualifiers(),
883 /*IsInit*/ IsInitializer: true);
884 GroScope->ForceCleanup();
885 Builder.CreateBr(Dest: AfterConvBB);
886
887 CGF.EmitBlock(BB: AfterConvBB);
888 if (IsFinalExit)
889 Builder.CreateCondBr(Cond: IsFinalExit, True: AfterReadyBB, False: RetBB);
890 else
891 Builder.CreateBr(Dest: RetBB);
892 Builder.SetInsertPoint(AfterReadyBB);
893 }
894};
895} // namespace
896
897static void emitBodyAndFallthrough(CodeGenFunction &CGF,
898 const CoroutineBodyStmt &S, Stmt *Body) {
899 CGF.EmitStmt(S: Body);
900 const bool CanFallthrough = CGF.Builder.GetInsertBlock();
901 if (CanFallthrough)
902 if (Stmt *OnFallthrough = S.getFallthroughHandler())
903 CGF.EmitStmt(S: OnFallthrough);
904}
905
906void CodeGenFunction::EmitCoroutineBody(const CoroutineBodyStmt &S) {
907 auto *NullPtr = llvm::ConstantPointerNull::get(T: Builder.getPtrTy());
908 auto &TI = CGM.getContext().getTargetInfo();
909 unsigned NewAlign = TI.getNewAlign() / TI.getCharWidth();
910
911 auto *EntryBB = Builder.GetInsertBlock();
912 auto *AllocBB = createBasicBlock(name: "coro.alloc");
913 auto *InitBB = createBasicBlock(name: "coro.init");
914 auto *FinalBB = createBasicBlock(name: "coro.final");
915 auto *CleanupBB = createBasicBlock(name: "coro.cleanup");
916 auto *RetBB = createBasicBlock(name: "coro.ret");
917
918 auto *CoroId = Builder.CreateCall(
919 Callee: CGM.getIntrinsic(IID: llvm::Intrinsic::coro_id),
920 Args: {Builder.getInt32(C: NewAlign), NullPtr, NullPtr, NullPtr});
921 createCoroData(CGF&: *this, CurCoro, CoroId);
922
923 GetReturnObjectManager GroManager(*this, S);
924 CurCoro.Data->SuspendBB =
925 GroManager.DirectEmit ? RetBB : createBasicBlock(name: "pre.gvo.conv");
926 assert(ShouldEmitLifetimeMarkers &&
927 "Must emit lifetime intrinsics for coroutines");
928
929 // Backend is allowed to elide memory allocations, to help it, emit
930 // auto mem = coro.alloc() ? 0 : ... allocation code ...;
931 auto *CoroAlloc = Builder.CreateCall(
932 Callee: CGM.getIntrinsic(IID: llvm::Intrinsic::coro_alloc), Args: {CoroId});
933
934 Builder.CreateCondBr(Cond: CoroAlloc, True: AllocBB, False: InitBB);
935
936 EmitBlock(BB: AllocBB);
937 auto *AllocateCall = EmitScalarExpr(E: S.getAllocate());
938 auto *AllocOrInvokeContBB = Builder.GetInsertBlock();
939
940 // Handle allocation failure if 'ReturnStmtOnAllocFailure' was provided.
941 if (auto *RetOnAllocFailure = S.getReturnStmtOnAllocFailure()) {
942 auto *RetOnFailureBB = createBasicBlock(name: "coro.ret.on.failure");
943
944 // See if allocation was successful.
945 auto *NullPtr = llvm::ConstantPointerNull::get(T: Int8PtrTy);
946 auto *Cond = Builder.CreateICmpNE(LHS: AllocateCall, RHS: NullPtr);
947 // Expect the allocation to be successful.
948 emitCondLikelihoodViaExpectIntrinsic(Cond, LH: Stmt::LH_Likely);
949 Builder.CreateCondBr(Cond, True: InitBB, False: RetOnFailureBB);
950
951 // If not, return OnAllocFailure object.
952 EmitBlock(BB: RetOnFailureBB);
953 EmitStmt(S: RetOnAllocFailure);
954 }
955 else {
956 Builder.CreateBr(Dest: InitBB);
957 }
958
959 EmitBlock(BB: InitBB);
960
961 // Pass the result of the allocation to coro.begin.
962 auto *Phi = Builder.CreatePHI(Ty: VoidPtrTy, NumReservedValues: 2);
963 Phi->addIncoming(V: NullPtr, BB: EntryBB);
964 Phi->addIncoming(V: AllocateCall, BB: AllocOrInvokeContBB);
965 auto *CoroBegin = Builder.CreateCall(
966 Callee: CGM.getIntrinsic(IID: llvm::Intrinsic::coro_begin), Args: {CoroId, Phi});
967 CurCoro.Data->CoroBegin = CoroBegin;
968 {
969 CGDebugInfo *DI = getDebugInfo();
970 ParamReferenceReplacerRAII ParamReplacer(LocalDeclMap);
971 CodeGenFunction::RunCleanupsScope ResumeScope(*this);
972 EHStack.pushCleanup<CallCoroDelete>(Kind: NormalAndEHCleanup, A: S.getDeallocate());
973
974 // Create mapping between parameters and copy-params for coroutine function.
975 llvm::ArrayRef<const Stmt *> ParamMoves = S.getParamMoves();
976 assert(
977 (ParamMoves.size() == 0 || (ParamMoves.size() == FnArgs.size())) &&
978 "ParamMoves and FnArgs should be the same size for coroutine function");
979 if (ParamMoves.size() == FnArgs.size() && DI)
980 for (const auto Pair : llvm::zip(t&: FnArgs, u&: ParamMoves))
981 DI->getCoroutineParameterMappings().insert(
982 KV: {std::get<0>(t: Pair), std::get<1>(t: Pair)});
983
984 // Create parameter copies. We do it before creating a promise, since an
985 // evolution of coroutine TS may allow promise constructor to observe
986 // parameter copies.
987 for (const ParmVarDecl *Parm : FnArgs) {
988 // If the original param is in an alloca, exclude it from the coroutine
989 // frame. The parameter copy will be part of the frame, but the original
990 // parameter memory should remain on the stack. This is necessary to
991 // ensure that parameters destroyed in callees, as with `trivial_abi` or
992 // in the MSVC C++ ABI, are appropriately destroyed after setting up the
993 // coroutine.
994 Address ParmAddr = GetAddrOfLocalVar(VD: Parm);
995 if (auto *ParmAlloca =
996 dyn_cast<llvm::AllocaInst>(Val: ParmAddr.getBasePointer())) {
997 ParmAlloca->setMetadata(KindID: llvm::LLVMContext::MD_coro_outside_frame,
998 Node: llvm::MDNode::get(Context&: CGM.getLLVMContext(), MDs: {}));
999 }
1000 }
1001 for (auto *PM : S.getParamMoves()) {
1002 EmitStmt(S: PM);
1003 ParamReplacer.addCopy(PM: cast<DeclStmt>(Val: PM));
1004 // TODO: if(CoroParam(...)) need to surround ctor and dtor
1005 // for the copy, so that llvm can elide it if the copy is
1006 // not needed.
1007 }
1008
1009 GroManager.EmitGroActive();
1010 EmitStmt(S: S.getPromiseDeclStmt());
1011
1012 Address PromiseAddr = GetAddrOfLocalVar(VD: S.getPromiseDecl());
1013 // Update CoroId to refer to the promise. We could not do it earlier because
1014 // promise local variable was not emitted yet.
1015 CoroId->setArgOperand(i: 1, v: PromiseAddr.emitRawPointer(CGF&: *this));
1016
1017 // Now we have the promise, initialize the GRO
1018 GroManager.EmitGroAlloca();
1019 GroManager.EmitGroInit();
1020
1021 EHStack.pushCleanup<CallCoroEnd>(Kind: EHCleanup);
1022
1023 CurCoro.Data->CleanupJD = getJumpDestInCurrentScope(Target: CleanupBB);
1024 CurCoro.Data->CurrentAwaitKind = AwaitKind::Init;
1025 CurCoro.Data->ExceptionHandler = S.getExceptionHandler();
1026 EmitStmt(S: S.getInitSuspendStmt());
1027 CurCoro.Data->FinalJD = getJumpDestInCurrentScope(Target: FinalBB);
1028
1029 CurCoro.Data->CurrentAwaitKind = AwaitKind::Normal;
1030
1031 if (CurCoro.Data->ExceptionHandler) {
1032 // If we generated IR to record whether an exception was thrown from
1033 // 'await_resume', then use that IR to determine whether the coroutine
1034 // body should be skipped.
1035 // If we didn't generate the IR (perhaps because 'await_resume' was marked
1036 // as 'noexcept'), then we skip this check.
1037 BasicBlock *ContBB = nullptr;
1038 if (CurCoro.Data->ResumeEHVar) {
1039 BasicBlock *BodyBB = createBasicBlock(name: "coro.resumed.body");
1040 ContBB = createBasicBlock(name: "coro.resumed.cont");
1041 Value *SkipBody = Builder.CreateFlagLoad(Addr: CurCoro.Data->ResumeEHVar,
1042 Name: "coro.resumed.eh");
1043 Builder.CreateCondBr(Cond: SkipBody, True: ContBB, False: BodyBB);
1044 EmitBlock(BB: BodyBB);
1045 }
1046
1047 auto Loc = S.getBeginLoc();
1048 CXXCatchStmt Catch(Loc, /*exDecl=*/nullptr,
1049 CurCoro.Data->ExceptionHandler);
1050 auto *TryStmt =
1051 CXXTryStmt::Create(C: getContext(), tryLoc: Loc, tryBlock: S.getBody(), handlers: &Catch);
1052
1053 EnterCXXTryStmt(S: *TryStmt);
1054 emitBodyAndFallthrough(CGF&: *this, S, Body: TryStmt->getTryBlock());
1055 ExitCXXTryStmt(S: *TryStmt);
1056
1057 if (ContBB)
1058 EmitBlock(BB: ContBB);
1059 }
1060 else {
1061 emitBodyAndFallthrough(CGF&: *this, S, Body: S.getBody());
1062 }
1063
1064 // See if we need to generate final suspend.
1065 const bool CanFallthrough = Builder.GetInsertBlock();
1066 const bool HasCoreturns = CurCoro.Data->CoreturnCount > 0;
1067 if (CanFallthrough || HasCoreturns) {
1068 EmitBlock(BB: FinalBB);
1069 CurCoro.Data->CurrentAwaitKind = AwaitKind::Final;
1070 EmitStmt(S: S.getFinalSuspendStmt());
1071 } else {
1072 // We don't need FinalBB. Emit it to make sure the block is deleted.
1073 EmitBlock(BB: FinalBB, /*IsFinished=*/true);
1074 }
1075
1076 // We need conversion if get_return_object's type doesn't matches the
1077 // coroutine return type.
1078 if (!GroManager.DirectEmit)
1079 GroManager.EmitGroConv(RetBB);
1080 EmitBlock(BB: CleanupBB);
1081 }
1082
1083 EmitBlock(BB: RetBB);
1084 // Emit coro.end before ret instruction, since resume and destroy parts of the
1085 // coroutine should return void.
1086 llvm::Function *CoroEnd = CGM.getIntrinsic(IID: llvm::Intrinsic::coro_end);
1087 Builder.CreateCall(Callee: CoroEnd,
1088 Args: {NullPtr, Builder.getFalse(),
1089 llvm::ConstantTokenNone::get(Context&: CoroEnd->getContext())});
1090
1091 if (auto *Ret = cast_or_null<ReturnStmt>(Val: S.getReturnStmt())) {
1092 // Since we already emitted the return value above, so we shouldn't
1093 // emit it again here.
1094 Expr *PreviousRetValue = Ret->getRetValue();
1095 Ret->setRetValue(nullptr);
1096 EmitStmt(S: Ret);
1097 // Set the return value back. The code generator, as the AST **Consumer**,
1098 // shouldn't change the AST.
1099 Ret->setRetValue(PreviousRetValue);
1100 }
1101 // LLVM require the frontend to mark the coroutine.
1102 CurFn->setPresplitCoroutine();
1103
1104 if (CXXRecordDecl *RD = FnRetTy->getAsCXXRecordDecl();
1105 RD && RD->hasAttr<CoroOnlyDestroyWhenCompleteAttr>())
1106 CurFn->setCoroDestroyOnlyWhenComplete();
1107}
1108
1109// Emit coroutine intrinsic and patch up arguments of the token type.
1110RValue CodeGenFunction::EmitCoroutineIntrinsic(const CallExpr *E,
1111 unsigned int IID) {
1112 SmallVector<llvm::Value *, 8> Args;
1113 switch (IID) {
1114 default:
1115 break;
1116 // The coro.frame builtin is replaced with an SSA value of the coro.begin
1117 // intrinsic.
1118 case llvm::Intrinsic::coro_frame: {
1119 if (CurCoro.Data && CurCoro.Data->CoroBegin) {
1120 return RValue::get(V: CurCoro.Data->CoroBegin);
1121 }
1122
1123 if (CurAwaitSuspendWrapper.FramePtr) {
1124 return RValue::get(V: CurAwaitSuspendWrapper.FramePtr);
1125 }
1126
1127 CGM.Error(loc: E->getBeginLoc(), error: "this builtin expect that __builtin_coro_begin "
1128 "has been used earlier in this function");
1129 auto *NullPtr = llvm::ConstantPointerNull::get(T: Builder.getPtrTy());
1130 return RValue::get(V: NullPtr);
1131 }
1132 case llvm::Intrinsic::coro_size: {
1133 auto &Context = getContext();
1134 llvm::IntegerType *T =
1135 Builder.getIntNTy(N: Context.getTypeSize(T: Context.getSizeType()));
1136 llvm::Function *F = CGM.getIntrinsic(IID: llvm::Intrinsic::coro_size, Tys: T);
1137 return RValue::get(V: Builder.CreateCall(Callee: F));
1138 }
1139 case llvm::Intrinsic::coro_align: {
1140 auto &Context = getContext();
1141 llvm::IntegerType *T =
1142 Builder.getIntNTy(N: Context.getTypeSize(T: Context.getSizeType()));
1143 llvm::Function *F = CGM.getIntrinsic(IID: llvm::Intrinsic::coro_align, Tys: T);
1144 return RValue::get(V: Builder.CreateCall(Callee: F));
1145 }
1146 // The following three intrinsics take a token parameter referring to a token
1147 // returned by earlier call to @llvm.coro.id. Since we cannot represent it in
1148 // builtins, we patch it up here.
1149 case llvm::Intrinsic::coro_alloc:
1150 case llvm::Intrinsic::coro_begin:
1151 case llvm::Intrinsic::coro_free: {
1152 if (CurCoro.Data && CurCoro.Data->CoroId) {
1153 Args.push_back(Elt: CurCoro.Data->CoroId);
1154 break;
1155 }
1156 CGM.Error(loc: E->getBeginLoc(), error: "this builtin expect that __builtin_coro_id has"
1157 " been used earlier in this function");
1158 // Fallthrough to the next case to add TokenNone as the first argument.
1159 [[fallthrough]];
1160 }
1161 // @llvm.coro.suspend takes a token parameter. Add token 'none' as the first
1162 // argument.
1163 case llvm::Intrinsic::coro_suspend:
1164 Args.push_back(Elt: llvm::ConstantTokenNone::get(Context&: getLLVMContext()));
1165 break;
1166 }
1167 for (const Expr *Arg : E->arguments())
1168 Args.push_back(Elt: EmitScalarExpr(E: Arg));
1169 // @llvm.coro.end takes a token parameter. Add token 'none' as the last
1170 // argument.
1171 if (IID == llvm::Intrinsic::coro_end)
1172 Args.push_back(Elt: llvm::ConstantTokenNone::get(Context&: getLLVMContext()));
1173
1174 llvm::Function *F = CGM.getIntrinsic(IID);
1175 llvm::CallInst *Call = Builder.CreateCall(Callee: F, Args);
1176
1177 // Note: The following code is to enable to emit coro.id and coro.begin by
1178 // hand to experiment with coroutines in C.
1179 // If we see @llvm.coro.id remember it in the CoroData. We will update
1180 // coro.alloc, coro.begin and coro.free intrinsics to refer to it.
1181 if (IID == llvm::Intrinsic::coro_id) {
1182 createCoroData(CGF&: *this, CurCoro, CoroId: Call, CoroIdExpr: E);
1183 }
1184 else if (IID == llvm::Intrinsic::coro_begin) {
1185 if (CurCoro.Data)
1186 CurCoro.Data->CoroBegin = Call;
1187 }
1188 else if (IID == llvm::Intrinsic::coro_free) {
1189 // Remember the last coro_free as we need it to build the conditional
1190 // deletion of the coroutine frame.
1191 if (CurCoro.Data)
1192 CurCoro.Data->LastCoroFree = Call;
1193 }
1194 return RValue::get(V: Call);
1195}
1196