clang 19.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
132// Check if function can throw based on prototype noexcept, also works for
133// destructors which are implicitly noexcept but can be marked noexcept(false).
134static bool FunctionCanThrow(const FunctionDecl *D) {
135 const auto *Proto = D->getType()->getAs<FunctionProtoType>();
136 if (!Proto) {
137 // Function proto is not found, we conservatively assume throwing.
138 return true;
139 }
140 return !isNoexceptExceptionSpec(Proto->getExceptionSpecType()) ||
141 Proto->canThrow() != CT_Cannot;
142}
143
144static bool StmtCanThrow(const Stmt *S) {
145 if (const auto *CE = dyn_cast<CallExpr>(S)) {
146 const auto *Callee = CE->getDirectCallee();
147 if (!Callee)
148 // We don't have direct callee. Conservatively assume throwing.
149 return true;
150
151 if (FunctionCanThrow(Callee))
152 return true;
153
154 // Fall through to visit the children.
155 }
156
157 if (const auto *TE = dyn_cast<CXXBindTemporaryExpr>(S)) {
158 // Special handling of CXXBindTemporaryExpr here as calling of Dtor of the
159 // temporary is not part of `children()` as covered in the fall through.
160 // We need to mark entire statement as throwing if the destructor of the
161 // temporary throws.
162 const auto *Dtor = TE->getTemporary()->getDestructor();
163 if (FunctionCanThrow(Dtor))
164 return true;
165
166 // Fall through to visit the children.
167 }
168
169 for (const auto *child : S->children())
170 if (StmtCanThrow(child))
171 return true;
172
173 return false;
174}
175
176// Emit suspend expression which roughly looks like:
177//
178// auto && x = CommonExpr();
179// if (!x.await_ready()) {
180// llvm_coro_save();
181// llvm_coro_await_suspend(&x, frame, wrapper) (*) (**)
182// llvm_coro_suspend(); (***)
183// }
184// x.await_resume();
185//
186// where the result of the entire expression is the result of x.await_resume()
187//
188// (*) llvm_coro_await_suspend_{void, bool, handle} is lowered to
189// wrapper(&x, frame) when it's certain not to interfere with
190// coroutine transform. await_suspend expression is
191// asynchronous to the coroutine body and not all analyses
192// and transformations can handle it correctly at the moment.
193//
194// Wrapper function encapsulates x.await_suspend(...) call and looks like:
195//
196// auto __await_suspend_wrapper(auto& awaiter, void* frame) {
197// std::coroutine_handle<> handle(frame);
198// return awaiter.await_suspend(handle);
199// }
200//
201// (**) If x.await_suspend return type is bool, it allows to veto a suspend:
202// if (x.await_suspend(...))
203// llvm_coro_suspend();
204//
205// (***) llvm_coro_suspend() encodes three possible continuations as
206// a switch instruction:
207//
208// %where-to = call i8 @llvm.coro.suspend(...)
209// switch i8 %where-to, label %coro.ret [ ; jump to epilogue to suspend
210// i8 0, label %yield.ready ; go here when resumed
211// i8 1, label %yield.cleanup ; go here when destroyed
212// ]
213//
214// See llvm's docs/Coroutines.rst for more details.
215//
216namespace {
217 struct LValueOrRValue {
218 LValue LV;
219 RValue RV;
220 };
221}
222static LValueOrRValue emitSuspendExpression(CodeGenFunction &CGF, CGCoroData &Coro,
223 CoroutineSuspendExpr const &S,
224 AwaitKind Kind, AggValueSlot aggSlot,
225 bool ignoreResult, bool forLValue) {
226 auto *E = S.getCommonExpr();
227
228 auto CommonBinder =
229 CodeGenFunction::OpaqueValueMappingData::bind(CGF, S.getOpaqueValue(), E);
230 auto UnbindCommonOnExit =
231 llvm::make_scope_exit([&] { CommonBinder.unbind(CGF); });
232
233 auto Prefix = buildSuspendPrefixStr(Coro, Kind);
234 BasicBlock *ReadyBlock = CGF.createBasicBlock(Prefix + Twine(".ready"));
235 BasicBlock *SuspendBlock = CGF.createBasicBlock(Prefix + Twine(".suspend"));
236 BasicBlock *CleanupBlock = CGF.createBasicBlock(Prefix + Twine(".cleanup"));
237
238 // If expression is ready, no need to suspend.
239 CGF.EmitBranchOnBoolExpr(S.getReadyExpr(), ReadyBlock, SuspendBlock, 0);
240
241 // Otherwise, emit suspend logic.
242 CGF.EmitBlock(SuspendBlock);
243
244 auto &Builder = CGF.Builder;
245 llvm::Function *CoroSave = CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_save);
246 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.CGM.Int8PtrTy);
247 auto *SaveCall = Builder.CreateCall(CoroSave, {NullPtr});
248
249 auto SuspendWrapper = CodeGenFunction(CGF.CGM).generateAwaitSuspendWrapper(
250 CGF.CurFn->getName(), Prefix, S);
251
252 CGF.CurCoro.InSuspendBlock = true;
253
254 assert(CGF.CurCoro.Data && CGF.CurCoro.Data->CoroBegin &&
255 "expected to be called in coroutine context");
256
257 SmallVector<llvm::Value *, 3> SuspendIntrinsicCallArgs;
258 SuspendIntrinsicCallArgs.push_back(
259 CGF.getOrCreateOpaqueLValueMapping(S.getOpaqueValue()).getPointer(CGF));
260
261 SuspendIntrinsicCallArgs.push_back(CGF.CurCoro.Data->CoroBegin);
262 SuspendIntrinsicCallArgs.push_back(SuspendWrapper);
263
264 const auto SuspendReturnType = S.getSuspendReturnType();
265 llvm::Intrinsic::ID AwaitSuspendIID;
266
267 switch (SuspendReturnType) {
269 AwaitSuspendIID = llvm::Intrinsic::coro_await_suspend_void;
270 break;
272 AwaitSuspendIID = llvm::Intrinsic::coro_await_suspend_bool;
273 break;
275 AwaitSuspendIID = llvm::Intrinsic::coro_await_suspend_handle;
276 break;
277 }
278
279 llvm::Function *AwaitSuspendIntrinsic = CGF.CGM.getIntrinsic(AwaitSuspendIID);
280
281 const auto AwaitSuspendCanThrow = StmtCanThrow(S.getSuspendExpr());
282
283 llvm::CallBase *SuspendRet = nullptr;
284 // FIXME: add call attributes?
285 if (AwaitSuspendCanThrow)
286 SuspendRet =
287 CGF.EmitCallOrInvoke(AwaitSuspendIntrinsic, SuspendIntrinsicCallArgs);
288 else
289 SuspendRet = CGF.EmitNounwindRuntimeCall(AwaitSuspendIntrinsic,
290 SuspendIntrinsicCallArgs);
291
292 assert(SuspendRet);
293 CGF.CurCoro.InSuspendBlock = false;
294
295 switch (SuspendReturnType) {
297 assert(SuspendRet->getType()->isVoidTy());
298 break;
300 assert(SuspendRet->getType()->isIntegerTy());
301
302 // Veto suspension if requested by bool returning await_suspend.
303 BasicBlock *RealSuspendBlock =
304 CGF.createBasicBlock(Prefix + Twine(".suspend.bool"));
305 CGF.Builder.CreateCondBr(SuspendRet, RealSuspendBlock, ReadyBlock);
306 CGF.EmitBlock(RealSuspendBlock);
307 break;
308 }
310 assert(SuspendRet->getType()->isPointerTy());
311
312 auto ResumeIntrinsic = CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_resume);
313 Builder.CreateCall(ResumeIntrinsic, SuspendRet);
314 break;
315 }
316 }
317
318 // Emit the suspend point.
319 const bool IsFinalSuspend = (Kind == AwaitKind::Final);
320 llvm::Function *CoroSuspend =
321 CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_suspend);
322 auto *SuspendResult = Builder.CreateCall(
323 CoroSuspend, {SaveCall, Builder.getInt1(IsFinalSuspend)});
324
325 // Create a switch capturing three possible continuations.
326 auto *Switch = Builder.CreateSwitch(SuspendResult, Coro.SuspendBB, 2);
327 Switch->addCase(Builder.getInt8(0), ReadyBlock);
328 Switch->addCase(Builder.getInt8(1), CleanupBlock);
329
330 // Emit cleanup for this suspend point.
331 CGF.EmitBlock(CleanupBlock);
333
334 // Emit await_resume expression.
335 CGF.EmitBlock(ReadyBlock);
336
337 // Exception handling requires additional IR. If the 'await_resume' function
338 // is marked as 'noexcept', we avoid generating this additional IR.
339 CXXTryStmt *TryStmt = nullptr;
340 if (Coro.ExceptionHandler && Kind == AwaitKind::Init &&
341 StmtCanThrow(S.getResumeExpr())) {
342 Coro.ResumeEHVar =
343 CGF.CreateTempAlloca(Builder.getInt1Ty(), Prefix + Twine("resume.eh"));
345
346 auto Loc = S.getResumeExpr()->getExprLoc();
347 auto *Catch = new (CGF.getContext())
348 CXXCatchStmt(Loc, /*exDecl=*/nullptr, Coro.ExceptionHandler);
349 auto *TryBody = CompoundStmt::Create(CGF.getContext(), S.getResumeExpr(),
350 FPOptionsOverride(), Loc, Loc);
351 TryStmt = CXXTryStmt::Create(CGF.getContext(), Loc, TryBody, Catch);
352 CGF.EnterCXXTryStmt(*TryStmt);
353 CGF.EmitStmt(TryBody);
354 // We don't use EmitCXXTryStmt here. We need to store to ResumeEHVar that
355 // doesn't exist in the body.
357 CGF.ExitCXXTryStmt(*TryStmt);
358 LValueOrRValue Res;
359 // We are not supposed to obtain the value from init suspend await_resume().
360 Res.RV = RValue::getIgnored();
361 return Res;
362 }
363
364 LValueOrRValue Res;
365 if (forLValue)
366 Res.LV = CGF.EmitLValue(S.getResumeExpr());
367 else
368 Res.RV = CGF.EmitAnyExpr(S.getResumeExpr(), aggSlot, ignoreResult);
369
370 return Res;
371}
372
374 AggValueSlot aggSlot,
375 bool ignoreResult) {
376 return emitSuspendExpression(*this, *CurCoro.Data, E,
377 CurCoro.Data->CurrentAwaitKind, aggSlot,
378 ignoreResult, /*forLValue*/false).RV;
379}
381 AggValueSlot aggSlot,
382 bool ignoreResult) {
383 return emitSuspendExpression(*this, *CurCoro.Data, E, AwaitKind::Yield,
384 aggSlot, ignoreResult, /*forLValue*/false).RV;
385}
386
388 ++CurCoro.Data->CoreturnCount;
389 const Expr *RV = S.getOperand();
390 if (RV && RV->getType()->isVoidType() && !isa<InitListExpr>(RV)) {
391 // Make sure to evaluate the non initlist expression of a co_return
392 // with a void expression for side effects.
393 RunCleanupsScope cleanupScope(*this);
394 EmitIgnoredExpr(RV);
395 }
396 EmitStmt(S.getPromiseCall());
398}
399
400
401#ifndef NDEBUG
403 const CoroutineSuspendExpr *E) {
404 const auto *RE = E->getResumeExpr();
405 // Is it possible for RE to be a CXXBindTemporaryExpr wrapping
406 // a MemberCallExpr?
407 assert(isa<CallExpr>(RE) && "unexpected suspend expression type");
408 return cast<CallExpr>(RE)->getCallReturnType(Ctx);
409}
410#endif
411
412llvm::Function *
414 Twine const &SuspendPointName,
415 CoroutineSuspendExpr const &S) {
416 std::string FuncName = "__await_suspend_wrapper_";
417 FuncName += CoroName.str();
418 FuncName += '_';
419 FuncName += SuspendPointName.str();
420
422
423 FunctionArgList args;
424
425 ImplicitParamDecl AwaiterDecl(C, C.VoidPtrTy, ImplicitParamKind::Other);
426 ImplicitParamDecl FrameDecl(C, C.VoidPtrTy, ImplicitParamKind::Other);
427 QualType ReturnTy = S.getSuspendExpr()->getType();
428
429 args.push_back(&AwaiterDecl);
430 args.push_back(&FrameDecl);
431
432 const CGFunctionInfo &FI =
434
435 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
436
437 llvm::Function *Fn = llvm::Function::Create(
438 LTy, llvm::GlobalValue::PrivateLinkage, FuncName, &CGM.getModule());
439
440 Fn->addParamAttr(0, llvm::Attribute::AttrKind::NonNull);
441 Fn->addParamAttr(0, llvm::Attribute::AttrKind::NoUndef);
442
443 Fn->addParamAttr(1, llvm::Attribute::AttrKind::NoUndef);
444
445 Fn->setMustProgress();
446 Fn->addFnAttr(llvm::Attribute::AttrKind::AlwaysInline);
447
448 StartFunction(GlobalDecl(), ReturnTy, Fn, FI, args);
449
450 // FIXME: add TBAA metadata to the loads
451 llvm::Value *AwaiterPtr = Builder.CreateLoad(GetAddrOfLocalVar(&AwaiterDecl));
452 auto AwaiterLValue =
453 MakeNaturalAlignAddrLValue(AwaiterPtr, AwaiterDecl.getType());
454
457
459 *this, S.getOpaqueValue(), AwaiterLValue);
460
461 auto *SuspendRet = EmitScalarExpr(S.getSuspendExpr());
462
463 auto UnbindCommonOnExit =
464 llvm::make_scope_exit([&] { AwaiterBinder.unbind(*this); });
465 if (SuspendRet != nullptr) {
466 Fn->addRetAttr(llvm::Attribute::AttrKind::NoUndef);
467 Builder.CreateStore(SuspendRet, ReturnValue);
468 }
469
472 return Fn;
473}
474
475LValue
477 assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
478 "Can't have a scalar return unless the return type is a "
479 "reference type!");
480 return emitSuspendExpression(*this, *CurCoro.Data, *E,
481 CurCoro.Data->CurrentAwaitKind, AggValueSlot::ignored(),
482 /*ignoreResult*/false, /*forLValue*/true).LV;
483}
484
485LValue
487 assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
488 "Can't have a scalar return unless the return type is a "
489 "reference type!");
490 return emitSuspendExpression(*this, *CurCoro.Data, *E,
491 AwaitKind::Yield, AggValueSlot::ignored(),
492 /*ignoreResult*/false, /*forLValue*/true).LV;
493}
494
495// Hunts for the parameter reference in the parameter copy/move declaration.
496namespace {
497struct GetParamRef : public StmtVisitor<GetParamRef> {
498public:
499 DeclRefExpr *Expr = nullptr;
500 GetParamRef() {}
501 void VisitDeclRefExpr(DeclRefExpr *E) {
502 assert(Expr == nullptr && "multilple declref in param move");
503 Expr = E;
504 }
505 void VisitStmt(Stmt *S) {
506 for (auto *C : S->children()) {
507 if (C)
508 Visit(C);
509 }
510 }
511};
512}
513
514// This class replaces references to parameters to their copies by changing
515// the addresses in CGF.LocalDeclMap and restoring back the original values in
516// its destructor.
517
518namespace {
519 struct ParamReferenceReplacerRAII {
520 CodeGenFunction::DeclMapTy SavedLocals;
521 CodeGenFunction::DeclMapTy& LocalDeclMap;
522
523 ParamReferenceReplacerRAII(CodeGenFunction::DeclMapTy &LocalDeclMap)
524 : LocalDeclMap(LocalDeclMap) {}
525
526 void addCopy(DeclStmt const *PM) {
527 // Figure out what param it refers to.
528
529 assert(PM->isSingleDecl());
530 VarDecl const*VD = static_cast<VarDecl const*>(PM->getSingleDecl());
531 Expr const *InitExpr = VD->getInit();
532 GetParamRef Visitor;
533 Visitor.Visit(const_cast<Expr*>(InitExpr));
534 assert(Visitor.Expr);
535 DeclRefExpr *DREOrig = Visitor.Expr;
536 auto *PD = DREOrig->getDecl();
537
538 auto it = LocalDeclMap.find(PD);
539 assert(it != LocalDeclMap.end() && "parameter is not found");
540 SavedLocals.insert({ PD, it->second });
541
542 auto copyIt = LocalDeclMap.find(VD);
543 assert(copyIt != LocalDeclMap.end() && "parameter copy is not found");
544 it->second = copyIt->getSecond();
545 }
546
547 ~ParamReferenceReplacerRAII() {
548 for (auto&& SavedLocal : SavedLocals) {
549 LocalDeclMap.insert({SavedLocal.first, SavedLocal.second});
550 }
551 }
552 };
553}
554
555// For WinEH exception representation backend needs to know what funclet coro.end
556// belongs to. That information is passed in a funclet bundle.
560
561 if (llvm::Instruction *EHPad = CGF.CurrentFuncletPad)
562 BundleList.emplace_back("funclet", EHPad);
563
564 return BundleList;
565}
566
567namespace {
568// We will insert coro.end to cut any of the destructors for objects that
569// do not need to be destroyed once the coroutine is resumed.
570// See llvm/docs/Coroutines.rst for more details about coro.end.
571struct CallCoroEnd final : public EHScopeStack::Cleanup {
572 void Emit(CodeGenFunction &CGF, Flags flags) override {
573 auto &CGM = CGF.CGM;
574 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
575 llvm::Function *CoroEndFn = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
576 // See if we have a funclet bundle to associate coro.end with. (WinEH)
577 auto Bundles = getBundlesForCoroEnd(CGF);
578 auto *CoroEnd =
579 CGF.Builder.CreateCall(CoroEndFn,
580 {NullPtr, CGF.Builder.getTrue(),
581 llvm::ConstantTokenNone::get(CoroEndFn->getContext())},
582 Bundles);
583 if (Bundles.empty()) {
584 // Otherwise, (landingpad model), create a conditional branch that leads
585 // either to a cleanup block or a block with EH resume instruction.
586 auto *ResumeBB = CGF.getEHResumeBlock(/*isCleanup=*/true);
587 auto *CleanupContBB = CGF.createBasicBlock("cleanup.cont");
588 CGF.Builder.CreateCondBr(CoroEnd, ResumeBB, CleanupContBB);
589 CGF.EmitBlock(CleanupContBB);
590 }
591 }
592};
593}
594
595namespace {
596// Make sure to call coro.delete on scope exit.
597struct CallCoroDelete final : public EHScopeStack::Cleanup {
598 Stmt *Deallocate;
599
600 // Emit "if (coro.free(CoroId, CoroBegin)) Deallocate;"
601
602 // Note: That deallocation will be emitted twice: once for a normal exit and
603 // once for exceptional exit. This usage is safe because Deallocate does not
604 // contain any declarations. The SubStmtBuilder::makeNewAndDeleteExpr()
605 // builds a single call to a deallocation function which is safe to emit
606 // multiple times.
607 void Emit(CodeGenFunction &CGF, Flags) override {
608 // Remember the current point, as we are going to emit deallocation code
609 // first to get to coro.free instruction that is an argument to a delete
610 // call.
611 BasicBlock *SaveInsertBlock = CGF.Builder.GetInsertBlock();
612
613 auto *FreeBB = CGF.createBasicBlock("coro.free");
614 CGF.EmitBlock(FreeBB);
615 CGF.EmitStmt(Deallocate);
616
617 auto *AfterFreeBB = CGF.createBasicBlock("after.coro.free");
618 CGF.EmitBlock(AfterFreeBB);
619
620 // We should have captured coro.free from the emission of deallocate.
621 auto *CoroFree = CGF.CurCoro.Data->LastCoroFree;
622 if (!CoroFree) {
623 CGF.CGM.Error(Deallocate->getBeginLoc(),
624 "Deallocation expressoin does not refer to coro.free");
625 return;
626 }
627
628 // Get back to the block we were originally and move coro.free there.
629 auto *InsertPt = SaveInsertBlock->getTerminator();
630 CoroFree->moveBefore(InsertPt);
631 CGF.Builder.SetInsertPoint(InsertPt);
632
633 // Add if (auto *mem = coro.free) Deallocate;
634 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
635 auto *Cond = CGF.Builder.CreateICmpNE(CoroFree, NullPtr);
636 CGF.Builder.CreateCondBr(Cond, FreeBB, AfterFreeBB);
637
638 // No longer need old terminator.
639 InsertPt->eraseFromParent();
640 CGF.Builder.SetInsertPoint(AfterFreeBB);
641 }
642 explicit CallCoroDelete(Stmt *DeallocStmt) : Deallocate(DeallocStmt) {}
643};
644}
645
646namespace {
647struct GetReturnObjectManager {
648 CodeGenFunction &CGF;
649 CGBuilderTy &Builder;
650 const CoroutineBodyStmt &S;
651 // When true, performs RVO for the return object.
652 bool DirectEmit = false;
653
654 Address GroActiveFlag;
655 CodeGenFunction::AutoVarEmission GroEmission;
656
657 GetReturnObjectManager(CodeGenFunction &CGF, const CoroutineBodyStmt &S)
658 : CGF(CGF), Builder(CGF.Builder), S(S), GroActiveFlag(Address::invalid()),
659 GroEmission(CodeGenFunction::AutoVarEmission::invalid()) {
660 // The call to get_­return_­object is sequenced before the call to
661 // initial_­suspend and is invoked at most once, but there are caveats
662 // regarding on whether the prvalue result object may be initialized
663 // directly/eager or delayed, depending on the types involved.
664 //
665 // More info at https://github.com/cplusplus/papers/issues/1414
666 //
667 // The general cases:
668 // 1. Same type of get_return_object and coroutine return type (direct
669 // emission):
670 // - Constructed in the return slot.
671 // 2. Different types (delayed emission):
672 // - Constructed temporary object prior to initial suspend initialized with
673 // a call to get_return_object()
674 // - When coroutine needs to to return to the caller and needs to construct
675 // return value for the coroutine it is initialized with expiring value of
676 // the temporary obtained above.
677 //
678 // Direct emission for void returning coroutines or GROs.
679 DirectEmit = [&]() {
680 auto *RVI = S.getReturnValueInit();
681 assert(RVI && "expected RVI");
682 auto GroType = RVI->getType();
683 return CGF.getContext().hasSameType(GroType, CGF.FnRetTy);
684 }();
685 }
686
687 // The gro variable has to outlive coroutine frame and coroutine promise, but,
688 // it can only be initialized after coroutine promise was created, thus, we
689 // split its emission in two parts. EmitGroAlloca emits an alloca and sets up
690 // cleanups. Later when coroutine promise is available we initialize the gro
691 // and sets the flag that the cleanup is now active.
692 void EmitGroAlloca() {
693 if (DirectEmit)
694 return;
695
696 auto *GroDeclStmt = dyn_cast_or_null<DeclStmt>(S.getResultDecl());
697 if (!GroDeclStmt) {
698 // If get_return_object returns void, no need to do an alloca.
699 return;
700 }
701
702 auto *GroVarDecl = cast<VarDecl>(GroDeclStmt->getSingleDecl());
703
704 // Set GRO flag that it is not initialized yet
705 GroActiveFlag = CGF.CreateTempAlloca(Builder.getInt1Ty(), CharUnits::One(),
706 "gro.active");
707 Builder.CreateStore(Builder.getFalse(), GroActiveFlag);
708
709 GroEmission = CGF.EmitAutoVarAlloca(*GroVarDecl);
710 auto *GroAlloca = dyn_cast_or_null<llvm::AllocaInst>(
711 GroEmission.getOriginalAllocatedAddress().getPointer());
712 assert(GroAlloca && "expected alloca to be emitted");
713 GroAlloca->setMetadata(llvm::LLVMContext::MD_coro_outside_frame,
714 llvm::MDNode::get(CGF.CGM.getLLVMContext(), {}));
715
716 // Remember the top of EHStack before emitting the cleanup.
717 auto old_top = CGF.EHStack.stable_begin();
718 CGF.EmitAutoVarCleanups(GroEmission);
719 auto top = CGF.EHStack.stable_begin();
720
721 // Make the cleanup conditional on gro.active
722 for (auto b = CGF.EHStack.find(top), e = CGF.EHStack.find(old_top); b != e;
723 b++) {
724 if (auto *Cleanup = dyn_cast<EHCleanupScope>(&*b)) {
725 assert(!Cleanup->hasActiveFlag() && "cleanup already has active flag?");
726 Cleanup->setActiveFlag(GroActiveFlag);
727 Cleanup->setTestFlagInEHCleanup();
728 Cleanup->setTestFlagInNormalCleanup();
729 }
730 }
731 }
732
733 void EmitGroInit() {
734 if (DirectEmit) {
735 // ReturnValue should be valid as long as the coroutine's return type
736 // is not void. The assertion could help us to reduce the check later.
737 assert(CGF.ReturnValue.isValid() == (bool)S.getReturnStmt());
738 // Now we have the promise, initialize the GRO.
739 // We need to emit `get_return_object` first. According to:
740 // [dcl.fct.def.coroutine]p7
741 // The call to get_return_­object is sequenced before the call to
742 // initial_suspend and is invoked at most once.
743 //
744 // So we couldn't emit return value when we emit return statment,
745 // otherwise the call to get_return_object wouldn't be in front
746 // of initial_suspend.
747 if (CGF.ReturnValue.isValid()) {
748 CGF.EmitAnyExprToMem(S.getReturnValue(), CGF.ReturnValue,
749 S.getReturnValue()->getType().getQualifiers(),
750 /*IsInit*/ true);
751 }
752 return;
753 }
754
755 if (!GroActiveFlag.isValid()) {
756 // No Gro variable was allocated. Simply emit the call to
757 // get_return_object.
758 CGF.EmitStmt(S.getResultDecl());
759 return;
760 }
761
762 CGF.EmitAutoVarInit(GroEmission);
763 Builder.CreateStore(Builder.getTrue(), GroActiveFlag);
764 }
765};
766} // namespace
767
769 const CoroutineBodyStmt &S, Stmt *Body) {
770 CGF.EmitStmt(Body);
771 const bool CanFallthrough = CGF.Builder.GetInsertBlock();
772 if (CanFallthrough)
773 if (Stmt *OnFallthrough = S.getFallthroughHandler())
774 CGF.EmitStmt(OnFallthrough);
775}
776
778 auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getPtrTy());
779 auto &TI = CGM.getContext().getTargetInfo();
780 unsigned NewAlign = TI.getNewAlign() / TI.getCharWidth();
781
782 auto *EntryBB = Builder.GetInsertBlock();
783 auto *AllocBB = createBasicBlock("coro.alloc");
784 auto *InitBB = createBasicBlock("coro.init");
785 auto *FinalBB = createBasicBlock("coro.final");
786 auto *RetBB = createBasicBlock("coro.ret");
787
788 auto *CoroId = Builder.CreateCall(
789 CGM.getIntrinsic(llvm::Intrinsic::coro_id),
790 {Builder.getInt32(NewAlign), NullPtr, NullPtr, NullPtr});
791 createCoroData(*this, CurCoro, CoroId);
792 CurCoro.Data->SuspendBB = RetBB;
793 assert(ShouldEmitLifetimeMarkers &&
794 "Must emit lifetime intrinsics for coroutines");
795
796 // Backend is allowed to elide memory allocations, to help it, emit
797 // auto mem = coro.alloc() ? 0 : ... allocation code ...;
798 auto *CoroAlloc = Builder.CreateCall(
799 CGM.getIntrinsic(llvm::Intrinsic::coro_alloc), {CoroId});
800
801 Builder.CreateCondBr(CoroAlloc, AllocBB, InitBB);
802
803 EmitBlock(AllocBB);
804 auto *AllocateCall = EmitScalarExpr(S.getAllocate());
805 auto *AllocOrInvokeContBB = Builder.GetInsertBlock();
806
807 // Handle allocation failure if 'ReturnStmtOnAllocFailure' was provided.
808 if (auto *RetOnAllocFailure = S.getReturnStmtOnAllocFailure()) {
809 auto *RetOnFailureBB = createBasicBlock("coro.ret.on.failure");
810
811 // See if allocation was successful.
812 auto *NullPtr = llvm::ConstantPointerNull::get(Int8PtrTy);
813 auto *Cond = Builder.CreateICmpNE(AllocateCall, NullPtr);
814 // Expect the allocation to be successful.
815 emitCondLikelihoodViaExpectIntrinsic(Cond, Stmt::LH_Likely);
816 Builder.CreateCondBr(Cond, InitBB, RetOnFailureBB);
817
818 // If not, return OnAllocFailure object.
819 EmitBlock(RetOnFailureBB);
820 EmitStmt(RetOnAllocFailure);
821 }
822 else {
823 Builder.CreateBr(InitBB);
824 }
825
826 EmitBlock(InitBB);
827
828 // Pass the result of the allocation to coro.begin.
829 auto *Phi = Builder.CreatePHI(VoidPtrTy, 2);
830 Phi->addIncoming(NullPtr, EntryBB);
831 Phi->addIncoming(AllocateCall, AllocOrInvokeContBB);
832 auto *CoroBegin = Builder.CreateCall(
833 CGM.getIntrinsic(llvm::Intrinsic::coro_begin), {CoroId, Phi});
834 CurCoro.Data->CoroBegin = CoroBegin;
835
836 GetReturnObjectManager GroManager(*this, S);
837 GroManager.EmitGroAlloca();
838
839 CurCoro.Data->CleanupJD = getJumpDestInCurrentScope(RetBB);
840 {
842 ParamReferenceReplacerRAII ParamReplacer(LocalDeclMap);
843 CodeGenFunction::RunCleanupsScope ResumeScope(*this);
844 EHStack.pushCleanup<CallCoroDelete>(NormalAndEHCleanup, S.getDeallocate());
845
846 // Create mapping between parameters and copy-params for coroutine function.
847 llvm::ArrayRef<const Stmt *> ParamMoves = S.getParamMoves();
848 assert(
849 (ParamMoves.size() == 0 || (ParamMoves.size() == FnArgs.size())) &&
850 "ParamMoves and FnArgs should be the same size for coroutine function");
851 if (ParamMoves.size() == FnArgs.size() && DI)
852 for (const auto Pair : llvm::zip(FnArgs, ParamMoves))
854 {std::get<0>(Pair), std::get<1>(Pair)});
855
856 // Create parameter copies. We do it before creating a promise, since an
857 // evolution of coroutine TS may allow promise constructor to observe
858 // parameter copies.
859 for (auto *PM : S.getParamMoves()) {
860 EmitStmt(PM);
861 ParamReplacer.addCopy(cast<DeclStmt>(PM));
862 // TODO: if(CoroParam(...)) need to surround ctor and dtor
863 // for the copy, so that llvm can elide it if the copy is
864 // not needed.
865 }
866
867 EmitStmt(S.getPromiseDeclStmt());
868
869 Address PromiseAddr = GetAddrOfLocalVar(S.getPromiseDecl());
870 auto *PromiseAddrVoidPtr =
871 new llvm::BitCastInst(PromiseAddr.getPointer(), VoidPtrTy, "", CoroId);
872 // Update CoroId to refer to the promise. We could not do it earlier because
873 // promise local variable was not emitted yet.
874 CoroId->setArgOperand(1, PromiseAddrVoidPtr);
875
876 // Now we have the promise, initialize the GRO
877 GroManager.EmitGroInit();
878
879 EHStack.pushCleanup<CallCoroEnd>(EHCleanup);
880
881 CurCoro.Data->CurrentAwaitKind = AwaitKind::Init;
882 CurCoro.Data->ExceptionHandler = S.getExceptionHandler();
883 EmitStmt(S.getInitSuspendStmt());
884 CurCoro.Data->FinalJD = getJumpDestInCurrentScope(FinalBB);
885
886 CurCoro.Data->CurrentAwaitKind = AwaitKind::Normal;
887
888 if (CurCoro.Data->ExceptionHandler) {
889 // If we generated IR to record whether an exception was thrown from
890 // 'await_resume', then use that IR to determine whether the coroutine
891 // body should be skipped.
892 // If we didn't generate the IR (perhaps because 'await_resume' was marked
893 // as 'noexcept'), then we skip this check.
894 BasicBlock *ContBB = nullptr;
895 if (CurCoro.Data->ResumeEHVar) {
896 BasicBlock *BodyBB = createBasicBlock("coro.resumed.body");
897 ContBB = createBasicBlock("coro.resumed.cont");
898 Value *SkipBody = Builder.CreateFlagLoad(CurCoro.Data->ResumeEHVar,
899 "coro.resumed.eh");
900 Builder.CreateCondBr(SkipBody, ContBB, BodyBB);
901 EmitBlock(BodyBB);
902 }
903
904 auto Loc = S.getBeginLoc();
905 CXXCatchStmt Catch(Loc, /*exDecl=*/nullptr,
906 CurCoro.Data->ExceptionHandler);
907 auto *TryStmt =
908 CXXTryStmt::Create(getContext(), Loc, S.getBody(), &Catch);
909
910 EnterCXXTryStmt(*TryStmt);
911 emitBodyAndFallthrough(*this, S, TryStmt->getTryBlock());
912 ExitCXXTryStmt(*TryStmt);
913
914 if (ContBB)
915 EmitBlock(ContBB);
916 }
917 else {
918 emitBodyAndFallthrough(*this, S, S.getBody());
919 }
920
921 // See if we need to generate final suspend.
922 const bool CanFallthrough = Builder.GetInsertBlock();
923 const bool HasCoreturns = CurCoro.Data->CoreturnCount > 0;
924 if (CanFallthrough || HasCoreturns) {
925 EmitBlock(FinalBB);
926 CurCoro.Data->CurrentAwaitKind = AwaitKind::Final;
927 EmitStmt(S.getFinalSuspendStmt());
928 } else {
929 // We don't need FinalBB. Emit it to make sure the block is deleted.
930 EmitBlock(FinalBB, /*IsFinished=*/true);
931 }
932 }
933
934 EmitBlock(RetBB);
935 // Emit coro.end before getReturnStmt (and parameter destructors), since
936 // resume and destroy parts of the coroutine should not include them.
937 llvm::Function *CoroEnd = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
938 Builder.CreateCall(CoroEnd,
939 {NullPtr, Builder.getFalse(),
940 llvm::ConstantTokenNone::get(CoroEnd->getContext())});
941
942 if (Stmt *Ret = S.getReturnStmt()) {
943 // Since we already emitted the return value above, so we shouldn't
944 // emit it again here.
945 if (GroManager.DirectEmit)
946 cast<ReturnStmt>(Ret)->setRetValue(nullptr);
947 EmitStmt(Ret);
948 }
949
950 // LLVM require the frontend to mark the coroutine.
951 CurFn->setPresplitCoroutine();
952
954 RD && RD->hasAttr<CoroOnlyDestroyWhenCompleteAttr>())
955 CurFn->setCoroDestroyOnlyWhenComplete();
956}
957
958// Emit coroutine intrinsic and patch up arguments of the token type.
960 unsigned int IID) {
962 switch (IID) {
963 default:
964 break;
965 // The coro.frame builtin is replaced with an SSA value of the coro.begin
966 // intrinsic.
967 case llvm::Intrinsic::coro_frame: {
968 if (CurCoro.Data && CurCoro.Data->CoroBegin) {
969 return RValue::get(CurCoro.Data->CoroBegin);
970 }
971
974 }
975
976 CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_begin "
977 "has been used earlier in this function");
978 auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getPtrTy());
979 return RValue::get(NullPtr);
980 }
981 case llvm::Intrinsic::coro_size: {
982 auto &Context = getContext();
983 CanQualType SizeTy = Context.getSizeType();
984 llvm::IntegerType *T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
985 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::coro_size, T);
986 return RValue::get(Builder.CreateCall(F));
987 }
988 case llvm::Intrinsic::coro_align: {
989 auto &Context = getContext();
990 CanQualType SizeTy = Context.getSizeType();
991 llvm::IntegerType *T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
992 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::coro_align, T);
993 return RValue::get(Builder.CreateCall(F));
994 }
995 // The following three intrinsics take a token parameter referring to a token
996 // returned by earlier call to @llvm.coro.id. Since we cannot represent it in
997 // builtins, we patch it up here.
998 case llvm::Intrinsic::coro_alloc:
999 case llvm::Intrinsic::coro_begin:
1000 case llvm::Intrinsic::coro_free: {
1001 if (CurCoro.Data && CurCoro.Data->CoroId) {
1002 Args.push_back(CurCoro.Data->CoroId);
1003 break;
1004 }
1005 CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_id has"
1006 " been used earlier in this function");
1007 // Fallthrough to the next case to add TokenNone as the first argument.
1008 [[fallthrough]];
1009 }
1010 // @llvm.coro.suspend takes a token parameter. Add token 'none' as the first
1011 // argument.
1012 case llvm::Intrinsic::coro_suspend:
1013 Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
1014 break;
1015 }
1016 for (const Expr *Arg : E->arguments())
1017 Args.push_back(EmitScalarExpr(Arg));
1018 // @llvm.coro.end takes a token parameter. Add token 'none' as the last
1019 // argument.
1020 if (IID == llvm::Intrinsic::coro_end)
1021 Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
1022
1023 llvm::Function *F = CGM.getIntrinsic(IID);
1024 llvm::CallInst *Call = Builder.CreateCall(F, Args);
1025
1026 // Note: The following code is to enable to emit coro.id and coro.begin by
1027 // hand to experiment with coroutines in C.
1028 // If we see @llvm.coro.id remember it in the CoroData. We will update
1029 // coro.alloc, coro.begin and coro.free intrinsics to refer to it.
1030 if (IID == llvm::Intrinsic::coro_id) {
1031 createCoroData(*this, CurCoro, Call, E);
1032 }
1033 else if (IID == llvm::Intrinsic::coro_begin) {
1034 if (CurCoro.Data)
1035 CurCoro.Data->CoroBegin = Call;
1036 }
1037 else if (IID == llvm::Intrinsic::coro_free) {
1038 // Remember the last coro_free as we need it to build the conditional
1039 // deletion of the coroutine frame.
1040 if (CurCoro.Data)
1041 CurCoro.Data->LastCoroFree = Call;
1042 }
1043 return RValue::get(Call);
1044}
static LValueOrRValue emitSuspendExpression(CodeGenFunction &CGF, CGCoroData &Coro, CoroutineSuspendExpr const &S, AwaitKind Kind, AggValueSlot aggSlot, bool ignoreResult, bool forLValue)
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 bool StmtCanThrow(const Stmt *S)
static bool FunctionCanThrow(const FunctionDecl *D)
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:2565
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:2315
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:752
CXXCatchStmt - This represents a C++ catch block.
Definition: StmtCXX.h:28
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
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:2819
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1618
arg_range arguments()
Definition: Expr.h:3058
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition: CharUnits.h:58
Represents a 'co_await' expression.
Definition: ExprCXX.h:5144
An aligned address.
Definition: Address.h:29
llvm::Value * getPointer() const
Definition: Address.h:51
bool isValid() const
Definition: Address.h:47
An aggregate value slot.
Definition: CGValue.h:512
static AggValueSlot ignored()
ignored - Returns an aggregate value slot indicating that the aggregate value is being ignored.
Definition: CGValue.h:580
llvm::StoreInst * CreateFlagStore(bool Value, llvm::Value *Addr)
Emit a store to an i1 flag variable.
Definition: CGBuilder.h:125
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:97
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition: CGBuilder.h:71
llvm::LoadInst * CreateFlagLoad(llvm::Value *Addr, const llvm::Twine &Name="")
Emit a load from an i1 flag variable.
Definition: CGBuilder.h:119
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:601
CGFunctionInfo - Class to encapsulate the information about a function definition.
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...
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount, Stmt::Likelihood LH=Stmt::LH_None, const Expr *ConditionalOp=nullptr)
EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g.
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 getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its LValue mapping if it exists, otherwise create one.
AwaitSuspendWrapperInfo CurAwaitSuspendWrapper
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::Function * generateAwaitSuspendWrapper(Twine const &CoroName, Twine const &SuspendPointName, CoroutineSuspendExpr const &S)
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)
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.
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
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)
llvm::CallInst * EmitNounwindRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
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::CallBase * EmitCallOrInvoke(llvm::FunctionCallee Callee, ArrayRef< llvm::Value * > Args, const Twine &Name="")
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T)
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,...
llvm::Module & getModule() const
void Error(SourceLocation loc, StringRef error)
Emit a general error that something can't be done.
ASTContext & getContext() const
llvm::LLVMContext & getLLVMContext()
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys=std::nullopt)
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition: CGCall.cpp:1625
const CGFunctionInfo & arrangeBuiltinFunctionDeclaration(QualType resultType, const FunctionArgList &args)
A builtin function is a freestanding function using the default C conventions.
Definition: CGCall.cpp:674
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:393
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:584
FunctionArgList - Type for representing both the decl and type of parameters to a function.
Definition: CGCall.h:352
LValue - This represents an lvalue references.
Definition: CGValue.h:171
llvm::Value * getPointer(CodeGenFunction &CGF) const
Definition: CGValue.h:346
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition: CGValue.h:39
static RValue getIgnored()
Definition: CGValue.h:84
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:383
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:5030
Expr * getResumeExpr() const
Definition: ExprCXX.h:5094
Represents a 'co_yield' expression.
Definition: ExprCXX.h:5225
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
ValueDecl * getDecl()
Definition: Expr.h:1328
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition: Stmt.h:1495
bool isSingleDecl() const
isSingleDecl - This method returns true if this DeclStmt refers to a single Decl.
Definition: Stmt.h:1508
const Decl * getSingleDecl() const
Definition: Stmt.h:1510
bool hasAttr() const
Definition: DeclBase.h:582
This represents one expression.
Definition: Expr.h:110
QualType getType() const
Definition: Expr.h:142
Represents difference between two FPOptions values.
Definition: LangOptions.h:870
Represents a function declaration or definition.
Definition: Decl.h:1959
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4199
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
A (possibly-)qualified type.
Definition: Type.h:737
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:185
Stmt - This represents one statement.
Definition: Stmt.h:84
@ LH_Likely
Branch has the [[likely]] attribute.
Definition: Stmt.h:1303
unsigned getNewAlign() const
Return the largest alignment for which a suitably-sized allocation with '::operator new(size_t)' is g...
Definition: TargetInfo.h:718
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1819
bool isVoidType() const
Definition: Type.h:7443
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7657
QualType getType() const
Definition: Decl.h:717
Represents a variable declaration or definition.
Definition: Decl.h:918
const Expr * getInit() const
Definition: Decl.h:1352
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
Definition: EHScopeStack.h:80
The JSON file list parser is used to communicate input to InstallAPI.
bool isNoexceptExceptionSpec(ExceptionSpecificationType ESpecType)
@ Other
Other implicit parameter.
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...