Path: blob/main/contrib/llvm-project/clang/lib/Sema/SemaCoroutine.cpp
35234 views
//===-- SemaCoroutine.cpp - Semantic Analysis for Coroutines --------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements semantic analysis for C++ Coroutines.9//10// This file contains references to sections of the Coroutines TS, which11// can be found at http://wg21.link/coroutines.12//13//===----------------------------------------------------------------------===//1415#include "CoroutineStmtBuilder.h"16#include "clang/AST/ASTLambda.h"17#include "clang/AST/Decl.h"18#include "clang/AST/Expr.h"19#include "clang/AST/ExprCXX.h"20#include "clang/AST/StmtCXX.h"21#include "clang/Basic/Builtins.h"22#include "clang/Lex/Preprocessor.h"23#include "clang/Sema/EnterExpressionEvaluationContext.h"24#include "clang/Sema/Initialization.h"25#include "clang/Sema/Overload.h"26#include "clang/Sema/ScopeInfo.h"27#include "clang/Sema/SemaInternal.h"28#include "llvm/ADT/SmallSet.h"2930using namespace clang;31using namespace sema;3233static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,34SourceLocation Loc, bool &Res) {35DeclarationName DN = S.PP.getIdentifierInfo(Name);36LookupResult LR(S, DN, Loc, Sema::LookupMemberName);37// Suppress diagnostics when a private member is selected. The same warnings38// will be produced again when building the call.39LR.suppressDiagnostics();40Res = S.LookupQualifiedName(LR, RD);41return LR;42}4344static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,45SourceLocation Loc) {46bool Res;47lookupMember(S, Name, RD, Loc, Res);48return Res;49}5051/// Look up the std::coroutine_traits<...>::promise_type for the given52/// function type.53static QualType lookupPromiseType(Sema &S, const FunctionDecl *FD,54SourceLocation KwLoc) {55const FunctionProtoType *FnType = FD->getType()->castAs<FunctionProtoType>();56const SourceLocation FuncLoc = FD->getLocation();5758ClassTemplateDecl *CoroTraits =59S.lookupCoroutineTraits(KwLoc, FuncLoc);60if (!CoroTraits)61return QualType();6263// Form template argument list for coroutine_traits<R, P1, P2, ...> according64// to [dcl.fct.def.coroutine]365TemplateArgumentListInfo Args(KwLoc, KwLoc);66auto AddArg = [&](QualType T) {67Args.addArgument(TemplateArgumentLoc(68TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));69};70AddArg(FnType->getReturnType());71// If the function is a non-static member function, add the type72// of the implicit object parameter before the formal parameters.73if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {74if (MD->isImplicitObjectMemberFunction()) {75// [over.match.funcs]476// For non-static member functions, the type of the implicit object77// parameter is78// -- "lvalue reference to cv X" for functions declared without a79// ref-qualifier or with the & ref-qualifier80// -- "rvalue reference to cv X" for functions declared with the &&81// ref-qualifier82QualType T = MD->getFunctionObjectParameterType();83T = FnType->getRefQualifier() == RQ_RValue84? S.Context.getRValueReferenceType(T)85: S.Context.getLValueReferenceType(T, /*SpelledAsLValue*/ true);86AddArg(T);87}88}89for (QualType T : FnType->getParamTypes())90AddArg(T);9192// Build the template-id.93QualType CoroTrait =94S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);95if (CoroTrait.isNull())96return QualType();97if (S.RequireCompleteType(KwLoc, CoroTrait,98diag::err_coroutine_type_missing_specialization))99return QualType();100101auto *RD = CoroTrait->getAsCXXRecordDecl();102assert(RD && "specialization of class template is not a class?");103104// Look up the ::promise_type member.105LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,106Sema::LookupOrdinaryName);107S.LookupQualifiedName(R, RD);108auto *Promise = R.getAsSingle<TypeDecl>();109if (!Promise) {110S.Diag(FuncLoc,111diag::err_implied_std_coroutine_traits_promise_type_not_found)112<< RD;113return QualType();114}115// The promise type is required to be a class type.116QualType PromiseType = S.Context.getTypeDeclType(Promise);117118auto buildElaboratedType = [&]() {119auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, S.getStdNamespace());120NNS = NestedNameSpecifier::Create(S.Context, NNS, false,121CoroTrait.getTypePtr());122return S.Context.getElaboratedType(ElaboratedTypeKeyword::None, NNS,123PromiseType);124};125126if (!PromiseType->getAsCXXRecordDecl()) {127S.Diag(FuncLoc,128diag::err_implied_std_coroutine_traits_promise_type_not_class)129<< buildElaboratedType();130return QualType();131}132if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),133diag::err_coroutine_promise_type_incomplete))134return QualType();135136return PromiseType;137}138139/// Look up the std::coroutine_handle<PromiseType>.140static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,141SourceLocation Loc) {142if (PromiseType.isNull())143return QualType();144145NamespaceDecl *CoroNamespace = S.getStdNamespace();146assert(CoroNamespace && "Should already be diagnosed");147148LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),149Loc, Sema::LookupOrdinaryName);150if (!S.LookupQualifiedName(Result, CoroNamespace)) {151S.Diag(Loc, diag::err_implied_coroutine_type_not_found)152<< "std::coroutine_handle";153return QualType();154}155156ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();157if (!CoroHandle) {158Result.suppressDiagnostics();159// We found something weird. Complain about the first thing we found.160NamedDecl *Found = *Result.begin();161S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);162return QualType();163}164165// Form template argument list for coroutine_handle<Promise>.166TemplateArgumentListInfo Args(Loc, Loc);167Args.addArgument(TemplateArgumentLoc(168TemplateArgument(PromiseType),169S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));170171// Build the template-id.172QualType CoroHandleType =173S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);174if (CoroHandleType.isNull())175return QualType();176if (S.RequireCompleteType(Loc, CoroHandleType,177diag::err_coroutine_type_missing_specialization))178return QualType();179180return CoroHandleType;181}182183static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,184StringRef Keyword) {185// [expr.await]p2 dictates that 'co_await' and 'co_yield' must be used within186// a function body.187// FIXME: This also covers [expr.await]p2: "An await-expression shall not188// appear in a default argument." But the diagnostic QoI here could be189// improved to inform the user that default arguments specifically are not190// allowed.191auto *FD = dyn_cast<FunctionDecl>(S.CurContext);192if (!FD) {193S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)194? diag::err_coroutine_objc_method195: diag::err_coroutine_outside_function) << Keyword;196return false;197}198199// An enumeration for mapping the diagnostic type to the correct diagnostic200// selection index.201enum InvalidFuncDiag {202DiagCtor = 0,203DiagDtor,204DiagMain,205DiagConstexpr,206DiagAutoRet,207DiagVarargs,208DiagConsteval,209};210bool Diagnosed = false;211auto DiagInvalid = [&](InvalidFuncDiag ID) {212S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;213Diagnosed = true;214return false;215};216217// Diagnose when a constructor, destructor218// or the function 'main' are declared as a coroutine.219auto *MD = dyn_cast<CXXMethodDecl>(FD);220// [class.ctor]p11: "A constructor shall not be a coroutine."221if (MD && isa<CXXConstructorDecl>(MD))222return DiagInvalid(DiagCtor);223// [class.dtor]p17: "A destructor shall not be a coroutine."224else if (MD && isa<CXXDestructorDecl>(MD))225return DiagInvalid(DiagDtor);226// [basic.start.main]p3: "The function main shall not be a coroutine."227else if (FD->isMain())228return DiagInvalid(DiagMain);229230// Emit a diagnostics for each of the following conditions which is not met.231// [expr.const]p2: "An expression e is a core constant expression unless the232// evaluation of e [...] would evaluate one of the following expressions:233// [...] an await-expression [...] a yield-expression."234if (FD->isConstexpr())235DiagInvalid(FD->isConsteval() ? DiagConsteval : DiagConstexpr);236// [dcl.spec.auto]p15: "A function declared with a return type that uses a237// placeholder type shall not be a coroutine."238if (FD->getReturnType()->isUndeducedType())239DiagInvalid(DiagAutoRet);240// [dcl.fct.def.coroutine]p1241// The parameter-declaration-clause of the coroutine shall not terminate with242// an ellipsis that is not part of a parameter-declaration.243if (FD->isVariadic())244DiagInvalid(DiagVarargs);245246return !Diagnosed;247}248249/// Build a call to 'operator co_await' if there is a suitable operator for250/// the given expression.251ExprResult Sema::BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E,252UnresolvedLookupExpr *Lookup) {253UnresolvedSet<16> Functions;254Functions.append(Lookup->decls_begin(), Lookup->decls_end());255return CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);256}257258static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,259SourceLocation Loc, Expr *E) {260ExprResult R = SemaRef.BuildOperatorCoawaitLookupExpr(S, Loc);261if (R.isInvalid())262return ExprError();263return SemaRef.BuildOperatorCoawaitCall(Loc, E,264cast<UnresolvedLookupExpr>(R.get()));265}266267static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,268SourceLocation Loc) {269QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);270if (CoroHandleType.isNull())271return ExprError();272273DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);274LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,275Sema::LookupOrdinaryName);276if (!S.LookupQualifiedName(Found, LookupCtx)) {277S.Diag(Loc, diag::err_coroutine_handle_missing_member)278<< "from_address";279return ExprError();280}281282Expr *FramePtr =283S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_frame, {});284285CXXScopeSpec SS;286ExprResult FromAddr =287S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);288if (FromAddr.isInvalid())289return ExprError();290291return S.BuildCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);292}293294struct ReadySuspendResumeResult {295enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume };296Expr *Results[3];297OpaqueValueExpr *OpaqueValue;298bool IsInvalid;299};300301static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,302StringRef Name, MultiExprArg Args) {303DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);304305// FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.306CXXScopeSpec SS;307ExprResult Result = S.BuildMemberReferenceExpr(308Base, Base->getType(), Loc, /*IsPtr=*/false, SS,309SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,310/*Scope=*/nullptr);311if (Result.isInvalid())312return ExprError();313314// We meant exactly what we asked for. No need for typo correction.315if (auto *TE = dyn_cast<TypoExpr>(Result.get())) {316S.clearDelayedTypo(TE);317S.Diag(Loc, diag::err_no_member)318<< NameInfo.getName() << Base->getType()->getAsCXXRecordDecl()319<< Base->getSourceRange();320return ExprError();321}322323auto EndLoc = Args.empty() ? Loc : Args.back()->getEndLoc();324return S.BuildCallExpr(nullptr, Result.get(), Loc, Args, EndLoc, nullptr);325}326327// See if return type is coroutine-handle and if so, invoke builtin coro-resume328// on its address. This is to enable the support for coroutine-handle329// returning await_suspend that results in a guaranteed tail call to the target330// coroutine.331static Expr *maybeTailCall(Sema &S, QualType RetType, Expr *E,332SourceLocation Loc) {333if (RetType->isReferenceType())334return nullptr;335Type const *T = RetType.getTypePtr();336if (!T->isClassType() && !T->isStructureType())337return nullptr;338339// FIXME: Add convertability check to coroutine_handle<>. Possibly via340// EvaluateBinaryTypeTrait(BTT_IsConvertible, ...) which is at the moment341// a private function in SemaExprCXX.cpp342343ExprResult AddressExpr = buildMemberCall(S, E, Loc, "address", std::nullopt);344if (AddressExpr.isInvalid())345return nullptr;346347Expr *JustAddress = AddressExpr.get();348349// Check that the type of AddressExpr is void*350if (!JustAddress->getType().getTypePtr()->isVoidPointerType())351S.Diag(cast<CallExpr>(JustAddress)->getCalleeDecl()->getLocation(),352diag::warn_coroutine_handle_address_invalid_return_type)353<< JustAddress->getType();354355// Clean up temporary objects, because the resulting expression356// will become the body of await_suspend wrapper.357return S.MaybeCreateExprWithCleanups(JustAddress);358}359360/// Build calls to await_ready, await_suspend, and await_resume for a co_await361/// expression.362/// The generated AST tries to clean up temporary objects as early as363/// possible so that they don't live across suspension points if possible.364/// Having temporary objects living across suspension points unnecessarily can365/// lead to large frame size, and also lead to memory corruptions if the366/// coroutine frame is destroyed after coming back from suspension. This is done367/// by wrapping both the await_ready call and the await_suspend call with368/// ExprWithCleanups. In the end of this function, we also need to explicitly369/// set cleanup state so that the CoawaitExpr is also wrapped with an370/// ExprWithCleanups to clean up the awaiter associated with the co_await371/// expression.372static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,373SourceLocation Loc, Expr *E) {374OpaqueValueExpr *Operand = new (S.Context)375OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);376377// Assume valid until we see otherwise.378// Further operations are responsible for setting IsInalid to true.379ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/false};380381using ACT = ReadySuspendResumeResult::AwaitCallType;382383auto BuildSubExpr = [&](ACT CallType, StringRef Func,384MultiExprArg Arg) -> Expr * {385ExprResult Result = buildMemberCall(S, Operand, Loc, Func, Arg);386if (Result.isInvalid()) {387Calls.IsInvalid = true;388return nullptr;389}390Calls.Results[CallType] = Result.get();391return Result.get();392};393394CallExpr *AwaitReady = cast_or_null<CallExpr>(395BuildSubExpr(ACT::ACT_Ready, "await_ready", std::nullopt));396if (!AwaitReady)397return Calls;398if (!AwaitReady->getType()->isDependentType()) {399// [expr.await]p3 [...]400// — await-ready is the expression e.await_ready(), contextually converted401// to bool.402ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady);403if (Conv.isInvalid()) {404S.Diag(AwaitReady->getDirectCallee()->getBeginLoc(),405diag::note_await_ready_no_bool_conversion);406S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)407<< AwaitReady->getDirectCallee() << E->getSourceRange();408Calls.IsInvalid = true;409} else410Calls.Results[ACT::ACT_Ready] = S.MaybeCreateExprWithCleanups(Conv.get());411}412413ExprResult CoroHandleRes =414buildCoroutineHandle(S, CoroPromise->getType(), Loc);415if (CoroHandleRes.isInvalid()) {416Calls.IsInvalid = true;417return Calls;418}419Expr *CoroHandle = CoroHandleRes.get();420CallExpr *AwaitSuspend = cast_or_null<CallExpr>(421BuildSubExpr(ACT::ACT_Suspend, "await_suspend", CoroHandle));422if (!AwaitSuspend)423return Calls;424if (!AwaitSuspend->getType()->isDependentType()) {425// [expr.await]p3 [...]426// - await-suspend is the expression e.await_suspend(h), which shall be427// a prvalue of type void, bool, or std::coroutine_handle<Z> for some428// type Z.429QualType RetType = AwaitSuspend->getCallReturnType(S.Context);430431// Support for coroutine_handle returning await_suspend.432if (Expr *TailCallSuspend =433maybeTailCall(S, RetType, AwaitSuspend, Loc))434// Note that we don't wrap the expression with ExprWithCleanups here435// because that might interfere with tailcall contract (e.g. inserting436// clean up instructions in-between tailcall and return). Instead437// ExprWithCleanups is wrapped within maybeTailCall() prior to the resume438// call.439Calls.Results[ACT::ACT_Suspend] = TailCallSuspend;440else {441// non-class prvalues always have cv-unqualified types442if (RetType->isReferenceType() ||443(!RetType->isBooleanType() && !RetType->isVoidType())) {444S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),445diag::err_await_suspend_invalid_return_type)446<< RetType;447S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)448<< AwaitSuspend->getDirectCallee();449Calls.IsInvalid = true;450} else451Calls.Results[ACT::ACT_Suspend] =452S.MaybeCreateExprWithCleanups(AwaitSuspend);453}454}455456BuildSubExpr(ACT::ACT_Resume, "await_resume", std::nullopt);457458// Make sure the awaiter object gets a chance to be cleaned up.459S.Cleanup.setExprNeedsCleanups(true);460461return Calls;462}463464static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,465SourceLocation Loc, StringRef Name,466MultiExprArg Args) {467468// Form a reference to the promise.469ExprResult PromiseRef = S.BuildDeclRefExpr(470Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);471if (PromiseRef.isInvalid())472return ExprError();473474return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);475}476477VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {478assert(isa<FunctionDecl>(CurContext) && "not in a function scope");479auto *FD = cast<FunctionDecl>(CurContext);480bool IsThisDependentType = [&] {481if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(FD))482return MD->isImplicitObjectMemberFunction() &&483MD->getThisType()->isDependentType();484return false;485}();486487QualType T = FD->getType()->isDependentType() || IsThisDependentType488? Context.DependentTy489: lookupPromiseType(*this, FD, Loc);490if (T.isNull())491return nullptr;492493auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),494&PP.getIdentifierTable().get("__promise"), T,495Context.getTrivialTypeSourceInfo(T, Loc), SC_None);496VD->setImplicit();497CheckVariableDeclarationType(VD);498if (VD->isInvalidDecl())499return nullptr;500501auto *ScopeInfo = getCurFunction();502503// Build a list of arguments, based on the coroutine function's arguments,504// that if present will be passed to the promise type's constructor.505llvm::SmallVector<Expr *, 4> CtorArgExprs;506507// Add implicit object parameter.508if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {509if (MD->isImplicitObjectMemberFunction() && !isLambdaCallOperator(MD)) {510ExprResult ThisExpr = ActOnCXXThis(Loc);511if (ThisExpr.isInvalid())512return nullptr;513ThisExpr = CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());514if (ThisExpr.isInvalid())515return nullptr;516CtorArgExprs.push_back(ThisExpr.get());517}518}519520// Add the coroutine function's parameters.521auto &Moves = ScopeInfo->CoroutineParameterMoves;522for (auto *PD : FD->parameters()) {523if (PD->getType()->isDependentType())524continue;525526auto RefExpr = ExprEmpty();527auto Move = Moves.find(PD);528assert(Move != Moves.end() &&529"Coroutine function parameter not inserted into move map");530// If a reference to the function parameter exists in the coroutine531// frame, use that reference.532auto *MoveDecl =533cast<VarDecl>(cast<DeclStmt>(Move->second)->getSingleDecl());534RefExpr =535BuildDeclRefExpr(MoveDecl, MoveDecl->getType().getNonReferenceType(),536ExprValueKind::VK_LValue, FD->getLocation());537if (RefExpr.isInvalid())538return nullptr;539CtorArgExprs.push_back(RefExpr.get());540}541542// If we have a non-zero number of constructor arguments, try to use them.543// Otherwise, fall back to the promise type's default constructor.544if (!CtorArgExprs.empty()) {545// Create an initialization sequence for the promise type using the546// constructor arguments, wrapped in a parenthesized list expression.547Expr *PLE = ParenListExpr::Create(Context, FD->getLocation(),548CtorArgExprs, FD->getLocation());549InitializedEntity Entity = InitializedEntity::InitializeVariable(VD);550InitializationKind Kind = InitializationKind::CreateForInit(551VD->getLocation(), /*DirectInit=*/true, PLE);552InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs,553/*TopLevelOfInitList=*/false,554/*TreatUnavailableAsInvalid=*/false);555556// [dcl.fct.def.coroutine]5.7557// promise-constructor-arguments is determined as follows: overload558// resolution is performed on a promise constructor call created by559// assembling an argument list q_1 ... q_n . If a viable constructor is560// found ([over.match.viable]), then promise-constructor-arguments is ( q_1561// , ..., q_n ), otherwise promise-constructor-arguments is empty.562if (InitSeq) {563ExprResult Result = InitSeq.Perform(*this, Entity, Kind, CtorArgExprs);564if (Result.isInvalid()) {565VD->setInvalidDecl();566} else if (Result.get()) {567VD->setInit(MaybeCreateExprWithCleanups(Result.get()));568VD->setInitStyle(VarDecl::CallInit);569CheckCompleteVariableDeclaration(VD);570}571} else572ActOnUninitializedDecl(VD);573} else574ActOnUninitializedDecl(VD);575576FD->addDecl(VD);577return VD;578}579580/// Check that this is a context in which a coroutine suspension can appear.581static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,582StringRef Keyword,583bool IsImplicit = false) {584if (!isValidCoroutineContext(S, Loc, Keyword))585return nullptr;586587assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");588589auto *ScopeInfo = S.getCurFunction();590assert(ScopeInfo && "missing function scope for function");591592if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)593ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);594595if (ScopeInfo->CoroutinePromise)596return ScopeInfo;597598if (!S.buildCoroutineParameterMoves(Loc))599return nullptr;600601ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);602if (!ScopeInfo->CoroutinePromise)603return nullptr;604605return ScopeInfo;606}607608/// Recursively check \p E and all its children to see if any call target609/// (including constructor call) is declared noexcept. Also any value returned610/// from the call has a noexcept destructor.611static void checkNoThrow(Sema &S, const Stmt *E,612llvm::SmallPtrSetImpl<const Decl *> &ThrowingDecls) {613auto checkDeclNoexcept = [&](const Decl *D, bool IsDtor = false) {614// In the case of dtor, the call to dtor is implicit and hence we should615// pass nullptr to canCalleeThrow.616if (Sema::canCalleeThrow(S, IsDtor ? nullptr : cast<Expr>(E), D)) {617if (const auto *FD = dyn_cast<FunctionDecl>(D)) {618// co_await promise.final_suspend() could end up calling619// __builtin_coro_resume for symmetric transfer if await_suspend()620// returns a handle. In that case, even __builtin_coro_resume is not621// declared as noexcept and may throw, it does not throw _into_ the622// coroutine that just suspended, but rather throws back out from623// whoever called coroutine_handle::resume(), hence we claim that624// logically it does not throw.625if (FD->getBuiltinID() == Builtin::BI__builtin_coro_resume)626return;627}628if (ThrowingDecls.empty()) {629// [dcl.fct.def.coroutine]p15630// The expression co_await promise.final_suspend() shall not be631// potentially-throwing ([except.spec]).632//633// First time seeing an error, emit the error message.634S.Diag(cast<FunctionDecl>(S.CurContext)->getLocation(),635diag::err_coroutine_promise_final_suspend_requires_nothrow);636}637ThrowingDecls.insert(D);638}639};640641if (auto *CE = dyn_cast<CXXConstructExpr>(E)) {642CXXConstructorDecl *Ctor = CE->getConstructor();643checkDeclNoexcept(Ctor);644// Check the corresponding destructor of the constructor.645checkDeclNoexcept(Ctor->getParent()->getDestructor(), /*IsDtor=*/true);646} else if (auto *CE = dyn_cast<CallExpr>(E)) {647if (CE->isTypeDependent())648return;649650checkDeclNoexcept(CE->getCalleeDecl());651QualType ReturnType = CE->getCallReturnType(S.getASTContext());652// Check the destructor of the call return type, if any.653if (ReturnType.isDestructedType() ==654QualType::DestructionKind::DK_cxx_destructor) {655const auto *T =656cast<RecordType>(ReturnType.getCanonicalType().getTypePtr());657checkDeclNoexcept(cast<CXXRecordDecl>(T->getDecl())->getDestructor(),658/*IsDtor=*/true);659}660} else661for (const auto *Child : E->children()) {662if (!Child)663continue;664checkNoThrow(S, Child, ThrowingDecls);665}666}667668bool Sema::checkFinalSuspendNoThrow(const Stmt *FinalSuspend) {669llvm::SmallPtrSet<const Decl *, 4> ThrowingDecls;670// We first collect all declarations that should not throw but not declared671// with noexcept. We then sort them based on the location before printing.672// This is to avoid emitting the same note multiple times on the same673// declaration, and also provide a deterministic order for the messages.674checkNoThrow(*this, FinalSuspend, ThrowingDecls);675auto SortedDecls = llvm::SmallVector<const Decl *, 4>{ThrowingDecls.begin(),676ThrowingDecls.end()};677sort(SortedDecls, [](const Decl *A, const Decl *B) {678return A->getEndLoc() < B->getEndLoc();679});680for (const auto *D : SortedDecls) {681Diag(D->getEndLoc(), diag::note_coroutine_function_declare_noexcept);682}683return ThrowingDecls.empty();684}685686bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc,687StringRef Keyword) {688// Ignore previous expr evaluation contexts.689EnterExpressionEvaluationContext PotentiallyEvaluated(690*this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);691if (!checkCoroutineContext(*this, KWLoc, Keyword))692return false;693auto *ScopeInfo = getCurFunction();694assert(ScopeInfo->CoroutinePromise);695696// If we have existing coroutine statements then we have already built697// the initial and final suspend points.698if (!ScopeInfo->NeedsCoroutineSuspends)699return true;700701ScopeInfo->setNeedsCoroutineSuspends(false);702703auto *Fn = cast<FunctionDecl>(CurContext);704SourceLocation Loc = Fn->getLocation();705// Build the initial suspend point706auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {707ExprResult Operand = buildPromiseCall(*this, ScopeInfo->CoroutinePromise,708Loc, Name, std::nullopt);709if (Operand.isInvalid())710return StmtError();711ExprResult Suspend =712buildOperatorCoawaitCall(*this, SC, Loc, Operand.get());713if (Suspend.isInvalid())714return StmtError();715Suspend = BuildResolvedCoawaitExpr(Loc, Operand.get(), Suspend.get(),716/*IsImplicit*/ true);717Suspend = ActOnFinishFullExpr(Suspend.get(), /*DiscardedValue*/ false);718if (Suspend.isInvalid()) {719Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)720<< ((Name == "initial_suspend") ? 0 : 1);721Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;722return StmtError();723}724return cast<Stmt>(Suspend.get());725};726727StmtResult InitSuspend = buildSuspends("initial_suspend");728if (InitSuspend.isInvalid())729return true;730731StmtResult FinalSuspend = buildSuspends("final_suspend");732if (FinalSuspend.isInvalid() || !checkFinalSuspendNoThrow(FinalSuspend.get()))733return true;734735ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());736737return true;738}739740// Recursively walks up the scope hierarchy until either a 'catch' or a function741// scope is found, whichever comes first.742static bool isWithinCatchScope(Scope *S) {743// 'co_await' and 'co_yield' keywords are disallowed within catch blocks, but744// lambdas that use 'co_await' are allowed. The loop below ends when a745// function scope is found in order to ensure the following behavior:746//747// void foo() { // <- function scope748// try { //749// co_await x; // <- 'co_await' is OK within a function scope750// } catch { // <- catch scope751// co_await x; // <- 'co_await' is not OK within a catch scope752// []() { // <- function scope753// co_await x; // <- 'co_await' is OK within a function scope754// }();755// }756// }757while (S && !S->isFunctionScope()) {758if (S->isCatchScope())759return true;760S = S->getParent();761}762return false;763}764765// [expr.await]p2, emphasis added: "An await-expression shall appear only in766// a *potentially evaluated* expression within the compound-statement of a767// function-body *outside of a handler* [...] A context within a function768// where an await-expression can appear is called a suspension context of the769// function."770static bool checkSuspensionContext(Sema &S, SourceLocation Loc,771StringRef Keyword) {772// First emphasis of [expr.await]p2: must be a potentially evaluated context.773// That is, 'co_await' and 'co_yield' cannot appear in subexpressions of774// \c sizeof.775if (S.isUnevaluatedContext()) {776S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;777return false;778}779780// Second emphasis of [expr.await]p2: must be outside of an exception handler.781if (isWithinCatchScope(S.getCurScope())) {782S.Diag(Loc, diag::err_coroutine_within_handler) << Keyword;783return false;784}785786return true;787}788789ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {790if (!checkSuspensionContext(*this, Loc, "co_await"))791return ExprError();792793if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) {794CorrectDelayedTyposInExpr(E);795return ExprError();796}797798if (E->hasPlaceholderType()) {799ExprResult R = CheckPlaceholderExpr(E);800if (R.isInvalid()) return ExprError();801E = R.get();802}803ExprResult Lookup = BuildOperatorCoawaitLookupExpr(S, Loc);804if (Lookup.isInvalid())805return ExprError();806return BuildUnresolvedCoawaitExpr(Loc, E,807cast<UnresolvedLookupExpr>(Lookup.get()));808}809810ExprResult Sema::BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc) {811DeclarationName OpName =812Context.DeclarationNames.getCXXOperatorName(OO_Coawait);813LookupResult Operators(*this, OpName, SourceLocation(),814Sema::LookupOperatorName);815LookupName(Operators, S);816817assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");818const auto &Functions = Operators.asUnresolvedSet();819Expr *CoawaitOp = UnresolvedLookupExpr::Create(820Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),821DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, Functions.begin(),822Functions.end(), /*KnownDependent=*/false,823/*KnownInstantiationDependent=*/false);824assert(CoawaitOp);825return CoawaitOp;826}827828// Attempts to resolve and build a CoawaitExpr from "raw" inputs, bailing out to829// DependentCoawaitExpr if needed.830ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *Operand,831UnresolvedLookupExpr *Lookup) {832auto *FSI = checkCoroutineContext(*this, Loc, "co_await");833if (!FSI)834return ExprError();835836if (Operand->hasPlaceholderType()) {837ExprResult R = CheckPlaceholderExpr(Operand);838if (R.isInvalid())839return ExprError();840Operand = R.get();841}842843auto *Promise = FSI->CoroutinePromise;844if (Promise->getType()->isDependentType()) {845Expr *Res = new (Context)846DependentCoawaitExpr(Loc, Context.DependentTy, Operand, Lookup);847return Res;848}849850auto *RD = Promise->getType()->getAsCXXRecordDecl();851auto *Transformed = Operand;852if (lookupMember(*this, "await_transform", RD, Loc)) {853ExprResult R =854buildPromiseCall(*this, Promise, Loc, "await_transform", Operand);855if (R.isInvalid()) {856Diag(Loc,857diag::note_coroutine_promise_implicit_await_transform_required_here)858<< Operand->getSourceRange();859return ExprError();860}861Transformed = R.get();862}863ExprResult Awaiter = BuildOperatorCoawaitCall(Loc, Transformed, Lookup);864if (Awaiter.isInvalid())865return ExprError();866867return BuildResolvedCoawaitExpr(Loc, Operand, Awaiter.get());868}869870ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *Operand,871Expr *Awaiter, bool IsImplicit) {872auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);873if (!Coroutine)874return ExprError();875876if (Awaiter->hasPlaceholderType()) {877ExprResult R = CheckPlaceholderExpr(Awaiter);878if (R.isInvalid()) return ExprError();879Awaiter = R.get();880}881882if (Awaiter->getType()->isDependentType()) {883Expr *Res = new (Context)884CoawaitExpr(Loc, Context.DependentTy, Operand, Awaiter, IsImplicit);885return Res;886}887888// If the expression is a temporary, materialize it as an lvalue so that we889// can use it multiple times.890if (Awaiter->isPRValue())891Awaiter = CreateMaterializeTemporaryExpr(Awaiter->getType(), Awaiter, true);892893// The location of the `co_await` token cannot be used when constructing894// the member call expressions since it's before the location of `Expr`, which895// is used as the start of the member call expression.896SourceLocation CallLoc = Awaiter->getExprLoc();897898// Build the await_ready, await_suspend, await_resume calls.899ReadySuspendResumeResult RSS =900buildCoawaitCalls(*this, Coroutine->CoroutinePromise, CallLoc, Awaiter);901if (RSS.IsInvalid)902return ExprError();903904Expr *Res = new (Context)905CoawaitExpr(Loc, Operand, Awaiter, RSS.Results[0], RSS.Results[1],906RSS.Results[2], RSS.OpaqueValue, IsImplicit);907908return Res;909}910911ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {912if (!checkSuspensionContext(*this, Loc, "co_yield"))913return ExprError();914915if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) {916CorrectDelayedTyposInExpr(E);917return ExprError();918}919920// Build yield_value call.921ExprResult Awaitable = buildPromiseCall(922*this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);923if (Awaitable.isInvalid())924return ExprError();925926// Build 'operator co_await' call.927Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());928if (Awaitable.isInvalid())929return ExprError();930931return BuildCoyieldExpr(Loc, Awaitable.get());932}933ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {934auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");935if (!Coroutine)936return ExprError();937938if (E->hasPlaceholderType()) {939ExprResult R = CheckPlaceholderExpr(E);940if (R.isInvalid()) return ExprError();941E = R.get();942}943944Expr *Operand = E;945946if (E->getType()->isDependentType()) {947Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, Operand, E);948return Res;949}950951// If the expression is a temporary, materialize it as an lvalue so that we952// can use it multiple times.953if (E->isPRValue())954E = CreateMaterializeTemporaryExpr(E->getType(), E, true);955956// Build the await_ready, await_suspend, await_resume calls.957ReadySuspendResumeResult RSS = buildCoawaitCalls(958*this, Coroutine->CoroutinePromise, Loc, E);959if (RSS.IsInvalid)960return ExprError();961962Expr *Res =963new (Context) CoyieldExpr(Loc, Operand, E, RSS.Results[0], RSS.Results[1],964RSS.Results[2], RSS.OpaqueValue);965966return Res;967}968969StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {970if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) {971CorrectDelayedTyposInExpr(E);972return StmtError();973}974return BuildCoreturnStmt(Loc, E);975}976977StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,978bool IsImplicit) {979auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);980if (!FSI)981return StmtError();982983if (E && E->hasPlaceholderType() &&984!E->hasPlaceholderType(BuiltinType::Overload)) {985ExprResult R = CheckPlaceholderExpr(E);986if (R.isInvalid()) return StmtError();987E = R.get();988}989990VarDecl *Promise = FSI->CoroutinePromise;991ExprResult PC;992if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {993getNamedReturnInfo(E, SimplerImplicitMoveMode::ForceOn);994PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);995} else {996E = MakeFullDiscardedValueExpr(E).get();997PC = buildPromiseCall(*this, Promise, Loc, "return_void", std::nullopt);998}999if (PC.isInvalid())1000return StmtError();10011002Expr *PCE = ActOnFinishFullExpr(PC.get(), /*DiscardedValue*/ false).get();10031004Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);1005return Res;1006}10071008/// Look up the std::nothrow object.1009static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {1010NamespaceDecl *Std = S.getStdNamespace();1011assert(Std && "Should already be diagnosed");10121013LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,1014Sema::LookupOrdinaryName);1015if (!S.LookupQualifiedName(Result, Std)) {1016// <coroutine> is not requred to include <new>, so we couldn't omit1017// the check here.1018S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);1019return nullptr;1020}10211022auto *VD = Result.getAsSingle<VarDecl>();1023if (!VD) {1024Result.suppressDiagnostics();1025// We found something weird. Complain about the first thing we found.1026NamedDecl *Found = *Result.begin();1027S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);1028return nullptr;1029}10301031ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);1032if (DR.isInvalid())1033return nullptr;10341035return DR.get();1036}10371038static TypeSourceInfo *getTypeSourceInfoForStdAlignValT(Sema &S,1039SourceLocation Loc) {1040EnumDecl *StdAlignValT = S.getStdAlignValT();1041QualType StdAlignValDecl = S.Context.getTypeDeclType(StdAlignValT);1042return S.Context.getTrivialTypeSourceInfo(StdAlignValDecl);1043}10441045// Find an appropriate delete for the promise.1046static bool findDeleteForPromise(Sema &S, SourceLocation Loc, QualType PromiseType,1047FunctionDecl *&OperatorDelete) {1048DeclarationName DeleteName =1049S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);10501051auto *PointeeRD = PromiseType->getAsCXXRecordDecl();1052assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");10531054const bool Overaligned = S.getLangOpts().CoroAlignedAllocation;10551056// [dcl.fct.def.coroutine]p121057// The deallocation function's name is looked up by searching for it in the1058// scope of the promise type. If nothing is found, a search is performed in1059// the global scope.1060if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete,1061/*Diagnose*/ true, /*WantSize*/ true,1062/*WantAligned*/ Overaligned))1063return false;10641065// [dcl.fct.def.coroutine]p121066// If both a usual deallocation function with only a pointer parameter and a1067// usual deallocation function with both a pointer parameter and a size1068// parameter are found, then the selected deallocation function shall be the1069// one with two parameters. Otherwise, the selected deallocation function1070// shall be the function with one parameter.1071if (!OperatorDelete) {1072// Look for a global declaration.1073// Coroutines can always provide their required size.1074const bool CanProvideSize = true;1075// Sema::FindUsualDeallocationFunction will try to find the one with two1076// parameters first. It will return the deallocation function with one1077// parameter if failed.1078OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,1079Overaligned, DeleteName);10801081if (!OperatorDelete)1082return false;1083}10841085S.MarkFunctionReferenced(Loc, OperatorDelete);1086return true;1087}108810891090void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {1091FunctionScopeInfo *Fn = getCurFunction();1092assert(Fn && Fn->isCoroutine() && "not a coroutine");1093if (!Body) {1094assert(FD->isInvalidDecl() &&1095"a null body is only allowed for invalid declarations");1096return;1097}1098// We have a function that uses coroutine keywords, but we failed to build1099// the promise type.1100if (!Fn->CoroutinePromise)1101return FD->setInvalidDecl();11021103if (isa<CoroutineBodyStmt>(Body)) {1104// Nothing todo. the body is already a transformed coroutine body statement.1105return;1106}11071108// The always_inline attribute doesn't reliably apply to a coroutine,1109// because the coroutine will be split into pieces and some pieces1110// might be called indirectly, as in a virtual call. Even the ramp1111// function cannot be inlined at -O0, due to pipeline ordering1112// problems (see https://llvm.org/PR53413). Tell the user about it.1113if (FD->hasAttr<AlwaysInlineAttr>())1114Diag(FD->getLocation(), diag::warn_always_inline_coroutine);11151116// The design of coroutines means we cannot allow use of VLAs within one, so1117// diagnose if we've seen a VLA in the body of this function.1118if (Fn->FirstVLALoc.isValid())1119Diag(Fn->FirstVLALoc, diag::err_vla_in_coroutine_unsupported);11201121// [stmt.return.coroutine]p1:1122// A coroutine shall not enclose a return statement ([stmt.return]).1123if (Fn->FirstReturnLoc.isValid()) {1124assert(Fn->FirstCoroutineStmtLoc.isValid() &&1125"first coroutine location not set");1126Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);1127Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)1128<< Fn->getFirstCoroutineStmtKeyword();1129}11301131// Coroutines will get splitted into pieces. The GNU address of label1132// extension wouldn't be meaningful in coroutines.1133for (AddrLabelExpr *ALE : Fn->AddrLabels)1134Diag(ALE->getBeginLoc(), diag::err_coro_invalid_addr_of_label);11351136CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);1137if (Builder.isInvalid() || !Builder.buildStatements())1138return FD->setInvalidDecl();11391140// Build body for the coroutine wrapper statement.1141Body = CoroutineBodyStmt::Create(Context, Builder);1142}11431144static CompoundStmt *buildCoroutineBody(Stmt *Body, ASTContext &Context) {1145if (auto *CS = dyn_cast<CompoundStmt>(Body))1146return CS;11471148// The body of the coroutine may be a try statement if it is in1149// 'function-try-block' syntax. Here we wrap it into a compound1150// statement for consistency.1151assert(isa<CXXTryStmt>(Body) && "Unimaged coroutine body type");1152return CompoundStmt::Create(Context, {Body}, FPOptionsOverride(),1153SourceLocation(), SourceLocation());1154}11551156CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,1157sema::FunctionScopeInfo &Fn,1158Stmt *Body)1159: S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),1160IsPromiseDependentType(1161!Fn.CoroutinePromise ||1162Fn.CoroutinePromise->getType()->isDependentType()) {1163this->Body = buildCoroutineBody(Body, S.getASTContext());11641165for (auto KV : Fn.CoroutineParameterMoves)1166this->ParamMovesVector.push_back(KV.second);1167this->ParamMoves = this->ParamMovesVector;11681169if (!IsPromiseDependentType) {1170PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();1171assert(PromiseRecordDecl && "Type should have already been checked");1172}1173this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();1174}11751176bool CoroutineStmtBuilder::buildStatements() {1177assert(this->IsValid && "coroutine already invalid");1178this->IsValid = makeReturnObject();1179if (this->IsValid && !IsPromiseDependentType)1180buildDependentStatements();1181return this->IsValid;1182}11831184bool CoroutineStmtBuilder::buildDependentStatements() {1185assert(this->IsValid && "coroutine already invalid");1186assert(!this->IsPromiseDependentType &&1187"coroutine cannot have a dependent promise type");1188this->IsValid = makeOnException() && makeOnFallthrough() &&1189makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&1190makeNewAndDeleteExpr();1191return this->IsValid;1192}11931194bool CoroutineStmtBuilder::makePromiseStmt() {1195// Form a declaration statement for the promise declaration, so that AST1196// visitors can more easily find it.1197StmtResult PromiseStmt =1198S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);1199if (PromiseStmt.isInvalid())1200return false;12011202this->Promise = PromiseStmt.get();1203return true;1204}12051206bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {1207if (Fn.hasInvalidCoroutineSuspends())1208return false;1209this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);1210this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);1211return true;1212}12131214static bool diagReturnOnAllocFailure(Sema &S, Expr *E,1215CXXRecordDecl *PromiseRecordDecl,1216FunctionScopeInfo &Fn) {1217auto Loc = E->getExprLoc();1218if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {1219auto *Decl = DeclRef->getDecl();1220if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {1221if (Method->isStatic())1222return true;1223else1224Loc = Decl->getLocation();1225}1226}12271228S.Diag(1229Loc,1230diag::err_coroutine_promise_get_return_object_on_allocation_failure)1231<< PromiseRecordDecl;1232S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)1233<< Fn.getFirstCoroutineStmtKeyword();1234return false;1235}12361237bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {1238assert(!IsPromiseDependentType &&1239"cannot make statement while the promise type is dependent");12401241// [dcl.fct.def.coroutine]p101242// If a search for the name get_return_object_on_allocation_failure in1243// the scope of the promise type ([class.member.lookup]) finds any1244// declarations, then the result of a call to an allocation function used to1245// obtain storage for the coroutine state is assumed to return nullptr if it1246// fails to obtain storage, ... If the allocation function returns nullptr,1247// ... and the return value is obtained by a call to1248// T::get_return_object_on_allocation_failure(), where T is the1249// promise type.1250DeclarationName DN =1251S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");1252LookupResult Found(S, DN, Loc, Sema::LookupMemberName);1253if (!S.LookupQualifiedName(Found, PromiseRecordDecl))1254return true;12551256CXXScopeSpec SS;1257ExprResult DeclNameExpr =1258S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);1259if (DeclNameExpr.isInvalid())1260return false;12611262if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))1263return false;12641265ExprResult ReturnObjectOnAllocationFailure =1266S.BuildCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);1267if (ReturnObjectOnAllocationFailure.isInvalid())1268return false;12691270StmtResult ReturnStmt =1271S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());1272if (ReturnStmt.isInvalid()) {1273S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)1274<< DN;1275S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)1276<< Fn.getFirstCoroutineStmtKeyword();1277return false;1278}12791280this->ReturnStmtOnAllocFailure = ReturnStmt.get();1281return true;1282}12831284// Collect placement arguments for allocation function of coroutine FD.1285// Return true if we collect placement arguments succesfully. Return false,1286// otherwise.1287static bool collectPlacementArgs(Sema &S, FunctionDecl &FD, SourceLocation Loc,1288SmallVectorImpl<Expr *> &PlacementArgs) {1289if (auto *MD = dyn_cast<CXXMethodDecl>(&FD)) {1290if (MD->isImplicitObjectMemberFunction() && !isLambdaCallOperator(MD)) {1291ExprResult ThisExpr = S.ActOnCXXThis(Loc);1292if (ThisExpr.isInvalid())1293return false;1294ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());1295if (ThisExpr.isInvalid())1296return false;1297PlacementArgs.push_back(ThisExpr.get());1298}1299}13001301for (auto *PD : FD.parameters()) {1302if (PD->getType()->isDependentType())1303continue;13041305// Build a reference to the parameter.1306auto PDLoc = PD->getLocation();1307ExprResult PDRefExpr =1308S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),1309ExprValueKind::VK_LValue, PDLoc);1310if (PDRefExpr.isInvalid())1311return false;13121313PlacementArgs.push_back(PDRefExpr.get());1314}13151316return true;1317}13181319bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {1320// Form and check allocation and deallocation calls.1321assert(!IsPromiseDependentType &&1322"cannot make statement while the promise type is dependent");1323QualType PromiseType = Fn.CoroutinePromise->getType();13241325if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))1326return false;13271328const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;13291330// According to [dcl.fct.def.coroutine]p9, Lookup allocation functions using a1331// parameter list composed of the requested size of the coroutine state being1332// allocated, followed by the coroutine function's arguments. If a matching1333// allocation function exists, use it. Otherwise, use an allocation function1334// that just takes the requested size.1335//1336// [dcl.fct.def.coroutine]p91337// An implementation may need to allocate additional storage for a1338// coroutine.1339// This storage is known as the coroutine state and is obtained by calling a1340// non-array allocation function ([basic.stc.dynamic.allocation]). The1341// allocation function's name is looked up by searching for it in the scope of1342// the promise type.1343// - If any declarations are found, overload resolution is performed on a1344// function call created by assembling an argument list. The first argument is1345// the amount of space requested, and has type std::size_t. The1346// lvalues p1 ... pn are the succeeding arguments.1347//1348// ...where "p1 ... pn" are defined earlier as:1349//1350// [dcl.fct.def.coroutine]p31351// The promise type of a coroutine is `std::coroutine_traits<R, P1, ...,1352// Pn>`1353// , where R is the return type of the function, and `P1, ..., Pn` are the1354// sequence of types of the non-object function parameters, preceded by the1355// type of the object parameter ([dcl.fct]) if the coroutine is a non-static1356// member function. [dcl.fct.def.coroutine]p4 In the following, p_i is an1357// lvalue of type P_i, where p1 denotes the object parameter and p_i+1 denotes1358// the i-th non-object function parameter for a non-static member function,1359// and p_i denotes the i-th function parameter otherwise. For a non-static1360// member function, q_1 is an lvalue that denotes *this; any other q_i is an1361// lvalue that denotes the parameter copy corresponding to p_i.13621363FunctionDecl *OperatorNew = nullptr;1364SmallVector<Expr *, 1> PlacementArgs;13651366const bool PromiseContainsNew = [this, &PromiseType]() -> bool {1367DeclarationName NewName =1368S.getASTContext().DeclarationNames.getCXXOperatorName(OO_New);1369LookupResult R(S, NewName, Loc, Sema::LookupOrdinaryName);13701371if (PromiseType->isRecordType())1372S.LookupQualifiedName(R, PromiseType->getAsCXXRecordDecl());13731374return !R.empty() && !R.isAmbiguous();1375}();13761377// Helper function to indicate whether the last lookup found the aligned1378// allocation function.1379bool PassAlignment = S.getLangOpts().CoroAlignedAllocation;1380auto LookupAllocationFunction = [&](Sema::AllocationFunctionScope NewScope =1381Sema::AFS_Both,1382bool WithoutPlacementArgs = false,1383bool ForceNonAligned = false) {1384// [dcl.fct.def.coroutine]p91385// The allocation function's name is looked up by searching for it in the1386// scope of the promise type.1387// - If any declarations are found, ...1388// - If no declarations are found in the scope of the promise type, a search1389// is performed in the global scope.1390if (NewScope == Sema::AFS_Both)1391NewScope = PromiseContainsNew ? Sema::AFS_Class : Sema::AFS_Global;13921393PassAlignment = !ForceNonAligned && S.getLangOpts().CoroAlignedAllocation;1394FunctionDecl *UnusedResult = nullptr;1395S.FindAllocationFunctions(Loc, SourceRange(), NewScope,1396/*DeleteScope*/ Sema::AFS_Both, PromiseType,1397/*isArray*/ false, PassAlignment,1398WithoutPlacementArgs ? MultiExprArg{}1399: PlacementArgs,1400OperatorNew, UnusedResult, /*Diagnose*/ false);1401};14021403// We don't expect to call to global operator new with (size, p0, …, pn).1404// So if we choose to lookup the allocation function in global scope, we1405// shouldn't lookup placement arguments.1406if (PromiseContainsNew && !collectPlacementArgs(S, FD, Loc, PlacementArgs))1407return false;14081409LookupAllocationFunction();14101411if (PromiseContainsNew && !PlacementArgs.empty()) {1412// [dcl.fct.def.coroutine]p91413// If no viable function is found ([over.match.viable]), overload1414// resolution1415// is performed again on a function call created by passing just the amount1416// of space required as an argument of type std::size_t.1417//1418// Proposed Change of [dcl.fct.def.coroutine]p9 in P2014R0:1419// Otherwise, overload resolution is performed again on a function call1420// created1421// by passing the amount of space requested as an argument of type1422// std::size_t as the first argument, and the requested alignment as1423// an argument of type std:align_val_t as the second argument.1424if (!OperatorNew ||1425(S.getLangOpts().CoroAlignedAllocation && !PassAlignment))1426LookupAllocationFunction(/*NewScope*/ Sema::AFS_Class,1427/*WithoutPlacementArgs*/ true);1428}14291430// Proposed Change of [dcl.fct.def.coroutine]p12 in P2014R0:1431// Otherwise, overload resolution is performed again on a function call1432// created1433// by passing the amount of space requested as an argument of type1434// std::size_t as the first argument, and the lvalues p1 ... pn as the1435// succeeding arguments. Otherwise, overload resolution is performed again1436// on a function call created by passing just the amount of space required as1437// an argument of type std::size_t.1438//1439// So within the proposed change in P2014RO, the priority order of aligned1440// allocation functions wiht promise_type is:1441//1442// void* operator new( std::size_t, std::align_val_t, placement_args... );1443// void* operator new( std::size_t, std::align_val_t);1444// void* operator new( std::size_t, placement_args... );1445// void* operator new( std::size_t);14461447// Helper variable to emit warnings.1448bool FoundNonAlignedInPromise = false;1449if (PromiseContainsNew && S.getLangOpts().CoroAlignedAllocation)1450if (!OperatorNew || !PassAlignment) {1451FoundNonAlignedInPromise = OperatorNew;14521453LookupAllocationFunction(/*NewScope*/ Sema::AFS_Class,1454/*WithoutPlacementArgs*/ false,1455/*ForceNonAligned*/ true);14561457if (!OperatorNew && !PlacementArgs.empty())1458LookupAllocationFunction(/*NewScope*/ Sema::AFS_Class,1459/*WithoutPlacementArgs*/ true,1460/*ForceNonAligned*/ true);1461}14621463bool IsGlobalOverload =1464OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());1465// If we didn't find a class-local new declaration and non-throwing new1466// was is required then we need to lookup the non-throwing global operator1467// instead.1468if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {1469auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);1470if (!StdNoThrow)1471return false;1472PlacementArgs = {StdNoThrow};1473OperatorNew = nullptr;1474LookupAllocationFunction(Sema::AFS_Global);1475}14761477// If we found a non-aligned allocation function in the promise_type,1478// it indicates the user forgot to update the allocation function. Let's emit1479// a warning here.1480if (FoundNonAlignedInPromise) {1481S.Diag(OperatorNew->getLocation(),1482diag::warn_non_aligned_allocation_function)1483<< &FD;1484}14851486if (!OperatorNew) {1487if (PromiseContainsNew)1488S.Diag(Loc, diag::err_coroutine_unusable_new) << PromiseType << &FD;1489else if (RequiresNoThrowAlloc)1490S.Diag(Loc, diag::err_coroutine_unfound_nothrow_new)1491<< &FD << S.getLangOpts().CoroAlignedAllocation;14921493return false;1494}14951496if (RequiresNoThrowAlloc) {1497const auto *FT = OperatorNew->getType()->castAs<FunctionProtoType>();1498if (!FT->isNothrow(/*ResultIfDependent*/ false)) {1499S.Diag(OperatorNew->getLocation(),1500diag::err_coroutine_promise_new_requires_nothrow)1501<< OperatorNew;1502S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)1503<< OperatorNew;1504return false;1505}1506}15071508FunctionDecl *OperatorDelete = nullptr;1509if (!findDeleteForPromise(S, Loc, PromiseType, OperatorDelete)) {1510// FIXME: We should add an error here. According to:1511// [dcl.fct.def.coroutine]p121512// If no usual deallocation function is found, the program is ill-formed.1513return false;1514}15151516Expr *FramePtr =1517S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_frame, {});15181519Expr *FrameSize =1520S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_size, {});15211522Expr *FrameAlignment = nullptr;15231524if (S.getLangOpts().CoroAlignedAllocation) {1525FrameAlignment =1526S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_align, {});15271528TypeSourceInfo *AlignValTy = getTypeSourceInfoForStdAlignValT(S, Loc);1529if (!AlignValTy)1530return false;15311532FrameAlignment = S.BuildCXXNamedCast(Loc, tok::kw_static_cast, AlignValTy,1533FrameAlignment, SourceRange(Loc, Loc),1534SourceRange(Loc, Loc))1535.get();1536}15371538// Make new call.1539ExprResult NewRef =1540S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);1541if (NewRef.isInvalid())1542return false;15431544SmallVector<Expr *, 2> NewArgs(1, FrameSize);1545if (S.getLangOpts().CoroAlignedAllocation && PassAlignment)1546NewArgs.push_back(FrameAlignment);15471548if (OperatorNew->getNumParams() > NewArgs.size())1549llvm::append_range(NewArgs, PlacementArgs);15501551ExprResult NewExpr =1552S.BuildCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);1553NewExpr = S.ActOnFinishFullExpr(NewExpr.get(), /*DiscardedValue*/ false);1554if (NewExpr.isInvalid())1555return false;15561557// Make delete call.15581559QualType OpDeleteQualType = OperatorDelete->getType();15601561ExprResult DeleteRef =1562S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);1563if (DeleteRef.isInvalid())1564return false;15651566Expr *CoroFree =1567S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_free, {FramePtr});15681569SmallVector<Expr *, 2> DeleteArgs{CoroFree};15701571// [dcl.fct.def.coroutine]p121572// The selected deallocation function shall be called with the address of1573// the block of storage to be reclaimed as its first argument. If a1574// deallocation function with a parameter of type std::size_t is1575// used, the size of the block is passed as the corresponding argument.1576const auto *OpDeleteType =1577OpDeleteQualType.getTypePtr()->castAs<FunctionProtoType>();1578if (OpDeleteType->getNumParams() > DeleteArgs.size() &&1579S.getASTContext().hasSameUnqualifiedType(1580OpDeleteType->getParamType(DeleteArgs.size()), FrameSize->getType()))1581DeleteArgs.push_back(FrameSize);15821583// Proposed Change of [dcl.fct.def.coroutine]p12 in P2014R0:1584// If deallocation function lookup finds a usual deallocation function with1585// a pointer parameter, size parameter and alignment parameter then this1586// will be the selected deallocation function, otherwise if lookup finds a1587// usual deallocation function with both a pointer parameter and a size1588// parameter, then this will be the selected deallocation function.1589// Otherwise, if lookup finds a usual deallocation function with only a1590// pointer parameter, then this will be the selected deallocation1591// function.1592//1593// So we are not forced to pass alignment to the deallocation function.1594if (S.getLangOpts().CoroAlignedAllocation &&1595OpDeleteType->getNumParams() > DeleteArgs.size() &&1596S.getASTContext().hasSameUnqualifiedType(1597OpDeleteType->getParamType(DeleteArgs.size()),1598FrameAlignment->getType()))1599DeleteArgs.push_back(FrameAlignment);16001601ExprResult DeleteExpr =1602S.BuildCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);1603DeleteExpr =1604S.ActOnFinishFullExpr(DeleteExpr.get(), /*DiscardedValue*/ false);1605if (DeleteExpr.isInvalid())1606return false;16071608this->Allocate = NewExpr.get();1609this->Deallocate = DeleteExpr.get();16101611return true;1612}16131614bool CoroutineStmtBuilder::makeOnFallthrough() {1615assert(!IsPromiseDependentType &&1616"cannot make statement while the promise type is dependent");16171618// [dcl.fct.def.coroutine]/p61619// If searches for the names return_void and return_value in the scope of1620// the promise type each find any declarations, the program is ill-formed.1621// [Note 1: If return_void is found, flowing off the end of a coroutine is1622// equivalent to a co_return with no operand. Otherwise, flowing off the end1623// of a coroutine results in undefined behavior ([stmt.return.coroutine]). —1624// end note]1625bool HasRVoid, HasRValue;1626LookupResult LRVoid =1627lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);1628LookupResult LRValue =1629lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);16301631StmtResult Fallthrough;1632if (HasRVoid && HasRValue) {1633// FIXME Improve this diagnostic1634S.Diag(FD.getLocation(),1635diag::err_coroutine_promise_incompatible_return_functions)1636<< PromiseRecordDecl;1637S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),1638diag::note_member_first_declared_here)1639<< LRVoid.getLookupName();1640S.Diag(LRValue.getRepresentativeDecl()->getLocation(),1641diag::note_member_first_declared_here)1642<< LRValue.getLookupName();1643return false;1644} else if (!HasRVoid && !HasRValue) {1645// We need to set 'Fallthrough'. Otherwise the other analysis part might1646// think the coroutine has defined a return_value method. So it might emit1647// **false** positive warning. e.g.,1648//1649// promise_without_return_func foo() {1650// co_await something();1651// }1652//1653// Then AnalysisBasedWarning would emit a warning about `foo()` lacking a1654// co_return statements, which isn't correct.1655Fallthrough = S.ActOnNullStmt(PromiseRecordDecl->getLocation());1656if (Fallthrough.isInvalid())1657return false;1658} else if (HasRVoid) {1659Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,1660/*IsImplicit=*/true);1661Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());1662if (Fallthrough.isInvalid())1663return false;1664}16651666this->OnFallthrough = Fallthrough.get();1667return true;1668}16691670bool CoroutineStmtBuilder::makeOnException() {1671// Try to form 'p.unhandled_exception();'1672assert(!IsPromiseDependentType &&1673"cannot make statement while the promise type is dependent");16741675const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;16761677if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {1678auto DiagID =1679RequireUnhandledException1680? diag::err_coroutine_promise_unhandled_exception_required1681: diag::1682warn_coroutine_promise_unhandled_exception_required_with_exceptions;1683S.Diag(Loc, DiagID) << PromiseRecordDecl;1684S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)1685<< PromiseRecordDecl;1686return !RequireUnhandledException;1687}16881689// If exceptions are disabled, don't try to build OnException.1690if (!S.getLangOpts().CXXExceptions)1691return true;16921693ExprResult UnhandledException = buildPromiseCall(1694S, Fn.CoroutinePromise, Loc, "unhandled_exception", std::nullopt);1695UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc,1696/*DiscardedValue*/ false);1697if (UnhandledException.isInvalid())1698return false;16991700// Since the body of the coroutine will be wrapped in try-catch, it will1701// be incompatible with SEH __try if present in a function.1702if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {1703S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);1704S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)1705<< Fn.getFirstCoroutineStmtKeyword();1706return false;1707}17081709this->OnException = UnhandledException.get();1710return true;1711}17121713bool CoroutineStmtBuilder::makeReturnObject() {1714// [dcl.fct.def.coroutine]p71715// The expression promise.get_return_object() is used to initialize the1716// returned reference or prvalue result object of a call to a coroutine.1717ExprResult ReturnObject = buildPromiseCall(S, Fn.CoroutinePromise, Loc,1718"get_return_object", std::nullopt);1719if (ReturnObject.isInvalid())1720return false;17211722this->ReturnValue = ReturnObject.get();1723return true;1724}17251726static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {1727if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {1728auto *MethodDecl = MbrRef->getMethodDecl();1729S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)1730<< MethodDecl;1731}1732S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)1733<< Fn.getFirstCoroutineStmtKeyword();1734}17351736bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {1737assert(!IsPromiseDependentType &&1738"cannot make statement while the promise type is dependent");1739assert(this->ReturnValue && "ReturnValue must be already formed");17401741QualType const GroType = this->ReturnValue->getType();1742assert(!GroType->isDependentType() &&1743"get_return_object type must no longer be dependent");17441745QualType const FnRetType = FD.getReturnType();1746assert(!FnRetType->isDependentType() &&1747"get_return_object type must no longer be dependent");17481749// The call to get_return_object is sequenced before the call to1750// initial_suspend and is invoked at most once, but there are caveats1751// regarding on whether the prvalue result object may be initialized1752// directly/eager or delayed, depending on the types involved.1753//1754// More info at https://github.com/cplusplus/papers/issues/14141755bool GroMatchesRetType = S.getASTContext().hasSameType(GroType, FnRetType);17561757if (FnRetType->isVoidType()) {1758ExprResult Res =1759S.ActOnFinishFullExpr(this->ReturnValue, Loc, /*DiscardedValue*/ false);1760if (Res.isInvalid())1761return false;17621763if (!GroMatchesRetType)1764this->ResultDecl = Res.get();1765return true;1766}17671768if (GroType->isVoidType()) {1769// Trigger a nice error message.1770InitializedEntity Entity =1771InitializedEntity::InitializeResult(Loc, FnRetType);1772S.PerformCopyInitialization(Entity, SourceLocation(), ReturnValue);1773noteMemberDeclaredHere(S, ReturnValue, Fn);1774return false;1775}17761777StmtResult ReturnStmt;1778clang::VarDecl *GroDecl = nullptr;1779if (GroMatchesRetType) {1780ReturnStmt = S.BuildReturnStmt(Loc, ReturnValue);1781} else {1782GroDecl = VarDecl::Create(1783S.Context, &FD, FD.getLocation(), FD.getLocation(),1784&S.PP.getIdentifierTable().get("__coro_gro"), GroType,1785S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);1786GroDecl->setImplicit();17871788S.CheckVariableDeclarationType(GroDecl);1789if (GroDecl->isInvalidDecl())1790return false;17911792InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);1793ExprResult Res =1794S.PerformCopyInitialization(Entity, SourceLocation(), ReturnValue);1795if (Res.isInvalid())1796return false;17971798Res = S.ActOnFinishFullExpr(Res.get(), /*DiscardedValue*/ false);1799if (Res.isInvalid())1800return false;18011802S.AddInitializerToDecl(GroDecl, Res.get(),1803/*DirectInit=*/false);18041805S.FinalizeDeclaration(GroDecl);18061807// Form a declaration statement for the return declaration, so that AST1808// visitors can more easily find it.1809StmtResult GroDeclStmt =1810S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);1811if (GroDeclStmt.isInvalid())1812return false;18131814this->ResultDecl = GroDeclStmt.get();18151816ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);1817if (declRef.isInvalid())1818return false;18191820ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());1821}18221823if (ReturnStmt.isInvalid()) {1824noteMemberDeclaredHere(S, ReturnValue, Fn);1825return false;1826}18271828if (!GroMatchesRetType &&1829cast<clang::ReturnStmt>(ReturnStmt.get())->getNRVOCandidate() == GroDecl)1830GroDecl->setNRVOVariable(true);18311832this->ReturnStmt = ReturnStmt.get();1833return true;1834}18351836// Create a static_cast\<T&&>(expr).1837static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {1838if (T.isNull())1839T = E->getType();1840QualType TargetType = S.BuildReferenceType(1841T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());1842SourceLocation ExprLoc = E->getBeginLoc();1843TypeSourceInfo *TargetLoc =1844S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);18451846return S1847.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,1848SourceRange(ExprLoc, ExprLoc), E->getSourceRange())1849.get();1850}18511852/// Build a variable declaration for move parameter.1853static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,1854IdentifierInfo *II) {1855TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);1856VarDecl *Decl = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type,1857TInfo, SC_None);1858Decl->setImplicit();1859return Decl;1860}18611862// Build statements that move coroutine function parameters to the coroutine1863// frame, and store them on the function scope info.1864bool Sema::buildCoroutineParameterMoves(SourceLocation Loc) {1865assert(isa<FunctionDecl>(CurContext) && "not in a function scope");1866auto *FD = cast<FunctionDecl>(CurContext);18671868auto *ScopeInfo = getCurFunction();1869if (!ScopeInfo->CoroutineParameterMoves.empty())1870return false;18711872// [dcl.fct.def.coroutine]p131873// When a coroutine is invoked, after initializing its parameters1874// ([expr.call]), a copy is created for each coroutine parameter. For a1875// parameter of type cv T, the copy is a variable of type cv T with1876// automatic storage duration that is direct-initialized from an xvalue of1877// type T referring to the parameter.1878for (auto *PD : FD->parameters()) {1879if (PD->getType()->isDependentType())1880continue;18811882// Preserve the referenced state for unused parameter diagnostics.1883bool DeclReferenced = PD->isReferenced();18841885ExprResult PDRefExpr =1886BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),1887ExprValueKind::VK_LValue, Loc); // FIXME: scope?18881889PD->setReferenced(DeclReferenced);18901891if (PDRefExpr.isInvalid())1892return false;18931894Expr *CExpr = nullptr;1895if (PD->getType()->getAsCXXRecordDecl() ||1896PD->getType()->isRValueReferenceType())1897CExpr = castForMoving(*this, PDRefExpr.get());1898else1899CExpr = PDRefExpr.get();1900// [dcl.fct.def.coroutine]p131901// The initialization and destruction of each parameter copy occurs in the1902// context of the called coroutine.1903auto *D = buildVarDecl(*this, Loc, PD->getType(), PD->getIdentifier());1904AddInitializerToDecl(D, CExpr, /*DirectInit=*/true);19051906// Convert decl to a statement.1907StmtResult Stmt = ActOnDeclStmt(ConvertDeclToDeclGroup(D), Loc, Loc);1908if (Stmt.isInvalid())1909return false;19101911ScopeInfo->CoroutineParameterMoves.insert(std::make_pair(PD, Stmt.get()));1912}1913return true;1914}19151916StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {1917CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);1918if (!Res)1919return StmtError();1920return Res;1921}19221923ClassTemplateDecl *Sema::lookupCoroutineTraits(SourceLocation KwLoc,1924SourceLocation FuncLoc) {1925if (StdCoroutineTraitsCache)1926return StdCoroutineTraitsCache;19271928IdentifierInfo const &TraitIdent =1929PP.getIdentifierTable().get("coroutine_traits");19301931NamespaceDecl *StdSpace = getStdNamespace();1932LookupResult Result(*this, &TraitIdent, FuncLoc, LookupOrdinaryName);1933bool Found = StdSpace && LookupQualifiedName(Result, StdSpace);19341935if (!Found) {1936// The goggles, we found nothing!1937Diag(KwLoc, diag::err_implied_coroutine_type_not_found)1938<< "std::coroutine_traits";1939return nullptr;1940}19411942// coroutine_traits is required to be a class template.1943StdCoroutineTraitsCache = Result.getAsSingle<ClassTemplateDecl>();1944if (!StdCoroutineTraitsCache) {1945Result.suppressDiagnostics();1946NamedDecl *Found = *Result.begin();1947Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);1948return nullptr;1949}19501951return StdCoroutineTraitsCache;1952}195319541955