xref: /src/contrib/llvm-project/clang/lib/CodeGen/CGCoroutine.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1bab175ecSDimitry Andric //===----- CGCoroutine.cpp - Emit LLVM Code for C++ coroutines ------------===//
2bab175ecSDimitry Andric //
322989816SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
422989816SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
522989816SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6bab175ecSDimitry Andric //
7bab175ecSDimitry Andric //===----------------------------------------------------------------------===//
8bab175ecSDimitry Andric //
9bab175ecSDimitry Andric // This contains code dealing with C++ code generation of coroutines.
10bab175ecSDimitry Andric //
11bab175ecSDimitry Andric //===----------------------------------------------------------------------===//
12bab175ecSDimitry Andric 
13b5aee35cSDimitry Andric #include "CGCleanup.h"
14bab175ecSDimitry Andric #include "CodeGenFunction.h"
157442d6faSDimitry Andric #include "llvm/ADT/ScopeExit.h"
16bab175ecSDimitry Andric #include "clang/AST/StmtCXX.h"
17b5aee35cSDimitry Andric #include "clang/AST/StmtVisitor.h"
18bab175ecSDimitry Andric 
19bab175ecSDimitry Andric using namespace clang;
20bab175ecSDimitry Andric using namespace CodeGen;
21bab175ecSDimitry Andric 
227442d6faSDimitry Andric using llvm::Value;
237442d6faSDimitry Andric using llvm::BasicBlock;
24bab175ecSDimitry Andric 
257442d6faSDimitry Andric namespace {
267442d6faSDimitry Andric enum class AwaitKind { Init, Normal, Yield, Final };
277442d6faSDimitry Andric static constexpr llvm::StringLiteral AwaitKindStr[] = {"init", "await", "yield",
287442d6faSDimitry Andric                                                        "final"};
297442d6faSDimitry Andric }
307442d6faSDimitry Andric 
317442d6faSDimitry Andric struct clang::CodeGen::CGCoroData {
327442d6faSDimitry Andric   // What is the current await expression kind and how many
337442d6faSDimitry Andric   // await/yield expressions were encountered so far.
347442d6faSDimitry Andric   // These are used to generate pretty labels for await expressions in LLVM IR.
357442d6faSDimitry Andric   AwaitKind CurrentAwaitKind = AwaitKind::Init;
367442d6faSDimitry Andric   unsigned AwaitNum = 0;
377442d6faSDimitry Andric   unsigned YieldNum = 0;
387442d6faSDimitry Andric 
397442d6faSDimitry Andric   // How many co_return statements are in the coroutine. Used to decide whether
407442d6faSDimitry Andric   // we need to add co_return; equivalent at the end of the user authored body.
417442d6faSDimitry Andric   unsigned CoreturnCount = 0;
427442d6faSDimitry Andric 
437442d6faSDimitry Andric   // A branch to this block is emitted when coroutine needs to suspend.
447442d6faSDimitry Andric   llvm::BasicBlock *SuspendBB = nullptr;
457442d6faSDimitry Andric 
4648675466SDimitry Andric   // The promise type's 'unhandled_exception' handler, if it defines one.
4748675466SDimitry Andric   Stmt *ExceptionHandler = nullptr;
4848675466SDimitry Andric 
4948675466SDimitry Andric   // A temporary i1 alloca that stores whether 'await_resume' threw an
5048675466SDimitry Andric   // exception. If it did, 'true' is stored in this variable, and the coroutine
5148675466SDimitry Andric   // body must be skipped. If the promise type does not define an exception
5248675466SDimitry Andric   // handler, this is null.
5348675466SDimitry Andric   llvm::Value *ResumeEHVar = nullptr;
5448675466SDimitry Andric 
557442d6faSDimitry Andric   // Stores the jump destination just before the coroutine memory is freed.
567442d6faSDimitry Andric   // This is the destination that every suspend point jumps to for the cleanup
577442d6faSDimitry Andric   // branch.
587442d6faSDimitry Andric   CodeGenFunction::JumpDest CleanupJD;
597442d6faSDimitry Andric 
607442d6faSDimitry Andric   // Stores the jump destination just before the final suspend. The co_return
617442d6faSDimitry Andric   // statements jumps to this point after calling return_xxx promise member.
627442d6faSDimitry Andric   CodeGenFunction::JumpDest FinalJD;
637442d6faSDimitry Andric 
64bab175ecSDimitry Andric   // Stores the llvm.coro.id emitted in the function so that we can supply it
65bab175ecSDimitry Andric   // as the first argument to coro.begin, coro.alloc and coro.free intrinsics.
66bab175ecSDimitry Andric   // Note: llvm.coro.id returns a token that cannot be directly expressed in a
67bab175ecSDimitry Andric   // builtin.
68bab175ecSDimitry Andric   llvm::CallInst *CoroId = nullptr;
697442d6faSDimitry Andric 
70b5aee35cSDimitry Andric   // Stores the llvm.coro.begin emitted in the function so that we can replace
71b5aee35cSDimitry Andric   // all coro.frame intrinsics with direct SSA value of coro.begin that returns
72b5aee35cSDimitry Andric   // the address of the coroutine frame of the current coroutine.
73b5aee35cSDimitry Andric   llvm::CallInst *CoroBegin = nullptr;
74b5aee35cSDimitry Andric 
75b5aee35cSDimitry Andric   // Stores the last emitted coro.free for the deallocate expressions, we use it
76b5aee35cSDimitry Andric   // to wrap dealloc code with if(auto mem = coro.free) dealloc(mem).
77b5aee35cSDimitry Andric   llvm::CallInst *LastCoroFree = nullptr;
78b5aee35cSDimitry Andric 
79bab175ecSDimitry Andric   // If coro.id came from the builtin, remember the expression to give better
80bab175ecSDimitry Andric   // diagnostic. If CoroIdExpr is nullptr, the coro.id was created by
81bab175ecSDimitry Andric   // EmitCoroutineBody.
82bab175ecSDimitry Andric   CallExpr const *CoroIdExpr = nullptr;
83bab175ecSDimitry Andric };
84bab175ecSDimitry Andric 
857442d6faSDimitry Andric // Defining these here allows to keep CGCoroData private to this file.
CGCoroInfo()86bab175ecSDimitry Andric clang::CodeGen::CodeGenFunction::CGCoroInfo::CGCoroInfo() {}
~CGCoroInfo()87bab175ecSDimitry Andric CodeGenFunction::CGCoroInfo::~CGCoroInfo() {}
88bab175ecSDimitry Andric 
createCoroData(CodeGenFunction & CGF,CodeGenFunction::CGCoroInfo & CurCoro,llvm::CallInst * CoroId,CallExpr const * CoroIdExpr=nullptr)89bab175ecSDimitry Andric static void createCoroData(CodeGenFunction &CGF,
90bab175ecSDimitry Andric                            CodeGenFunction::CGCoroInfo &CurCoro,
91bab175ecSDimitry Andric                            llvm::CallInst *CoroId,
92bab175ecSDimitry Andric                            CallExpr const *CoroIdExpr = nullptr) {
93bab175ecSDimitry Andric   if (CurCoro.Data) {
94bab175ecSDimitry Andric     if (CurCoro.Data->CoroIdExpr)
95676fbe81SDimitry Andric       CGF.CGM.Error(CoroIdExpr->getBeginLoc(),
96bab175ecSDimitry Andric                     "only one __builtin_coro_id can be used in a function");
97bab175ecSDimitry Andric     else if (CoroIdExpr)
98676fbe81SDimitry Andric       CGF.CGM.Error(CoroIdExpr->getBeginLoc(),
99bab175ecSDimitry Andric                     "__builtin_coro_id shall not be used in a C++ coroutine");
100bab175ecSDimitry Andric     else
101bab175ecSDimitry Andric       llvm_unreachable("EmitCoroutineBodyStatement called twice?");
102bab175ecSDimitry Andric 
103bab175ecSDimitry Andric     return;
104bab175ecSDimitry Andric   }
105bab175ecSDimitry Andric 
106ac9a064cSDimitry Andric   CurCoro.Data = std::make_unique<CGCoroData>();
107bab175ecSDimitry Andric   CurCoro.Data->CoroId = CoroId;
108bab175ecSDimitry Andric   CurCoro.Data->CoroIdExpr = CoroIdExpr;
109bab175ecSDimitry Andric }
110bab175ecSDimitry Andric 
1117442d6faSDimitry Andric // Synthesize a pretty name for a suspend point.
buildSuspendPrefixStr(CGCoroData & Coro,AwaitKind Kind)1127442d6faSDimitry Andric static SmallString<32> buildSuspendPrefixStr(CGCoroData &Coro, AwaitKind Kind) {
1137442d6faSDimitry Andric   unsigned No = 0;
1147442d6faSDimitry Andric   switch (Kind) {
1157442d6faSDimitry Andric   case AwaitKind::Init:
1167442d6faSDimitry Andric   case AwaitKind::Final:
1177442d6faSDimitry Andric     break;
1187442d6faSDimitry Andric   case AwaitKind::Normal:
1197442d6faSDimitry Andric     No = ++Coro.AwaitNum;
1207442d6faSDimitry Andric     break;
1217442d6faSDimitry Andric   case AwaitKind::Yield:
1227442d6faSDimitry Andric     No = ++Coro.YieldNum;
1237442d6faSDimitry Andric     break;
1247442d6faSDimitry Andric   }
1257442d6faSDimitry Andric   SmallString<32> Prefix(AwaitKindStr[static_cast<unsigned>(Kind)]);
1267442d6faSDimitry Andric   if (No > 1) {
1277442d6faSDimitry Andric     Twine(No).toVector(Prefix);
1287442d6faSDimitry Andric   }
1297442d6faSDimitry Andric   return Prefix;
1307442d6faSDimitry Andric }
1317442d6faSDimitry Andric 
132b1c73532SDimitry Andric // Check if function can throw based on prototype noexcept, also works for
133b1c73532SDimitry Andric // destructors which are implicitly noexcept but can be marked noexcept(false).
FunctionCanThrow(const FunctionDecl * D)134b1c73532SDimitry Andric static bool FunctionCanThrow(const FunctionDecl *D) {
135b1c73532SDimitry Andric   const auto *Proto = D->getType()->getAs<FunctionProtoType>();
136b1c73532SDimitry Andric   if (!Proto) {
137b1c73532SDimitry Andric     // Function proto is not found, we conservatively assume throwing.
13848675466SDimitry Andric     return true;
13948675466SDimitry Andric   }
140b1c73532SDimitry Andric   return !isNoexceptExceptionSpec(Proto->getExceptionSpecType()) ||
141b1c73532SDimitry Andric          Proto->canThrow() != CT_Cannot;
142b1c73532SDimitry Andric }
143b1c73532SDimitry Andric 
StmtCanThrow(const Stmt * S)144ac9a064cSDimitry Andric static bool StmtCanThrow(const Stmt *S) {
145b1c73532SDimitry Andric   if (const auto *CE = dyn_cast<CallExpr>(S)) {
146b1c73532SDimitry Andric     const auto *Callee = CE->getDirectCallee();
147b1c73532SDimitry Andric     if (!Callee)
148b1c73532SDimitry Andric       // We don't have direct callee. Conservatively assume throwing.
149b1c73532SDimitry Andric       return true;
150b1c73532SDimitry Andric 
151b1c73532SDimitry Andric     if (FunctionCanThrow(Callee))
152b1c73532SDimitry Andric       return true;
153b1c73532SDimitry Andric 
154b1c73532SDimitry Andric     // Fall through to visit the children.
155b1c73532SDimitry Andric   }
156b1c73532SDimitry Andric 
157b1c73532SDimitry Andric   if (const auto *TE = dyn_cast<CXXBindTemporaryExpr>(S)) {
158b1c73532SDimitry Andric     // Special handling of CXXBindTemporaryExpr here as calling of Dtor of the
159b1c73532SDimitry Andric     // temporary is not part of `children()` as covered in the fall through.
160b1c73532SDimitry Andric     // We need to mark entire statement as throwing if the destructor of the
161b1c73532SDimitry Andric     // temporary throws.
162b1c73532SDimitry Andric     const auto *Dtor = TE->getTemporary()->getDestructor();
163b1c73532SDimitry Andric     if (FunctionCanThrow(Dtor))
164b1c73532SDimitry Andric       return true;
165b1c73532SDimitry Andric 
166b1c73532SDimitry Andric     // Fall through to visit the children.
167b1c73532SDimitry Andric   }
168b1c73532SDimitry Andric 
169b1c73532SDimitry Andric   for (const auto *child : S->children())
170ac9a064cSDimitry Andric     if (StmtCanThrow(child))
171b1c73532SDimitry Andric       return true;
172b1c73532SDimitry Andric 
173b1c73532SDimitry Andric   return false;
174b1c73532SDimitry Andric }
17548675466SDimitry Andric 
1767442d6faSDimitry Andric // Emit suspend expression which roughly looks like:
1777442d6faSDimitry Andric //
1787442d6faSDimitry Andric //   auto && x = CommonExpr();
1797442d6faSDimitry Andric //   if (!x.await_ready()) {
1807442d6faSDimitry Andric //      llvm_coro_save();
181ac9a064cSDimitry Andric //      llvm_coro_await_suspend(&x, frame, wrapper) (*) (**)
182ac9a064cSDimitry Andric //      llvm_coro_suspend(); (***)
1837442d6faSDimitry Andric //   }
1847442d6faSDimitry Andric //   x.await_resume();
1857442d6faSDimitry Andric //
1867442d6faSDimitry Andric // where the result of the entire expression is the result of x.await_resume()
1877442d6faSDimitry Andric //
188ac9a064cSDimitry Andric //   (*) llvm_coro_await_suspend_{void, bool, handle} is lowered to
189ac9a064cSDimitry Andric //      wrapper(&x, frame) when it's certain not to interfere with
190ac9a064cSDimitry Andric //      coroutine transform. await_suspend expression is
191ac9a064cSDimitry Andric //      asynchronous to the coroutine body and not all analyses
192ac9a064cSDimitry Andric //      and transformations can handle it correctly at the moment.
193ac9a064cSDimitry Andric //
194ac9a064cSDimitry Andric //      Wrapper function encapsulates x.await_suspend(...) call and looks like:
195ac9a064cSDimitry Andric //
196ac9a064cSDimitry Andric //      auto __await_suspend_wrapper(auto& awaiter, void* frame) {
197ac9a064cSDimitry Andric //        std::coroutine_handle<> handle(frame);
198ac9a064cSDimitry Andric //        return awaiter.await_suspend(handle);
199ac9a064cSDimitry Andric //      }
200ac9a064cSDimitry Andric //
201ac9a064cSDimitry Andric //  (**) If x.await_suspend return type is bool, it allows to veto a suspend:
2027442d6faSDimitry Andric //      if (x.await_suspend(...))
2037442d6faSDimitry Andric //        llvm_coro_suspend();
2047442d6faSDimitry Andric //
205ac9a064cSDimitry Andric //  (***) llvm_coro_suspend() encodes three possible continuations as
2067442d6faSDimitry Andric //       a switch instruction:
2077442d6faSDimitry Andric //
2087442d6faSDimitry Andric //  %where-to = call i8 @llvm.coro.suspend(...)
2097442d6faSDimitry Andric //  switch i8 %where-to, label %coro.ret [ ; jump to epilogue to suspend
2107442d6faSDimitry Andric //    i8 0, label %yield.ready   ; go here when resumed
2117442d6faSDimitry Andric //    i8 1, label %yield.cleanup ; go here when destroyed
2127442d6faSDimitry Andric //  ]
2137442d6faSDimitry Andric //
2147442d6faSDimitry Andric //  See llvm's docs/Coroutines.rst for more details.
2157442d6faSDimitry Andric //
216325377b5SDimitry Andric namespace {
217325377b5SDimitry Andric   struct LValueOrRValue {
218325377b5SDimitry Andric     LValue LV;
219325377b5SDimitry Andric     RValue RV;
220325377b5SDimitry Andric   };
221325377b5SDimitry Andric }
emitSuspendExpression(CodeGenFunction & CGF,CGCoroData & Coro,CoroutineSuspendExpr const & S,AwaitKind Kind,AggValueSlot aggSlot,bool ignoreResult,bool forLValue)222325377b5SDimitry Andric static LValueOrRValue emitSuspendExpression(CodeGenFunction &CGF, CGCoroData &Coro,
2237442d6faSDimitry Andric                                     CoroutineSuspendExpr const &S,
2247442d6faSDimitry Andric                                     AwaitKind Kind, AggValueSlot aggSlot,
225325377b5SDimitry Andric                                     bool ignoreResult, bool forLValue) {
2267442d6faSDimitry Andric   auto *E = S.getCommonExpr();
227b5aee35cSDimitry Andric 
228ac9a064cSDimitry Andric   auto CommonBinder =
2297442d6faSDimitry Andric       CodeGenFunction::OpaqueValueMappingData::bind(CGF, S.getOpaqueValue(), E);
230ac9a064cSDimitry Andric   auto UnbindCommonOnExit =
231ac9a064cSDimitry Andric       llvm::make_scope_exit([&] { CommonBinder.unbind(CGF); });
2327442d6faSDimitry Andric 
2337442d6faSDimitry Andric   auto Prefix = buildSuspendPrefixStr(Coro, Kind);
2347442d6faSDimitry Andric   BasicBlock *ReadyBlock = CGF.createBasicBlock(Prefix + Twine(".ready"));
2357442d6faSDimitry Andric   BasicBlock *SuspendBlock = CGF.createBasicBlock(Prefix + Twine(".suspend"));
2367442d6faSDimitry Andric   BasicBlock *CleanupBlock = CGF.createBasicBlock(Prefix + Twine(".cleanup"));
2377442d6faSDimitry Andric 
2387442d6faSDimitry Andric   // If expression is ready, no need to suspend.
2397442d6faSDimitry Andric   CGF.EmitBranchOnBoolExpr(S.getReadyExpr(), ReadyBlock, SuspendBlock, 0);
2407442d6faSDimitry Andric 
2417442d6faSDimitry Andric   // Otherwise, emit suspend logic.
2427442d6faSDimitry Andric   CGF.EmitBlock(SuspendBlock);
2437442d6faSDimitry Andric 
2447442d6faSDimitry Andric   auto &Builder = CGF.Builder;
2457442d6faSDimitry Andric   llvm::Function *CoroSave = CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_save);
2467442d6faSDimitry Andric   auto *NullPtr = llvm::ConstantPointerNull::get(CGF.CGM.Int8PtrTy);
2477442d6faSDimitry Andric   auto *SaveCall = Builder.CreateCall(CoroSave, {NullPtr});
2487442d6faSDimitry Andric 
249ac9a064cSDimitry Andric   auto SuspendWrapper = CodeGenFunction(CGF.CGM).generateAwaitSuspendWrapper(
250ac9a064cSDimitry Andric       CGF.CurFn->getName(), Prefix, S);
251ac9a064cSDimitry Andric 
2527fa27ce4SDimitry Andric   CGF.CurCoro.InSuspendBlock = true;
253ac9a064cSDimitry Andric 
254ac9a064cSDimitry Andric   assert(CGF.CurCoro.Data && CGF.CurCoro.Data->CoroBegin &&
255ac9a064cSDimitry Andric          "expected to be called in coroutine context");
256ac9a064cSDimitry Andric 
257ac9a064cSDimitry Andric   SmallVector<llvm::Value *, 3> SuspendIntrinsicCallArgs;
258ac9a064cSDimitry Andric   SuspendIntrinsicCallArgs.push_back(
259ac9a064cSDimitry Andric       CGF.getOrCreateOpaqueLValueMapping(S.getOpaqueValue()).getPointer(CGF));
260ac9a064cSDimitry Andric 
261ac9a064cSDimitry Andric   SuspendIntrinsicCallArgs.push_back(CGF.CurCoro.Data->CoroBegin);
262ac9a064cSDimitry Andric   SuspendIntrinsicCallArgs.push_back(SuspendWrapper);
263ac9a064cSDimitry Andric 
264ac9a064cSDimitry Andric   const auto SuspendReturnType = S.getSuspendReturnType();
265ac9a064cSDimitry Andric   llvm::Intrinsic::ID AwaitSuspendIID;
266ac9a064cSDimitry Andric 
267ac9a064cSDimitry Andric   switch (SuspendReturnType) {
268ac9a064cSDimitry Andric   case CoroutineSuspendExpr::SuspendReturnType::SuspendVoid:
269ac9a064cSDimitry Andric     AwaitSuspendIID = llvm::Intrinsic::coro_await_suspend_void;
270ac9a064cSDimitry Andric     break;
271ac9a064cSDimitry Andric   case CoroutineSuspendExpr::SuspendReturnType::SuspendBool:
272ac9a064cSDimitry Andric     AwaitSuspendIID = llvm::Intrinsic::coro_await_suspend_bool;
273ac9a064cSDimitry Andric     break;
274ac9a064cSDimitry Andric   case CoroutineSuspendExpr::SuspendReturnType::SuspendHandle:
275ac9a064cSDimitry Andric     AwaitSuspendIID = llvm::Intrinsic::coro_await_suspend_handle;
276ac9a064cSDimitry Andric     break;
277ac9a064cSDimitry Andric   }
278ac9a064cSDimitry Andric 
279ac9a064cSDimitry Andric   llvm::Function *AwaitSuspendIntrinsic = CGF.CGM.getIntrinsic(AwaitSuspendIID);
280ac9a064cSDimitry Andric 
281ac9a064cSDimitry Andric   // SuspendHandle might throw since it also resumes the returned handle.
282ac9a064cSDimitry Andric   const bool AwaitSuspendCanThrow =
283ac9a064cSDimitry Andric       SuspendReturnType ==
284ac9a064cSDimitry Andric           CoroutineSuspendExpr::SuspendReturnType::SuspendHandle ||
285ac9a064cSDimitry Andric       StmtCanThrow(S.getSuspendExpr());
286ac9a064cSDimitry Andric 
287ac9a064cSDimitry Andric   llvm::CallBase *SuspendRet = nullptr;
288ac9a064cSDimitry Andric   // FIXME: add call attributes?
289ac9a064cSDimitry Andric   if (AwaitSuspendCanThrow)
290ac9a064cSDimitry Andric     SuspendRet =
291ac9a064cSDimitry Andric         CGF.EmitCallOrInvoke(AwaitSuspendIntrinsic, SuspendIntrinsicCallArgs);
292ac9a064cSDimitry Andric   else
293ac9a064cSDimitry Andric     SuspendRet = CGF.EmitNounwindRuntimeCall(AwaitSuspendIntrinsic,
294ac9a064cSDimitry Andric                                              SuspendIntrinsicCallArgs);
295ac9a064cSDimitry Andric 
296ac9a064cSDimitry Andric   assert(SuspendRet);
2977fa27ce4SDimitry Andric   CGF.CurCoro.InSuspendBlock = false;
298b1c73532SDimitry Andric 
299ac9a064cSDimitry Andric   switch (SuspendReturnType) {
300ac9a064cSDimitry Andric   case CoroutineSuspendExpr::SuspendReturnType::SuspendVoid:
301ac9a064cSDimitry Andric     assert(SuspendRet->getType()->isVoidTy());
302ac9a064cSDimitry Andric     break;
303ac9a064cSDimitry Andric   case CoroutineSuspendExpr::SuspendReturnType::SuspendBool: {
304ac9a064cSDimitry Andric     assert(SuspendRet->getType()->isIntegerTy());
305ac9a064cSDimitry Andric 
3067442d6faSDimitry Andric     // Veto suspension if requested by bool returning await_suspend.
3077442d6faSDimitry Andric     BasicBlock *RealSuspendBlock =
3087442d6faSDimitry Andric         CGF.createBasicBlock(Prefix + Twine(".suspend.bool"));
3097442d6faSDimitry Andric     CGF.Builder.CreateCondBr(SuspendRet, RealSuspendBlock, ReadyBlock);
3107442d6faSDimitry Andric     CGF.EmitBlock(RealSuspendBlock);
311ac9a064cSDimitry Andric     break;
312ac9a064cSDimitry Andric   }
313ac9a064cSDimitry Andric   case CoroutineSuspendExpr::SuspendReturnType::SuspendHandle: {
314ac9a064cSDimitry Andric     assert(SuspendRet->getType()->isVoidTy());
315ac9a064cSDimitry Andric     break;
316ac9a064cSDimitry Andric   }
3177442d6faSDimitry Andric   }
3187442d6faSDimitry Andric 
3197442d6faSDimitry Andric   // Emit the suspend point.
3207442d6faSDimitry Andric   const bool IsFinalSuspend = (Kind == AwaitKind::Final);
3217442d6faSDimitry Andric   llvm::Function *CoroSuspend =
3227442d6faSDimitry Andric       CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_suspend);
3237442d6faSDimitry Andric   auto *SuspendResult = Builder.CreateCall(
3247442d6faSDimitry Andric       CoroSuspend, {SaveCall, Builder.getInt1(IsFinalSuspend)});
3257442d6faSDimitry Andric 
3267442d6faSDimitry Andric   // Create a switch capturing three possible continuations.
3277442d6faSDimitry Andric   auto *Switch = Builder.CreateSwitch(SuspendResult, Coro.SuspendBB, 2);
3287442d6faSDimitry Andric   Switch->addCase(Builder.getInt8(0), ReadyBlock);
3297442d6faSDimitry Andric   Switch->addCase(Builder.getInt8(1), CleanupBlock);
3307442d6faSDimitry Andric 
3317442d6faSDimitry Andric   // Emit cleanup for this suspend point.
3327442d6faSDimitry Andric   CGF.EmitBlock(CleanupBlock);
3337442d6faSDimitry Andric   CGF.EmitBranchThroughCleanup(Coro.CleanupJD);
3347442d6faSDimitry Andric 
3357442d6faSDimitry Andric   // Emit await_resume expression.
3367442d6faSDimitry Andric   CGF.EmitBlock(ReadyBlock);
33748675466SDimitry Andric 
33848675466SDimitry Andric   // Exception handling requires additional IR. If the 'await_resume' function
33948675466SDimitry Andric   // is marked as 'noexcept', we avoid generating this additional IR.
34048675466SDimitry Andric   CXXTryStmt *TryStmt = nullptr;
34148675466SDimitry Andric   if (Coro.ExceptionHandler && Kind == AwaitKind::Init &&
342ac9a064cSDimitry Andric       StmtCanThrow(S.getResumeExpr())) {
34348675466SDimitry Andric     Coro.ResumeEHVar =
34448675466SDimitry Andric         CGF.CreateTempAlloca(Builder.getInt1Ty(), Prefix + Twine("resume.eh"));
34548675466SDimitry Andric     Builder.CreateFlagStore(true, Coro.ResumeEHVar);
34648675466SDimitry Andric 
34748675466SDimitry Andric     auto Loc = S.getResumeExpr()->getExprLoc();
34848675466SDimitry Andric     auto *Catch = new (CGF.getContext())
34948675466SDimitry Andric         CXXCatchStmt(Loc, /*exDecl=*/nullptr, Coro.ExceptionHandler);
350145449b1SDimitry Andric     auto *TryBody = CompoundStmt::Create(CGF.getContext(), S.getResumeExpr(),
351145449b1SDimitry Andric                                          FPOptionsOverride(), Loc, Loc);
35248675466SDimitry Andric     TryStmt = CXXTryStmt::Create(CGF.getContext(), Loc, TryBody, Catch);
35348675466SDimitry Andric     CGF.EnterCXXTryStmt(*TryStmt);
354b1c73532SDimitry Andric     CGF.EmitStmt(TryBody);
355b1c73532SDimitry Andric     // We don't use EmitCXXTryStmt here. We need to store to ResumeEHVar that
356b1c73532SDimitry Andric     // doesn't exist in the body.
357b1c73532SDimitry Andric     Builder.CreateFlagStore(false, Coro.ResumeEHVar);
358b1c73532SDimitry Andric     CGF.ExitCXXTryStmt(*TryStmt);
359b1c73532SDimitry Andric     LValueOrRValue Res;
360b1c73532SDimitry Andric     // We are not supposed to obtain the value from init suspend await_resume().
361b1c73532SDimitry Andric     Res.RV = RValue::getIgnored();
362b1c73532SDimitry Andric     return Res;
36348675466SDimitry Andric   }
36448675466SDimitry Andric 
365325377b5SDimitry Andric   LValueOrRValue Res;
366325377b5SDimitry Andric   if (forLValue)
367325377b5SDimitry Andric     Res.LV = CGF.EmitLValue(S.getResumeExpr());
368325377b5SDimitry Andric   else
369325377b5SDimitry Andric     Res.RV = CGF.EmitAnyExpr(S.getResumeExpr(), aggSlot, ignoreResult);
37048675466SDimitry Andric 
371325377b5SDimitry Andric   return Res;
3727442d6faSDimitry Andric }
3737442d6faSDimitry Andric 
EmitCoawaitExpr(const CoawaitExpr & E,AggValueSlot aggSlot,bool ignoreResult)3747442d6faSDimitry Andric RValue CodeGenFunction::EmitCoawaitExpr(const CoawaitExpr &E,
3757442d6faSDimitry Andric                                         AggValueSlot aggSlot,
3767442d6faSDimitry Andric                                         bool ignoreResult) {
3777442d6faSDimitry Andric   return emitSuspendExpression(*this, *CurCoro.Data, E,
3787442d6faSDimitry Andric                                CurCoro.Data->CurrentAwaitKind, aggSlot,
379325377b5SDimitry Andric                                ignoreResult, /*forLValue*/false).RV;
3807442d6faSDimitry Andric }
EmitCoyieldExpr(const CoyieldExpr & E,AggValueSlot aggSlot,bool ignoreResult)3817442d6faSDimitry Andric RValue CodeGenFunction::EmitCoyieldExpr(const CoyieldExpr &E,
3827442d6faSDimitry Andric                                         AggValueSlot aggSlot,
3837442d6faSDimitry Andric                                         bool ignoreResult) {
3847442d6faSDimitry Andric   return emitSuspendExpression(*this, *CurCoro.Data, E, AwaitKind::Yield,
385325377b5SDimitry Andric                                aggSlot, ignoreResult, /*forLValue*/false).RV;
3867442d6faSDimitry Andric }
3877442d6faSDimitry Andric 
EmitCoreturnStmt(CoreturnStmt const & S)3887442d6faSDimitry Andric void CodeGenFunction::EmitCoreturnStmt(CoreturnStmt const &S) {
3897442d6faSDimitry Andric   ++CurCoro.Data->CoreturnCount;
390461a67faSDimitry Andric   const Expr *RV = S.getOperand();
391cfca06d7SDimitry Andric   if (RV && RV->getType()->isVoidType() && !isa<InitListExpr>(RV)) {
392cfca06d7SDimitry Andric     // Make sure to evaluate the non initlist expression of a co_return
393cfca06d7SDimitry Andric     // with a void expression for side effects.
394461a67faSDimitry Andric     RunCleanupsScope cleanupScope(*this);
395461a67faSDimitry Andric     EmitIgnoredExpr(RV);
396461a67faSDimitry Andric   }
3977442d6faSDimitry Andric   EmitStmt(S.getPromiseCall());
3987442d6faSDimitry Andric   EmitBranchThroughCleanup(CurCoro.Data->FinalJD);
3997442d6faSDimitry Andric }
4007442d6faSDimitry Andric 
401325377b5SDimitry Andric 
402325377b5SDimitry Andric #ifndef NDEBUG
getCoroutineSuspendExprReturnType(const ASTContext & Ctx,const CoroutineSuspendExpr * E)403325377b5SDimitry Andric static QualType getCoroutineSuspendExprReturnType(const ASTContext &Ctx,
404325377b5SDimitry Andric   const CoroutineSuspendExpr *E) {
405325377b5SDimitry Andric   const auto *RE = E->getResumeExpr();
406325377b5SDimitry Andric   // Is it possible for RE to be a CXXBindTemporaryExpr wrapping
407325377b5SDimitry Andric   // a MemberCallExpr?
408325377b5SDimitry Andric   assert(isa<CallExpr>(RE) && "unexpected suspend expression type");
409325377b5SDimitry Andric   return cast<CallExpr>(RE)->getCallReturnType(Ctx);
410325377b5SDimitry Andric }
411325377b5SDimitry Andric #endif
412325377b5SDimitry Andric 
413ac9a064cSDimitry Andric llvm::Function *
generateAwaitSuspendWrapper(Twine const & CoroName,Twine const & SuspendPointName,CoroutineSuspendExpr const & S)414ac9a064cSDimitry Andric CodeGenFunction::generateAwaitSuspendWrapper(Twine const &CoroName,
415ac9a064cSDimitry Andric                                              Twine const &SuspendPointName,
416ac9a064cSDimitry Andric                                              CoroutineSuspendExpr const &S) {
417ac9a064cSDimitry Andric   std::string FuncName =
418ac9a064cSDimitry Andric       (CoroName + ".__await_suspend_wrapper__" + SuspendPointName).str();
419ac9a064cSDimitry Andric 
420ac9a064cSDimitry Andric   ASTContext &C = getContext();
421ac9a064cSDimitry Andric 
422ac9a064cSDimitry Andric   FunctionArgList args;
423ac9a064cSDimitry Andric 
424ac9a064cSDimitry Andric   ImplicitParamDecl AwaiterDecl(C, C.VoidPtrTy, ImplicitParamKind::Other);
425ac9a064cSDimitry Andric   ImplicitParamDecl FrameDecl(C, C.VoidPtrTy, ImplicitParamKind::Other);
426ac9a064cSDimitry Andric   QualType ReturnTy = S.getSuspendExpr()->getType();
427ac9a064cSDimitry Andric 
428ac9a064cSDimitry Andric   args.push_back(&AwaiterDecl);
429ac9a064cSDimitry Andric   args.push_back(&FrameDecl);
430ac9a064cSDimitry Andric 
431ac9a064cSDimitry Andric   const CGFunctionInfo &FI =
432ac9a064cSDimitry Andric       CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
433ac9a064cSDimitry Andric 
434ac9a064cSDimitry Andric   llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
435ac9a064cSDimitry Andric 
436ac9a064cSDimitry Andric   llvm::Function *Fn = llvm::Function::Create(
437ac9a064cSDimitry Andric       LTy, llvm::GlobalValue::PrivateLinkage, FuncName, &CGM.getModule());
438ac9a064cSDimitry Andric 
439ac9a064cSDimitry Andric   Fn->addParamAttr(0, llvm::Attribute::AttrKind::NonNull);
440ac9a064cSDimitry Andric   Fn->addParamAttr(0, llvm::Attribute::AttrKind::NoUndef);
441ac9a064cSDimitry Andric 
442ac9a064cSDimitry Andric   Fn->addParamAttr(1, llvm::Attribute::AttrKind::NoUndef);
443ac9a064cSDimitry Andric 
444ac9a064cSDimitry Andric   Fn->setMustProgress();
445ac9a064cSDimitry Andric   Fn->addFnAttr(llvm::Attribute::AttrKind::AlwaysInline);
446ac9a064cSDimitry Andric 
447ac9a064cSDimitry Andric   StartFunction(GlobalDecl(), ReturnTy, Fn, FI, args);
448ac9a064cSDimitry Andric 
449ac9a064cSDimitry Andric   // FIXME: add TBAA metadata to the loads
450ac9a064cSDimitry Andric   llvm::Value *AwaiterPtr = Builder.CreateLoad(GetAddrOfLocalVar(&AwaiterDecl));
451ac9a064cSDimitry Andric   auto AwaiterLValue =
452ac9a064cSDimitry Andric       MakeNaturalAlignAddrLValue(AwaiterPtr, AwaiterDecl.getType());
453ac9a064cSDimitry Andric 
454ac9a064cSDimitry Andric   CurAwaitSuspendWrapper.FramePtr =
455ac9a064cSDimitry Andric       Builder.CreateLoad(GetAddrOfLocalVar(&FrameDecl));
456ac9a064cSDimitry Andric 
457ac9a064cSDimitry Andric   auto AwaiterBinder = CodeGenFunction::OpaqueValueMappingData::bind(
458ac9a064cSDimitry Andric       *this, S.getOpaqueValue(), AwaiterLValue);
459ac9a064cSDimitry Andric 
460ac9a064cSDimitry Andric   auto *SuspendRet = EmitScalarExpr(S.getSuspendExpr());
461ac9a064cSDimitry Andric 
462ac9a064cSDimitry Andric   auto UnbindCommonOnExit =
463ac9a064cSDimitry Andric       llvm::make_scope_exit([&] { AwaiterBinder.unbind(*this); });
464ac9a064cSDimitry Andric   if (SuspendRet != nullptr) {
465ac9a064cSDimitry Andric     Fn->addRetAttr(llvm::Attribute::AttrKind::NoUndef);
466ac9a064cSDimitry Andric     Builder.CreateStore(SuspendRet, ReturnValue);
467ac9a064cSDimitry Andric   }
468ac9a064cSDimitry Andric 
469ac9a064cSDimitry Andric   CurAwaitSuspendWrapper.FramePtr = nullptr;
470ac9a064cSDimitry Andric   FinishFunction();
471ac9a064cSDimitry Andric   return Fn;
472ac9a064cSDimitry Andric }
473ac9a064cSDimitry Andric 
474325377b5SDimitry Andric LValue
EmitCoawaitLValue(const CoawaitExpr * E)475325377b5SDimitry Andric CodeGenFunction::EmitCoawaitLValue(const CoawaitExpr *E) {
476325377b5SDimitry Andric   assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
477325377b5SDimitry Andric          "Can't have a scalar return unless the return type is a "
478325377b5SDimitry Andric          "reference type!");
479325377b5SDimitry Andric   return emitSuspendExpression(*this, *CurCoro.Data, *E,
480325377b5SDimitry Andric                                CurCoro.Data->CurrentAwaitKind, AggValueSlot::ignored(),
481325377b5SDimitry Andric                                /*ignoreResult*/false, /*forLValue*/true).LV;
482325377b5SDimitry Andric }
483325377b5SDimitry Andric 
484325377b5SDimitry Andric LValue
EmitCoyieldLValue(const CoyieldExpr * E)485325377b5SDimitry Andric CodeGenFunction::EmitCoyieldLValue(const CoyieldExpr *E) {
486325377b5SDimitry Andric   assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
487325377b5SDimitry Andric          "Can't have a scalar return unless the return type is a "
488325377b5SDimitry Andric          "reference type!");
489325377b5SDimitry Andric   return emitSuspendExpression(*this, *CurCoro.Data, *E,
490325377b5SDimitry Andric                                AwaitKind::Yield, AggValueSlot::ignored(),
491325377b5SDimitry Andric                                /*ignoreResult*/false, /*forLValue*/true).LV;
492325377b5SDimitry Andric }
493325377b5SDimitry Andric 
494b5aee35cSDimitry Andric // Hunts for the parameter reference in the parameter copy/move declaration.
495b5aee35cSDimitry Andric namespace {
496b5aee35cSDimitry Andric struct GetParamRef : public StmtVisitor<GetParamRef> {
497b5aee35cSDimitry Andric public:
498b5aee35cSDimitry Andric   DeclRefExpr *Expr = nullptr;
GetParamRef__anonf0638e350511::GetParamRef499b5aee35cSDimitry Andric   GetParamRef() {}
VisitDeclRefExpr__anonf0638e350511::GetParamRef500b5aee35cSDimitry Andric   void VisitDeclRefExpr(DeclRefExpr *E) {
501b5aee35cSDimitry Andric     assert(Expr == nullptr && "multilple declref in param move");
502b5aee35cSDimitry Andric     Expr = E;
503b5aee35cSDimitry Andric   }
VisitStmt__anonf0638e350511::GetParamRef504b5aee35cSDimitry Andric   void VisitStmt(Stmt *S) {
505b5aee35cSDimitry Andric     for (auto *C : S->children()) {
506b5aee35cSDimitry Andric       if (C)
507b5aee35cSDimitry Andric         Visit(C);
508b5aee35cSDimitry Andric     }
509b5aee35cSDimitry Andric   }
510b5aee35cSDimitry Andric };
511b5aee35cSDimitry Andric }
512b5aee35cSDimitry Andric 
513b5aee35cSDimitry Andric // This class replaces references to parameters to their copies by changing
514b5aee35cSDimitry Andric // the addresses in CGF.LocalDeclMap and restoring back the original values in
515b5aee35cSDimitry Andric // its destructor.
516b5aee35cSDimitry Andric 
517b5aee35cSDimitry Andric namespace {
518b5aee35cSDimitry Andric   struct ParamReferenceReplacerRAII {
519b5aee35cSDimitry Andric     CodeGenFunction::DeclMapTy SavedLocals;
520b5aee35cSDimitry Andric     CodeGenFunction::DeclMapTy& LocalDeclMap;
521b5aee35cSDimitry Andric 
ParamReferenceReplacerRAII__anonf0638e350611::ParamReferenceReplacerRAII522b5aee35cSDimitry Andric     ParamReferenceReplacerRAII(CodeGenFunction::DeclMapTy &LocalDeclMap)
523b5aee35cSDimitry Andric         : LocalDeclMap(LocalDeclMap) {}
524b5aee35cSDimitry Andric 
addCopy__anonf0638e350611::ParamReferenceReplacerRAII525b5aee35cSDimitry Andric     void addCopy(DeclStmt const *PM) {
526b5aee35cSDimitry Andric       // Figure out what param it refers to.
527b5aee35cSDimitry Andric 
528b5aee35cSDimitry Andric       assert(PM->isSingleDecl());
529b5aee35cSDimitry Andric       VarDecl const*VD = static_cast<VarDecl const*>(PM->getSingleDecl());
530b5aee35cSDimitry Andric       Expr const *InitExpr = VD->getInit();
531b5aee35cSDimitry Andric       GetParamRef Visitor;
532b5aee35cSDimitry Andric       Visitor.Visit(const_cast<Expr*>(InitExpr));
533b5aee35cSDimitry Andric       assert(Visitor.Expr);
53448675466SDimitry Andric       DeclRefExpr *DREOrig = Visitor.Expr;
535b5aee35cSDimitry Andric       auto *PD = DREOrig->getDecl();
536b5aee35cSDimitry Andric 
537b5aee35cSDimitry Andric       auto it = LocalDeclMap.find(PD);
538b5aee35cSDimitry Andric       assert(it != LocalDeclMap.end() && "parameter is not found");
539b5aee35cSDimitry Andric       SavedLocals.insert({ PD, it->second });
540b5aee35cSDimitry Andric 
541b5aee35cSDimitry Andric       auto copyIt = LocalDeclMap.find(VD);
542b5aee35cSDimitry Andric       assert(copyIt != LocalDeclMap.end() && "parameter copy is not found");
543b5aee35cSDimitry Andric       it->second = copyIt->getSecond();
544b5aee35cSDimitry Andric     }
545b5aee35cSDimitry Andric 
~ParamReferenceReplacerRAII__anonf0638e350611::ParamReferenceReplacerRAII546b5aee35cSDimitry Andric     ~ParamReferenceReplacerRAII() {
547b5aee35cSDimitry Andric       for (auto&& SavedLocal : SavedLocals) {
548b5aee35cSDimitry Andric         LocalDeclMap.insert({SavedLocal.first, SavedLocal.second});
549b5aee35cSDimitry Andric       }
550b5aee35cSDimitry Andric     }
551b5aee35cSDimitry Andric   };
552b5aee35cSDimitry Andric }
553b5aee35cSDimitry Andric 
554b5aee35cSDimitry Andric // For WinEH exception representation backend needs to know what funclet coro.end
5557442d6faSDimitry Andric // belongs to. That information is passed in a funclet bundle.
5567442d6faSDimitry Andric static SmallVector<llvm::OperandBundleDef, 1>
getBundlesForCoroEnd(CodeGenFunction & CGF)5577442d6faSDimitry Andric getBundlesForCoroEnd(CodeGenFunction &CGF) {
5587442d6faSDimitry Andric   SmallVector<llvm::OperandBundleDef, 1> BundleList;
5597442d6faSDimitry Andric 
5607442d6faSDimitry Andric   if (llvm::Instruction *EHPad = CGF.CurrentFuncletPad)
5617442d6faSDimitry Andric     BundleList.emplace_back("funclet", EHPad);
5627442d6faSDimitry Andric 
5637442d6faSDimitry Andric   return BundleList;
5647442d6faSDimitry Andric }
5657442d6faSDimitry Andric 
5667442d6faSDimitry Andric namespace {
5677442d6faSDimitry Andric // We will insert coro.end to cut any of the destructors for objects that
5687442d6faSDimitry Andric // do not need to be destroyed once the coroutine is resumed.
5697442d6faSDimitry Andric // See llvm/docs/Coroutines.rst for more details about coro.end.
5707442d6faSDimitry Andric struct CallCoroEnd final : public EHScopeStack::Cleanup {
Emit__anonf0638e350711::CallCoroEnd5717442d6faSDimitry Andric   void Emit(CodeGenFunction &CGF, Flags flags) override {
5727442d6faSDimitry Andric     auto &CGM = CGF.CGM;
5737442d6faSDimitry Andric     auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
5747442d6faSDimitry Andric     llvm::Function *CoroEndFn = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
5757442d6faSDimitry Andric     // See if we have a funclet bundle to associate coro.end with. (WinEH)
5767442d6faSDimitry Andric     auto Bundles = getBundlesForCoroEnd(CGF);
577b1c73532SDimitry Andric     auto *CoroEnd =
578b1c73532SDimitry Andric       CGF.Builder.CreateCall(CoroEndFn,
579b1c73532SDimitry Andric                              {NullPtr, CGF.Builder.getTrue(),
580b1c73532SDimitry Andric                               llvm::ConstantTokenNone::get(CoroEndFn->getContext())},
581b1c73532SDimitry Andric                              Bundles);
5827442d6faSDimitry Andric     if (Bundles.empty()) {
5837442d6faSDimitry Andric       // Otherwise, (landingpad model), create a conditional branch that leads
5847442d6faSDimitry Andric       // either to a cleanup block or a block with EH resume instruction.
58522989816SDimitry Andric       auto *ResumeBB = CGF.getEHResumeBlock(/*isCleanup=*/true);
5867442d6faSDimitry Andric       auto *CleanupContBB = CGF.createBasicBlock("cleanup.cont");
5877442d6faSDimitry Andric       CGF.Builder.CreateCondBr(CoroEnd, ResumeBB, CleanupContBB);
5887442d6faSDimitry Andric       CGF.EmitBlock(CleanupContBB);
5897442d6faSDimitry Andric     }
5907442d6faSDimitry Andric   }
5917442d6faSDimitry Andric };
5927442d6faSDimitry Andric }
5937442d6faSDimitry Andric 
5947442d6faSDimitry Andric namespace {
5957442d6faSDimitry Andric // Make sure to call coro.delete on scope exit.
5967442d6faSDimitry Andric struct CallCoroDelete final : public EHScopeStack::Cleanup {
5977442d6faSDimitry Andric   Stmt *Deallocate;
5987442d6faSDimitry Andric 
599b5aee35cSDimitry Andric   // Emit "if (coro.free(CoroId, CoroBegin)) Deallocate;"
600b5aee35cSDimitry Andric 
6017442d6faSDimitry Andric   // Note: That deallocation will be emitted twice: once for a normal exit and
6027442d6faSDimitry Andric   // once for exceptional exit. This usage is safe because Deallocate does not
6037442d6faSDimitry Andric   // contain any declarations. The SubStmtBuilder::makeNewAndDeleteExpr()
6047442d6faSDimitry Andric   // builds a single call to a deallocation function which is safe to emit
6057442d6faSDimitry Andric   // multiple times.
Emit__anonf0638e350811::CallCoroDelete606b5aee35cSDimitry Andric   void Emit(CodeGenFunction &CGF, Flags) override {
607b5aee35cSDimitry Andric     // Remember the current point, as we are going to emit deallocation code
608b5aee35cSDimitry Andric     // first to get to coro.free instruction that is an argument to a delete
609b5aee35cSDimitry Andric     // call.
610b5aee35cSDimitry Andric     BasicBlock *SaveInsertBlock = CGF.Builder.GetInsertBlock();
611b5aee35cSDimitry Andric 
612b5aee35cSDimitry Andric     auto *FreeBB = CGF.createBasicBlock("coro.free");
613b5aee35cSDimitry Andric     CGF.EmitBlock(FreeBB);
6147442d6faSDimitry Andric     CGF.EmitStmt(Deallocate);
615b5aee35cSDimitry Andric 
616b5aee35cSDimitry Andric     auto *AfterFreeBB = CGF.createBasicBlock("after.coro.free");
617b5aee35cSDimitry Andric     CGF.EmitBlock(AfterFreeBB);
618b5aee35cSDimitry Andric 
619b5aee35cSDimitry Andric     // We should have captured coro.free from the emission of deallocate.
620b5aee35cSDimitry Andric     auto *CoroFree = CGF.CurCoro.Data->LastCoroFree;
621b5aee35cSDimitry Andric     if (!CoroFree) {
622676fbe81SDimitry Andric       CGF.CGM.Error(Deallocate->getBeginLoc(),
623b5aee35cSDimitry Andric                     "Deallocation expressoin does not refer to coro.free");
624b5aee35cSDimitry Andric       return;
625b5aee35cSDimitry Andric     }
626b5aee35cSDimitry Andric 
627b5aee35cSDimitry Andric     // Get back to the block we were originally and move coro.free there.
628b5aee35cSDimitry Andric     auto *InsertPt = SaveInsertBlock->getTerminator();
629b5aee35cSDimitry Andric     CoroFree->moveBefore(InsertPt);
630b5aee35cSDimitry Andric     CGF.Builder.SetInsertPoint(InsertPt);
631b5aee35cSDimitry Andric 
632b5aee35cSDimitry Andric     // Add if (auto *mem = coro.free) Deallocate;
633b5aee35cSDimitry Andric     auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
634b5aee35cSDimitry Andric     auto *Cond = CGF.Builder.CreateICmpNE(CoroFree, NullPtr);
635b5aee35cSDimitry Andric     CGF.Builder.CreateCondBr(Cond, FreeBB, AfterFreeBB);
636b5aee35cSDimitry Andric 
637b5aee35cSDimitry Andric     // No longer need old terminator.
638b5aee35cSDimitry Andric     InsertPt->eraseFromParent();
639b5aee35cSDimitry Andric     CGF.Builder.SetInsertPoint(AfterFreeBB);
6407442d6faSDimitry Andric   }
CallCoroDelete__anonf0638e350811::CallCoroDelete6417442d6faSDimitry Andric   explicit CallCoroDelete(Stmt *DeallocStmt) : Deallocate(DeallocStmt) {}
6427442d6faSDimitry Andric };
6437442d6faSDimitry Andric }
6447442d6faSDimitry Andric 
6457fa27ce4SDimitry Andric namespace {
6467fa27ce4SDimitry Andric struct GetReturnObjectManager {
6477fa27ce4SDimitry Andric   CodeGenFunction &CGF;
6487fa27ce4SDimitry Andric   CGBuilderTy &Builder;
6497fa27ce4SDimitry Andric   const CoroutineBodyStmt &S;
6507fa27ce4SDimitry Andric   // When true, performs RVO for the return object.
6517fa27ce4SDimitry Andric   bool DirectEmit = false;
6527fa27ce4SDimitry Andric 
6537fa27ce4SDimitry Andric   Address GroActiveFlag;
6547fa27ce4SDimitry Andric   CodeGenFunction::AutoVarEmission GroEmission;
6557fa27ce4SDimitry Andric 
GetReturnObjectManager__anonf0638e350911::GetReturnObjectManager6567fa27ce4SDimitry Andric   GetReturnObjectManager(CodeGenFunction &CGF, const CoroutineBodyStmt &S)
6577fa27ce4SDimitry Andric       : CGF(CGF), Builder(CGF.Builder), S(S), GroActiveFlag(Address::invalid()),
6587fa27ce4SDimitry Andric         GroEmission(CodeGenFunction::AutoVarEmission::invalid()) {
6597fa27ce4SDimitry Andric     // The call to get_­return_­object is sequenced before the call to
6607fa27ce4SDimitry Andric     // initial_­suspend and is invoked at most once, but there are caveats
6617fa27ce4SDimitry Andric     // regarding on whether the prvalue result object may be initialized
6627fa27ce4SDimitry Andric     // directly/eager or delayed, depending on the types involved.
6637fa27ce4SDimitry Andric     //
6647fa27ce4SDimitry Andric     // More info at https://github.com/cplusplus/papers/issues/1414
6657fa27ce4SDimitry Andric     //
6667fa27ce4SDimitry Andric     // The general cases:
6677fa27ce4SDimitry Andric     // 1. Same type of get_return_object and coroutine return type (direct
6687fa27ce4SDimitry Andric     // emission):
6697fa27ce4SDimitry Andric     //  - Constructed in the return slot.
6707fa27ce4SDimitry Andric     // 2. Different types (delayed emission):
6717fa27ce4SDimitry Andric     //  - Constructed temporary object prior to initial suspend initialized with
6727fa27ce4SDimitry Andric     //  a call to get_return_object()
6737fa27ce4SDimitry Andric     //  - When coroutine needs to to return to the caller and needs to construct
6747fa27ce4SDimitry Andric     //  return value for the coroutine it is initialized with expiring value of
6757fa27ce4SDimitry Andric     //  the temporary obtained above.
6767fa27ce4SDimitry Andric     //
6777fa27ce4SDimitry Andric     // Direct emission for void returning coroutines or GROs.
6787fa27ce4SDimitry Andric     DirectEmit = [&]() {
6797fa27ce4SDimitry Andric       auto *RVI = S.getReturnValueInit();
6807fa27ce4SDimitry Andric       assert(RVI && "expected RVI");
6817fa27ce4SDimitry Andric       auto GroType = RVI->getType();
6827fa27ce4SDimitry Andric       return CGF.getContext().hasSameType(GroType, CGF.FnRetTy);
6837fa27ce4SDimitry Andric     }();
6847fa27ce4SDimitry Andric   }
6857fa27ce4SDimitry Andric 
6867fa27ce4SDimitry Andric   // The gro variable has to outlive coroutine frame and coroutine promise, but,
6877fa27ce4SDimitry Andric   // it can only be initialized after coroutine promise was created, thus, we
6887fa27ce4SDimitry Andric   // split its emission in two parts. EmitGroAlloca emits an alloca and sets up
6897fa27ce4SDimitry Andric   // cleanups. Later when coroutine promise is available we initialize the gro
6907fa27ce4SDimitry Andric   // and sets the flag that the cleanup is now active.
EmitGroAlloca__anonf0638e350911::GetReturnObjectManager6917fa27ce4SDimitry Andric   void EmitGroAlloca() {
6927fa27ce4SDimitry Andric     if (DirectEmit)
6937fa27ce4SDimitry Andric       return;
6947fa27ce4SDimitry Andric 
6957fa27ce4SDimitry Andric     auto *GroDeclStmt = dyn_cast_or_null<DeclStmt>(S.getResultDecl());
6967fa27ce4SDimitry Andric     if (!GroDeclStmt) {
6977fa27ce4SDimitry Andric       // If get_return_object returns void, no need to do an alloca.
6987fa27ce4SDimitry Andric       return;
6997fa27ce4SDimitry Andric     }
7007fa27ce4SDimitry Andric 
7017fa27ce4SDimitry Andric     auto *GroVarDecl = cast<VarDecl>(GroDeclStmt->getSingleDecl());
7027fa27ce4SDimitry Andric 
7037fa27ce4SDimitry Andric     // Set GRO flag that it is not initialized yet
7047fa27ce4SDimitry Andric     GroActiveFlag = CGF.CreateTempAlloca(Builder.getInt1Ty(), CharUnits::One(),
7057fa27ce4SDimitry Andric                                          "gro.active");
7067fa27ce4SDimitry Andric     Builder.CreateStore(Builder.getFalse(), GroActiveFlag);
7077fa27ce4SDimitry Andric 
7087fa27ce4SDimitry Andric     GroEmission = CGF.EmitAutoVarAlloca(*GroVarDecl);
709b1c73532SDimitry Andric     auto *GroAlloca = dyn_cast_or_null<llvm::AllocaInst>(
710b1c73532SDimitry Andric         GroEmission.getOriginalAllocatedAddress().getPointer());
711b1c73532SDimitry Andric     assert(GroAlloca && "expected alloca to be emitted");
712b1c73532SDimitry Andric     GroAlloca->setMetadata(llvm::LLVMContext::MD_coro_outside_frame,
713b1c73532SDimitry Andric                            llvm::MDNode::get(CGF.CGM.getLLVMContext(), {}));
7147fa27ce4SDimitry Andric 
7157fa27ce4SDimitry Andric     // Remember the top of EHStack before emitting the cleanup.
7167fa27ce4SDimitry Andric     auto old_top = CGF.EHStack.stable_begin();
7177fa27ce4SDimitry Andric     CGF.EmitAutoVarCleanups(GroEmission);
7187fa27ce4SDimitry Andric     auto top = CGF.EHStack.stable_begin();
7197fa27ce4SDimitry Andric 
7207fa27ce4SDimitry Andric     // Make the cleanup conditional on gro.active
7217fa27ce4SDimitry Andric     for (auto b = CGF.EHStack.find(top), e = CGF.EHStack.find(old_top); b != e;
7227fa27ce4SDimitry Andric          b++) {
7237fa27ce4SDimitry Andric       if (auto *Cleanup = dyn_cast<EHCleanupScope>(&*b)) {
7247fa27ce4SDimitry Andric         assert(!Cleanup->hasActiveFlag() && "cleanup already has active flag?");
7257fa27ce4SDimitry Andric         Cleanup->setActiveFlag(GroActiveFlag);
7267fa27ce4SDimitry Andric         Cleanup->setTestFlagInEHCleanup();
7277fa27ce4SDimitry Andric         Cleanup->setTestFlagInNormalCleanup();
7287fa27ce4SDimitry Andric       }
7297fa27ce4SDimitry Andric     }
7307fa27ce4SDimitry Andric   }
7317fa27ce4SDimitry Andric 
EmitGroInit__anonf0638e350911::GetReturnObjectManager7327fa27ce4SDimitry Andric   void EmitGroInit() {
7337fa27ce4SDimitry Andric     if (DirectEmit) {
7347fa27ce4SDimitry Andric       // ReturnValue should be valid as long as the coroutine's return type
7357fa27ce4SDimitry Andric       // is not void. The assertion could help us to reduce the check later.
7367fa27ce4SDimitry Andric       assert(CGF.ReturnValue.isValid() == (bool)S.getReturnStmt());
7377fa27ce4SDimitry Andric       // Now we have the promise, initialize the GRO.
7387fa27ce4SDimitry Andric       // We need to emit `get_return_object` first. According to:
7397fa27ce4SDimitry Andric       // [dcl.fct.def.coroutine]p7
7407fa27ce4SDimitry Andric       // The call to get_return_­object is sequenced before the call to
7417fa27ce4SDimitry Andric       // initial_suspend and is invoked at most once.
7427fa27ce4SDimitry Andric       //
7437fa27ce4SDimitry Andric       // So we couldn't emit return value when we emit return statment,
7447fa27ce4SDimitry Andric       // otherwise the call to get_return_object wouldn't be in front
7457fa27ce4SDimitry Andric       // of initial_suspend.
7467fa27ce4SDimitry Andric       if (CGF.ReturnValue.isValid()) {
7477fa27ce4SDimitry Andric         CGF.EmitAnyExprToMem(S.getReturnValue(), CGF.ReturnValue,
7487fa27ce4SDimitry Andric                              S.getReturnValue()->getType().getQualifiers(),
7497fa27ce4SDimitry Andric                              /*IsInit*/ true);
7507fa27ce4SDimitry Andric       }
7517fa27ce4SDimitry Andric       return;
7527fa27ce4SDimitry Andric     }
7537fa27ce4SDimitry Andric 
7547fa27ce4SDimitry Andric     if (!GroActiveFlag.isValid()) {
7557fa27ce4SDimitry Andric       // No Gro variable was allocated. Simply emit the call to
7567fa27ce4SDimitry Andric       // get_return_object.
7577fa27ce4SDimitry Andric       CGF.EmitStmt(S.getResultDecl());
7587fa27ce4SDimitry Andric       return;
7597fa27ce4SDimitry Andric     }
7607fa27ce4SDimitry Andric 
7617fa27ce4SDimitry Andric     CGF.EmitAutoVarInit(GroEmission);
7627fa27ce4SDimitry Andric     Builder.CreateStore(Builder.getTrue(), GroActiveFlag);
7637fa27ce4SDimitry Andric   }
7647fa27ce4SDimitry Andric };
7657fa27ce4SDimitry Andric } // namespace
7667fa27ce4SDimitry Andric 
emitBodyAndFallthrough(CodeGenFunction & CGF,const CoroutineBodyStmt & S,Stmt * Body)767b5aee35cSDimitry Andric static void emitBodyAndFallthrough(CodeGenFunction &CGF,
768b5aee35cSDimitry Andric                                    const CoroutineBodyStmt &S, Stmt *Body) {
769b5aee35cSDimitry Andric   CGF.EmitStmt(Body);
770b5aee35cSDimitry Andric   const bool CanFallthrough = CGF.Builder.GetInsertBlock();
771b5aee35cSDimitry Andric   if (CanFallthrough)
772b5aee35cSDimitry Andric     if (Stmt *OnFallthrough = S.getFallthroughHandler())
773b5aee35cSDimitry Andric       CGF.EmitStmt(OnFallthrough);
774b5aee35cSDimitry Andric }
775b5aee35cSDimitry Andric 
EmitCoroutineBody(const CoroutineBodyStmt & S)776bab175ecSDimitry Andric void CodeGenFunction::EmitCoroutineBody(const CoroutineBodyStmt &S) {
777b1c73532SDimitry Andric   auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getPtrTy());
778bab175ecSDimitry Andric   auto &TI = CGM.getContext().getTargetInfo();
779bab175ecSDimitry Andric   unsigned NewAlign = TI.getNewAlign() / TI.getCharWidth();
780bab175ecSDimitry Andric 
781b5aee35cSDimitry Andric   auto *EntryBB = Builder.GetInsertBlock();
782b5aee35cSDimitry Andric   auto *AllocBB = createBasicBlock("coro.alloc");
783b5aee35cSDimitry Andric   auto *InitBB = createBasicBlock("coro.init");
7847442d6faSDimitry Andric   auto *FinalBB = createBasicBlock("coro.final");
7857442d6faSDimitry Andric   auto *RetBB = createBasicBlock("coro.ret");
7867442d6faSDimitry Andric 
787bab175ecSDimitry Andric   auto *CoroId = Builder.CreateCall(
788bab175ecSDimitry Andric       CGM.getIntrinsic(llvm::Intrinsic::coro_id),
789bab175ecSDimitry Andric       {Builder.getInt32(NewAlign), NullPtr, NullPtr, NullPtr});
790bab175ecSDimitry Andric   createCoroData(*this, CurCoro, CoroId);
7917442d6faSDimitry Andric   CurCoro.Data->SuspendBB = RetBB;
792344a3780SDimitry Andric   assert(ShouldEmitLifetimeMarkers &&
793344a3780SDimitry Andric          "Must emit lifetime intrinsics for coroutines");
794bab175ecSDimitry Andric 
795b5aee35cSDimitry Andric   // Backend is allowed to elide memory allocations, to help it, emit
796b5aee35cSDimitry Andric   // auto mem = coro.alloc() ? 0 : ... allocation code ...;
797b5aee35cSDimitry Andric   auto *CoroAlloc = Builder.CreateCall(
798b5aee35cSDimitry Andric       CGM.getIntrinsic(llvm::Intrinsic::coro_alloc), {CoroId});
799b5aee35cSDimitry Andric 
800b5aee35cSDimitry Andric   Builder.CreateCondBr(CoroAlloc, AllocBB, InitBB);
801b5aee35cSDimitry Andric 
802b5aee35cSDimitry Andric   EmitBlock(AllocBB);
8037442d6faSDimitry Andric   auto *AllocateCall = EmitScalarExpr(S.getAllocate());
804b5aee35cSDimitry Andric   auto *AllocOrInvokeContBB = Builder.GetInsertBlock();
8057442d6faSDimitry Andric 
8067442d6faSDimitry Andric   // Handle allocation failure if 'ReturnStmtOnAllocFailure' was provided.
8077442d6faSDimitry Andric   if (auto *RetOnAllocFailure = S.getReturnStmtOnAllocFailure()) {
8087442d6faSDimitry Andric     auto *RetOnFailureBB = createBasicBlock("coro.ret.on.failure");
8097442d6faSDimitry Andric 
8107442d6faSDimitry Andric     // See if allocation was successful.
8117442d6faSDimitry Andric     auto *NullPtr = llvm::ConstantPointerNull::get(Int8PtrTy);
8127442d6faSDimitry Andric     auto *Cond = Builder.CreateICmpNE(AllocateCall, NullPtr);
8137fa27ce4SDimitry Andric     // Expect the allocation to be successful.
8147fa27ce4SDimitry Andric     emitCondLikelihoodViaExpectIntrinsic(Cond, Stmt::LH_Likely);
8157442d6faSDimitry Andric     Builder.CreateCondBr(Cond, InitBB, RetOnFailureBB);
8167442d6faSDimitry Andric 
8177442d6faSDimitry Andric     // If not, return OnAllocFailure object.
8187442d6faSDimitry Andric     EmitBlock(RetOnFailureBB);
8197442d6faSDimitry Andric     EmitStmt(RetOnAllocFailure);
820b5aee35cSDimitry Andric   }
821b5aee35cSDimitry Andric   else {
822b5aee35cSDimitry Andric     Builder.CreateBr(InitBB);
823b5aee35cSDimitry Andric   }
8247442d6faSDimitry Andric 
8257442d6faSDimitry Andric   EmitBlock(InitBB);
826b5aee35cSDimitry Andric 
827b5aee35cSDimitry Andric   // Pass the result of the allocation to coro.begin.
828b5aee35cSDimitry Andric   auto *Phi = Builder.CreatePHI(VoidPtrTy, 2);
829b5aee35cSDimitry Andric   Phi->addIncoming(NullPtr, EntryBB);
830b5aee35cSDimitry Andric   Phi->addIncoming(AllocateCall, AllocOrInvokeContBB);
831b5aee35cSDimitry Andric   auto *CoroBegin = Builder.CreateCall(
832b5aee35cSDimitry Andric       CGM.getIntrinsic(llvm::Intrinsic::coro_begin), {CoroId, Phi});
833b5aee35cSDimitry Andric   CurCoro.Data->CoroBegin = CoroBegin;
834b5aee35cSDimitry Andric 
8357fa27ce4SDimitry Andric   GetReturnObjectManager GroManager(*this, S);
8367fa27ce4SDimitry Andric   GroManager.EmitGroAlloca();
8377fa27ce4SDimitry Andric 
8387442d6faSDimitry Andric   CurCoro.Data->CleanupJD = getJumpDestInCurrentScope(RetBB);
8397442d6faSDimitry Andric   {
840344a3780SDimitry Andric     CGDebugInfo *DI = getDebugInfo();
841b5aee35cSDimitry Andric     ParamReferenceReplacerRAII ParamReplacer(LocalDeclMap);
8427442d6faSDimitry Andric     CodeGenFunction::RunCleanupsScope ResumeScope(*this);
8437442d6faSDimitry Andric     EHStack.pushCleanup<CallCoroDelete>(NormalAndEHCleanup, S.getDeallocate());
8447442d6faSDimitry Andric 
845344a3780SDimitry Andric     // Create mapping between parameters and copy-params for coroutine function.
846e3b55780SDimitry Andric     llvm::ArrayRef<const Stmt *> ParamMoves = S.getParamMoves();
847344a3780SDimitry Andric     assert(
848344a3780SDimitry Andric         (ParamMoves.size() == 0 || (ParamMoves.size() == FnArgs.size())) &&
849344a3780SDimitry Andric         "ParamMoves and FnArgs should be the same size for coroutine function");
850344a3780SDimitry Andric     if (ParamMoves.size() == FnArgs.size() && DI)
851344a3780SDimitry Andric       for (const auto Pair : llvm::zip(FnArgs, ParamMoves))
852344a3780SDimitry Andric         DI->getCoroutineParameterMappings().insert(
853344a3780SDimitry Andric             {std::get<0>(Pair), std::get<1>(Pair)});
854344a3780SDimitry Andric 
855b5aee35cSDimitry Andric     // Create parameter copies. We do it before creating a promise, since an
856b5aee35cSDimitry Andric     // evolution of coroutine TS may allow promise constructor to observe
857b5aee35cSDimitry Andric     // parameter copies.
858b5aee35cSDimitry Andric     for (auto *PM : S.getParamMoves()) {
859b5aee35cSDimitry Andric       EmitStmt(PM);
860b5aee35cSDimitry Andric       ParamReplacer.addCopy(cast<DeclStmt>(PM));
861b5aee35cSDimitry Andric       // TODO: if(CoroParam(...)) need to surround ctor and dtor
862b5aee35cSDimitry Andric       // for the copy, so that llvm can elide it if the copy is
863b5aee35cSDimitry Andric       // not needed.
864b5aee35cSDimitry Andric     }
865b5aee35cSDimitry Andric 
8667442d6faSDimitry Andric     EmitStmt(S.getPromiseDeclStmt());
8677442d6faSDimitry Andric 
868b5aee35cSDimitry Andric     Address PromiseAddr = GetAddrOfLocalVar(S.getPromiseDecl());
869ac9a064cSDimitry Andric     auto *PromiseAddrVoidPtr = new llvm::BitCastInst(
870ac9a064cSDimitry Andric         PromiseAddr.emitRawPointer(*this), VoidPtrTy, "", CoroId);
871b5aee35cSDimitry Andric     // Update CoroId to refer to the promise. We could not do it earlier because
872b5aee35cSDimitry Andric     // promise local variable was not emitted yet.
873b5aee35cSDimitry Andric     CoroId->setArgOperand(1, PromiseAddrVoidPtr);
874b5aee35cSDimitry Andric 
8757fa27ce4SDimitry Andric     // Now we have the promise, initialize the GRO
8767fa27ce4SDimitry Andric     GroManager.EmitGroInit();
877b5aee35cSDimitry Andric 
8787442d6faSDimitry Andric     EHStack.pushCleanup<CallCoroEnd>(EHCleanup);
8797442d6faSDimitry Andric 
880b5aee35cSDimitry Andric     CurCoro.Data->CurrentAwaitKind = AwaitKind::Init;
88148675466SDimitry Andric     CurCoro.Data->ExceptionHandler = S.getExceptionHandler();
882b5aee35cSDimitry Andric     EmitStmt(S.getInitSuspendStmt());
8837442d6faSDimitry Andric     CurCoro.Data->FinalJD = getJumpDestInCurrentScope(FinalBB);
8847442d6faSDimitry Andric 
8857442d6faSDimitry Andric     CurCoro.Data->CurrentAwaitKind = AwaitKind::Normal;
886b5aee35cSDimitry Andric 
88748675466SDimitry Andric     if (CurCoro.Data->ExceptionHandler) {
88848675466SDimitry Andric       // If we generated IR to record whether an exception was thrown from
88948675466SDimitry Andric       // 'await_resume', then use that IR to determine whether the coroutine
89048675466SDimitry Andric       // body should be skipped.
89148675466SDimitry Andric       // If we didn't generate the IR (perhaps because 'await_resume' was marked
89248675466SDimitry Andric       // as 'noexcept'), then we skip this check.
89348675466SDimitry Andric       BasicBlock *ContBB = nullptr;
89448675466SDimitry Andric       if (CurCoro.Data->ResumeEHVar) {
89548675466SDimitry Andric         BasicBlock *BodyBB = createBasicBlock("coro.resumed.body");
89648675466SDimitry Andric         ContBB = createBasicBlock("coro.resumed.cont");
89748675466SDimitry Andric         Value *SkipBody = Builder.CreateFlagLoad(CurCoro.Data->ResumeEHVar,
89848675466SDimitry Andric                                                  "coro.resumed.eh");
89948675466SDimitry Andric         Builder.CreateCondBr(SkipBody, ContBB, BodyBB);
90048675466SDimitry Andric         EmitBlock(BodyBB);
90148675466SDimitry Andric       }
90248675466SDimitry Andric 
903676fbe81SDimitry Andric       auto Loc = S.getBeginLoc();
90448675466SDimitry Andric       CXXCatchStmt Catch(Loc, /*exDecl=*/nullptr,
90548675466SDimitry Andric                          CurCoro.Data->ExceptionHandler);
90648675466SDimitry Andric       auto *TryStmt =
90748675466SDimitry Andric           CXXTryStmt::Create(getContext(), Loc, S.getBody(), &Catch);
908b5aee35cSDimitry Andric 
909b5aee35cSDimitry Andric       EnterCXXTryStmt(*TryStmt);
910b5aee35cSDimitry Andric       emitBodyAndFallthrough(*this, S, TryStmt->getTryBlock());
911b5aee35cSDimitry Andric       ExitCXXTryStmt(*TryStmt);
91248675466SDimitry Andric 
91348675466SDimitry Andric       if (ContBB)
91448675466SDimitry Andric         EmitBlock(ContBB);
915b5aee35cSDimitry Andric     }
916b5aee35cSDimitry Andric     else {
917b5aee35cSDimitry Andric       emitBodyAndFallthrough(*this, S, S.getBody());
918b5aee35cSDimitry Andric     }
9197442d6faSDimitry Andric 
9207442d6faSDimitry Andric     // See if we need to generate final suspend.
9217442d6faSDimitry Andric     const bool CanFallthrough = Builder.GetInsertBlock();
9227442d6faSDimitry Andric     const bool HasCoreturns = CurCoro.Data->CoreturnCount > 0;
9237442d6faSDimitry Andric     if (CanFallthrough || HasCoreturns) {
9247442d6faSDimitry Andric       EmitBlock(FinalBB);
925b5aee35cSDimitry Andric       CurCoro.Data->CurrentAwaitKind = AwaitKind::Final;
926b5aee35cSDimitry Andric       EmitStmt(S.getFinalSuspendStmt());
927550ae89aSDimitry Andric     } else {
928b5aee35cSDimitry Andric       // We don't need FinalBB. Emit it to make sure the block is deleted.
929b5aee35cSDimitry Andric       EmitBlock(FinalBB, /*IsFinished=*/true);
9307442d6faSDimitry Andric     }
9317442d6faSDimitry Andric   }
9327442d6faSDimitry Andric 
9337442d6faSDimitry Andric   EmitBlock(RetBB);
934b5aee35cSDimitry Andric   // Emit coro.end before getReturnStmt (and parameter destructors), since
935b5aee35cSDimitry Andric   // resume and destroy parts of the coroutine should not include them.
9367442d6faSDimitry Andric   llvm::Function *CoroEnd = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
937b1c73532SDimitry Andric   Builder.CreateCall(CoroEnd,
938b1c73532SDimitry Andric                      {NullPtr, Builder.getFalse(),
939b1c73532SDimitry Andric                       llvm::ConstantTokenNone::get(CoroEnd->getContext())});
9407442d6faSDimitry Andric 
941145449b1SDimitry Andric   if (Stmt *Ret = S.getReturnStmt()) {
942145449b1SDimitry Andric     // Since we already emitted the return value above, so we shouldn't
943145449b1SDimitry Andric     // emit it again here.
9447fa27ce4SDimitry Andric     if (GroManager.DirectEmit)
945145449b1SDimitry Andric       cast<ReturnStmt>(Ret)->setRetValue(nullptr);
946b5aee35cSDimitry Andric     EmitStmt(Ret);
947145449b1SDimitry Andric   }
9486f8fc217SDimitry Andric 
949145449b1SDimitry Andric   // LLVM require the frontend to mark the coroutine.
950145449b1SDimitry Andric   CurFn->setPresplitCoroutine();
951b1c73532SDimitry Andric 
952b1c73532SDimitry Andric   if (CXXRecordDecl *RD = FnRetTy->getAsCXXRecordDecl();
953b1c73532SDimitry Andric       RD && RD->hasAttr<CoroOnlyDestroyWhenCompleteAttr>())
954b1c73532SDimitry Andric     CurFn->setCoroDestroyOnlyWhenComplete();
955bab175ecSDimitry Andric }
956bab175ecSDimitry Andric 
957bab175ecSDimitry Andric // Emit coroutine intrinsic and patch up arguments of the token type.
EmitCoroutineIntrinsic(const CallExpr * E,unsigned int IID)958bab175ecSDimitry Andric RValue CodeGenFunction::EmitCoroutineIntrinsic(const CallExpr *E,
959bab175ecSDimitry Andric                                                unsigned int IID) {
960bab175ecSDimitry Andric   SmallVector<llvm::Value *, 8> Args;
961bab175ecSDimitry Andric   switch (IID) {
962bab175ecSDimitry Andric   default:
963bab175ecSDimitry Andric     break;
964b5aee35cSDimitry Andric   // The coro.frame builtin is replaced with an SSA value of the coro.begin
965b5aee35cSDimitry Andric   // intrinsic.
966b5aee35cSDimitry Andric   case llvm::Intrinsic::coro_frame: {
967b5aee35cSDimitry Andric     if (CurCoro.Data && CurCoro.Data->CoroBegin) {
968b5aee35cSDimitry Andric       return RValue::get(CurCoro.Data->CoroBegin);
969b5aee35cSDimitry Andric     }
970ac9a064cSDimitry Andric 
971ac9a064cSDimitry Andric     if (CurAwaitSuspendWrapper.FramePtr) {
972ac9a064cSDimitry Andric       return RValue::get(CurAwaitSuspendWrapper.FramePtr);
973ac9a064cSDimitry Andric     }
974ac9a064cSDimitry Andric 
975676fbe81SDimitry Andric     CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_begin "
976b5aee35cSDimitry Andric                                 "has been used earlier in this function");
977b1c73532SDimitry Andric     auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getPtrTy());
978b5aee35cSDimitry Andric     return RValue::get(NullPtr);
979b5aee35cSDimitry Andric   }
980e3b55780SDimitry Andric   case llvm::Intrinsic::coro_size: {
981e3b55780SDimitry Andric     auto &Context = getContext();
982e3b55780SDimitry Andric     CanQualType SizeTy = Context.getSizeType();
983e3b55780SDimitry Andric     llvm::IntegerType *T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
984e3b55780SDimitry Andric     llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::coro_size, T);
985e3b55780SDimitry Andric     return RValue::get(Builder.CreateCall(F));
986e3b55780SDimitry Andric   }
987e3b55780SDimitry Andric   case llvm::Intrinsic::coro_align: {
988e3b55780SDimitry Andric     auto &Context = getContext();
989e3b55780SDimitry Andric     CanQualType SizeTy = Context.getSizeType();
990e3b55780SDimitry Andric     llvm::IntegerType *T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
991e3b55780SDimitry Andric     llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::coro_align, T);
992e3b55780SDimitry Andric     return RValue::get(Builder.CreateCall(F));
993e3b55780SDimitry Andric   }
994bab175ecSDimitry Andric   // The following three intrinsics take a token parameter referring to a token
995bab175ecSDimitry Andric   // returned by earlier call to @llvm.coro.id. Since we cannot represent it in
996bab175ecSDimitry Andric   // builtins, we patch it up here.
997bab175ecSDimitry Andric   case llvm::Intrinsic::coro_alloc:
998bab175ecSDimitry Andric   case llvm::Intrinsic::coro_begin:
999bab175ecSDimitry Andric   case llvm::Intrinsic::coro_free: {
1000bab175ecSDimitry Andric     if (CurCoro.Data && CurCoro.Data->CoroId) {
1001bab175ecSDimitry Andric       Args.push_back(CurCoro.Data->CoroId);
1002bab175ecSDimitry Andric       break;
1003bab175ecSDimitry Andric     }
1004676fbe81SDimitry Andric     CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_id has"
1005bab175ecSDimitry Andric                                 " been used earlier in this function");
1006bab175ecSDimitry Andric     // Fallthrough to the next case to add TokenNone as the first argument.
1007e3b55780SDimitry Andric     [[fallthrough]];
1008bab175ecSDimitry Andric   }
1009bab175ecSDimitry Andric   // @llvm.coro.suspend takes a token parameter. Add token 'none' as the first
1010bab175ecSDimitry Andric   // argument.
1011bab175ecSDimitry Andric   case llvm::Intrinsic::coro_suspend:
1012bab175ecSDimitry Andric     Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
1013bab175ecSDimitry Andric     break;
1014bab175ecSDimitry Andric   }
101522989816SDimitry Andric   for (const Expr *Arg : E->arguments())
1016bab175ecSDimitry Andric     Args.push_back(EmitScalarExpr(Arg));
1017b1c73532SDimitry Andric   // @llvm.coro.end takes a token parameter. Add token 'none' as the last
1018b1c73532SDimitry Andric   // argument.
1019b1c73532SDimitry Andric   if (IID == llvm::Intrinsic::coro_end)
1020b1c73532SDimitry Andric     Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
1021bab175ecSDimitry Andric 
102222989816SDimitry Andric   llvm::Function *F = CGM.getIntrinsic(IID);
1023bab175ecSDimitry Andric   llvm::CallInst *Call = Builder.CreateCall(F, Args);
1024bab175ecSDimitry Andric 
1025b5aee35cSDimitry Andric   // Note: The following code is to enable to emit coro.id and coro.begin by
1026b5aee35cSDimitry Andric   // hand to experiment with coroutines in C.
1027bab175ecSDimitry Andric   // If we see @llvm.coro.id remember it in the CoroData. We will update
1028bab175ecSDimitry Andric   // coro.alloc, coro.begin and coro.free intrinsics to refer to it.
1029bab175ecSDimitry Andric   if (IID == llvm::Intrinsic::coro_id) {
1030bab175ecSDimitry Andric     createCoroData(*this, CurCoro, Call, E);
1031bab175ecSDimitry Andric   }
1032b5aee35cSDimitry Andric   else if (IID == llvm::Intrinsic::coro_begin) {
1033b5aee35cSDimitry Andric     if (CurCoro.Data)
1034b5aee35cSDimitry Andric       CurCoro.Data->CoroBegin = Call;
1035b5aee35cSDimitry Andric   }
1036b5aee35cSDimitry Andric   else if (IID == llvm::Intrinsic::coro_free) {
1037b5aee35cSDimitry Andric     // Remember the last coro_free as we need it to build the conditional
1038b5aee35cSDimitry Andric     // deletion of the coroutine frame.
1039b5aee35cSDimitry Andric     if (CurCoro.Data)
1040b5aee35cSDimitry Andric       CurCoro.Data->LastCoroFree = Call;
1041b5aee35cSDimitry Andric   }
1042bab175ecSDimitry Andric   return RValue::get(Call);
1043bab175ecSDimitry Andric }
1044