CGCoroutine.cpp 28 KB

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