1 //===--- SemaCoroutines.cpp - Semantic Analysis for Coroutines ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for C++ Coroutines.
12 //===----------------------------------------------------------------------===//
14 #include "CoroutineStmtBuilder.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/ExprCXX.h"
17 #include "clang/AST/StmtCXX.h"
18 #include "clang/Lex/Preprocessor.h"
19 #include "clang/Sema/Initialization.h"
20 #include "clang/Sema/Overload.h"
21 #include "clang/Sema/SemaInternal.h"
23 using namespace clang;
26 static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
27 SourceLocation Loc, bool &Res) {
28 DeclarationName DN = S.PP.getIdentifierInfo(Name);
29 LookupResult LR(S, DN, Loc, Sema::LookupMemberName);
30 // Suppress diagnostics when a private member is selected. The same warnings
31 // will be produced again when building the call.
32 LR.suppressDiagnostics();
33 Res = S.LookupQualifiedName(LR, RD);
37 static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
40 lookupMember(S, Name, RD, Loc, Res);
44 /// Look up the std::coroutine_traits<...>::promise_type for the given
46 static QualType lookupPromiseType(Sema &S, const FunctionProtoType *FnType,
48 SourceLocation FuncLoc) {
49 // FIXME: Cache std::coroutine_traits once we've found it.
50 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
52 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
53 << "std::experimental::coroutine_traits";
57 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_traits"),
58 FuncLoc, Sema::LookupOrdinaryName);
59 if (!S.LookupQualifiedName(Result, StdExp)) {
60 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
61 << "std::experimental::coroutine_traits";
65 ClassTemplateDecl *CoroTraits = Result.getAsSingle<ClassTemplateDecl>();
67 Result.suppressDiagnostics();
68 // We found something weird. Complain about the first thing we found.
69 NamedDecl *Found = *Result.begin();
70 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
74 // Form template argument list for coroutine_traits<R, P1, P2, ...>.
75 TemplateArgumentListInfo Args(KwLoc, KwLoc);
76 Args.addArgument(TemplateArgumentLoc(
77 TemplateArgument(FnType->getReturnType()),
78 S.Context.getTrivialTypeSourceInfo(FnType->getReturnType(), KwLoc)));
79 // FIXME: If the function is a non-static member function, add the type
80 // of the implicit object parameter before the formal parameters.
81 for (QualType T : FnType->getParamTypes())
82 Args.addArgument(TemplateArgumentLoc(
83 TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));
85 // Build the template-id.
87 S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
88 if (CoroTrait.isNull())
90 if (S.RequireCompleteType(KwLoc, CoroTrait,
91 diag::err_coroutine_type_missing_specialization))
94 auto *RD = CoroTrait->getAsCXXRecordDecl();
95 assert(RD && "specialization of class template is not a class?");
97 // Look up the ::promise_type member.
98 LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
99 Sema::LookupOrdinaryName);
100 S.LookupQualifiedName(R, RD);
101 auto *Promise = R.getAsSingle<TypeDecl>();
104 diag::err_implied_std_coroutine_traits_promise_type_not_found)
108 // The promise type is required to be a class type.
109 QualType PromiseType = S.Context.getTypeDeclType(Promise);
111 auto buildElaboratedType = [&]() {
112 auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, StdExp);
113 NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
114 CoroTrait.getTypePtr());
115 return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
118 if (!PromiseType->getAsCXXRecordDecl()) {
120 diag::err_implied_std_coroutine_traits_promise_type_not_class)
121 << buildElaboratedType();
124 if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
125 diag::err_coroutine_promise_type_incomplete))
131 /// Look up the std::experimental::coroutine_handle<PromiseType>.
132 static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
133 SourceLocation Loc) {
134 if (PromiseType.isNull())
137 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
138 assert(StdExp && "Should already be diagnosed");
140 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
141 Loc, Sema::LookupOrdinaryName);
142 if (!S.LookupQualifiedName(Result, StdExp)) {
143 S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
144 << "std::experimental::coroutine_handle";
148 ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
150 Result.suppressDiagnostics();
151 // We found something weird. Complain about the first thing we found.
152 NamedDecl *Found = *Result.begin();
153 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
157 // Form template argument list for coroutine_handle<Promise>.
158 TemplateArgumentListInfo Args(Loc, Loc);
159 Args.addArgument(TemplateArgumentLoc(
160 TemplateArgument(PromiseType),
161 S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
163 // Build the template-id.
164 QualType CoroHandleType =
165 S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
166 if (CoroHandleType.isNull())
168 if (S.RequireCompleteType(Loc, CoroHandleType,
169 diag::err_coroutine_type_missing_specialization))
172 return CoroHandleType;
175 static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
177 // 'co_await' and 'co_yield' are not permitted in unevaluated operands.
178 if (S.isUnevaluatedContext()) {
179 S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
183 // Any other usage must be within a function.
184 auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
186 S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
187 ? diag::err_coroutine_objc_method
188 : diag::err_coroutine_outside_function) << Keyword;
192 // An enumeration for mapping the diagnostic type to the correct diagnostic
194 enum InvalidFuncDiag {
204 bool Diagnosed = false;
205 auto DiagInvalid = [&](InvalidFuncDiag ID) {
206 S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
211 // Diagnose when a constructor, destructor, copy/move assignment operator,
212 // or the function 'main' are declared as a coroutine.
213 auto *MD = dyn_cast<CXXMethodDecl>(FD);
214 if (MD && isa<CXXConstructorDecl>(MD))
215 return DiagInvalid(DiagCtor);
216 else if (MD && isa<CXXDestructorDecl>(MD))
217 return DiagInvalid(DiagDtor);
218 else if (MD && MD->isCopyAssignmentOperator())
219 return DiagInvalid(DiagCopyAssign);
220 else if (MD && MD->isMoveAssignmentOperator())
221 return DiagInvalid(DiagMoveAssign);
222 else if (FD->isMain())
223 return DiagInvalid(DiagMain);
225 // Emit a diagnostics for each of the following conditions which is not met.
226 if (FD->isConstexpr())
227 DiagInvalid(DiagConstexpr);
228 if (FD->getReturnType()->isUndeducedType())
229 DiagInvalid(DiagAutoRet);
230 if (FD->isVariadic())
231 DiagInvalid(DiagVarargs);
236 static ExprResult buildOperatorCoawaitLookupExpr(Sema &SemaRef, Scope *S,
237 SourceLocation Loc) {
238 DeclarationName OpName =
239 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
240 LookupResult Operators(SemaRef, OpName, SourceLocation(),
241 Sema::LookupOperatorName);
242 SemaRef.LookupName(Operators, S);
244 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
245 const auto &Functions = Operators.asUnresolvedSet();
247 Functions.size() > 1 ||
248 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
249 Expr *CoawaitOp = UnresolvedLookupExpr::Create(
250 SemaRef.Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
251 DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
252 Functions.begin(), Functions.end());
257 /// Build a call to 'operator co_await' if there is a suitable operator for
258 /// the given expression.
259 static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, SourceLocation Loc,
261 UnresolvedLookupExpr *Lookup) {
262 UnresolvedSet<16> Functions;
263 Functions.append(Lookup->decls_begin(), Lookup->decls_end());
264 return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
267 static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
268 SourceLocation Loc, Expr *E) {
269 ExprResult R = buildOperatorCoawaitLookupExpr(SemaRef, S, Loc);
272 return buildOperatorCoawaitCall(SemaRef, Loc, E,
273 cast<UnresolvedLookupExpr>(R.get()));
276 static Expr *buildBuiltinCall(Sema &S, SourceLocation Loc, Builtin::ID Id,
277 MultiExprArg CallArgs) {
278 StringRef Name = S.Context.BuiltinInfo.getName(Id);
279 LookupResult R(S, &S.Context.Idents.get(Name), Loc, Sema::LookupOrdinaryName);
280 S.LookupName(R, S.TUScope, /*AllowBuiltinCreation=*/true);
282 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
283 assert(BuiltInDecl && "failed to find builtin declaration");
286 S.BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
287 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
290 S.ActOnCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
292 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
296 static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
297 SourceLocation Loc) {
298 QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
299 if (CoroHandleType.isNull())
302 DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
303 LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
304 Sema::LookupOrdinaryName);
305 if (!S.LookupQualifiedName(Found, LookupCtx)) {
306 S.Diag(Loc, diag::err_coroutine_handle_missing_member)
312 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
315 ExprResult FromAddr =
316 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
317 if (FromAddr.isInvalid())
320 return S.ActOnCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
323 struct ReadySuspendResumeResult {
324 enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume };
326 OpaqueValueExpr *OpaqueValue;
330 static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
331 StringRef Name, MultiExprArg Args) {
332 DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
334 // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
336 ExprResult Result = S.BuildMemberReferenceExpr(
337 Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
338 SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
340 if (Result.isInvalid())
343 return S.ActOnCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
346 /// Build calls to await_ready, await_suspend, and await_resume for a co_await
348 static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
349 SourceLocation Loc, Expr *E) {
350 OpaqueValueExpr *Operand = new (S.Context)
351 OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
353 // Assume invalid until we see otherwise.
354 ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true};
356 ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc);
357 if (CoroHandleRes.isInvalid())
359 Expr *CoroHandle = CoroHandleRes.get();
361 const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
362 MultiExprArg Args[] = {None, CoroHandle, None};
363 for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
364 ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]);
365 if (Result.isInvalid())
367 Calls.Results[I] = Result.get();
370 // Assume the calls are valid; all further checking should make them invalid.
371 Calls.IsInvalid = false;
373 using ACT = ReadySuspendResumeResult::AwaitCallType;
374 CallExpr *AwaitReady = cast<CallExpr>(Calls.Results[ACT::ACT_Ready]);
375 if (!AwaitReady->getType()->isDependentType()) {
376 // [expr.await]p3 [...]
377 // — await-ready is the expression e.await_ready(), contextually converted
379 ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady);
380 if (Conv.isInvalid()) {
381 S.Diag(AwaitReady->getDirectCallee()->getLocStart(),
382 diag::note_await_ready_no_bool_conversion);
383 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
384 << AwaitReady->getDirectCallee() << E->getSourceRange();
385 Calls.IsInvalid = true;
387 Calls.Results[ACT::ACT_Ready] = Conv.get();
389 CallExpr *AwaitSuspend = cast<CallExpr>(Calls.Results[ACT::ACT_Suspend]);
390 if (!AwaitSuspend->getType()->isDependentType()) {
391 // [expr.await]p3 [...]
392 // - await-suspend is the expression e.await_suspend(h), which shall be
393 // a prvalue of type void or bool.
394 QualType RetType = AwaitSuspend->getType();
395 if (RetType != S.Context.BoolTy && RetType != S.Context.VoidTy) {
396 S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
397 diag::err_await_suspend_invalid_return_type)
399 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
400 << AwaitSuspend->getDirectCallee();
401 Calls.IsInvalid = true;
408 static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
409 SourceLocation Loc, StringRef Name,
412 // Form a reference to the promise.
413 ExprResult PromiseRef = S.BuildDeclRefExpr(
414 Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
415 if (PromiseRef.isInvalid())
418 return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
421 VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
422 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
423 auto *FD = cast<FunctionDecl>(CurContext);
426 FD->getType()->isDependentType()
427 ? Context.DependentTy
428 : lookupPromiseType(*this, FD->getType()->castAs<FunctionProtoType>(),
429 Loc, FD->getLocation());
433 auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
434 &PP.getIdentifierTable().get("__promise"), T,
435 Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
436 CheckVariableDeclarationType(VD);
437 if (VD->isInvalidDecl())
439 ActOnUninitializedDecl(VD);
440 assert(!VD->isInvalidDecl());
444 /// Check that this is a context in which a coroutine suspension can appear.
445 static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
447 bool IsImplicit = false) {
448 if (!isValidCoroutineContext(S, Loc, Keyword))
451 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
453 auto *ScopeInfo = S.getCurFunction();
454 assert(ScopeInfo && "missing function scope for function");
456 if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
457 ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
459 if (ScopeInfo->CoroutinePromise)
462 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
463 if (!ScopeInfo->CoroutinePromise)
469 static bool actOnCoroutineBodyStart(Sema &S, Scope *SC, SourceLocation KWLoc,
471 if (!checkCoroutineContext(S, KWLoc, Keyword))
473 auto *ScopeInfo = S.getCurFunction();
474 assert(ScopeInfo->CoroutinePromise);
476 // If we have existing coroutine statements then we have already built
477 // the initial and final suspend points.
478 if (!ScopeInfo->NeedsCoroutineSuspends)
481 ScopeInfo->setNeedsCoroutineSuspends(false);
483 auto *Fn = cast<FunctionDecl>(S.CurContext);
484 SourceLocation Loc = Fn->getLocation();
485 // Build the initial suspend point
486 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
488 buildPromiseCall(S, ScopeInfo->CoroutinePromise, Loc, Name, None);
489 if (Suspend.isInvalid())
491 Suspend = buildOperatorCoawaitCall(S, SC, Loc, Suspend.get());
492 if (Suspend.isInvalid())
494 Suspend = S.BuildResolvedCoawaitExpr(Loc, Suspend.get(),
495 /*IsImplicit*/ true);
496 Suspend = S.ActOnFinishFullExpr(Suspend.get());
497 if (Suspend.isInvalid()) {
498 S.Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
499 << ((Name == "initial_suspend") ? 0 : 1);
500 S.Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
503 return cast<Stmt>(Suspend.get());
506 StmtResult InitSuspend = buildSuspends("initial_suspend");
507 if (InitSuspend.isInvalid())
510 StmtResult FinalSuspend = buildSuspends("final_suspend");
511 if (FinalSuspend.isInvalid())
514 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
519 ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
520 if (!actOnCoroutineBodyStart(*this, S, Loc, "co_await")) {
521 CorrectDelayedTyposInExpr(E);
525 if (E->getType()->isPlaceholderType()) {
526 ExprResult R = CheckPlaceholderExpr(E);
527 if (R.isInvalid()) return ExprError();
530 ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
531 if (Lookup.isInvalid())
533 return BuildUnresolvedCoawaitExpr(Loc, E,
534 cast<UnresolvedLookupExpr>(Lookup.get()));
537 ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E,
538 UnresolvedLookupExpr *Lookup) {
539 auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
543 if (E->getType()->isPlaceholderType()) {
544 ExprResult R = CheckPlaceholderExpr(E);
550 auto *Promise = FSI->CoroutinePromise;
551 if (Promise->getType()->isDependentType()) {
553 new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
557 auto *RD = Promise->getType()->getAsCXXRecordDecl();
558 if (lookupMember(*this, "await_transform", RD, Loc)) {
559 ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
562 diag::note_coroutine_promise_implicit_await_transform_required_here)
563 << E->getSourceRange();
568 ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
569 if (Awaitable.isInvalid())
572 return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
575 ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E,
577 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
581 if (E->getType()->isPlaceholderType()) {
582 ExprResult R = CheckPlaceholderExpr(E);
583 if (R.isInvalid()) return ExprError();
587 if (E->getType()->isDependentType()) {
588 Expr *Res = new (Context)
589 CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
593 // If the expression is a temporary, materialize it as an lvalue so that we
594 // can use it multiple times.
595 if (E->getValueKind() == VK_RValue)
596 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
598 // Build the await_ready, await_suspend, await_resume calls.
599 ReadySuspendResumeResult RSS =
600 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
605 new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
606 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
611 ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
612 if (!actOnCoroutineBodyStart(*this, S, Loc, "co_yield")) {
613 CorrectDelayedTyposInExpr(E);
617 // Build yield_value call.
618 ExprResult Awaitable = buildPromiseCall(
619 *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
620 if (Awaitable.isInvalid())
623 // Build 'operator co_await' call.
624 Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
625 if (Awaitable.isInvalid())
628 return BuildCoyieldExpr(Loc, Awaitable.get());
630 ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
631 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
635 if (E->getType()->isPlaceholderType()) {
636 ExprResult R = CheckPlaceholderExpr(E);
637 if (R.isInvalid()) return ExprError();
641 if (E->getType()->isDependentType()) {
642 Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
646 // If the expression is a temporary, materialize it as an lvalue so that we
647 // can use it multiple times.
648 if (E->getValueKind() == VK_RValue)
649 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
651 // Build the await_ready, await_suspend, await_resume calls.
652 ReadySuspendResumeResult RSS =
653 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
657 Expr *Res = new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
658 RSS.Results[2], RSS.OpaqueValue);
663 StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
664 if (!actOnCoroutineBodyStart(*this, S, Loc, "co_return")) {
665 CorrectDelayedTyposInExpr(E);
668 return BuildCoreturnStmt(Loc, E);
671 StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
673 auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
677 if (E && E->getType()->isPlaceholderType() &&
678 !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
679 ExprResult R = CheckPlaceholderExpr(E);
680 if (R.isInvalid()) return StmtError();
684 // FIXME: If the operand is a reference to a variable that's about to go out
685 // of scope, we should treat the operand as an xvalue for this overload
687 VarDecl *Promise = FSI->CoroutinePromise;
689 if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
690 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
692 E = MakeFullDiscardedValueExpr(E).get();
693 PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
698 Expr *PCE = ActOnFinishFullExpr(PC.get()).get();
700 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
704 /// Look up the std::nothrow object.
705 static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
706 NamespaceDecl *Std = S.getStdNamespace();
707 assert(Std && "Should already be diagnosed");
709 LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
710 Sema::LookupOrdinaryName);
711 if (!S.LookupQualifiedName(Result, Std)) {
712 // FIXME: <experimental/coroutine> should have been included already.
713 // If we require it to include <new> then this diagnostic is no longer
715 S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
719 // FIXME: Mark the variable as ODR used. This currently does not work
720 // likely due to the scope at in which this function is called.
721 auto *VD = Result.getAsSingle<VarDecl>();
723 Result.suppressDiagnostics();
724 // We found something weird. Complain about the first thing we found.
725 NamedDecl *Found = *Result.begin();
726 S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
730 ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
737 // Find an appropriate delete for the promise.
738 static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc,
739 QualType PromiseType) {
740 FunctionDecl *OperatorDelete = nullptr;
742 DeclarationName DeleteName =
743 S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
745 auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
746 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
748 if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
751 if (!OperatorDelete) {
752 // Look for a global declaration.
753 const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
754 const bool Overaligned = false;
755 OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
756 Overaligned, DeleteName);
758 S.MarkFunctionReferenced(Loc, OperatorDelete);
759 return OperatorDelete;
763 void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
764 FunctionScopeInfo *Fn = getCurFunction();
765 assert(Fn && Fn->isCoroutine() && "not a coroutine");
767 assert(FD->isInvalidDecl() &&
768 "a null body is only allowed for invalid declarations");
771 // We have a function that uses coroutine keywords, but we failed to build
773 if (!Fn->CoroutinePromise)
774 return FD->setInvalidDecl();
776 if (isa<CoroutineBodyStmt>(Body)) {
777 // Nothing todo. the body is already a transformed coroutine body statement.
781 // Coroutines [stmt.return]p1:
782 // A return statement shall not appear in a coroutine.
783 if (Fn->FirstReturnLoc.isValid()) {
784 assert(Fn->FirstCoroutineStmtLoc.isValid() &&
785 "first coroutine location not set");
786 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
787 Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
788 << Fn->getFirstCoroutineStmtKeyword();
790 CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
791 if (Builder.isInvalid() || !Builder.buildStatements())
792 return FD->setInvalidDecl();
794 // Build body for the coroutine wrapper statement.
795 Body = CoroutineBodyStmt::Create(Context, Builder);
798 CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
799 sema::FunctionScopeInfo &Fn,
801 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
802 IsPromiseDependentType(
803 !Fn.CoroutinePromise ||
804 Fn.CoroutinePromise->getType()->isDependentType()) {
806 if (!IsPromiseDependentType) {
807 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
808 assert(PromiseRecordDecl && "Type should have already been checked");
810 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
813 bool CoroutineStmtBuilder::buildStatements() {
814 assert(this->IsValid && "coroutine already invalid");
815 this->IsValid = makeReturnObject() && makeParamMoves();
816 if (this->IsValid && !IsPromiseDependentType)
817 buildDependentStatements();
818 return this->IsValid;
821 bool CoroutineStmtBuilder::buildDependentStatements() {
822 assert(this->IsValid && "coroutine already invalid");
823 assert(!this->IsPromiseDependentType &&
824 "coroutine cannot have a dependent promise type");
825 this->IsValid = makeOnException() && makeOnFallthrough() &&
826 makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
827 makeNewAndDeleteExpr();
828 return this->IsValid;
831 bool CoroutineStmtBuilder::makePromiseStmt() {
832 // Form a declaration statement for the promise declaration, so that AST
833 // visitors can more easily find it.
834 StmtResult PromiseStmt =
835 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
836 if (PromiseStmt.isInvalid())
839 this->Promise = PromiseStmt.get();
843 bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
844 if (Fn.hasInvalidCoroutineSuspends())
846 this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
847 this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
851 static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
852 CXXRecordDecl *PromiseRecordDecl,
853 FunctionScopeInfo &Fn) {
854 auto Loc = E->getExprLoc();
855 if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
856 auto *Decl = DeclRef->getDecl();
857 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
858 if (Method->isStatic())
861 Loc = Decl->getLocation();
867 diag::err_coroutine_promise_get_return_object_on_allocation_failure)
868 << PromiseRecordDecl;
869 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
870 << Fn.getFirstCoroutineStmtKeyword();
874 bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
875 assert(!IsPromiseDependentType &&
876 "cannot make statement while the promise type is dependent");
878 // [dcl.fct.def.coroutine]/8
879 // The unqualified-id get_return_object_on_allocation_failure is looked up in
880 // the scope of class P by class member access lookup (3.4.5). ...
881 // If an allocation function returns nullptr, ... the coroutine return value
882 // is obtained by a call to ... get_return_object_on_allocation_failure().
885 S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
886 LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
887 if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
891 ExprResult DeclNameExpr =
892 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
893 if (DeclNameExpr.isInvalid())
896 if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
899 ExprResult ReturnObjectOnAllocationFailure =
900 S.ActOnCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
901 if (ReturnObjectOnAllocationFailure.isInvalid())
904 StmtResult ReturnStmt =
905 S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
906 if (ReturnStmt.isInvalid()) {
907 S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
909 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
910 << Fn.getFirstCoroutineStmtKeyword();
914 this->ReturnStmtOnAllocFailure = ReturnStmt.get();
918 bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
919 // Form and check allocation and deallocation calls.
920 assert(!IsPromiseDependentType &&
921 "cannot make statement while the promise type is dependent");
922 QualType PromiseType = Fn.CoroutinePromise->getType();
924 if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
927 const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
929 // FIXME: Add support for stateful allocators.
931 FunctionDecl *OperatorNew = nullptr;
932 FunctionDecl *OperatorDelete = nullptr;
933 FunctionDecl *UnusedResult = nullptr;
934 bool PassAlignment = false;
935 SmallVector<Expr *, 1> PlacementArgs;
937 S.FindAllocationFunctions(Loc, SourceRange(),
938 /*UseGlobal*/ false, PromiseType,
939 /*isArray*/ false, PassAlignment, PlacementArgs,
940 OperatorNew, UnusedResult);
942 bool IsGlobalOverload =
943 OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
944 // If we didn't find a class-local new declaration and non-throwing new
945 // was is required then we need to lookup the non-throwing global operator
947 if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
948 auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
951 PlacementArgs = {StdNoThrow};
952 OperatorNew = nullptr;
953 S.FindAllocationFunctions(Loc, SourceRange(),
954 /*UseGlobal*/ true, PromiseType,
955 /*isArray*/ false, PassAlignment, PlacementArgs,
956 OperatorNew, UnusedResult);
959 assert(OperatorNew && "expected definition of operator new to be found");
961 if (RequiresNoThrowAlloc) {
962 const auto *FT = OperatorNew->getType()->getAs<FunctionProtoType>();
963 if (!FT->isNothrow(S.Context, /*ResultIfDependent*/ false)) {
964 S.Diag(OperatorNew->getLocation(),
965 diag::err_coroutine_promise_new_requires_nothrow)
967 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
973 if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr)
977 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
980 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {});
985 S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
986 if (NewRef.isInvalid())
989 SmallVector<Expr *, 2> NewArgs(1, FrameSize);
990 for (auto Arg : PlacementArgs)
991 NewArgs.push_back(Arg);
994 S.ActOnCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
995 NewExpr = S.ActOnFinishFullExpr(NewExpr.get());
996 if (NewExpr.isInvalid())
1001 QualType OpDeleteQualType = OperatorDelete->getType();
1003 ExprResult DeleteRef =
1004 S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
1005 if (DeleteRef.isInvalid())
1009 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr});
1011 SmallVector<Expr *, 2> DeleteArgs{CoroFree};
1013 // Check if we need to pass the size.
1014 const auto *OpDeleteType =
1015 OpDeleteQualType.getTypePtr()->getAs<FunctionProtoType>();
1016 if (OpDeleteType->getNumParams() > 1)
1017 DeleteArgs.push_back(FrameSize);
1019 ExprResult DeleteExpr =
1020 S.ActOnCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
1021 DeleteExpr = S.ActOnFinishFullExpr(DeleteExpr.get());
1022 if (DeleteExpr.isInvalid())
1025 this->Allocate = NewExpr.get();
1026 this->Deallocate = DeleteExpr.get();
1031 bool CoroutineStmtBuilder::makeOnFallthrough() {
1032 assert(!IsPromiseDependentType &&
1033 "cannot make statement while the promise type is dependent");
1035 // [dcl.fct.def.coroutine]/4
1036 // The unqualified-ids 'return_void' and 'return_value' are looked up in
1037 // the scope of class P. If both are found, the program is ill-formed.
1038 bool HasRVoid, HasRValue;
1039 LookupResult LRVoid =
1040 lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
1041 LookupResult LRValue =
1042 lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
1044 StmtResult Fallthrough;
1045 if (HasRVoid && HasRValue) {
1046 // FIXME Improve this diagnostic
1047 S.Diag(FD.getLocation(),
1048 diag::err_coroutine_promise_incompatible_return_functions)
1049 << PromiseRecordDecl;
1050 S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
1051 diag::note_member_first_declared_here)
1052 << LRVoid.getLookupName();
1053 S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
1054 diag::note_member_first_declared_here)
1055 << LRValue.getLookupName();
1057 } else if (!HasRVoid && !HasRValue) {
1058 // FIXME: The PDTS currently specifies this case as UB, not ill-formed.
1059 // However we still diagnose this as an error since until the PDTS is fixed.
1060 S.Diag(FD.getLocation(),
1061 diag::err_coroutine_promise_requires_return_function)
1062 << PromiseRecordDecl;
1063 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1064 << PromiseRecordDecl;
1066 } else if (HasRVoid) {
1067 // If the unqualified-id return_void is found, flowing off the end of a
1068 // coroutine is equivalent to a co_return with no operand. Otherwise,
1069 // flowing off the end of a coroutine results in undefined behavior.
1070 Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
1071 /*IsImplicit*/false);
1072 Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
1073 if (Fallthrough.isInvalid())
1077 this->OnFallthrough = Fallthrough.get();
1081 bool CoroutineStmtBuilder::makeOnException() {
1082 // Try to form 'p.unhandled_exception();'
1083 assert(!IsPromiseDependentType &&
1084 "cannot make statement while the promise type is dependent");
1086 const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1088 if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
1090 RequireUnhandledException
1091 ? diag::err_coroutine_promise_unhandled_exception_required
1093 warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1094 S.Diag(Loc, DiagID) << PromiseRecordDecl;
1095 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1096 << PromiseRecordDecl;
1097 return !RequireUnhandledException;
1100 // If exceptions are disabled, don't try to build OnException.
1101 if (!S.getLangOpts().CXXExceptions)
1104 ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
1105 "unhandled_exception", None);
1106 UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc);
1107 if (UnhandledException.isInvalid())
1110 // Since the body of the coroutine will be wrapped in try-catch, it will
1111 // be incompatible with SEH __try if present in a function.
1112 if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1113 S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1114 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1115 << Fn.getFirstCoroutineStmtKeyword();
1119 this->OnException = UnhandledException.get();
1123 bool CoroutineStmtBuilder::makeReturnObject() {
1124 // Build implicit 'p.get_return_object()' expression and form initialization
1125 // of return type from it.
1126 ExprResult ReturnObject =
1127 buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
1128 if (ReturnObject.isInvalid())
1131 this->ReturnValue = ReturnObject.get();
1135 static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
1136 if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
1137 auto *MethodDecl = MbrRef->getMethodDecl();
1138 S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
1141 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1142 << Fn.getFirstCoroutineStmtKeyword();
1145 bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1146 assert(!IsPromiseDependentType &&
1147 "cannot make statement while the promise type is dependent");
1148 assert(this->ReturnValue && "ReturnValue must be already formed");
1150 QualType const GroType = this->ReturnValue->getType();
1151 assert(!GroType->isDependentType() &&
1152 "get_return_object type must no longer be dependent");
1154 QualType const FnRetType = FD.getReturnType();
1155 assert(!FnRetType->isDependentType() &&
1156 "get_return_object type must no longer be dependent");
1158 if (FnRetType->isVoidType()) {
1159 ExprResult Res = S.ActOnFinishFullExpr(this->ReturnValue, Loc);
1160 if (Res.isInvalid())
1163 this->ResultDecl = Res.get();
1167 if (GroType->isVoidType()) {
1168 // Trigger a nice error message.
1169 InitializedEntity Entity =
1170 InitializedEntity::InitializeResult(Loc, FnRetType, false);
1171 S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue);
1172 noteMemberDeclaredHere(S, ReturnValue, Fn);
1176 auto *GroDecl = VarDecl::Create(
1177 S.Context, &FD, FD.getLocation(), FD.getLocation(),
1178 &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
1179 S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
1181 S.CheckVariableDeclarationType(GroDecl);
1182 if (GroDecl->isInvalidDecl())
1185 InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
1186 ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType,
1188 if (Res.isInvalid())
1191 Res = S.ActOnFinishFullExpr(Res.get());
1192 if (Res.isInvalid())
1195 if (GroType == FnRetType) {
1196 GroDecl->setNRVOVariable(true);
1199 S.AddInitializerToDecl(GroDecl, Res.get(),
1200 /*DirectInit=*/false);
1202 S.FinalizeDeclaration(GroDecl);
1204 // Form a declaration statement for the return declaration, so that AST
1205 // visitors can more easily find it.
1206 StmtResult GroDeclStmt =
1207 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
1208 if (GroDeclStmt.isInvalid())
1211 this->ResultDecl = GroDeclStmt.get();
1213 ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
1214 if (declRef.isInvalid())
1217 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
1218 if (ReturnStmt.isInvalid()) {
1219 noteMemberDeclaredHere(S, ReturnValue, Fn);
1223 this->ReturnStmt = ReturnStmt.get();
1227 // Create a static_cast\<T&&>(expr).
1228 static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
1231 QualType TargetType = S.BuildReferenceType(
1232 T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());
1233 SourceLocation ExprLoc = E->getLocStart();
1234 TypeSourceInfo *TargetLoc =
1235 S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
1238 .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1239 SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
1243 /// \brief Build a variable declaration for move parameter.
1244 static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
1246 DeclContext *DC = S.CurContext;
1247 IdentifierInfo *II = &S.PP.getIdentifierTable().get(Name);
1248 TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);
1250 VarDecl::Create(S.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1251 Decl->setImplicit();
1255 bool CoroutineStmtBuilder::makeParamMoves() {
1256 for (auto *paramDecl : FD.parameters()) {
1257 auto Ty = paramDecl->getType();
1258 if (Ty->isDependentType())
1261 // No need to copy scalars, llvm will take care of them.
1262 if (Ty->getAsCXXRecordDecl()) {
1263 if (!paramDecl->getIdentifier())
1266 ExprResult ParamRef =
1267 S.BuildDeclRefExpr(paramDecl, paramDecl->getType(),
1268 ExprValueKind::VK_LValue, Loc); // FIXME: scope?
1269 if (ParamRef.isInvalid())
1272 Expr *RCast = castForMoving(S, ParamRef.get());
1274 auto D = buildVarDecl(S, Loc, Ty, paramDecl->getIdentifier()->getName());
1276 S.AddInitializerToDecl(D, RCast, /*DirectInit=*/true);
1278 // Convert decl to a statement.
1279 StmtResult Stmt = S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(D), Loc, Loc);
1280 if (Stmt.isInvalid())
1283 ParamMovesVector.push_back(Stmt.get());
1287 // Convert to ArrayRef in CtorArgs structure that builder inherits from.
1288 ParamMoves = ParamMovesVector;
1292 StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1293 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);