#include "CoroutineStmtBuilder.h"
#include "clang/AST/ASTLambda.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/StmtCXX.h"
#include "clang/Basic/Builtins.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/EnterExpressionEvaluationContext.h"
#include "clang/Sema/Initialization.h"
#include "clang/Sema/Overload.h"
#include "clang/Sema/ScopeInfo.h"
#include "clang/Sema/SemaInternal.h"
#include "llvm/ADT/SmallSet.h"
using namespace clang;
using namespace sema;
static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
SourceLocation Loc, bool &Res) {
DeclarationName DN = S.PP.getIdentifierInfo(Name);
LookupResult LR(S, DN, Loc, Sema::LookupMemberName);
LR.suppressDiagnostics();
Res = S.LookupQualifiedName(LR, RD);
return LR;
}
static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
SourceLocation Loc) {
bool Res;
lookupMember(S, Name, RD, Loc, Res);
return Res;
}
static QualType lookupPromiseType(Sema &S, const FunctionDecl *FD,
SourceLocation KwLoc) {
const FunctionProtoType *FnType = FD->getType()->castAs<FunctionProtoType>();
const SourceLocation FuncLoc = FD->getLocation();
ClassTemplateDecl *CoroTraits =
S.lookupCoroutineTraits(KwLoc, FuncLoc);
if (!CoroTraits)
return QualType();
TemplateArgumentListInfo Args(KwLoc, KwLoc);
auto AddArg = [&](QualType T) {
Args.addArgument(TemplateArgumentLoc(
TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));
};
AddArg(FnType->getReturnType());
if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
if (MD->isImplicitObjectMemberFunction()) {
QualType T = MD->getFunctionObjectParameterType();
T = FnType->getRefQualifier() == RQ_RValue
? S.Context.getRValueReferenceType(T)
: S.Context.getLValueReferenceType(T, true);
AddArg(T);
}
}
for (QualType T : FnType->getParamTypes())
AddArg(T);
QualType CoroTrait =
S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
if (CoroTrait.isNull())
return QualType();
if (S.RequireCompleteType(KwLoc, CoroTrait,
diag::err_coroutine_type_missing_specialization))
return QualType();
auto *RD = CoroTrait->getAsCXXRecordDecl();
assert(RD && "specialization of class template is not a class?");
LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
Sema::LookupOrdinaryName);
S.LookupQualifiedName(R, RD);
auto *Promise = R.getAsSingle<TypeDecl>();
if (!Promise) {
S.Diag(FuncLoc,
diag::err_implied_std_coroutine_traits_promise_type_not_found)
<< RD;
return QualType();
}
QualType PromiseType = S.Context.getTypeDeclType(Promise);
auto buildElaboratedType = [&]() {
auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, S.getStdNamespace());
NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
CoroTrait.getTypePtr());
return S.Context.getElaboratedType(ElaboratedTypeKeyword::None, NNS,
PromiseType);
};
if (!PromiseType->getAsCXXRecordDecl()) {
S.Diag(FuncLoc,
diag::err_implied_std_coroutine_traits_promise_type_not_class)
<< buildElaboratedType();
return QualType();
}
if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
diag::err_coroutine_promise_type_incomplete))
return QualType();
return PromiseType;
}
static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
SourceLocation Loc) {
if (PromiseType.isNull())
return QualType();
NamespaceDecl *CoroNamespace = S.getStdNamespace();
assert(CoroNamespace && "Should already be diagnosed");
LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
Loc, Sema::LookupOrdinaryName);
if (!S.LookupQualifiedName(Result, CoroNamespace)) {
S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
<< "std::coroutine_handle";
return QualType();
}
ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
if (!CoroHandle) {
Result.suppressDiagnostics();
NamedDecl *Found = *Result.begin();
S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
return QualType();
}
TemplateArgumentListInfo Args(Loc, Loc);
Args.addArgument(TemplateArgumentLoc(
TemplateArgument(PromiseType),
S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
QualType CoroHandleType =
S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
if (CoroHandleType.isNull())
return QualType();
if (S.RequireCompleteType(Loc, CoroHandleType,
diag::err_coroutine_type_missing_specialization))
return QualType();
return CoroHandleType;
}
static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
StringRef Keyword) {
auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
if (!FD) {
S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
? diag::err_coroutine_objc_method
: diag::err_coroutine_outside_function) << Keyword;
return false;
}
enum InvalidFuncDiag {
DiagCtor = 0,
DiagDtor,
DiagMain,
DiagConstexpr,
DiagAutoRet,
DiagVarargs,
DiagConsteval,
};
bool Diagnosed = false;
auto DiagInvalid = [&](InvalidFuncDiag ID) {
S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
Diagnosed = true;
return false;
};
auto *MD = dyn_cast<CXXMethodDecl>(FD);
if (MD && isa<CXXConstructorDecl>(MD))
return DiagInvalid(DiagCtor);
else if (MD && isa<CXXDestructorDecl>(MD))
return DiagInvalid(DiagDtor);
else if (FD->isMain())
return DiagInvalid(DiagMain);
if (FD->isConstexpr())
DiagInvalid(FD->isConsteval() ? DiagConsteval : DiagConstexpr);
if (FD->getReturnType()->isUndeducedType())
DiagInvalid(DiagAutoRet);
if (FD->isVariadic())
DiagInvalid(DiagVarargs);
return !Diagnosed;
}
ExprResult Sema::BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E,
UnresolvedLookupExpr *Lookup) {
UnresolvedSet<16> Functions;
Functions.append(Lookup->decls_begin(), Lookup->decls_end());
return CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
}
static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
SourceLocation Loc, Expr *E) {
ExprResult R = SemaRef.BuildOperatorCoawaitLookupExpr(S, Loc);
if (R.isInvalid())
return ExprError();
return SemaRef.BuildOperatorCoawaitCall(Loc, E,
cast<UnresolvedLookupExpr>(R.get()));
}
static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
SourceLocation Loc) {
QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
if (CoroHandleType.isNull())
return ExprError();
DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
Sema::LookupOrdinaryName);
if (!S.LookupQualifiedName(Found, LookupCtx)) {
S.Diag(Loc, diag::err_coroutine_handle_missing_member)
<< "from_address";
return ExprError();
}
Expr *FramePtr =
S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_frame, {});
CXXScopeSpec SS;
ExprResult FromAddr =
S.BuildDeclarationNameExpr(SS, Found, false);
if (FromAddr.isInvalid())
return ExprError();
return S.BuildCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
}
struct ReadySuspendResumeResult {
enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume };
Expr *Results[3];
OpaqueValueExpr *OpaqueValue;
bool IsInvalid;
};
static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
StringRef Name, MultiExprArg Args) {
DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
CXXScopeSpec SS;
ExprResult Result = S.BuildMemberReferenceExpr(
Base, Base->getType(), Loc, false, SS,
SourceLocation(), nullptr, NameInfo, nullptr,
nullptr);
if (Result.isInvalid())
return ExprError();
if (auto *TE = dyn_cast<TypoExpr>(Result.get())) {
S.clearDelayedTypo(TE);
S.Diag(Loc, diag::err_no_member)
<< NameInfo.getName() << Base->getType()->getAsCXXRecordDecl()
<< Base->getSourceRange();
return ExprError();
}
auto EndLoc = Args.empty() ? Loc : Args.back()->getEndLoc();
return S.BuildCallExpr(nullptr, Result.get(), Loc, Args, EndLoc, nullptr);
}
static Expr *maybeTailCall(Sema &S, QualType RetType, Expr *E,
SourceLocation Loc) {
if (RetType->isReferenceType())
return nullptr;
Type const *T = RetType.getTypePtr();
if (!T->isClassType() && !T->isStructureType())
return nullptr;
ExprResult AddressExpr = buildMemberCall(S, E, Loc, "address", std::nullopt);
if (AddressExpr.isInvalid())
return nullptr;
Expr *JustAddress = AddressExpr.get();
if (!JustAddress->getType().getTypePtr()->isVoidPointerType())
S.Diag(cast<CallExpr>(JustAddress)->getCalleeDecl()->getLocation(),
diag::warn_coroutine_handle_address_invalid_return_type)
<< JustAddress->getType();
return S.MaybeCreateExprWithCleanups(JustAddress);
}
static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
SourceLocation Loc, Expr *E) {
OpaqueValueExpr *Operand = new (S.Context)
OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
ReadySuspendResumeResult Calls = {{}, Operand, false};
using ACT = ReadySuspendResumeResult::AwaitCallType;
auto BuildSubExpr = [&](ACT CallType, StringRef Func,
MultiExprArg Arg) -> Expr * {
ExprResult Result = buildMemberCall(S, Operand, Loc, Func, Arg);
if (Result.isInvalid()) {
Calls.IsInvalid = true;
return nullptr;
}
Calls.Results[CallType] = Result.get();
return Result.get();
};
CallExpr *AwaitReady = cast_or_null<CallExpr>(
BuildSubExpr(ACT::ACT_Ready, "await_ready", std::nullopt));
if (!AwaitReady)
return Calls;
if (!AwaitReady->getType()->isDependentType()) {
ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady);
if (Conv.isInvalid()) {
S.Diag(AwaitReady->getDirectCallee()->getBeginLoc(),
diag::note_await_ready_no_bool_conversion);
S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
<< AwaitReady->getDirectCallee() << E->getSourceRange();
Calls.IsInvalid = true;
} else
Calls.Results[ACT::ACT_Ready] = S.MaybeCreateExprWithCleanups(Conv.get());
}
ExprResult CoroHandleRes =
buildCoroutineHandle(S, CoroPromise->getType(), Loc);
if (CoroHandleRes.isInvalid()) {
Calls.IsInvalid = true;
return Calls;
}
Expr *CoroHandle = CoroHandleRes.get();
CallExpr *AwaitSuspend = cast_or_null<CallExpr>(
BuildSubExpr(ACT::ACT_Suspend, "await_suspend", CoroHandle));
if (!AwaitSuspend)
return Calls;
if (!AwaitSuspend->getType()->isDependentType()) {
QualType RetType = AwaitSuspend->getCallReturnType(S.Context);
if (Expr *TailCallSuspend =
maybeTailCall(S, RetType, AwaitSuspend, Loc))
Calls.Results[ACT::ACT_Suspend] = TailCallSuspend;
else {
if (RetType->isReferenceType() ||
(!RetType->isBooleanType() && !RetType->isVoidType())) {
S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
diag::err_await_suspend_invalid_return_type)
<< RetType;
S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
<< AwaitSuspend->getDirectCallee();
Calls.IsInvalid = true;
} else
Calls.Results[ACT::ACT_Suspend] =
S.MaybeCreateExprWithCleanups(AwaitSuspend);
}
}
BuildSubExpr(ACT::ACT_Resume, "await_resume", std::nullopt);
S.Cleanup.setExprNeedsCleanups(true);
return Calls;
}
static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
SourceLocation Loc, StringRef Name,
MultiExprArg Args) {
ExprResult PromiseRef = S.BuildDeclRefExpr(
Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
if (PromiseRef.isInvalid())
return ExprError();
return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
}
VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
auto *FD = cast<FunctionDecl>(CurContext);
bool IsThisDependentType = [&] {
if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(FD))
return MD->isImplicitObjectMemberFunction() &&
MD->getThisType()->isDependentType();
return false;
}();
QualType T = FD->getType()->isDependentType() || IsThisDependentType
? Context.DependentTy
: lookupPromiseType(*this, FD, Loc);
if (T.isNull())
return nullptr;
auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
&PP.getIdentifierTable().get("__promise"), T,
Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
VD->setImplicit();
CheckVariableDeclarationType(VD);
if (VD->isInvalidDecl())
return nullptr;
auto *ScopeInfo = getCurFunction();
llvm::SmallVector<Expr *, 4> CtorArgExprs;
if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
if (MD->isImplicitObjectMemberFunction() && !isLambdaCallOperator(MD)) {
ExprResult ThisExpr = ActOnCXXThis(Loc);
if (ThisExpr.isInvalid())
return nullptr;
ThisExpr = CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
if (ThisExpr.isInvalid())
return nullptr;
CtorArgExprs.push_back(ThisExpr.get());
}
}
auto &Moves = ScopeInfo->CoroutineParameterMoves;
for (auto *PD : FD->parameters()) {
if (PD->getType()->isDependentType())
continue;
auto RefExpr = ExprEmpty();
auto Move = Moves.find(PD);
assert(Move != Moves.end() &&
"Coroutine function parameter not inserted into move map");
auto *MoveDecl =
cast<VarDecl>(cast<DeclStmt>(Move->second)->getSingleDecl());
RefExpr =
BuildDeclRefExpr(MoveDecl, MoveDecl->getType().getNonReferenceType(),
ExprValueKind::VK_LValue, FD->getLocation());
if (RefExpr.isInvalid())
return nullptr;
CtorArgExprs.push_back(RefExpr.get());
}
if (!CtorArgExprs.empty()) {
Expr *PLE = ParenListExpr::Create(Context, FD->getLocation(),
CtorArgExprs, FD->getLocation());
InitializedEntity Entity = InitializedEntity::InitializeVariable(VD);
InitializationKind Kind = InitializationKind::CreateForInit(
VD->getLocation(), true, PLE);
InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs,
false,
false);
if (InitSeq) {
ExprResult Result = InitSeq.Perform(*this, Entity, Kind, CtorArgExprs);
if (Result.isInvalid()) {
VD->setInvalidDecl();
} else if (Result.get()) {
VD->setInit(MaybeCreateExprWithCleanups(Result.get()));
VD->setInitStyle(VarDecl::CallInit);
CheckCompleteVariableDeclaration(VD);
}
} else
ActOnUninitializedDecl(VD);
} else
ActOnUninitializedDecl(VD);
FD->addDecl(VD);
return VD;
}
static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
StringRef Keyword,
bool IsImplicit = false) {
if (!isValidCoroutineContext(S, Loc, Keyword))
return nullptr;
assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
auto *ScopeInfo = S.getCurFunction();
assert(ScopeInfo && "missing function scope for function");
if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
if (ScopeInfo->CoroutinePromise)
return ScopeInfo;
if (!S.buildCoroutineParameterMoves(Loc))
return nullptr;
ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
if (!ScopeInfo->CoroutinePromise)
return nullptr;
return ScopeInfo;
}
static void checkNoThrow(Sema &S, const Stmt *E,
llvm::SmallPtrSetImpl<const Decl *> &ThrowingDecls) {
auto checkDeclNoexcept = [&](const Decl *D, bool IsDtor = false) {
if (Sema::canCalleeThrow(S, IsDtor ? nullptr : cast<Expr>(E), D)) {
if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
if (FD->getBuiltinID() == Builtin::BI__builtin_coro_resume)
return;
}
if (ThrowingDecls.empty()) {
S.Diag(cast<FunctionDecl>(S.CurContext)->getLocation(),
diag::err_coroutine_promise_final_suspend_requires_nothrow);
}
ThrowingDecls.insert(D);
}
};
if (auto *CE = dyn_cast<CXXConstructExpr>(E)) {
CXXConstructorDecl *Ctor = CE->getConstructor();
checkDeclNoexcept(Ctor);
checkDeclNoexcept(Ctor->getParent()->getDestructor(), true);
} else if (auto *CE = dyn_cast<CallExpr>(E)) {
if (CE->isTypeDependent())
return;
checkDeclNoexcept(CE->getCalleeDecl());
QualType ReturnType = CE->getCallReturnType(S.getASTContext());
if (ReturnType.isDestructedType() ==
QualType::DestructionKind::DK_cxx_destructor) {
const auto *T =
cast<RecordType>(ReturnType.getCanonicalType().getTypePtr());
checkDeclNoexcept(cast<CXXRecordDecl>(T->getDecl())->getDestructor(),
true);
}
} else
for (const auto *Child : E->children()) {
if (!Child)
continue;
checkNoThrow(S, Child, ThrowingDecls);
}
}
bool Sema::checkFinalSuspendNoThrow(const Stmt *FinalSuspend) {
llvm::SmallPtrSet<const Decl *, 4> ThrowingDecls;
checkNoThrow(*this, FinalSuspend, ThrowingDecls);
auto SortedDecls = llvm::SmallVector<const Decl *, 4>{ThrowingDecls.begin(),
ThrowingDecls.end()};
sort(SortedDecls, [](const Decl *A, const Decl *B) {
return A->getEndLoc() < B->getEndLoc();
});
for (const auto *D : SortedDecls) {
Diag(D->getEndLoc(), diag::note_coroutine_function_declare_noexcept);
}
return ThrowingDecls.empty();
}
bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc,
StringRef Keyword) {
EnterExpressionEvaluationContext PotentiallyEvaluated(
*this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
if (!checkCoroutineContext(*this, KWLoc, Keyword))
return false;
auto *ScopeInfo = getCurFunction();
assert(ScopeInfo->CoroutinePromise);
if (!ScopeInfo->NeedsCoroutineSuspends)
return true;
ScopeInfo->setNeedsCoroutineSuspends(false);
auto *Fn = cast<FunctionDecl>(CurContext);
SourceLocation Loc = Fn->getLocation();
auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
ExprResult Operand = buildPromiseCall(*this, ScopeInfo->CoroutinePromise,
Loc, Name, std::nullopt);
if (Operand.isInvalid())
return StmtError();
ExprResult Suspend =
buildOperatorCoawaitCall(*this, SC, Loc, Operand.get());
if (Suspend.isInvalid())
return StmtError();
Suspend = BuildResolvedCoawaitExpr(Loc, Operand.get(), Suspend.get(),
true);
Suspend = ActOnFinishFullExpr(Suspend.get(), false);
if (Suspend.isInvalid()) {
Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
<< ((Name == "initial_suspend") ? 0 : 1);
Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
return StmtError();
}
return cast<Stmt>(Suspend.get());
};
StmtResult InitSuspend = buildSuspends("initial_suspend");
if (InitSuspend.isInvalid())
return true;
StmtResult FinalSuspend = buildSuspends("final_suspend");
if (FinalSuspend.isInvalid() || !checkFinalSuspendNoThrow(FinalSuspend.get()))
return true;
ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
return true;
}
static bool isWithinCatchScope(Scope *S) {
while (S && !S->isFunctionScope()) {
if (S->isCatchScope())
return true;
S = S->getParent();
}
return false;
}
static bool checkSuspensionContext(Sema &S, SourceLocation Loc,
StringRef Keyword) {
if (S.isUnevaluatedContext()) {
S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
return false;
}
if (isWithinCatchScope(S.getCurScope())) {
S.Diag(Loc, diag::err_coroutine_within_handler) << Keyword;
return false;
}
return true;
}
ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
if (!checkSuspensionContext(*this, Loc, "co_await"))
return ExprError();
if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) {
CorrectDelayedTyposInExpr(E);
return ExprError();
}
if (E->hasPlaceholderType()) {
ExprResult R = CheckPlaceholderExpr(E);
if (R.isInvalid()) return ExprError();
E = R.get();
}
ExprResult Lookup = BuildOperatorCoawaitLookupExpr(S, Loc);
if (Lookup.isInvalid())
return ExprError();
return BuildUnresolvedCoawaitExpr(Loc, E,
cast<UnresolvedLookupExpr>(Lookup.get()));
}
ExprResult Sema::BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc) {
DeclarationName OpName =
Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
LookupResult Operators(*this, OpName, SourceLocation(),
Sema::LookupOperatorName);
LookupName(Operators, S);
assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
const auto &Functions = Operators.asUnresolvedSet();
Expr *CoawaitOp = UnresolvedLookupExpr::Create(
Context, nullptr, NestedNameSpecifierLoc(),
DeclarationNameInfo(OpName, Loc), true, Functions.begin(),
Functions.end(), false,
false);
assert(CoawaitOp);
return CoawaitOp;
}
ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *Operand,
UnresolvedLookupExpr *Lookup) {
auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
if (!FSI)
return ExprError();
if (Operand->hasPlaceholderType()) {
ExprResult R = CheckPlaceholderExpr(Operand);
if (R.isInvalid())
return ExprError();
Operand = R.get();
}
auto *Promise = FSI->CoroutinePromise;
if (Promise->getType()->isDependentType()) {
Expr *Res = new (Context)
DependentCoawaitExpr(Loc, Context.DependentTy, Operand, Lookup);
return Res;
}
auto *RD = Promise->getType()->getAsCXXRecordDecl();
auto *Transformed = Operand;
if (lookupMember(*this, "await_transform", RD, Loc)) {
ExprResult R =
buildPromiseCall(*this, Promise, Loc, "await_transform", Operand);
if (R.isInvalid()) {
Diag(Loc,
diag::note_coroutine_promise_implicit_await_transform_required_here)
<< Operand->getSourceRange();
return ExprError();
}
Transformed = R.get();
}
ExprResult Awaiter = BuildOperatorCoawaitCall(Loc, Transformed, Lookup);
if (Awaiter.isInvalid())
return ExprError();
return BuildResolvedCoawaitExpr(Loc, Operand, Awaiter.get());
}
ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *Operand,
Expr *Awaiter, bool IsImplicit) {
auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
if (!Coroutine)
return ExprError();
if (Awaiter->hasPlaceholderType()) {
ExprResult R = CheckPlaceholderExpr(Awaiter);
if (R.isInvalid()) return ExprError();
Awaiter = R.get();
}
if (Awaiter->getType()->isDependentType()) {
Expr *Res = new (Context)
CoawaitExpr(Loc, Context.DependentTy, Operand, Awaiter, IsImplicit);
return Res;
}
if (Awaiter->isPRValue())
Awaiter = CreateMaterializeTemporaryExpr(Awaiter->getType(), Awaiter, true);
SourceLocation CallLoc = Awaiter->getExprLoc();
ReadySuspendResumeResult RSS =
buildCoawaitCalls(*this, Coroutine->CoroutinePromise, CallLoc, Awaiter);
if (RSS.IsInvalid)
return ExprError();
Expr *Res = new (Context)
CoawaitExpr(Loc, Operand, Awaiter, RSS.Results[0], RSS.Results[1],
RSS.Results[2], RSS.OpaqueValue, IsImplicit);
return Res;
}
ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
if (!checkSuspensionContext(*this, Loc, "co_yield"))
return ExprError();
if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) {
CorrectDelayedTyposInExpr(E);
return ExprError();
}
ExprResult Awaitable = buildPromiseCall(
*this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
if (Awaitable.isInvalid())
return ExprError();
Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
if (Awaitable.isInvalid())
return ExprError();
return BuildCoyieldExpr(Loc, Awaitable.get());
}
ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
if (!Coroutine)
return ExprError();
if (E->hasPlaceholderType()) {
ExprResult R = CheckPlaceholderExpr(E);
if (R.isInvalid()) return ExprError();
E = R.get();
}
Expr *Operand = E;
if (E->getType()->isDependentType()) {
Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, Operand, E);
return Res;
}
if (E->isPRValue())
E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
ReadySuspendResumeResult RSS = buildCoawaitCalls(
*this, Coroutine->CoroutinePromise, Loc, E);
if (RSS.IsInvalid)
return ExprError();
Expr *Res =
new (Context) CoyieldExpr(Loc, Operand, E, RSS.Results[0], RSS.Results[1],
RSS.Results[2], RSS.OpaqueValue);
return Res;
}
StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) {
CorrectDelayedTyposInExpr(E);
return StmtError();
}
return BuildCoreturnStmt(Loc, E);
}
StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
bool IsImplicit) {
auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
if (!FSI)
return StmtError();
if (E && E->hasPlaceholderType() &&
!E->hasPlaceholderType(BuiltinType::Overload)) {
ExprResult R = CheckPlaceholderExpr(E);
if (R.isInvalid()) return StmtError();
E = R.get();
}
VarDecl *Promise = FSI->CoroutinePromise;
ExprResult PC;
if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
getNamedReturnInfo(E, SimplerImplicitMoveMode::ForceOn);
PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
} else {
E = MakeFullDiscardedValueExpr(E).get();
PC = buildPromiseCall(*this, Promise, Loc, "return_void", std::nullopt);
}
if (PC.isInvalid())
return StmtError();
Expr *PCE = ActOnFinishFullExpr(PC.get(), false).get();
Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
return Res;
}
static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
NamespaceDecl *Std = S.getStdNamespace();
assert(Std && "Should already be diagnosed");
LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
Sema::LookupOrdinaryName);
if (!S.LookupQualifiedName(Result, Std)) {
S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
return nullptr;
}
auto *VD = Result.getAsSingle<VarDecl>();
if (!VD) {
Result.suppressDiagnostics();
NamedDecl *Found = *Result.begin();
S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
return nullptr;
}
ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
if (DR.isInvalid())
return nullptr;
return DR.get();
}
static TypeSourceInfo *getTypeSourceInfoForStdAlignValT(Sema &S,
SourceLocation Loc) {
EnumDecl *StdAlignValT = S.getStdAlignValT();
QualType StdAlignValDecl = S.Context.getTypeDeclType(StdAlignValT);
return S.Context.getTrivialTypeSourceInfo(StdAlignValDecl);
}
static bool findDeleteForPromise(Sema &S, SourceLocation Loc, QualType PromiseType,
FunctionDecl *&OperatorDelete) {
DeclarationName DeleteName =
S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
const bool Overaligned = S.getLangOpts().CoroAlignedAllocation;
if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete,
true, true,
Overaligned))
return false;
if (!OperatorDelete) {
const bool CanProvideSize = true;
OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
Overaligned, DeleteName);
if (!OperatorDelete)
return false;
}
S.MarkFunctionReferenced(Loc, OperatorDelete);
return true;
}
void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
FunctionScopeInfo *Fn = getCurFunction();
assert(Fn && Fn->isCoroutine() && "not a coroutine");
if (!Body) {
assert(FD->isInvalidDecl() &&
"a null body is only allowed for invalid declarations");
return;
}
if (!Fn->CoroutinePromise)
return FD->setInvalidDecl();
if (isa<CoroutineBodyStmt>(Body)) {
return;
}
if (FD->hasAttr<AlwaysInlineAttr>())
Diag(FD->getLocation(), diag::warn_always_inline_coroutine);
if (Fn->FirstVLALoc.isValid())
Diag(Fn->FirstVLALoc, diag::err_vla_in_coroutine_unsupported);
if (Fn->FirstReturnLoc.isValid()) {
assert(Fn->FirstCoroutineStmtLoc.isValid() &&
"first coroutine location not set");
Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
<< Fn->getFirstCoroutineStmtKeyword();
}
for (AddrLabelExpr *ALE : Fn->AddrLabels)
Diag(ALE->getBeginLoc(), diag::err_coro_invalid_addr_of_label);
CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
if (Builder.isInvalid() || !Builder.buildStatements())
return FD->setInvalidDecl();
Body = CoroutineBodyStmt::Create(Context, Builder);
}
static CompoundStmt *buildCoroutineBody(Stmt *Body, ASTContext &Context) {
if (auto *CS = dyn_cast<CompoundStmt>(Body))
return CS;
assert(isa<CXXTryStmt>(Body) && "Unimaged coroutine body type");
return CompoundStmt::Create(Context, {Body}, FPOptionsOverride(),
SourceLocation(), SourceLocation());
}
CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
sema::FunctionScopeInfo &Fn,
Stmt *Body)
: S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
IsPromiseDependentType(
!Fn.CoroutinePromise ||
Fn.CoroutinePromise->getType()->isDependentType()) {
this->Body = buildCoroutineBody(Body, S.getASTContext());
for (auto KV : Fn.CoroutineParameterMoves)
this->ParamMovesVector.push_back(KV.second);
this->ParamMoves = this->ParamMovesVector;
if (!IsPromiseDependentType) {
PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
assert(PromiseRecordDecl && "Type should have already been checked");
}
this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
}
bool CoroutineStmtBuilder::buildStatements() {
assert(this->IsValid && "coroutine already invalid");
this->IsValid = makeReturnObject();
if (this->IsValid && !IsPromiseDependentType)
buildDependentStatements();
return this->IsValid;
}
bool CoroutineStmtBuilder::buildDependentStatements() {
assert(this->IsValid && "coroutine already invalid");
assert(!this->IsPromiseDependentType &&
"coroutine cannot have a dependent promise type");
this->IsValid = makeOnException() && makeOnFallthrough() &&
makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
makeNewAndDeleteExpr();
return this->IsValid;
}
bool CoroutineStmtBuilder::makePromiseStmt() {
StmtResult PromiseStmt =
S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
if (PromiseStmt.isInvalid())
return false;
this->Promise = PromiseStmt.get();
return true;
}
bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
if (Fn.hasInvalidCoroutineSuspends())
return false;
this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
return true;
}
static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
CXXRecordDecl *PromiseRecordDecl,
FunctionScopeInfo &Fn) {
auto Loc = E->getExprLoc();
if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
auto *Decl = DeclRef->getDecl();
if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
if (Method->isStatic())
return true;
else
Loc = Decl->getLocation();
}
}
S.Diag(
Loc,
diag::err_coroutine_promise_get_return_object_on_allocation_failure)
<< PromiseRecordDecl;
S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
<< Fn.getFirstCoroutineStmtKeyword();
return false;
}
bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
assert(!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent");
DeclarationName DN =
S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
return true;
CXXScopeSpec SS;
ExprResult DeclNameExpr =
S.BuildDeclarationNameExpr(SS, Found, false);
if (DeclNameExpr.isInvalid())
return false;
if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
return false;
ExprResult ReturnObjectOnAllocationFailure =
S.BuildCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
if (ReturnObjectOnAllocationFailure.isInvalid())
return false;
StmtResult ReturnStmt =
S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
if (ReturnStmt.isInvalid()) {
S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
<< DN;
S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
<< Fn.getFirstCoroutineStmtKeyword();
return false;
}
this->ReturnStmtOnAllocFailure = ReturnStmt.get();
return true;
}
static bool collectPlacementArgs(Sema &S, FunctionDecl &FD, SourceLocation Loc,
SmallVectorImpl<Expr *> &PlacementArgs) {
if (auto *MD = dyn_cast<CXXMethodDecl>(&FD)) {
if (MD->isImplicitObjectMemberFunction() && !isLambdaCallOperator(MD)) {
ExprResult ThisExpr = S.ActOnCXXThis(Loc);
if (ThisExpr.isInvalid())
return false;
ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
if (ThisExpr.isInvalid())
return false;
PlacementArgs.push_back(ThisExpr.get());
}
}
for (auto *PD : FD.parameters()) {
if (PD->getType()->isDependentType())
continue;
auto PDLoc = PD->getLocation();
ExprResult PDRefExpr =
S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),
ExprValueKind::VK_LValue, PDLoc);
if (PDRefExpr.isInvalid())
return false;
PlacementArgs.push_back(PDRefExpr.get());
}
return true;
}
bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
assert(!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent");
QualType PromiseType = Fn.CoroutinePromise->getType();
if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
return false;
const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
FunctionDecl *OperatorNew = nullptr;
SmallVector<Expr *, 1> PlacementArgs;
const bool PromiseContainsNew = [this, &PromiseType]() -> bool {
DeclarationName NewName =
S.getASTContext().DeclarationNames.getCXXOperatorName(OO_New);
LookupResult R(S, NewName, Loc, Sema::LookupOrdinaryName);
if (PromiseType->isRecordType())
S.LookupQualifiedName(R, PromiseType->getAsCXXRecordDecl());
return !R.empty() && !R.isAmbiguous();
}();
bool PassAlignment = S.getLangOpts().CoroAlignedAllocation;
auto LookupAllocationFunction = [&](Sema::AllocationFunctionScope NewScope =
Sema::AFS_Both,
bool WithoutPlacementArgs = false,
bool ForceNonAligned = false) {
if (NewScope == Sema::AFS_Both)
NewScope = PromiseContainsNew ? Sema::AFS_Class : Sema::AFS_Global;
PassAlignment = !ForceNonAligned && S.getLangOpts().CoroAlignedAllocation;
FunctionDecl *UnusedResult = nullptr;
S.FindAllocationFunctions(Loc, SourceRange(), NewScope,
Sema::AFS_Both, PromiseType,
false, PassAlignment,
WithoutPlacementArgs ? MultiExprArg{}
: PlacementArgs,
OperatorNew, UnusedResult, false);
};
if (PromiseContainsNew && !collectPlacementArgs(S, FD, Loc, PlacementArgs))
return false;
LookupAllocationFunction();
if (PromiseContainsNew && !PlacementArgs.empty()) {
if (!OperatorNew ||
(S.getLangOpts().CoroAlignedAllocation && !PassAlignment))
LookupAllocationFunction( Sema::AFS_Class,
true);
}
bool FoundNonAlignedInPromise = false;
if (PromiseContainsNew && S.getLangOpts().CoroAlignedAllocation)
if (!OperatorNew || !PassAlignment) {
FoundNonAlignedInPromise = OperatorNew;
LookupAllocationFunction( Sema::AFS_Class,
false,
true);
if (!OperatorNew && !PlacementArgs.empty())
LookupAllocationFunction( Sema::AFS_Class,
true,
true);
}
bool IsGlobalOverload =
OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
if (!StdNoThrow)
return false;
PlacementArgs = {StdNoThrow};
OperatorNew = nullptr;
LookupAllocationFunction(Sema::AFS_Global);
}
if (FoundNonAlignedInPromise) {
S.Diag(OperatorNew->getLocation(),
diag::warn_non_aligned_allocation_function)
<< &FD;
}
if (!OperatorNew) {
if (PromiseContainsNew)
S.Diag(Loc, diag::err_coroutine_unusable_new) << PromiseType << &FD;
else if (RequiresNoThrowAlloc)
S.Diag(Loc, diag::err_coroutine_unfound_nothrow_new)
<< &FD << S.getLangOpts().CoroAlignedAllocation;
return false;
}
if (RequiresNoThrowAlloc) {
const auto *FT = OperatorNew->getType()->castAs<FunctionProtoType>();
if (!FT->isNothrow( false)) {
S.Diag(OperatorNew->getLocation(),
diag::err_coroutine_promise_new_requires_nothrow)
<< OperatorNew;
S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
<< OperatorNew;
return false;
}
}
FunctionDecl *OperatorDelete = nullptr;
if (!findDeleteForPromise(S, Loc, PromiseType, OperatorDelete)) {
return false;
}
Expr *FramePtr =
S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_frame, {});
Expr *FrameSize =
S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_size, {});
Expr *FrameAlignment = nullptr;
if (S.getLangOpts().CoroAlignedAllocation) {
FrameAlignment =
S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_align, {});
TypeSourceInfo *AlignValTy = getTypeSourceInfoForStdAlignValT(S, Loc);
if (!AlignValTy)
return false;
FrameAlignment = S.BuildCXXNamedCast(Loc, tok::kw_static_cast, AlignValTy,
FrameAlignment, SourceRange(Loc, Loc),
SourceRange(Loc, Loc))
.get();
}
ExprResult NewRef =
S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
if (NewRef.isInvalid())
return false;
SmallVector<Expr *, 2> NewArgs(1, FrameSize);
if (S.getLangOpts().CoroAlignedAllocation && PassAlignment)
NewArgs.push_back(FrameAlignment);
if (OperatorNew->getNumParams() > NewArgs.size())
llvm::append_range(NewArgs, PlacementArgs);
ExprResult NewExpr =
S.BuildCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
NewExpr = S.ActOnFinishFullExpr(NewExpr.get(), false);
if (NewExpr.isInvalid())
return false;
QualType OpDeleteQualType = OperatorDelete->getType();
ExprResult DeleteRef =
S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
if (DeleteRef.isInvalid())
return false;
Expr *CoroFree =
S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_free, {FramePtr});
SmallVector<Expr *, 2> DeleteArgs{CoroFree};
const auto *OpDeleteType =
OpDeleteQualType.getTypePtr()->castAs<FunctionProtoType>();
if (OpDeleteType->getNumParams() > DeleteArgs.size() &&
S.getASTContext().hasSameUnqualifiedType(
OpDeleteType->getParamType(DeleteArgs.size()), FrameSize->getType()))
DeleteArgs.push_back(FrameSize);
if (S.getLangOpts().CoroAlignedAllocation &&
OpDeleteType->getNumParams() > DeleteArgs.size() &&
S.getASTContext().hasSameUnqualifiedType(
OpDeleteType->getParamType(DeleteArgs.size()),
FrameAlignment->getType()))
DeleteArgs.push_back(FrameAlignment);
ExprResult DeleteExpr =
S.BuildCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
DeleteExpr =
S.ActOnFinishFullExpr(DeleteExpr.get(), false);
if (DeleteExpr.isInvalid())
return false;
this->Allocate = NewExpr.get();
this->Deallocate = DeleteExpr.get();
return true;
}
bool CoroutineStmtBuilder::makeOnFallthrough() {
assert(!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent");
bool HasRVoid, HasRValue;
LookupResult LRVoid =
lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
LookupResult LRValue =
lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
StmtResult Fallthrough;
if (HasRVoid && HasRValue) {
S.Diag(FD.getLocation(),
diag::err_coroutine_promise_incompatible_return_functions)
<< PromiseRecordDecl;
S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
diag::note_member_first_declared_here)
<< LRVoid.getLookupName();
S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
diag::note_member_first_declared_here)
<< LRValue.getLookupName();
return false;
} else if (!HasRVoid && !HasRValue) {
Fallthrough = S.ActOnNullStmt(PromiseRecordDecl->getLocation());
if (Fallthrough.isInvalid())
return false;
} else if (HasRVoid) {
Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
true);
Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
if (Fallthrough.isInvalid())
return false;
}
this->OnFallthrough = Fallthrough.get();
return true;
}
bool CoroutineStmtBuilder::makeOnException() {
assert(!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent");
const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
auto DiagID =
RequireUnhandledException
? diag::err_coroutine_promise_unhandled_exception_required
: diag::
warn_coroutine_promise_unhandled_exception_required_with_exceptions;
S.Diag(Loc, DiagID) << PromiseRecordDecl;
S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
<< PromiseRecordDecl;
return !RequireUnhandledException;
}
if (!S.getLangOpts().CXXExceptions)
return true;
ExprResult UnhandledException = buildPromiseCall(
S, Fn.CoroutinePromise, Loc, "unhandled_exception", std::nullopt);
UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc,
false);
if (UnhandledException.isInvalid())
return false;
if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
<< Fn.getFirstCoroutineStmtKeyword();
return false;
}
this->OnException = UnhandledException.get();
return true;
}
bool CoroutineStmtBuilder::makeReturnObject() {
ExprResult ReturnObject = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
"get_return_object", std::nullopt);
if (ReturnObject.isInvalid())
return false;
this->ReturnValue = ReturnObject.get();
return true;
}
static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
auto *MethodDecl = MbrRef->getMethodDecl();
S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
<< MethodDecl;
}
S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
<< Fn.getFirstCoroutineStmtKeyword();
}
bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
assert(!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent");
assert(this->ReturnValue && "ReturnValue must be already formed");
QualType const GroType = this->ReturnValue->getType();
assert(!GroType->isDependentType() &&
"get_return_object type must no longer be dependent");
QualType const FnRetType = FD.getReturnType();
assert(!FnRetType->isDependentType() &&
"get_return_object type must no longer be dependent");
bool GroMatchesRetType = S.getASTContext().hasSameType(GroType, FnRetType);
if (FnRetType->isVoidType()) {
ExprResult Res =
S.ActOnFinishFullExpr(this->ReturnValue, Loc, false);
if (Res.isInvalid())
return false;
if (!GroMatchesRetType)
this->ResultDecl = Res.get();
return true;
}
if (GroType->isVoidType()) {
InitializedEntity Entity =
InitializedEntity::InitializeResult(Loc, FnRetType);
S.PerformCopyInitialization(Entity, SourceLocation(), ReturnValue);
noteMemberDeclaredHere(S, ReturnValue, Fn);
return false;
}
StmtResult ReturnStmt;
clang::VarDecl *GroDecl = nullptr;
if (GroMatchesRetType) {
ReturnStmt = S.BuildReturnStmt(Loc, ReturnValue);
} else {
GroDecl = VarDecl::Create(
S.Context, &FD, FD.getLocation(), FD.getLocation(),
&S.PP.getIdentifierTable().get("__coro_gro"), GroType,
S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
GroDecl->setImplicit();
S.CheckVariableDeclarationType(GroDecl);
if (GroDecl->isInvalidDecl())
return false;
InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
ExprResult Res =
S.PerformCopyInitialization(Entity, SourceLocation(), ReturnValue);
if (Res.isInvalid())
return false;
Res = S.ActOnFinishFullExpr(Res.get(), false);
if (Res.isInvalid())
return false;
S.AddInitializerToDecl(GroDecl, Res.get(),
false);
S.FinalizeDeclaration(GroDecl);
StmtResult GroDeclStmt =
S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
if (GroDeclStmt.isInvalid())
return false;
this->ResultDecl = GroDeclStmt.get();
ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
if (declRef.isInvalid())
return false;
ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
}
if (ReturnStmt.isInvalid()) {
noteMemberDeclaredHere(S, ReturnValue, Fn);
return false;
}
if (!GroMatchesRetType &&
cast<clang::ReturnStmt>(ReturnStmt.get())->getNRVOCandidate() == GroDecl)
GroDecl->setNRVOVariable(true);
this->ReturnStmt = ReturnStmt.get();
return true;
}
static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
if (T.isNull())
T = E->getType();
QualType TargetType = S.BuildReferenceType(
T, false, SourceLocation(), DeclarationName());
SourceLocation ExprLoc = E->getBeginLoc();
TypeSourceInfo *TargetLoc =
S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
return S
.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
.get();
}
static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
IdentifierInfo *II) {
TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);
VarDecl *Decl = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type,
TInfo, SC_None);
Decl->setImplicit();
return Decl;
}
bool Sema::buildCoroutineParameterMoves(SourceLocation Loc) {
assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
auto *FD = cast<FunctionDecl>(CurContext);
auto *ScopeInfo = getCurFunction();
if (!ScopeInfo->CoroutineParameterMoves.empty())
return false;
for (auto *PD : FD->parameters()) {
if (PD->getType()->isDependentType())
continue;
bool DeclReferenced = PD->isReferenced();
ExprResult PDRefExpr =
BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
ExprValueKind::VK_LValue, Loc);
PD->setReferenced(DeclReferenced);
if (PDRefExpr.isInvalid())
return false;
Expr *CExpr = nullptr;
if (PD->getType()->getAsCXXRecordDecl() ||
PD->getType()->isRValueReferenceType())
CExpr = castForMoving(*this, PDRefExpr.get());
else
CExpr = PDRefExpr.get();
auto *D = buildVarDecl(*this, Loc, PD->getType(), PD->getIdentifier());
AddInitializerToDecl(D, CExpr, true);
StmtResult Stmt = ActOnDeclStmt(ConvertDeclToDeclGroup(D), Loc, Loc);
if (Stmt.isInvalid())
return false;
ScopeInfo->CoroutineParameterMoves.insert(std::make_pair(PD, Stmt.get()));
}
return true;
}
StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
if (!Res)
return StmtError();
return Res;
}
ClassTemplateDecl *Sema::lookupCoroutineTraits(SourceLocation KwLoc,
SourceLocation FuncLoc) {
if (StdCoroutineTraitsCache)
return StdCoroutineTraitsCache;
IdentifierInfo const &TraitIdent =
PP.getIdentifierTable().get("coroutine_traits");
NamespaceDecl *StdSpace = getStdNamespace();
LookupResult Result(*this, &TraitIdent, FuncLoc, LookupOrdinaryName);
bool Found = StdSpace && LookupQualifiedName(Result, StdSpace);
if (!Found) {
Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
<< "std::coroutine_traits";
return nullptr;
}
StdCoroutineTraitsCache = Result.getAsSingle<ClassTemplateDecl>();
if (!StdCoroutineTraitsCache) {
Result.suppressDiagnostics();
NamedDecl *Found = *Result.begin();
Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
return nullptr;
}
return StdCoroutineTraitsCache;
}