xref: /openbsd-src/gnu/llvm/clang/lib/CodeGen/CGCoroutine.cpp (revision 12c855180aad702bbcca06e0398d774beeafb155)
1e5dd7070Spatrick //===----- CGCoroutine.cpp - Emit LLVM Code for C++ coroutines ------------===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick // This contains code dealing with C++ code generation of coroutines.
10e5dd7070Spatrick //
11e5dd7070Spatrick //===----------------------------------------------------------------------===//
12e5dd7070Spatrick 
13e5dd7070Spatrick #include "CGCleanup.h"
14e5dd7070Spatrick #include "CodeGenFunction.h"
15e5dd7070Spatrick #include "llvm/ADT/ScopeExit.h"
16e5dd7070Spatrick #include "clang/AST/StmtCXX.h"
17e5dd7070Spatrick #include "clang/AST/StmtVisitor.h"
18e5dd7070Spatrick 
19e5dd7070Spatrick using namespace clang;
20e5dd7070Spatrick using namespace CodeGen;
21e5dd7070Spatrick 
22e5dd7070Spatrick using llvm::Value;
23e5dd7070Spatrick using llvm::BasicBlock;
24e5dd7070Spatrick 
25e5dd7070Spatrick namespace {
26e5dd7070Spatrick enum class AwaitKind { Init, Normal, Yield, Final };
27e5dd7070Spatrick static constexpr llvm::StringLiteral AwaitKindStr[] = {"init", "await", "yield",
28e5dd7070Spatrick                                                        "final"};
29e5dd7070Spatrick }
30e5dd7070Spatrick 
31e5dd7070Spatrick struct clang::CodeGen::CGCoroData {
32e5dd7070Spatrick   // What is the current await expression kind and how many
33e5dd7070Spatrick   // await/yield expressions were encountered so far.
34e5dd7070Spatrick   // These are used to generate pretty labels for await expressions in LLVM IR.
35e5dd7070Spatrick   AwaitKind CurrentAwaitKind = AwaitKind::Init;
36e5dd7070Spatrick   unsigned AwaitNum = 0;
37e5dd7070Spatrick   unsigned YieldNum = 0;
38e5dd7070Spatrick 
39e5dd7070Spatrick   // How many co_return statements are in the coroutine. Used to decide whether
40e5dd7070Spatrick   // we need to add co_return; equivalent at the end of the user authored body.
41e5dd7070Spatrick   unsigned CoreturnCount = 0;
42e5dd7070Spatrick 
43e5dd7070Spatrick   // A branch to this block is emitted when coroutine needs to suspend.
44e5dd7070Spatrick   llvm::BasicBlock *SuspendBB = nullptr;
45e5dd7070Spatrick 
46e5dd7070Spatrick   // The promise type's 'unhandled_exception' handler, if it defines one.
47e5dd7070Spatrick   Stmt *ExceptionHandler = nullptr;
48e5dd7070Spatrick 
49e5dd7070Spatrick   // A temporary i1 alloca that stores whether 'await_resume' threw an
50e5dd7070Spatrick   // exception. If it did, 'true' is stored in this variable, and the coroutine
51e5dd7070Spatrick   // body must be skipped. If the promise type does not define an exception
52e5dd7070Spatrick   // handler, this is null.
53e5dd7070Spatrick   llvm::Value *ResumeEHVar = nullptr;
54e5dd7070Spatrick 
55e5dd7070Spatrick   // Stores the jump destination just before the coroutine memory is freed.
56e5dd7070Spatrick   // This is the destination that every suspend point jumps to for the cleanup
57e5dd7070Spatrick   // branch.
58e5dd7070Spatrick   CodeGenFunction::JumpDest CleanupJD;
59e5dd7070Spatrick 
60e5dd7070Spatrick   // Stores the jump destination just before the final suspend. The co_return
61e5dd7070Spatrick   // statements jumps to this point after calling return_xxx promise member.
62e5dd7070Spatrick   CodeGenFunction::JumpDest FinalJD;
63e5dd7070Spatrick 
64e5dd7070Spatrick   // Stores the llvm.coro.id emitted in the function so that we can supply it
65e5dd7070Spatrick   // as the first argument to coro.begin, coro.alloc and coro.free intrinsics.
66e5dd7070Spatrick   // Note: llvm.coro.id returns a token that cannot be directly expressed in a
67e5dd7070Spatrick   // builtin.
68e5dd7070Spatrick   llvm::CallInst *CoroId = nullptr;
69e5dd7070Spatrick 
70e5dd7070Spatrick   // Stores the llvm.coro.begin emitted in the function so that we can replace
71e5dd7070Spatrick   // all coro.frame intrinsics with direct SSA value of coro.begin that returns
72e5dd7070Spatrick   // the address of the coroutine frame of the current coroutine.
73e5dd7070Spatrick   llvm::CallInst *CoroBegin = nullptr;
74e5dd7070Spatrick 
75e5dd7070Spatrick   // Stores the last emitted coro.free for the deallocate expressions, we use it
76e5dd7070Spatrick   // to wrap dealloc code with if(auto mem = coro.free) dealloc(mem).
77e5dd7070Spatrick   llvm::CallInst *LastCoroFree = nullptr;
78e5dd7070Spatrick 
79e5dd7070Spatrick   // If coro.id came from the builtin, remember the expression to give better
80e5dd7070Spatrick   // diagnostic. If CoroIdExpr is nullptr, the coro.id was created by
81e5dd7070Spatrick   // EmitCoroutineBody.
82e5dd7070Spatrick   CallExpr const *CoroIdExpr = nullptr;
83e5dd7070Spatrick };
84e5dd7070Spatrick 
85e5dd7070Spatrick // Defining these here allows to keep CGCoroData private to this file.
CGCoroInfo()86e5dd7070Spatrick clang::CodeGen::CodeGenFunction::CGCoroInfo::CGCoroInfo() {}
~CGCoroInfo()87e5dd7070Spatrick CodeGenFunction::CGCoroInfo::~CGCoroInfo() {}
88e5dd7070Spatrick 
createCoroData(CodeGenFunction & CGF,CodeGenFunction::CGCoroInfo & CurCoro,llvm::CallInst * CoroId,CallExpr const * CoroIdExpr=nullptr)89e5dd7070Spatrick static void createCoroData(CodeGenFunction &CGF,
90e5dd7070Spatrick                            CodeGenFunction::CGCoroInfo &CurCoro,
91e5dd7070Spatrick                            llvm::CallInst *CoroId,
92e5dd7070Spatrick                            CallExpr const *CoroIdExpr = nullptr) {
93e5dd7070Spatrick   if (CurCoro.Data) {
94e5dd7070Spatrick     if (CurCoro.Data->CoroIdExpr)
95e5dd7070Spatrick       CGF.CGM.Error(CoroIdExpr->getBeginLoc(),
96e5dd7070Spatrick                     "only one __builtin_coro_id can be used in a function");
97e5dd7070Spatrick     else if (CoroIdExpr)
98e5dd7070Spatrick       CGF.CGM.Error(CoroIdExpr->getBeginLoc(),
99e5dd7070Spatrick                     "__builtin_coro_id shall not be used in a C++ coroutine");
100e5dd7070Spatrick     else
101e5dd7070Spatrick       llvm_unreachable("EmitCoroutineBodyStatement called twice?");
102e5dd7070Spatrick 
103e5dd7070Spatrick     return;
104e5dd7070Spatrick   }
105e5dd7070Spatrick 
106e5dd7070Spatrick   CurCoro.Data = std::unique_ptr<CGCoroData>(new CGCoroData);
107e5dd7070Spatrick   CurCoro.Data->CoroId = CoroId;
108e5dd7070Spatrick   CurCoro.Data->CoroIdExpr = CoroIdExpr;
109e5dd7070Spatrick }
110e5dd7070Spatrick 
111e5dd7070Spatrick // Synthesize a pretty name for a suspend point.
buildSuspendPrefixStr(CGCoroData & Coro,AwaitKind Kind)112e5dd7070Spatrick static SmallString<32> buildSuspendPrefixStr(CGCoroData &Coro, AwaitKind Kind) {
113e5dd7070Spatrick   unsigned No = 0;
114e5dd7070Spatrick   switch (Kind) {
115e5dd7070Spatrick   case AwaitKind::Init:
116e5dd7070Spatrick   case AwaitKind::Final:
117e5dd7070Spatrick     break;
118e5dd7070Spatrick   case AwaitKind::Normal:
119e5dd7070Spatrick     No = ++Coro.AwaitNum;
120e5dd7070Spatrick     break;
121e5dd7070Spatrick   case AwaitKind::Yield:
122e5dd7070Spatrick     No = ++Coro.YieldNum;
123e5dd7070Spatrick     break;
124e5dd7070Spatrick   }
125e5dd7070Spatrick   SmallString<32> Prefix(AwaitKindStr[static_cast<unsigned>(Kind)]);
126e5dd7070Spatrick   if (No > 1) {
127e5dd7070Spatrick     Twine(No).toVector(Prefix);
128e5dd7070Spatrick   }
129e5dd7070Spatrick   return Prefix;
130e5dd7070Spatrick }
131e5dd7070Spatrick 
memberCallExpressionCanThrow(const Expr * E)132e5dd7070Spatrick static bool memberCallExpressionCanThrow(const Expr *E) {
133e5dd7070Spatrick   if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
134e5dd7070Spatrick     if (const auto *Proto =
135e5dd7070Spatrick             CE->getMethodDecl()->getType()->getAs<FunctionProtoType>())
136e5dd7070Spatrick       if (isNoexceptExceptionSpec(Proto->getExceptionSpecType()) &&
137e5dd7070Spatrick           Proto->canThrow() == CT_Cannot)
138e5dd7070Spatrick         return false;
139e5dd7070Spatrick   return true;
140e5dd7070Spatrick }
141e5dd7070Spatrick 
142e5dd7070Spatrick // Emit suspend expression which roughly looks like:
143e5dd7070Spatrick //
144e5dd7070Spatrick //   auto && x = CommonExpr();
145e5dd7070Spatrick //   if (!x.await_ready()) {
146e5dd7070Spatrick //      llvm_coro_save();
147e5dd7070Spatrick //      x.await_suspend(...);     (*)
148e5dd7070Spatrick //      llvm_coro_suspend(); (**)
149e5dd7070Spatrick //   }
150e5dd7070Spatrick //   x.await_resume();
151e5dd7070Spatrick //
152e5dd7070Spatrick // where the result of the entire expression is the result of x.await_resume()
153e5dd7070Spatrick //
154e5dd7070Spatrick //   (*) If x.await_suspend return type is bool, it allows to veto a suspend:
155e5dd7070Spatrick //      if (x.await_suspend(...))
156e5dd7070Spatrick //        llvm_coro_suspend();
157e5dd7070Spatrick //
158e5dd7070Spatrick //  (**) llvm_coro_suspend() encodes three possible continuations as
159e5dd7070Spatrick //       a switch instruction:
160e5dd7070Spatrick //
161e5dd7070Spatrick //  %where-to = call i8 @llvm.coro.suspend(...)
162e5dd7070Spatrick //  switch i8 %where-to, label %coro.ret [ ; jump to epilogue to suspend
163e5dd7070Spatrick //    i8 0, label %yield.ready   ; go here when resumed
164e5dd7070Spatrick //    i8 1, label %yield.cleanup ; go here when destroyed
165e5dd7070Spatrick //  ]
166e5dd7070Spatrick //
167e5dd7070Spatrick //  See llvm's docs/Coroutines.rst for more details.
168e5dd7070Spatrick //
169e5dd7070Spatrick namespace {
170e5dd7070Spatrick   struct LValueOrRValue {
171e5dd7070Spatrick     LValue LV;
172e5dd7070Spatrick     RValue RV;
173e5dd7070Spatrick   };
174e5dd7070Spatrick }
emitSuspendExpression(CodeGenFunction & CGF,CGCoroData & Coro,CoroutineSuspendExpr const & S,AwaitKind Kind,AggValueSlot aggSlot,bool ignoreResult,bool forLValue)175e5dd7070Spatrick static LValueOrRValue emitSuspendExpression(CodeGenFunction &CGF, CGCoroData &Coro,
176e5dd7070Spatrick                                     CoroutineSuspendExpr const &S,
177e5dd7070Spatrick                                     AwaitKind Kind, AggValueSlot aggSlot,
178e5dd7070Spatrick                                     bool ignoreResult, bool forLValue) {
179e5dd7070Spatrick   auto *E = S.getCommonExpr();
180e5dd7070Spatrick 
181e5dd7070Spatrick   auto Binder =
182e5dd7070Spatrick       CodeGenFunction::OpaqueValueMappingData::bind(CGF, S.getOpaqueValue(), E);
183e5dd7070Spatrick   auto UnbindOnExit = llvm::make_scope_exit([&] { Binder.unbind(CGF); });
184e5dd7070Spatrick 
185e5dd7070Spatrick   auto Prefix = buildSuspendPrefixStr(Coro, Kind);
186e5dd7070Spatrick   BasicBlock *ReadyBlock = CGF.createBasicBlock(Prefix + Twine(".ready"));
187e5dd7070Spatrick   BasicBlock *SuspendBlock = CGF.createBasicBlock(Prefix + Twine(".suspend"));
188e5dd7070Spatrick   BasicBlock *CleanupBlock = CGF.createBasicBlock(Prefix + Twine(".cleanup"));
189e5dd7070Spatrick 
190e5dd7070Spatrick   // If expression is ready, no need to suspend.
191e5dd7070Spatrick   CGF.EmitBranchOnBoolExpr(S.getReadyExpr(), ReadyBlock, SuspendBlock, 0);
192e5dd7070Spatrick 
193e5dd7070Spatrick   // Otherwise, emit suspend logic.
194e5dd7070Spatrick   CGF.EmitBlock(SuspendBlock);
195e5dd7070Spatrick 
196e5dd7070Spatrick   auto &Builder = CGF.Builder;
197e5dd7070Spatrick   llvm::Function *CoroSave = CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_save);
198e5dd7070Spatrick   auto *NullPtr = llvm::ConstantPointerNull::get(CGF.CGM.Int8PtrTy);
199e5dd7070Spatrick   auto *SaveCall = Builder.CreateCall(CoroSave, {NullPtr});
200e5dd7070Spatrick 
201e5dd7070Spatrick   auto *SuspendRet = CGF.EmitScalarExpr(S.getSuspendExpr());
202e5dd7070Spatrick   if (SuspendRet != nullptr && SuspendRet->getType()->isIntegerTy(1)) {
203e5dd7070Spatrick     // Veto suspension if requested by bool returning await_suspend.
204e5dd7070Spatrick     BasicBlock *RealSuspendBlock =
205e5dd7070Spatrick         CGF.createBasicBlock(Prefix + Twine(".suspend.bool"));
206e5dd7070Spatrick     CGF.Builder.CreateCondBr(SuspendRet, RealSuspendBlock, ReadyBlock);
207e5dd7070Spatrick     CGF.EmitBlock(RealSuspendBlock);
208e5dd7070Spatrick   }
209e5dd7070Spatrick 
210e5dd7070Spatrick   // Emit the suspend point.
211e5dd7070Spatrick   const bool IsFinalSuspend = (Kind == AwaitKind::Final);
212e5dd7070Spatrick   llvm::Function *CoroSuspend =
213e5dd7070Spatrick       CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_suspend);
214e5dd7070Spatrick   auto *SuspendResult = Builder.CreateCall(
215e5dd7070Spatrick       CoroSuspend, {SaveCall, Builder.getInt1(IsFinalSuspend)});
216e5dd7070Spatrick 
217e5dd7070Spatrick   // Create a switch capturing three possible continuations.
218e5dd7070Spatrick   auto *Switch = Builder.CreateSwitch(SuspendResult, Coro.SuspendBB, 2);
219e5dd7070Spatrick   Switch->addCase(Builder.getInt8(0), ReadyBlock);
220e5dd7070Spatrick   Switch->addCase(Builder.getInt8(1), CleanupBlock);
221e5dd7070Spatrick 
222e5dd7070Spatrick   // Emit cleanup for this suspend point.
223e5dd7070Spatrick   CGF.EmitBlock(CleanupBlock);
224e5dd7070Spatrick   CGF.EmitBranchThroughCleanup(Coro.CleanupJD);
225e5dd7070Spatrick 
226e5dd7070Spatrick   // Emit await_resume expression.
227e5dd7070Spatrick   CGF.EmitBlock(ReadyBlock);
228e5dd7070Spatrick 
229e5dd7070Spatrick   // Exception handling requires additional IR. If the 'await_resume' function
230e5dd7070Spatrick   // is marked as 'noexcept', we avoid generating this additional IR.
231e5dd7070Spatrick   CXXTryStmt *TryStmt = nullptr;
232e5dd7070Spatrick   if (Coro.ExceptionHandler && Kind == AwaitKind::Init &&
233e5dd7070Spatrick       memberCallExpressionCanThrow(S.getResumeExpr())) {
234e5dd7070Spatrick     Coro.ResumeEHVar =
235e5dd7070Spatrick         CGF.CreateTempAlloca(Builder.getInt1Ty(), Prefix + Twine("resume.eh"));
236e5dd7070Spatrick     Builder.CreateFlagStore(true, Coro.ResumeEHVar);
237e5dd7070Spatrick 
238e5dd7070Spatrick     auto Loc = S.getResumeExpr()->getExprLoc();
239e5dd7070Spatrick     auto *Catch = new (CGF.getContext())
240e5dd7070Spatrick         CXXCatchStmt(Loc, /*exDecl=*/nullptr, Coro.ExceptionHandler);
241*12c85518Srobert     auto *TryBody = CompoundStmt::Create(CGF.getContext(), S.getResumeExpr(),
242*12c85518Srobert                                          FPOptionsOverride(), Loc, Loc);
243e5dd7070Spatrick     TryStmt = CXXTryStmt::Create(CGF.getContext(), Loc, TryBody, Catch);
244e5dd7070Spatrick     CGF.EnterCXXTryStmt(*TryStmt);
245e5dd7070Spatrick   }
246e5dd7070Spatrick 
247e5dd7070Spatrick   LValueOrRValue Res;
248e5dd7070Spatrick   if (forLValue)
249e5dd7070Spatrick     Res.LV = CGF.EmitLValue(S.getResumeExpr());
250e5dd7070Spatrick   else
251e5dd7070Spatrick     Res.RV = CGF.EmitAnyExpr(S.getResumeExpr(), aggSlot, ignoreResult);
252e5dd7070Spatrick 
253e5dd7070Spatrick   if (TryStmt) {
254e5dd7070Spatrick     Builder.CreateFlagStore(false, Coro.ResumeEHVar);
255e5dd7070Spatrick     CGF.ExitCXXTryStmt(*TryStmt);
256e5dd7070Spatrick   }
257e5dd7070Spatrick 
258e5dd7070Spatrick   return Res;
259e5dd7070Spatrick }
260e5dd7070Spatrick 
EmitCoawaitExpr(const CoawaitExpr & E,AggValueSlot aggSlot,bool ignoreResult)261e5dd7070Spatrick RValue CodeGenFunction::EmitCoawaitExpr(const CoawaitExpr &E,
262e5dd7070Spatrick                                         AggValueSlot aggSlot,
263e5dd7070Spatrick                                         bool ignoreResult) {
264e5dd7070Spatrick   return emitSuspendExpression(*this, *CurCoro.Data, E,
265e5dd7070Spatrick                                CurCoro.Data->CurrentAwaitKind, aggSlot,
266e5dd7070Spatrick                                ignoreResult, /*forLValue*/false).RV;
267e5dd7070Spatrick }
EmitCoyieldExpr(const CoyieldExpr & E,AggValueSlot aggSlot,bool ignoreResult)268e5dd7070Spatrick RValue CodeGenFunction::EmitCoyieldExpr(const CoyieldExpr &E,
269e5dd7070Spatrick                                         AggValueSlot aggSlot,
270e5dd7070Spatrick                                         bool ignoreResult) {
271e5dd7070Spatrick   return emitSuspendExpression(*this, *CurCoro.Data, E, AwaitKind::Yield,
272e5dd7070Spatrick                                aggSlot, ignoreResult, /*forLValue*/false).RV;
273e5dd7070Spatrick }
274e5dd7070Spatrick 
EmitCoreturnStmt(CoreturnStmt const & S)275e5dd7070Spatrick void CodeGenFunction::EmitCoreturnStmt(CoreturnStmt const &S) {
276e5dd7070Spatrick   ++CurCoro.Data->CoreturnCount;
277e5dd7070Spatrick   const Expr *RV = S.getOperand();
278ec727ea7Spatrick   if (RV && RV->getType()->isVoidType() && !isa<InitListExpr>(RV)) {
279ec727ea7Spatrick     // Make sure to evaluate the non initlist expression of a co_return
280ec727ea7Spatrick     // with a void expression for side effects.
281e5dd7070Spatrick     RunCleanupsScope cleanupScope(*this);
282e5dd7070Spatrick     EmitIgnoredExpr(RV);
283e5dd7070Spatrick   }
284e5dd7070Spatrick   EmitStmt(S.getPromiseCall());
285e5dd7070Spatrick   EmitBranchThroughCleanup(CurCoro.Data->FinalJD);
286e5dd7070Spatrick }
287e5dd7070Spatrick 
288e5dd7070Spatrick 
289e5dd7070Spatrick #ifndef NDEBUG
getCoroutineSuspendExprReturnType(const ASTContext & Ctx,const CoroutineSuspendExpr * E)290e5dd7070Spatrick static QualType getCoroutineSuspendExprReturnType(const ASTContext &Ctx,
291e5dd7070Spatrick   const CoroutineSuspendExpr *E) {
292e5dd7070Spatrick   const auto *RE = E->getResumeExpr();
293e5dd7070Spatrick   // Is it possible for RE to be a CXXBindTemporaryExpr wrapping
294e5dd7070Spatrick   // a MemberCallExpr?
295e5dd7070Spatrick   assert(isa<CallExpr>(RE) && "unexpected suspend expression type");
296e5dd7070Spatrick   return cast<CallExpr>(RE)->getCallReturnType(Ctx);
297e5dd7070Spatrick }
298e5dd7070Spatrick #endif
299e5dd7070Spatrick 
300e5dd7070Spatrick LValue
EmitCoawaitLValue(const CoawaitExpr * E)301e5dd7070Spatrick CodeGenFunction::EmitCoawaitLValue(const CoawaitExpr *E) {
302e5dd7070Spatrick   assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
303e5dd7070Spatrick          "Can't have a scalar return unless the return type is a "
304e5dd7070Spatrick          "reference type!");
305e5dd7070Spatrick   return emitSuspendExpression(*this, *CurCoro.Data, *E,
306e5dd7070Spatrick                                CurCoro.Data->CurrentAwaitKind, AggValueSlot::ignored(),
307e5dd7070Spatrick                                /*ignoreResult*/false, /*forLValue*/true).LV;
308e5dd7070Spatrick }
309e5dd7070Spatrick 
310e5dd7070Spatrick LValue
EmitCoyieldLValue(const CoyieldExpr * E)311e5dd7070Spatrick CodeGenFunction::EmitCoyieldLValue(const CoyieldExpr *E) {
312e5dd7070Spatrick   assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
313e5dd7070Spatrick          "Can't have a scalar return unless the return type is a "
314e5dd7070Spatrick          "reference type!");
315e5dd7070Spatrick   return emitSuspendExpression(*this, *CurCoro.Data, *E,
316e5dd7070Spatrick                                AwaitKind::Yield, AggValueSlot::ignored(),
317e5dd7070Spatrick                                /*ignoreResult*/false, /*forLValue*/true).LV;
318e5dd7070Spatrick }
319e5dd7070Spatrick 
320e5dd7070Spatrick // Hunts for the parameter reference in the parameter copy/move declaration.
321e5dd7070Spatrick namespace {
322e5dd7070Spatrick struct GetParamRef : public StmtVisitor<GetParamRef> {
323e5dd7070Spatrick public:
324e5dd7070Spatrick   DeclRefExpr *Expr = nullptr;
GetParamRef__anon4a0fbfb70411::GetParamRef325e5dd7070Spatrick   GetParamRef() {}
VisitDeclRefExpr__anon4a0fbfb70411::GetParamRef326e5dd7070Spatrick   void VisitDeclRefExpr(DeclRefExpr *E) {
327e5dd7070Spatrick     assert(Expr == nullptr && "multilple declref in param move");
328e5dd7070Spatrick     Expr = E;
329e5dd7070Spatrick   }
VisitStmt__anon4a0fbfb70411::GetParamRef330e5dd7070Spatrick   void VisitStmt(Stmt *S) {
331e5dd7070Spatrick     for (auto *C : S->children()) {
332e5dd7070Spatrick       if (C)
333e5dd7070Spatrick         Visit(C);
334e5dd7070Spatrick     }
335e5dd7070Spatrick   }
336e5dd7070Spatrick };
337e5dd7070Spatrick }
338e5dd7070Spatrick 
339e5dd7070Spatrick // This class replaces references to parameters to their copies by changing
340e5dd7070Spatrick // the addresses in CGF.LocalDeclMap and restoring back the original values in
341e5dd7070Spatrick // its destructor.
342e5dd7070Spatrick 
343e5dd7070Spatrick namespace {
344e5dd7070Spatrick   struct ParamReferenceReplacerRAII {
345e5dd7070Spatrick     CodeGenFunction::DeclMapTy SavedLocals;
346e5dd7070Spatrick     CodeGenFunction::DeclMapTy& LocalDeclMap;
347e5dd7070Spatrick 
ParamReferenceReplacerRAII__anon4a0fbfb70511::ParamReferenceReplacerRAII348e5dd7070Spatrick     ParamReferenceReplacerRAII(CodeGenFunction::DeclMapTy &LocalDeclMap)
349e5dd7070Spatrick         : LocalDeclMap(LocalDeclMap) {}
350e5dd7070Spatrick 
addCopy__anon4a0fbfb70511::ParamReferenceReplacerRAII351e5dd7070Spatrick     void addCopy(DeclStmt const *PM) {
352e5dd7070Spatrick       // Figure out what param it refers to.
353e5dd7070Spatrick 
354e5dd7070Spatrick       assert(PM->isSingleDecl());
355e5dd7070Spatrick       VarDecl const*VD = static_cast<VarDecl const*>(PM->getSingleDecl());
356e5dd7070Spatrick       Expr const *InitExpr = VD->getInit();
357e5dd7070Spatrick       GetParamRef Visitor;
358e5dd7070Spatrick       Visitor.Visit(const_cast<Expr*>(InitExpr));
359e5dd7070Spatrick       assert(Visitor.Expr);
360e5dd7070Spatrick       DeclRefExpr *DREOrig = Visitor.Expr;
361e5dd7070Spatrick       auto *PD = DREOrig->getDecl();
362e5dd7070Spatrick 
363e5dd7070Spatrick       auto it = LocalDeclMap.find(PD);
364e5dd7070Spatrick       assert(it != LocalDeclMap.end() && "parameter is not found");
365e5dd7070Spatrick       SavedLocals.insert({ PD, it->second });
366e5dd7070Spatrick 
367e5dd7070Spatrick       auto copyIt = LocalDeclMap.find(VD);
368e5dd7070Spatrick       assert(copyIt != LocalDeclMap.end() && "parameter copy is not found");
369e5dd7070Spatrick       it->second = copyIt->getSecond();
370e5dd7070Spatrick     }
371e5dd7070Spatrick 
~ParamReferenceReplacerRAII__anon4a0fbfb70511::ParamReferenceReplacerRAII372e5dd7070Spatrick     ~ParamReferenceReplacerRAII() {
373e5dd7070Spatrick       for (auto&& SavedLocal : SavedLocals) {
374e5dd7070Spatrick         LocalDeclMap.insert({SavedLocal.first, SavedLocal.second});
375e5dd7070Spatrick       }
376e5dd7070Spatrick     }
377e5dd7070Spatrick   };
378e5dd7070Spatrick }
379e5dd7070Spatrick 
380e5dd7070Spatrick // For WinEH exception representation backend needs to know what funclet coro.end
381e5dd7070Spatrick // belongs to. That information is passed in a funclet bundle.
382e5dd7070Spatrick static SmallVector<llvm::OperandBundleDef, 1>
getBundlesForCoroEnd(CodeGenFunction & CGF)383e5dd7070Spatrick getBundlesForCoroEnd(CodeGenFunction &CGF) {
384e5dd7070Spatrick   SmallVector<llvm::OperandBundleDef, 1> BundleList;
385e5dd7070Spatrick 
386e5dd7070Spatrick   if (llvm::Instruction *EHPad = CGF.CurrentFuncletPad)
387e5dd7070Spatrick     BundleList.emplace_back("funclet", EHPad);
388e5dd7070Spatrick 
389e5dd7070Spatrick   return BundleList;
390e5dd7070Spatrick }
391e5dd7070Spatrick 
392e5dd7070Spatrick namespace {
393e5dd7070Spatrick // We will insert coro.end to cut any of the destructors for objects that
394e5dd7070Spatrick // do not need to be destroyed once the coroutine is resumed.
395e5dd7070Spatrick // See llvm/docs/Coroutines.rst for more details about coro.end.
396e5dd7070Spatrick struct CallCoroEnd final : public EHScopeStack::Cleanup {
Emit__anon4a0fbfb70611::CallCoroEnd397e5dd7070Spatrick   void Emit(CodeGenFunction &CGF, Flags flags) override {
398e5dd7070Spatrick     auto &CGM = CGF.CGM;
399e5dd7070Spatrick     auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
400e5dd7070Spatrick     llvm::Function *CoroEndFn = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
401e5dd7070Spatrick     // See if we have a funclet bundle to associate coro.end with. (WinEH)
402e5dd7070Spatrick     auto Bundles = getBundlesForCoroEnd(CGF);
403e5dd7070Spatrick     auto *CoroEnd = CGF.Builder.CreateCall(
404e5dd7070Spatrick         CoroEndFn, {NullPtr, CGF.Builder.getTrue()}, Bundles);
405e5dd7070Spatrick     if (Bundles.empty()) {
406e5dd7070Spatrick       // Otherwise, (landingpad model), create a conditional branch that leads
407e5dd7070Spatrick       // either to a cleanup block or a block with EH resume instruction.
408e5dd7070Spatrick       auto *ResumeBB = CGF.getEHResumeBlock(/*isCleanup=*/true);
409e5dd7070Spatrick       auto *CleanupContBB = CGF.createBasicBlock("cleanup.cont");
410e5dd7070Spatrick       CGF.Builder.CreateCondBr(CoroEnd, ResumeBB, CleanupContBB);
411e5dd7070Spatrick       CGF.EmitBlock(CleanupContBB);
412e5dd7070Spatrick     }
413e5dd7070Spatrick   }
414e5dd7070Spatrick };
415e5dd7070Spatrick }
416e5dd7070Spatrick 
417e5dd7070Spatrick namespace {
418e5dd7070Spatrick // Make sure to call coro.delete on scope exit.
419e5dd7070Spatrick struct CallCoroDelete final : public EHScopeStack::Cleanup {
420e5dd7070Spatrick   Stmt *Deallocate;
421e5dd7070Spatrick 
422e5dd7070Spatrick   // Emit "if (coro.free(CoroId, CoroBegin)) Deallocate;"
423e5dd7070Spatrick 
424e5dd7070Spatrick   // Note: That deallocation will be emitted twice: once for a normal exit and
425e5dd7070Spatrick   // once for exceptional exit. This usage is safe because Deallocate does not
426e5dd7070Spatrick   // contain any declarations. The SubStmtBuilder::makeNewAndDeleteExpr()
427e5dd7070Spatrick   // builds a single call to a deallocation function which is safe to emit
428e5dd7070Spatrick   // multiple times.
Emit__anon4a0fbfb70711::CallCoroDelete429e5dd7070Spatrick   void Emit(CodeGenFunction &CGF, Flags) override {
430e5dd7070Spatrick     // Remember the current point, as we are going to emit deallocation code
431e5dd7070Spatrick     // first to get to coro.free instruction that is an argument to a delete
432e5dd7070Spatrick     // call.
433e5dd7070Spatrick     BasicBlock *SaveInsertBlock = CGF.Builder.GetInsertBlock();
434e5dd7070Spatrick 
435e5dd7070Spatrick     auto *FreeBB = CGF.createBasicBlock("coro.free");
436e5dd7070Spatrick     CGF.EmitBlock(FreeBB);
437e5dd7070Spatrick     CGF.EmitStmt(Deallocate);
438e5dd7070Spatrick 
439e5dd7070Spatrick     auto *AfterFreeBB = CGF.createBasicBlock("after.coro.free");
440e5dd7070Spatrick     CGF.EmitBlock(AfterFreeBB);
441e5dd7070Spatrick 
442e5dd7070Spatrick     // We should have captured coro.free from the emission of deallocate.
443e5dd7070Spatrick     auto *CoroFree = CGF.CurCoro.Data->LastCoroFree;
444e5dd7070Spatrick     if (!CoroFree) {
445e5dd7070Spatrick       CGF.CGM.Error(Deallocate->getBeginLoc(),
446e5dd7070Spatrick                     "Deallocation expressoin does not refer to coro.free");
447e5dd7070Spatrick       return;
448e5dd7070Spatrick     }
449e5dd7070Spatrick 
450e5dd7070Spatrick     // Get back to the block we were originally and move coro.free there.
451e5dd7070Spatrick     auto *InsertPt = SaveInsertBlock->getTerminator();
452e5dd7070Spatrick     CoroFree->moveBefore(InsertPt);
453e5dd7070Spatrick     CGF.Builder.SetInsertPoint(InsertPt);
454e5dd7070Spatrick 
455e5dd7070Spatrick     // Add if (auto *mem = coro.free) Deallocate;
456e5dd7070Spatrick     auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
457e5dd7070Spatrick     auto *Cond = CGF.Builder.CreateICmpNE(CoroFree, NullPtr);
458e5dd7070Spatrick     CGF.Builder.CreateCondBr(Cond, FreeBB, AfterFreeBB);
459e5dd7070Spatrick 
460e5dd7070Spatrick     // No longer need old terminator.
461e5dd7070Spatrick     InsertPt->eraseFromParent();
462e5dd7070Spatrick     CGF.Builder.SetInsertPoint(AfterFreeBB);
463e5dd7070Spatrick   }
CallCoroDelete__anon4a0fbfb70711::CallCoroDelete464e5dd7070Spatrick   explicit CallCoroDelete(Stmt *DeallocStmt) : Deallocate(DeallocStmt) {}
465e5dd7070Spatrick };
466e5dd7070Spatrick }
467e5dd7070Spatrick 
emitBodyAndFallthrough(CodeGenFunction & CGF,const CoroutineBodyStmt & S,Stmt * Body)468e5dd7070Spatrick static void emitBodyAndFallthrough(CodeGenFunction &CGF,
469e5dd7070Spatrick                                    const CoroutineBodyStmt &S, Stmt *Body) {
470e5dd7070Spatrick   CGF.EmitStmt(Body);
471e5dd7070Spatrick   const bool CanFallthrough = CGF.Builder.GetInsertBlock();
472e5dd7070Spatrick   if (CanFallthrough)
473e5dd7070Spatrick     if (Stmt *OnFallthrough = S.getFallthroughHandler())
474e5dd7070Spatrick       CGF.EmitStmt(OnFallthrough);
475e5dd7070Spatrick }
476e5dd7070Spatrick 
EmitCoroutineBody(const CoroutineBodyStmt & S)477e5dd7070Spatrick void CodeGenFunction::EmitCoroutineBody(const CoroutineBodyStmt &S) {
478e5dd7070Spatrick   auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
479e5dd7070Spatrick   auto &TI = CGM.getContext().getTargetInfo();
480e5dd7070Spatrick   unsigned NewAlign = TI.getNewAlign() / TI.getCharWidth();
481e5dd7070Spatrick 
482e5dd7070Spatrick   auto *EntryBB = Builder.GetInsertBlock();
483e5dd7070Spatrick   auto *AllocBB = createBasicBlock("coro.alloc");
484e5dd7070Spatrick   auto *InitBB = createBasicBlock("coro.init");
485e5dd7070Spatrick   auto *FinalBB = createBasicBlock("coro.final");
486e5dd7070Spatrick   auto *RetBB = createBasicBlock("coro.ret");
487e5dd7070Spatrick 
488e5dd7070Spatrick   auto *CoroId = Builder.CreateCall(
489e5dd7070Spatrick       CGM.getIntrinsic(llvm::Intrinsic::coro_id),
490e5dd7070Spatrick       {Builder.getInt32(NewAlign), NullPtr, NullPtr, NullPtr});
491e5dd7070Spatrick   createCoroData(*this, CurCoro, CoroId);
492e5dd7070Spatrick   CurCoro.Data->SuspendBB = RetBB;
493a9ac8606Spatrick   assert(ShouldEmitLifetimeMarkers &&
494a9ac8606Spatrick          "Must emit lifetime intrinsics for coroutines");
495e5dd7070Spatrick 
496e5dd7070Spatrick   // Backend is allowed to elide memory allocations, to help it, emit
497e5dd7070Spatrick   // auto mem = coro.alloc() ? 0 : ... allocation code ...;
498e5dd7070Spatrick   auto *CoroAlloc = Builder.CreateCall(
499e5dd7070Spatrick       CGM.getIntrinsic(llvm::Intrinsic::coro_alloc), {CoroId});
500e5dd7070Spatrick 
501e5dd7070Spatrick   Builder.CreateCondBr(CoroAlloc, AllocBB, InitBB);
502e5dd7070Spatrick 
503e5dd7070Spatrick   EmitBlock(AllocBB);
504e5dd7070Spatrick   auto *AllocateCall = EmitScalarExpr(S.getAllocate());
505e5dd7070Spatrick   auto *AllocOrInvokeContBB = Builder.GetInsertBlock();
506e5dd7070Spatrick 
507e5dd7070Spatrick   // Handle allocation failure if 'ReturnStmtOnAllocFailure' was provided.
508e5dd7070Spatrick   if (auto *RetOnAllocFailure = S.getReturnStmtOnAllocFailure()) {
509e5dd7070Spatrick     auto *RetOnFailureBB = createBasicBlock("coro.ret.on.failure");
510e5dd7070Spatrick 
511e5dd7070Spatrick     // See if allocation was successful.
512e5dd7070Spatrick     auto *NullPtr = llvm::ConstantPointerNull::get(Int8PtrTy);
513e5dd7070Spatrick     auto *Cond = Builder.CreateICmpNE(AllocateCall, NullPtr);
514e5dd7070Spatrick     Builder.CreateCondBr(Cond, InitBB, RetOnFailureBB);
515e5dd7070Spatrick 
516e5dd7070Spatrick     // If not, return OnAllocFailure object.
517e5dd7070Spatrick     EmitBlock(RetOnFailureBB);
518e5dd7070Spatrick     EmitStmt(RetOnAllocFailure);
519e5dd7070Spatrick   }
520e5dd7070Spatrick   else {
521e5dd7070Spatrick     Builder.CreateBr(InitBB);
522e5dd7070Spatrick   }
523e5dd7070Spatrick 
524e5dd7070Spatrick   EmitBlock(InitBB);
525e5dd7070Spatrick 
526e5dd7070Spatrick   // Pass the result of the allocation to coro.begin.
527e5dd7070Spatrick   auto *Phi = Builder.CreatePHI(VoidPtrTy, 2);
528e5dd7070Spatrick   Phi->addIncoming(NullPtr, EntryBB);
529e5dd7070Spatrick   Phi->addIncoming(AllocateCall, AllocOrInvokeContBB);
530e5dd7070Spatrick   auto *CoroBegin = Builder.CreateCall(
531e5dd7070Spatrick       CGM.getIntrinsic(llvm::Intrinsic::coro_begin), {CoroId, Phi});
532e5dd7070Spatrick   CurCoro.Data->CoroBegin = CoroBegin;
533e5dd7070Spatrick 
534e5dd7070Spatrick   CurCoro.Data->CleanupJD = getJumpDestInCurrentScope(RetBB);
535e5dd7070Spatrick   {
536a9ac8606Spatrick     CGDebugInfo *DI = getDebugInfo();
537e5dd7070Spatrick     ParamReferenceReplacerRAII ParamReplacer(LocalDeclMap);
538e5dd7070Spatrick     CodeGenFunction::RunCleanupsScope ResumeScope(*this);
539e5dd7070Spatrick     EHStack.pushCleanup<CallCoroDelete>(NormalAndEHCleanup, S.getDeallocate());
540e5dd7070Spatrick 
541a9ac8606Spatrick     // Create mapping between parameters and copy-params for coroutine function.
542*12c85518Srobert     llvm::ArrayRef<const Stmt *> ParamMoves = S.getParamMoves();
543a9ac8606Spatrick     assert(
544a9ac8606Spatrick         (ParamMoves.size() == 0 || (ParamMoves.size() == FnArgs.size())) &&
545a9ac8606Spatrick         "ParamMoves and FnArgs should be the same size for coroutine function");
546a9ac8606Spatrick     if (ParamMoves.size() == FnArgs.size() && DI)
547a9ac8606Spatrick       for (const auto Pair : llvm::zip(FnArgs, ParamMoves))
548a9ac8606Spatrick         DI->getCoroutineParameterMappings().insert(
549a9ac8606Spatrick             {std::get<0>(Pair), std::get<1>(Pair)});
550a9ac8606Spatrick 
551e5dd7070Spatrick     // Create parameter copies. We do it before creating a promise, since an
552e5dd7070Spatrick     // evolution of coroutine TS may allow promise constructor to observe
553e5dd7070Spatrick     // parameter copies.
554e5dd7070Spatrick     for (auto *PM : S.getParamMoves()) {
555e5dd7070Spatrick       EmitStmt(PM);
556e5dd7070Spatrick       ParamReplacer.addCopy(cast<DeclStmt>(PM));
557e5dd7070Spatrick       // TODO: if(CoroParam(...)) need to surround ctor and dtor
558e5dd7070Spatrick       // for the copy, so that llvm can elide it if the copy is
559e5dd7070Spatrick       // not needed.
560e5dd7070Spatrick     }
561e5dd7070Spatrick 
562e5dd7070Spatrick     EmitStmt(S.getPromiseDeclStmt());
563e5dd7070Spatrick 
564e5dd7070Spatrick     Address PromiseAddr = GetAddrOfLocalVar(S.getPromiseDecl());
565e5dd7070Spatrick     auto *PromiseAddrVoidPtr =
566e5dd7070Spatrick         new llvm::BitCastInst(PromiseAddr.getPointer(), VoidPtrTy, "", CoroId);
567e5dd7070Spatrick     // Update CoroId to refer to the promise. We could not do it earlier because
568e5dd7070Spatrick     // promise local variable was not emitted yet.
569e5dd7070Spatrick     CoroId->setArgOperand(1, PromiseAddrVoidPtr);
570e5dd7070Spatrick 
571*12c85518Srobert     // ReturnValue should be valid as long as the coroutine's return type
572*12c85518Srobert     // is not void. The assertion could help us to reduce the check later.
573*12c85518Srobert     assert(ReturnValue.isValid() == (bool)S.getReturnStmt());
574*12c85518Srobert     // Now we have the promise, initialize the GRO.
575*12c85518Srobert     // We need to emit `get_return_object` first. According to:
576*12c85518Srobert     // [dcl.fct.def.coroutine]p7
577*12c85518Srobert     // The call to get_return_­object is sequenced before the call to
578*12c85518Srobert     // initial_suspend and is invoked at most once.
579*12c85518Srobert     //
580*12c85518Srobert     // So we couldn't emit return value when we emit return statment,
581*12c85518Srobert     // otherwise the call to get_return_object wouldn't be in front
582*12c85518Srobert     // of initial_suspend.
583*12c85518Srobert     if (ReturnValue.isValid()) {
584*12c85518Srobert       EmitAnyExprToMem(S.getReturnValue(), ReturnValue,
585*12c85518Srobert                        S.getReturnValue()->getType().getQualifiers(),
586*12c85518Srobert                        /*IsInit*/ true);
587*12c85518Srobert     }
588e5dd7070Spatrick 
589e5dd7070Spatrick     EHStack.pushCleanup<CallCoroEnd>(EHCleanup);
590e5dd7070Spatrick 
591e5dd7070Spatrick     CurCoro.Data->CurrentAwaitKind = AwaitKind::Init;
592e5dd7070Spatrick     CurCoro.Data->ExceptionHandler = S.getExceptionHandler();
593e5dd7070Spatrick     EmitStmt(S.getInitSuspendStmt());
594e5dd7070Spatrick     CurCoro.Data->FinalJD = getJumpDestInCurrentScope(FinalBB);
595e5dd7070Spatrick 
596e5dd7070Spatrick     CurCoro.Data->CurrentAwaitKind = AwaitKind::Normal;
597e5dd7070Spatrick 
598e5dd7070Spatrick     if (CurCoro.Data->ExceptionHandler) {
599e5dd7070Spatrick       // If we generated IR to record whether an exception was thrown from
600e5dd7070Spatrick       // 'await_resume', then use that IR to determine whether the coroutine
601e5dd7070Spatrick       // body should be skipped.
602e5dd7070Spatrick       // If we didn't generate the IR (perhaps because 'await_resume' was marked
603e5dd7070Spatrick       // as 'noexcept'), then we skip this check.
604e5dd7070Spatrick       BasicBlock *ContBB = nullptr;
605e5dd7070Spatrick       if (CurCoro.Data->ResumeEHVar) {
606e5dd7070Spatrick         BasicBlock *BodyBB = createBasicBlock("coro.resumed.body");
607e5dd7070Spatrick         ContBB = createBasicBlock("coro.resumed.cont");
608e5dd7070Spatrick         Value *SkipBody = Builder.CreateFlagLoad(CurCoro.Data->ResumeEHVar,
609e5dd7070Spatrick                                                  "coro.resumed.eh");
610e5dd7070Spatrick         Builder.CreateCondBr(SkipBody, ContBB, BodyBB);
611e5dd7070Spatrick         EmitBlock(BodyBB);
612e5dd7070Spatrick       }
613e5dd7070Spatrick 
614e5dd7070Spatrick       auto Loc = S.getBeginLoc();
615e5dd7070Spatrick       CXXCatchStmt Catch(Loc, /*exDecl=*/nullptr,
616e5dd7070Spatrick                          CurCoro.Data->ExceptionHandler);
617e5dd7070Spatrick       auto *TryStmt =
618e5dd7070Spatrick           CXXTryStmt::Create(getContext(), Loc, S.getBody(), &Catch);
619e5dd7070Spatrick 
620e5dd7070Spatrick       EnterCXXTryStmt(*TryStmt);
621e5dd7070Spatrick       emitBodyAndFallthrough(*this, S, TryStmt->getTryBlock());
622e5dd7070Spatrick       ExitCXXTryStmt(*TryStmt);
623e5dd7070Spatrick 
624e5dd7070Spatrick       if (ContBB)
625e5dd7070Spatrick         EmitBlock(ContBB);
626e5dd7070Spatrick     }
627e5dd7070Spatrick     else {
628e5dd7070Spatrick       emitBodyAndFallthrough(*this, S, S.getBody());
629e5dd7070Spatrick     }
630e5dd7070Spatrick 
631e5dd7070Spatrick     // See if we need to generate final suspend.
632e5dd7070Spatrick     const bool CanFallthrough = Builder.GetInsertBlock();
633e5dd7070Spatrick     const bool HasCoreturns = CurCoro.Data->CoreturnCount > 0;
634e5dd7070Spatrick     if (CanFallthrough || HasCoreturns) {
635e5dd7070Spatrick       EmitBlock(FinalBB);
636e5dd7070Spatrick       CurCoro.Data->CurrentAwaitKind = AwaitKind::Final;
637e5dd7070Spatrick       EmitStmt(S.getFinalSuspendStmt());
638e5dd7070Spatrick     } else {
639e5dd7070Spatrick       // We don't need FinalBB. Emit it to make sure the block is deleted.
640e5dd7070Spatrick       EmitBlock(FinalBB, /*IsFinished=*/true);
641e5dd7070Spatrick     }
642e5dd7070Spatrick   }
643e5dd7070Spatrick 
644e5dd7070Spatrick   EmitBlock(RetBB);
645e5dd7070Spatrick   // Emit coro.end before getReturnStmt (and parameter destructors), since
646e5dd7070Spatrick   // resume and destroy parts of the coroutine should not include them.
647e5dd7070Spatrick   llvm::Function *CoroEnd = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
648e5dd7070Spatrick   Builder.CreateCall(CoroEnd, {NullPtr, Builder.getFalse()});
649e5dd7070Spatrick 
650*12c85518Srobert   if (Stmt *Ret = S.getReturnStmt()) {
651*12c85518Srobert     // Since we already emitted the return value above, so we shouldn't
652*12c85518Srobert     // emit it again here.
653*12c85518Srobert     cast<ReturnStmt>(Ret)->setRetValue(nullptr);
654e5dd7070Spatrick     EmitStmt(Ret);
655e5dd7070Spatrick   }
656e5dd7070Spatrick 
657*12c85518Srobert   // LLVM require the frontend to mark the coroutine.
658*12c85518Srobert   CurFn->setPresplitCoroutine();
659*12c85518Srobert }
660*12c85518Srobert 
661e5dd7070Spatrick // Emit coroutine intrinsic and patch up arguments of the token type.
EmitCoroutineIntrinsic(const CallExpr * E,unsigned int IID)662e5dd7070Spatrick RValue CodeGenFunction::EmitCoroutineIntrinsic(const CallExpr *E,
663e5dd7070Spatrick                                                unsigned int IID) {
664e5dd7070Spatrick   SmallVector<llvm::Value *, 8> Args;
665e5dd7070Spatrick   switch (IID) {
666e5dd7070Spatrick   default:
667e5dd7070Spatrick     break;
668e5dd7070Spatrick   // The coro.frame builtin is replaced with an SSA value of the coro.begin
669e5dd7070Spatrick   // intrinsic.
670e5dd7070Spatrick   case llvm::Intrinsic::coro_frame: {
671e5dd7070Spatrick     if (CurCoro.Data && CurCoro.Data->CoroBegin) {
672e5dd7070Spatrick       return RValue::get(CurCoro.Data->CoroBegin);
673e5dd7070Spatrick     }
674e5dd7070Spatrick     CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_begin "
675e5dd7070Spatrick                                 "has been used earlier in this function");
676*12c85518Srobert     auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
677e5dd7070Spatrick     return RValue::get(NullPtr);
678e5dd7070Spatrick   }
679*12c85518Srobert   case llvm::Intrinsic::coro_size: {
680*12c85518Srobert     auto &Context = getContext();
681*12c85518Srobert     CanQualType SizeTy = Context.getSizeType();
682*12c85518Srobert     llvm::IntegerType *T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
683*12c85518Srobert     llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::coro_size, T);
684*12c85518Srobert     return RValue::get(Builder.CreateCall(F));
685*12c85518Srobert   }
686*12c85518Srobert   case llvm::Intrinsic::coro_align: {
687*12c85518Srobert     auto &Context = getContext();
688*12c85518Srobert     CanQualType SizeTy = Context.getSizeType();
689*12c85518Srobert     llvm::IntegerType *T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
690*12c85518Srobert     llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::coro_align, T);
691*12c85518Srobert     return RValue::get(Builder.CreateCall(F));
692*12c85518Srobert   }
693e5dd7070Spatrick   // The following three intrinsics take a token parameter referring to a token
694e5dd7070Spatrick   // returned by earlier call to @llvm.coro.id. Since we cannot represent it in
695e5dd7070Spatrick   // builtins, we patch it up here.
696e5dd7070Spatrick   case llvm::Intrinsic::coro_alloc:
697e5dd7070Spatrick   case llvm::Intrinsic::coro_begin:
698e5dd7070Spatrick   case llvm::Intrinsic::coro_free: {
699e5dd7070Spatrick     if (CurCoro.Data && CurCoro.Data->CoroId) {
700e5dd7070Spatrick       Args.push_back(CurCoro.Data->CoroId);
701e5dd7070Spatrick       break;
702e5dd7070Spatrick     }
703e5dd7070Spatrick     CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_id has"
704e5dd7070Spatrick                                 " been used earlier in this function");
705e5dd7070Spatrick     // Fallthrough to the next case to add TokenNone as the first argument.
706*12c85518Srobert     [[fallthrough]];
707e5dd7070Spatrick   }
708e5dd7070Spatrick   // @llvm.coro.suspend takes a token parameter. Add token 'none' as the first
709e5dd7070Spatrick   // argument.
710e5dd7070Spatrick   case llvm::Intrinsic::coro_suspend:
711e5dd7070Spatrick     Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
712e5dd7070Spatrick     break;
713e5dd7070Spatrick   }
714e5dd7070Spatrick   for (const Expr *Arg : E->arguments())
715e5dd7070Spatrick     Args.push_back(EmitScalarExpr(Arg));
716e5dd7070Spatrick 
717e5dd7070Spatrick   llvm::Function *F = CGM.getIntrinsic(IID);
718e5dd7070Spatrick   llvm::CallInst *Call = Builder.CreateCall(F, Args);
719e5dd7070Spatrick 
720e5dd7070Spatrick   // Note: The following code is to enable to emit coro.id and coro.begin by
721e5dd7070Spatrick   // hand to experiment with coroutines in C.
722e5dd7070Spatrick   // If we see @llvm.coro.id remember it in the CoroData. We will update
723e5dd7070Spatrick   // coro.alloc, coro.begin and coro.free intrinsics to refer to it.
724e5dd7070Spatrick   if (IID == llvm::Intrinsic::coro_id) {
725e5dd7070Spatrick     createCoroData(*this, CurCoro, Call, E);
726e5dd7070Spatrick   }
727e5dd7070Spatrick   else if (IID == llvm::Intrinsic::coro_begin) {
728e5dd7070Spatrick     if (CurCoro.Data)
729e5dd7070Spatrick       CurCoro.Data->CoroBegin = Call;
730e5dd7070Spatrick   }
731e5dd7070Spatrick   else if (IID == llvm::Intrinsic::coro_free) {
732e5dd7070Spatrick     // Remember the last coro_free as we need it to build the conditional
733e5dd7070Spatrick     // deletion of the coroutine frame.
734e5dd7070Spatrick     if (CurCoro.Data)
735e5dd7070Spatrick       CurCoro.Data->LastCoroFree = Call;
736e5dd7070Spatrick   }
737e5dd7070Spatrick   return RValue::get(Call);
738e5dd7070Spatrick }
739