clang 17.0.0git
CGCoroutine.cpp
Go to the documentation of this file.
1//===----- CGCoroutine.cpp - Emit LLVM Code for C++ coroutines ------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This contains code dealing with C++ code generation of coroutines.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGCleanup.h"
14#include "CodeGenFunction.h"
15#include "llvm/ADT/ScopeExit.h"
16#include "clang/AST/StmtCXX.h"
18
19using namespace clang;
20using namespace CodeGen;
21
22using llvm::Value;
23using llvm::BasicBlock;
24
25namespace {
26enum class AwaitKind { Init, Normal, Yield, Final };
27static constexpr llvm::StringLiteral AwaitKindStr[] = {"init", "await", "yield",
28 "final"};
29}
30
32 // What is the current await expression kind and how many
33 // await/yield expressions were encountered so far.
34 // These are used to generate pretty labels for await expressions in LLVM IR.
35 AwaitKind CurrentAwaitKind = AwaitKind::Init;
36 unsigned AwaitNum = 0;
37 unsigned YieldNum = 0;
38
39 // How many co_return statements are in the coroutine. Used to decide whether
40 // we need to add co_return; equivalent at the end of the user authored body.
41 unsigned CoreturnCount = 0;
42
43 // A branch to this block is emitted when coroutine needs to suspend.
44 llvm::BasicBlock *SuspendBB = nullptr;
45
46 // The promise type's 'unhandled_exception' handler, if it defines one.
48
49 // A temporary i1 alloca that stores whether 'await_resume' threw an
50 // exception. If it did, 'true' is stored in this variable, and the coroutine
51 // body must be skipped. If the promise type does not define an exception
52 // handler, this is null.
53 llvm::Value *ResumeEHVar = nullptr;
54
55 // Stores the jump destination just before the coroutine memory is freed.
56 // This is the destination that every suspend point jumps to for the cleanup
57 // branch.
59
60 // Stores the jump destination just before the final suspend. The co_return
61 // statements jumps to this point after calling return_xxx promise member.
63
64 // Stores the llvm.coro.id emitted in the function so that we can supply it
65 // as the first argument to coro.begin, coro.alloc and coro.free intrinsics.
66 // Note: llvm.coro.id returns a token that cannot be directly expressed in a
67 // builtin.
68 llvm::CallInst *CoroId = nullptr;
69
70 // Stores the llvm.coro.begin emitted in the function so that we can replace
71 // all coro.frame intrinsics with direct SSA value of coro.begin that returns
72 // the address of the coroutine frame of the current coroutine.
73 llvm::CallInst *CoroBegin = nullptr;
74
75 // Stores the last emitted coro.free for the deallocate expressions, we use it
76 // to wrap dealloc code with if(auto mem = coro.free) dealloc(mem).
77 llvm::CallInst *LastCoroFree = nullptr;
78
79 // If coro.id came from the builtin, remember the expression to give better
80 // diagnostic. If CoroIdExpr is nullptr, the coro.id was created by
81 // EmitCoroutineBody.
82 CallExpr const *CoroIdExpr = nullptr;
83};
84
85// Defining these here allows to keep CGCoroData private to this file.
88
90 CodeGenFunction::CGCoroInfo &CurCoro,
91 llvm::CallInst *CoroId,
92 CallExpr const *CoroIdExpr = nullptr) {
93 if (CurCoro.Data) {
94 if (CurCoro.Data->CoroIdExpr)
95 CGF.CGM.Error(CoroIdExpr->getBeginLoc(),
96 "only one __builtin_coro_id can be used in a function");
97 else if (CoroIdExpr)
98 CGF.CGM.Error(CoroIdExpr->getBeginLoc(),
99 "__builtin_coro_id shall not be used in a C++ coroutine");
100 else
101 llvm_unreachable("EmitCoroutineBodyStatement called twice?");
102
103 return;
104 }
105
106 CurCoro.Data = std::unique_ptr<CGCoroData>(new CGCoroData);
107 CurCoro.Data->CoroId = CoroId;
108 CurCoro.Data->CoroIdExpr = CoroIdExpr;
109}
110
111// Synthesize a pretty name for a suspend point.
112static SmallString<32> buildSuspendPrefixStr(CGCoroData &Coro, AwaitKind Kind) {
113 unsigned No = 0;
114 switch (Kind) {
115 case AwaitKind::Init:
116 case AwaitKind::Final:
117 break;
118 case AwaitKind::Normal:
119 No = ++Coro.AwaitNum;
120 break;
121 case AwaitKind::Yield:
122 No = ++Coro.YieldNum;
123 break;
124 }
125 SmallString<32> Prefix(AwaitKindStr[static_cast<unsigned>(Kind)]);
126 if (No > 1) {
127 Twine(No).toVector(Prefix);
128 }
129 return Prefix;
130}
131
132static bool memberCallExpressionCanThrow(const Expr *E) {
133 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
134 if (const auto *Proto =
135 CE->getMethodDecl()->getType()->getAs<FunctionProtoType>())
136 if (isNoexceptExceptionSpec(Proto->getExceptionSpecType()) &&
137 Proto->canThrow() == CT_Cannot)
138 return false;
139 return true;
140}
141
142// Emit suspend expression which roughly looks like:
143//
144// auto && x = CommonExpr();
145// if (!x.await_ready()) {
146// llvm_coro_save();
147// x.await_suspend(...); (*)
148// llvm_coro_suspend(); (**)
149// }
150// x.await_resume();
151//
152// where the result of the entire expression is the result of x.await_resume()
153//
154// (*) If x.await_suspend return type is bool, it allows to veto a suspend:
155// if (x.await_suspend(...))
156// llvm_coro_suspend();
157//
158// (**) llvm_coro_suspend() encodes three possible continuations as
159// a switch instruction:
160//
161// %where-to = call i8 @llvm.coro.suspend(...)
162// switch i8 %where-to, label %coro.ret [ ; jump to epilogue to suspend
163// i8 0, label %yield.ready ; go here when resumed
164// i8 1, label %yield.cleanup ; go here when destroyed
165// ]
166//
167// See llvm's docs/Coroutines.rst for more details.
168//
169namespace {
170 struct LValueOrRValue {
171 LValue LV;
172 RValue RV;
173 };
174}
175static LValueOrRValue emitSuspendExpression(CodeGenFunction &CGF, CGCoroData &Coro,
176 CoroutineSuspendExpr const &S,
177 AwaitKind Kind, AggValueSlot aggSlot,
178 bool ignoreResult, bool forLValue) {
179 auto *E = S.getCommonExpr();
180
181 auto Binder =
182 CodeGenFunction::OpaqueValueMappingData::bind(CGF, S.getOpaqueValue(), E);
183 auto UnbindOnExit = llvm::make_scope_exit([&] { Binder.unbind(CGF); });
184
185 auto Prefix = buildSuspendPrefixStr(Coro, Kind);
186 BasicBlock *ReadyBlock = CGF.createBasicBlock(Prefix + Twine(".ready"));
187 BasicBlock *SuspendBlock = CGF.createBasicBlock(Prefix + Twine(".suspend"));
188 BasicBlock *CleanupBlock = CGF.createBasicBlock(Prefix + Twine(".cleanup"));
189
190 // If expression is ready, no need to suspend.
191 CGF.EmitBranchOnBoolExpr(S.getReadyExpr(), ReadyBlock, SuspendBlock, 0);
192
193 // Otherwise, emit suspend logic.
194 CGF.EmitBlock(SuspendBlock);
195
196 auto &Builder = CGF.Builder;
197 llvm::Function *CoroSave = CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_save);
198 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.CGM.Int8PtrTy);
199 auto *SaveCall = Builder.CreateCall(CoroSave, {NullPtr});
200
201 CGF.CurCoro.InSuspendBlock = true;
202 auto *SuspendRet = CGF.EmitScalarExpr(S.getSuspendExpr());
203 CGF.CurCoro.InSuspendBlock = false;
204 if (SuspendRet != nullptr && SuspendRet->getType()->isIntegerTy(1)) {
205 // Veto suspension if requested by bool returning await_suspend.
206 BasicBlock *RealSuspendBlock =
207 CGF.createBasicBlock(Prefix + Twine(".suspend.bool"));
208 CGF.Builder.CreateCondBr(SuspendRet, RealSuspendBlock, ReadyBlock);
209 CGF.EmitBlock(RealSuspendBlock);
210 }
211
212 // Emit the suspend point.
213 const bool IsFinalSuspend = (Kind == AwaitKind::Final);
214 llvm::Function *CoroSuspend =
215 CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_suspend);
216 auto *SuspendResult = Builder.CreateCall(
217 CoroSuspend, {SaveCall, Builder.getInt1(IsFinalSuspend)});
218
219 // Create a switch capturing three possible continuations.
220 auto *Switch = Builder.CreateSwitch(SuspendResult, Coro.SuspendBB, 2);
221 Switch->addCase(Builder.getInt8(0), ReadyBlock);
222 Switch->addCase(Builder.getInt8(1), CleanupBlock);
223
224 // Emit cleanup for this suspend point.
225 CGF.EmitBlock(CleanupBlock);
227
228 // Emit await_resume expression.
229 CGF.EmitBlock(ReadyBlock);
230
231 // Exception handling requires additional IR. If the 'await_resume' function
232 // is marked as 'noexcept', we avoid generating this additional IR.
233 CXXTryStmt *TryStmt = nullptr;
234 if (Coro.ExceptionHandler && Kind == AwaitKind::Init &&
235 memberCallExpressionCanThrow(S.getResumeExpr())) {
236 Coro.ResumeEHVar =
237 CGF.CreateTempAlloca(Builder.getInt1Ty(), Prefix + Twine("resume.eh"));
239
240 auto Loc = S.getResumeExpr()->getExprLoc();
241 auto *Catch = new (CGF.getContext())
242 CXXCatchStmt(Loc, /*exDecl=*/nullptr, Coro.ExceptionHandler);
243 auto *TryBody = CompoundStmt::Create(CGF.getContext(), S.getResumeExpr(),
244 FPOptionsOverride(), Loc, Loc);
245 TryStmt = CXXTryStmt::Create(CGF.getContext(), Loc, TryBody, Catch);
246 CGF.EnterCXXTryStmt(*TryStmt);
247 }
248
249 LValueOrRValue Res;
250 if (forLValue)
251 Res.LV = CGF.EmitLValue(S.getResumeExpr());
252 else
253 Res.RV = CGF.EmitAnyExpr(S.getResumeExpr(), aggSlot, ignoreResult);
254
255 if (TryStmt) {
257 CGF.ExitCXXTryStmt(*TryStmt);
258 }
259
260 return Res;
261}
262
264 AggValueSlot aggSlot,
265 bool ignoreResult) {
266 return emitSuspendExpression(*this, *CurCoro.Data, E,
267 CurCoro.Data->CurrentAwaitKind, aggSlot,
268 ignoreResult, /*forLValue*/false).RV;
269}
271 AggValueSlot aggSlot,
272 bool ignoreResult) {
273 return emitSuspendExpression(*this, *CurCoro.Data, E, AwaitKind::Yield,
274 aggSlot, ignoreResult, /*forLValue*/false).RV;
275}
276
278 ++CurCoro.Data->CoreturnCount;
279 const Expr *RV = S.getOperand();
280 if (RV && RV->getType()->isVoidType() && !isa<InitListExpr>(RV)) {
281 // Make sure to evaluate the non initlist expression of a co_return
282 // with a void expression for side effects.
283 RunCleanupsScope cleanupScope(*this);
284 EmitIgnoredExpr(RV);
285 }
286 EmitStmt(S.getPromiseCall());
288}
289
290
291#ifndef NDEBUG
293 const CoroutineSuspendExpr *E) {
294 const auto *RE = E->getResumeExpr();
295 // Is it possible for RE to be a CXXBindTemporaryExpr wrapping
296 // a MemberCallExpr?
297 assert(isa<CallExpr>(RE) && "unexpected suspend expression type");
298 return cast<CallExpr>(RE)->getCallReturnType(Ctx);
299}
300#endif
301
302LValue
304 assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
305 "Can't have a scalar return unless the return type is a "
306 "reference type!");
307 return emitSuspendExpression(*this, *CurCoro.Data, *E,
308 CurCoro.Data->CurrentAwaitKind, AggValueSlot::ignored(),
309 /*ignoreResult*/false, /*forLValue*/true).LV;
310}
311
312LValue
314 assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
315 "Can't have a scalar return unless the return type is a "
316 "reference type!");
317 return emitSuspendExpression(*this, *CurCoro.Data, *E,
318 AwaitKind::Yield, AggValueSlot::ignored(),
319 /*ignoreResult*/false, /*forLValue*/true).LV;
320}
321
322// Hunts for the parameter reference in the parameter copy/move declaration.
323namespace {
324struct GetParamRef : public StmtVisitor<GetParamRef> {
325public:
326 DeclRefExpr *Expr = nullptr;
327 GetParamRef() {}
328 void VisitDeclRefExpr(DeclRefExpr *E) {
329 assert(Expr == nullptr && "multilple declref in param move");
330 Expr = E;
331 }
332 void VisitStmt(Stmt *S) {
333 for (auto *C : S->children()) {
334 if (C)
335 Visit(C);
336 }
337 }
338};
339}
340
341// This class replaces references to parameters to their copies by changing
342// the addresses in CGF.LocalDeclMap and restoring back the original values in
343// its destructor.
344
345namespace {
346 struct ParamReferenceReplacerRAII {
347 CodeGenFunction::DeclMapTy SavedLocals;
348 CodeGenFunction::DeclMapTy& LocalDeclMap;
349
350 ParamReferenceReplacerRAII(CodeGenFunction::DeclMapTy &LocalDeclMap)
351 : LocalDeclMap(LocalDeclMap) {}
352
353 void addCopy(DeclStmt const *PM) {
354 // Figure out what param it refers to.
355
356 assert(PM->isSingleDecl());
357 VarDecl const*VD = static_cast<VarDecl const*>(PM->getSingleDecl());
358 Expr const *InitExpr = VD->getInit();
359 GetParamRef Visitor;
360 Visitor.Visit(const_cast<Expr*>(InitExpr));
361 assert(Visitor.Expr);
362 DeclRefExpr *DREOrig = Visitor.Expr;
363 auto *PD = DREOrig->getDecl();
364
365 auto it = LocalDeclMap.find(PD);
366 assert(it != LocalDeclMap.end() && "parameter is not found");
367 SavedLocals.insert({ PD, it->second });
368
369 auto copyIt = LocalDeclMap.find(VD);
370 assert(copyIt != LocalDeclMap.end() && "parameter copy is not found");
371 it->second = copyIt->getSecond();
372 }
373
374 ~ParamReferenceReplacerRAII() {
375 for (auto&& SavedLocal : SavedLocals) {
376 LocalDeclMap.insert({SavedLocal.first, SavedLocal.second});
377 }
378 }
379 };
380}
381
382// For WinEH exception representation backend needs to know what funclet coro.end
383// belongs to. That information is passed in a funclet bundle.
387
388 if (llvm::Instruction *EHPad = CGF.CurrentFuncletPad)
389 BundleList.emplace_back("funclet", EHPad);
390
391 return BundleList;
392}
393
394namespace {
395// We will insert coro.end to cut any of the destructors for objects that
396// do not need to be destroyed once the coroutine is resumed.
397// See llvm/docs/Coroutines.rst for more details about coro.end.
398struct CallCoroEnd final : public EHScopeStack::Cleanup {
399 void Emit(CodeGenFunction &CGF, Flags flags) override {
400 auto &CGM = CGF.CGM;
401 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
402 llvm::Function *CoroEndFn = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
403 // See if we have a funclet bundle to associate coro.end with. (WinEH)
404 auto Bundles = getBundlesForCoroEnd(CGF);
405 auto *CoroEnd = CGF.Builder.CreateCall(
406 CoroEndFn, {NullPtr, CGF.Builder.getTrue()}, Bundles);
407 if (Bundles.empty()) {
408 // Otherwise, (landingpad model), create a conditional branch that leads
409 // either to a cleanup block or a block with EH resume instruction.
410 auto *ResumeBB = CGF.getEHResumeBlock(/*isCleanup=*/true);
411 auto *CleanupContBB = CGF.createBasicBlock("cleanup.cont");
412 CGF.Builder.CreateCondBr(CoroEnd, ResumeBB, CleanupContBB);
413 CGF.EmitBlock(CleanupContBB);
414 }
415 }
416};
417}
418
419namespace {
420// Make sure to call coro.delete on scope exit.
421struct CallCoroDelete final : public EHScopeStack::Cleanup {
422 Stmt *Deallocate;
423
424 // Emit "if (coro.free(CoroId, CoroBegin)) Deallocate;"
425
426 // Note: That deallocation will be emitted twice: once for a normal exit and
427 // once for exceptional exit. This usage is safe because Deallocate does not
428 // contain any declarations. The SubStmtBuilder::makeNewAndDeleteExpr()
429 // builds a single call to a deallocation function which is safe to emit
430 // multiple times.
431 void Emit(CodeGenFunction &CGF, Flags) override {
432 // Remember the current point, as we are going to emit deallocation code
433 // first to get to coro.free instruction that is an argument to a delete
434 // call.
435 BasicBlock *SaveInsertBlock = CGF.Builder.GetInsertBlock();
436
437 auto *FreeBB = CGF.createBasicBlock("coro.free");
438 CGF.EmitBlock(FreeBB);
439 CGF.EmitStmt(Deallocate);
440
441 auto *AfterFreeBB = CGF.createBasicBlock("after.coro.free");
442 CGF.EmitBlock(AfterFreeBB);
443
444 // We should have captured coro.free from the emission of deallocate.
445 auto *CoroFree = CGF.CurCoro.Data->LastCoroFree;
446 if (!CoroFree) {
447 CGF.CGM.Error(Deallocate->getBeginLoc(),
448 "Deallocation expressoin does not refer to coro.free");
449 return;
450 }
451
452 // Get back to the block we were originally and move coro.free there.
453 auto *InsertPt = SaveInsertBlock->getTerminator();
454 CoroFree->moveBefore(InsertPt);
455 CGF.Builder.SetInsertPoint(InsertPt);
456
457 // Add if (auto *mem = coro.free) Deallocate;
458 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
459 auto *Cond = CGF.Builder.CreateICmpNE(CoroFree, NullPtr);
460 CGF.Builder.CreateCondBr(Cond, FreeBB, AfterFreeBB);
461
462 // No longer need old terminator.
463 InsertPt->eraseFromParent();
464 CGF.Builder.SetInsertPoint(AfterFreeBB);
465 }
466 explicit CallCoroDelete(Stmt *DeallocStmt) : Deallocate(DeallocStmt) {}
467};
468}
469
470namespace {
471struct GetReturnObjectManager {
472 CodeGenFunction &CGF;
473 CGBuilderTy &Builder;
474 const CoroutineBodyStmt &S;
475 // When true, performs RVO for the return object.
476 bool DirectEmit = false;
477
478 Address GroActiveFlag;
479 CodeGenFunction::AutoVarEmission GroEmission;
480
481 GetReturnObjectManager(CodeGenFunction &CGF, const CoroutineBodyStmt &S)
482 : CGF(CGF), Builder(CGF.Builder), S(S), GroActiveFlag(Address::invalid()),
483 GroEmission(CodeGenFunction::AutoVarEmission::invalid()) {
484 // The call to get_­return_­object is sequenced before the call to
485 // initial_­suspend and is invoked at most once, but there are caveats
486 // regarding on whether the prvalue result object may be initialized
487 // directly/eager or delayed, depending on the types involved.
488 //
489 // More info at https://github.com/cplusplus/papers/issues/1414
490 //
491 // The general cases:
492 // 1. Same type of get_return_object and coroutine return type (direct
493 // emission):
494 // - Constructed in the return slot.
495 // 2. Different types (delayed emission):
496 // - Constructed temporary object prior to initial suspend initialized with
497 // a call to get_return_object()
498 // - When coroutine needs to to return to the caller and needs to construct
499 // return value for the coroutine it is initialized with expiring value of
500 // the temporary obtained above.
501 //
502 // Direct emission for void returning coroutines or GROs.
503 DirectEmit = [&]() {
504 auto *RVI = S.getReturnValueInit();
505 assert(RVI && "expected RVI");
506 auto GroType = RVI->getType();
507 return CGF.getContext().hasSameType(GroType, CGF.FnRetTy);
508 }();
509 }
510
511 // The gro variable has to outlive coroutine frame and coroutine promise, but,
512 // it can only be initialized after coroutine promise was created, thus, we
513 // split its emission in two parts. EmitGroAlloca emits an alloca and sets up
514 // cleanups. Later when coroutine promise is available we initialize the gro
515 // and sets the flag that the cleanup is now active.
516 void EmitGroAlloca() {
517 if (DirectEmit)
518 return;
519
520 auto *GroDeclStmt = dyn_cast_or_null<DeclStmt>(S.getResultDecl());
521 if (!GroDeclStmt) {
522 // If get_return_object returns void, no need to do an alloca.
523 return;
524 }
525
526 auto *GroVarDecl = cast<VarDecl>(GroDeclStmt->getSingleDecl());
527
528 // Set GRO flag that it is not initialized yet
529 GroActiveFlag = CGF.CreateTempAlloca(Builder.getInt1Ty(), CharUnits::One(),
530 "gro.active");
531 Builder.CreateStore(Builder.getFalse(), GroActiveFlag);
532
533 GroEmission = CGF.EmitAutoVarAlloca(*GroVarDecl);
534
535 // Remember the top of EHStack before emitting the cleanup.
536 auto old_top = CGF.EHStack.stable_begin();
537 CGF.EmitAutoVarCleanups(GroEmission);
538 auto top = CGF.EHStack.stable_begin();
539
540 // Make the cleanup conditional on gro.active
541 for (auto b = CGF.EHStack.find(top), e = CGF.EHStack.find(old_top); b != e;
542 b++) {
543 if (auto *Cleanup = dyn_cast<EHCleanupScope>(&*b)) {
544 assert(!Cleanup->hasActiveFlag() && "cleanup already has active flag?");
545 Cleanup->setActiveFlag(GroActiveFlag);
546 Cleanup->setTestFlagInEHCleanup();
547 Cleanup->setTestFlagInNormalCleanup();
548 }
549 }
550 }
551
552 void EmitGroInit() {
553 if (DirectEmit) {
554 // ReturnValue should be valid as long as the coroutine's return type
555 // is not void. The assertion could help us to reduce the check later.
556 assert(CGF.ReturnValue.isValid() == (bool)S.getReturnStmt());
557 // Now we have the promise, initialize the GRO.
558 // We need to emit `get_return_object` first. According to:
559 // [dcl.fct.def.coroutine]p7
560 // The call to get_return_­object is sequenced before the call to
561 // initial_suspend and is invoked at most once.
562 //
563 // So we couldn't emit return value when we emit return statment,
564 // otherwise the call to get_return_object wouldn't be in front
565 // of initial_suspend.
566 if (CGF.ReturnValue.isValid()) {
567 CGF.EmitAnyExprToMem(S.getReturnValue(), CGF.ReturnValue,
568 S.getReturnValue()->getType().getQualifiers(),
569 /*IsInit*/ true);
570 }
571 return;
572 }
573
574 if (!GroActiveFlag.isValid()) {
575 // No Gro variable was allocated. Simply emit the call to
576 // get_return_object.
577 CGF.EmitStmt(S.getResultDecl());
578 return;
579 }
580
581 CGF.EmitAutoVarInit(GroEmission);
582 Builder.CreateStore(Builder.getTrue(), GroActiveFlag);
583 }
584};
585} // namespace
586
588 const CoroutineBodyStmt &S, Stmt *Body) {
589 CGF.EmitStmt(Body);
590 const bool CanFallthrough = CGF.Builder.GetInsertBlock();
591 if (CanFallthrough)
592 if (Stmt *OnFallthrough = S.getFallthroughHandler())
593 CGF.EmitStmt(OnFallthrough);
594}
595
597 auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
598 auto &TI = CGM.getContext().getTargetInfo();
599 unsigned NewAlign = TI.getNewAlign() / TI.getCharWidth();
600
601 auto *EntryBB = Builder.GetInsertBlock();
602 auto *AllocBB = createBasicBlock("coro.alloc");
603 auto *InitBB = createBasicBlock("coro.init");
604 auto *FinalBB = createBasicBlock("coro.final");
605 auto *RetBB = createBasicBlock("coro.ret");
606
607 auto *CoroId = Builder.CreateCall(
608 CGM.getIntrinsic(llvm::Intrinsic::coro_id),
609 {Builder.getInt32(NewAlign), NullPtr, NullPtr, NullPtr});
610 createCoroData(*this, CurCoro, CoroId);
611 CurCoro.Data->SuspendBB = RetBB;
612 assert(ShouldEmitLifetimeMarkers &&
613 "Must emit lifetime intrinsics for coroutines");
614
615 // Backend is allowed to elide memory allocations, to help it, emit
616 // auto mem = coro.alloc() ? 0 : ... allocation code ...;
617 auto *CoroAlloc = Builder.CreateCall(
618 CGM.getIntrinsic(llvm::Intrinsic::coro_alloc), {CoroId});
619
620 Builder.CreateCondBr(CoroAlloc, AllocBB, InitBB);
621
622 EmitBlock(AllocBB);
623 auto *AllocateCall = EmitScalarExpr(S.getAllocate());
624 auto *AllocOrInvokeContBB = Builder.GetInsertBlock();
625
626 // Handle allocation failure if 'ReturnStmtOnAllocFailure' was provided.
627 if (auto *RetOnAllocFailure = S.getReturnStmtOnAllocFailure()) {
628 auto *RetOnFailureBB = createBasicBlock("coro.ret.on.failure");
629
630 // See if allocation was successful.
631 auto *NullPtr = llvm::ConstantPointerNull::get(Int8PtrTy);
632 auto *Cond = Builder.CreateICmpNE(AllocateCall, NullPtr);
633 Builder.CreateCondBr(Cond, InitBB, RetOnFailureBB);
634
635 // If not, return OnAllocFailure object.
636 EmitBlock(RetOnFailureBB);
637 EmitStmt(RetOnAllocFailure);
638 }
639 else {
640 Builder.CreateBr(InitBB);
641 }
642
643 EmitBlock(InitBB);
644
645 // Pass the result of the allocation to coro.begin.
646 auto *Phi = Builder.CreatePHI(VoidPtrTy, 2);
647 Phi->addIncoming(NullPtr, EntryBB);
648 Phi->addIncoming(AllocateCall, AllocOrInvokeContBB);
649 auto *CoroBegin = Builder.CreateCall(
650 CGM.getIntrinsic(llvm::Intrinsic::coro_begin), {CoroId, Phi});
651 CurCoro.Data->CoroBegin = CoroBegin;
652
653 GetReturnObjectManager GroManager(*this, S);
654 GroManager.EmitGroAlloca();
655
656 CurCoro.Data->CleanupJD = getJumpDestInCurrentScope(RetBB);
657 {
659 ParamReferenceReplacerRAII ParamReplacer(LocalDeclMap);
660 CodeGenFunction::RunCleanupsScope ResumeScope(*this);
661 EHStack.pushCleanup<CallCoroDelete>(NormalAndEHCleanup, S.getDeallocate());
662
663 // Create mapping between parameters and copy-params for coroutine function.
664 llvm::ArrayRef<const Stmt *> ParamMoves = S.getParamMoves();
665 assert(
666 (ParamMoves.size() == 0 || (ParamMoves.size() == FnArgs.size())) &&
667 "ParamMoves and FnArgs should be the same size for coroutine function");
668 if (ParamMoves.size() == FnArgs.size() && DI)
669 for (const auto Pair : llvm::zip(FnArgs, ParamMoves))
671 {std::get<0>(Pair), std::get<1>(Pair)});
672
673 // Create parameter copies. We do it before creating a promise, since an
674 // evolution of coroutine TS may allow promise constructor to observe
675 // parameter copies.
676 for (auto *PM : S.getParamMoves()) {
677 EmitStmt(PM);
678 ParamReplacer.addCopy(cast<DeclStmt>(PM));
679 // TODO: if(CoroParam(...)) need to surround ctor and dtor
680 // for the copy, so that llvm can elide it if the copy is
681 // not needed.
682 }
683
684 EmitStmt(S.getPromiseDeclStmt());
685
686 Address PromiseAddr = GetAddrOfLocalVar(S.getPromiseDecl());
687 auto *PromiseAddrVoidPtr =
688 new llvm::BitCastInst(PromiseAddr.getPointer(), VoidPtrTy, "", CoroId);
689 // Update CoroId to refer to the promise. We could not do it earlier because
690 // promise local variable was not emitted yet.
691 CoroId->setArgOperand(1, PromiseAddrVoidPtr);
692
693 // Now we have the promise, initialize the GRO
694 GroManager.EmitGroInit();
695
696 EHStack.pushCleanup<CallCoroEnd>(EHCleanup);
697
698 CurCoro.Data->CurrentAwaitKind = AwaitKind::Init;
699 CurCoro.Data->ExceptionHandler = S.getExceptionHandler();
700 EmitStmt(S.getInitSuspendStmt());
701 CurCoro.Data->FinalJD = getJumpDestInCurrentScope(FinalBB);
702
703 CurCoro.Data->CurrentAwaitKind = AwaitKind::Normal;
704
705 if (CurCoro.Data->ExceptionHandler) {
706 // If we generated IR to record whether an exception was thrown from
707 // 'await_resume', then use that IR to determine whether the coroutine
708 // body should be skipped.
709 // If we didn't generate the IR (perhaps because 'await_resume' was marked
710 // as 'noexcept'), then we skip this check.
711 BasicBlock *ContBB = nullptr;
712 if (CurCoro.Data->ResumeEHVar) {
713 BasicBlock *BodyBB = createBasicBlock("coro.resumed.body");
714 ContBB = createBasicBlock("coro.resumed.cont");
715 Value *SkipBody = Builder.CreateFlagLoad(CurCoro.Data->ResumeEHVar,
716 "coro.resumed.eh");
717 Builder.CreateCondBr(SkipBody, ContBB, BodyBB);
718 EmitBlock(BodyBB);
719 }
720
721 auto Loc = S.getBeginLoc();
722 CXXCatchStmt Catch(Loc, /*exDecl=*/nullptr,
723 CurCoro.Data->ExceptionHandler);
724 auto *TryStmt =
725 CXXTryStmt::Create(getContext(), Loc, S.getBody(), &Catch);
726
727 EnterCXXTryStmt(*TryStmt);
728 emitBodyAndFallthrough(*this, S, TryStmt->getTryBlock());
729 ExitCXXTryStmt(*TryStmt);
730
731 if (ContBB)
732 EmitBlock(ContBB);
733 }
734 else {
735 emitBodyAndFallthrough(*this, S, S.getBody());
736 }
737
738 // See if we need to generate final suspend.
739 const bool CanFallthrough = Builder.GetInsertBlock();
740 const bool HasCoreturns = CurCoro.Data->CoreturnCount > 0;
741 if (CanFallthrough || HasCoreturns) {
742 EmitBlock(FinalBB);
743 CurCoro.Data->CurrentAwaitKind = AwaitKind::Final;
744 EmitStmt(S.getFinalSuspendStmt());
745 } else {
746 // We don't need FinalBB. Emit it to make sure the block is deleted.
747 EmitBlock(FinalBB, /*IsFinished=*/true);
748 }
749 }
750
751 EmitBlock(RetBB);
752 // Emit coro.end before getReturnStmt (and parameter destructors), since
753 // resume and destroy parts of the coroutine should not include them.
754 llvm::Function *CoroEnd = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
755 Builder.CreateCall(CoroEnd, {NullPtr, Builder.getFalse()});
756
757 if (Stmt *Ret = S.getReturnStmt()) {
758 // Since we already emitted the return value above, so we shouldn't
759 // emit it again here.
760 if (GroManager.DirectEmit)
761 cast<ReturnStmt>(Ret)->setRetValue(nullptr);
762 EmitStmt(Ret);
763 }
764
765 // LLVM require the frontend to mark the coroutine.
766 CurFn->setPresplitCoroutine();
767}
768
769// Emit coroutine intrinsic and patch up arguments of the token type.
771 unsigned int IID) {
773 switch (IID) {
774 default:
775 break;
776 // The coro.frame builtin is replaced with an SSA value of the coro.begin
777 // intrinsic.
778 case llvm::Intrinsic::coro_frame: {
779 if (CurCoro.Data && CurCoro.Data->CoroBegin) {
780 return RValue::get(CurCoro.Data->CoroBegin);
781 }
782 CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_begin "
783 "has been used earlier in this function");
784 auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
785 return RValue::get(NullPtr);
786 }
787 case llvm::Intrinsic::coro_size: {
788 auto &Context = getContext();
789 CanQualType SizeTy = Context.getSizeType();
790 llvm::IntegerType *T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
791 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::coro_size, T);
792 return RValue::get(Builder.CreateCall(F));
793 }
794 case llvm::Intrinsic::coro_align: {
795 auto &Context = getContext();
796 CanQualType SizeTy = Context.getSizeType();
797 llvm::IntegerType *T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
798 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::coro_align, T);
799 return RValue::get(Builder.CreateCall(F));
800 }
801 // The following three intrinsics take a token parameter referring to a token
802 // returned by earlier call to @llvm.coro.id. Since we cannot represent it in
803 // builtins, we patch it up here.
804 case llvm::Intrinsic::coro_alloc:
805 case llvm::Intrinsic::coro_begin:
806 case llvm::Intrinsic::coro_free: {
807 if (CurCoro.Data && CurCoro.Data->CoroId) {
808 Args.push_back(CurCoro.Data->CoroId);
809 break;
810 }
811 CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_id has"
812 " been used earlier in this function");
813 // Fallthrough to the next case to add TokenNone as the first argument.
814 [[fallthrough]];
815 }
816 // @llvm.coro.suspend takes a token parameter. Add token 'none' as the first
817 // argument.
818 case llvm::Intrinsic::coro_suspend:
819 Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
820 break;
821 }
822 for (const Expr *Arg : E->arguments())
823 Args.push_back(EmitScalarExpr(Arg));
824
825 llvm::Function *F = CGM.getIntrinsic(IID);
826 llvm::CallInst *Call = Builder.CreateCall(F, Args);
827
828 // Note: The following code is to enable to emit coro.id and coro.begin by
829 // hand to experiment with coroutines in C.
830 // If we see @llvm.coro.id remember it in the CoroData. We will update
831 // coro.alloc, coro.begin and coro.free intrinsics to refer to it.
832 if (IID == llvm::Intrinsic::coro_id) {
833 createCoroData(*this, CurCoro, Call, E);
834 }
835 else if (IID == llvm::Intrinsic::coro_begin) {
836 if (CurCoro.Data)
837 CurCoro.Data->CoroBegin = Call;
838 }
839 else if (IID == llvm::Intrinsic::coro_free) {
840 // Remember the last coro_free as we need it to build the conditional
841 // deletion of the coroutine frame.
842 if (CurCoro.Data)
843 CurCoro.Data->LastCoroFree = Call;
844 }
845 return RValue::get(Call);
846}
static LValueOrRValue emitSuspendExpression(CodeGenFunction &CGF, CGCoroData &Coro, CoroutineSuspendExpr const &S, AwaitKind Kind, AggValueSlot aggSlot, bool ignoreResult, bool forLValue)
static bool memberCallExpressionCanThrow(const Expr *E)
static SmallString< 32 > buildSuspendPrefixStr(CGCoroData &Coro, AwaitKind Kind)
static QualType getCoroutineSuspendExprReturnType(const ASTContext &Ctx, const CoroutineSuspendExpr *E)
static void createCoroData(CodeGenFunction &CGF, CodeGenFunction::CGCoroInfo &CurCoro, llvm::CallInst *CoroId, CallExpr const *CoroIdExpr=nullptr)
Definition: CGCoroutine.cpp:89
static void emitBodyAndFallthrough(CodeGenFunction &CGF, const CoroutineBodyStmt &S, Stmt *Body)
static SmallVector< llvm::OperandBundleDef, 1 > getBundlesForCoroEnd(CodeGenFunction &CGF)
__device__ __2f16 b
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2540
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2296
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:743
CXXCatchStmt - This represents a C++ catch block.
Definition: StmtCXX.h:28
CXXTryStmt - A C++ try block, including all handlers.
Definition: StmtCXX.h:69
static CXXTryStmt * Create(const ASTContext &C, SourceLocation tryLoc, CompoundStmt *tryBlock, ArrayRef< Stmt * > handlers)
Definition: StmtCXX.cpp:25
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2817
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1619
arg_range arguments()
Definition: Expr.h:3056
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition: CharUnits.h:58
Represents a 'co_await' expression.
Definition: ExprCXX.h:5008
An aligned address.
Definition: Address.h:29
llvm::Value * getPointer() const
Definition: Address.h:54
bool isValid() const
Definition: Address.h:50
An aggregate value slot.
Definition: CGValue.h:514
static AggValueSlot ignored()
ignored - Returns an aggregate value slot indicating that the aggregate value is being ignored.
Definition: CGValue.h:582
llvm::StoreInst * CreateFlagStore(bool Value, llvm::Value *Addr)
Emit a store to an i1 flag variable.
Definition: CGBuilder.h:129
llvm::LoadInst * CreateFlagLoad(llvm::Value *Addr, const llvm::Twine &Name="")
Emit a load from an i1 flag variable.
Definition: CGBuilder.h:121
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition: CGDebugInfo.h:55
ParamDecl2StmtTy & getCoroutineParameterMappings()
Definition: CGDebugInfo.h:598
static OpaqueValueMappingData bind(CodeGenFunction &CGF, const OpaqueValueExpr *ov, const Expr *e)
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target)
The given basic block lies in the current EH scope, but may be a target of a potentially scope-crossi...
LValue EmitCoawaitLValue(const CoawaitExpr *E)
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
llvm::BasicBlock * getEHResumeBlock(bool isCleanup)
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
void EmitAnyExprToMem(const Expr *E, Address Location, Qualifiers Quals, bool IsInitializer)
EmitAnyExprToMem - Emits the code necessary to evaluate an arbitrary expression into the given memory...
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
void EmitAutoVarInit(const AutoVarEmission &emission)
void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount, Stmt::Likelihood LH=Stmt::LH_None)
EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g.
LValue EmitCoyieldLValue(const CoyieldExpr *E)
RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID)
RValue EmitAnyExpr(const Expr *E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
EmitAnyExpr - Emit code to compute the specified expression which can have any type.
RValue EmitCoyieldExpr(const CoyieldExpr &E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock=false)
void EmitCoroutineBody(const CoroutineBodyStmt &S)
void EmitBranchThroughCleanup(JumpDest Dest)
EmitBranchThroughCleanup - Emit a branch from the current insert block through the normal cleanup han...
AutoVarEmission EmitAutoVarAlloca(const VarDecl &var)
void EmitAutoVarCleanups(const AutoVarEmission &emission)
llvm::SmallVector< const ParmVarDecl *, 4 > FnArgs
Save Parameter Decl for coroutine.
RValue EmitCoawaitExpr(const CoawaitExpr &E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
void EmitCoreturnStmt(const CoreturnStmt &S)
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock=false)
llvm::Instruction * CurrentFuncletPad
void EmitStmt(const Stmt *S, ArrayRef< const Attr * > Attrs=std::nullopt)
EmitStmt - Emit the code for the statement.
llvm::LLVMContext & getLLVMContext()
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
void Error(SourceLocation loc, StringRef error)
Emit a general error that something can't be done.
ASTContext & getContext() const
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys=std::nullopt)
Information for lazily generating a cleanup.
Definition: EHScopeStack.h:141
stable_iterator stable_begin() const
Create a stable reference to the top of the EH stack.
Definition: EHScopeStack.h:390
iterator find(stable_iterator save) const
Turn a stable reference to a scope depth into a unstable pointer to the EH stack.
Definition: CGCleanup.h:575
LValue - This represents an lvalue references.
Definition: CGValue.h:171
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition: CGValue.h:39
static RValue get(llvm::Value *V)
Definition: CGValue.h:89
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt * > Stmts, FPOptionsOverride FPFeatures, SourceLocation LB, SourceLocation RB)
Definition: Stmt.cpp:382
Represents a 'co_return' statement in the C++ Coroutines TS.
Definition: StmtCXX.h:473
Represents the body of a coroutine.
Definition: StmtCXX.h:320
Represents an expression that might suspend coroutine execution; either a co_await or co_yield expres...
Definition: ExprCXX.h:4915
Expr * getResumeExpr() const
Definition: ExprCXX.h:4976
Represents a 'co_yield' expression.
Definition: ExprCXX.h:5089
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1237
ValueDecl * getDecl()
Definition: Expr.h:1305
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition: Stmt.h:1315
bool isSingleDecl() const
isSingleDecl - This method returns true if this DeclStmt refers to a single Decl.
Definition: Stmt.h:1328
const Decl * getSingleDecl() const
Definition: Stmt.h:1330
This represents one expression.
Definition: Expr.h:110
QualType getType() const
Definition: Expr.h:142
Represents difference between two FPOptions values.
Definition: LangOptions.h:806
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4056
A (possibly-)qualified type.
Definition: Type.h:736
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:184
Stmt - This represents one statement.
Definition: Stmt.h:72
unsigned getNewAlign() const
Return the largest alignment for which a suitably-sized allocation with '::operator new(size_t)' is g...
Definition: TargetInfo.h:695
bool isVoidType() const
Definition: Type.h:7224
Represents a variable declaration or definition.
Definition: Decl.h:913
const Expr * getInit() const
Definition: Decl.h:1325
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
Definition: EHScopeStack.h:80
bool Call(InterpState &S, CodePtr OpPC, const Function *Func)
Definition: Interp.h:1585
@ C
Languages that the frontend can parse and compile.
bool isNoexceptExceptionSpec(ExceptionSpecificationType ESpecType)
CodeGenFunction::JumpDest FinalJD
Definition: CGCoroutine.cpp:62
CallExpr const * CoroIdExpr
Definition: CGCoroutine.cpp:82
CodeGenFunction::JumpDest CleanupJD
Definition: CGCoroutine.cpp:58
llvm::BasicBlock * SuspendBB
Definition: CGCoroutine.cpp:44
llvm::CallInst * CoroId
Definition: CGCoroutine.cpp:68
llvm::CallInst * CoroBegin
Definition: CGCoroutine.cpp:73
llvm::CallInst * LastCoroFree
Definition: CGCoroutine.cpp:77
A jump destination is an abstract label, branching to which may require a jump out through normal cle...