1//===-- SemaCoroutine.cpp - Semantic Analysis for Coroutines --------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ Coroutines.
10//
11// This file contains references to sections of the Coroutines TS, which
12// can be found at http://wg21.link/coroutines.
13//
14//===----------------------------------------------------------------------===//
15
16#include "CoroutineStmtBuilder.h"
17#include "clang/AST/ASTLambda.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/IgnoreExpr.h"
22#include "clang/AST/StmtCXX.h"
23#include "clang/Basic/Builtins.h"
24#include "clang/Basic/TargetInfo.h"
25#include "clang/Lex/Preprocessor.h"
26#include "clang/Sema/DynamicAllocationArgumentsCXX.h"
27#include "clang/Sema/EnterExpressionEvaluationContext.h"
28#include "clang/Sema/Initialization.h"
29#include "clang/Sema/Overload.h"
30#include "clang/Sema/ScopeInfo.h"
31
32using namespace clang;
33using namespace sema;
34
35static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
36 SourceLocation Loc, bool &Res) {
37 DeclarationName DN = S.PP.getIdentifierInfo(Name);
38 LookupResult LR(S, DN, Loc, Sema::LookupMemberName);
39 // Suppress diagnostics when a private member is selected. The same warnings
40 // will be produced again when building the call.
41 LR.suppressDiagnostics();
42 Res = S.LookupQualifiedName(R&: LR, LookupCtx: RD);
43 return LR;
44}
45
46static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
47 SourceLocation Loc) {
48 bool Res;
49 lookupMember(S, Name, RD, Loc, Res);
50 return Res;
51}
52
53/// Look up the std::coroutine_traits<...>::promise_type for the given
54/// function type.
55static QualType lookupPromiseType(Sema &S, const FunctionDecl *FD,
56 SourceLocation KwLoc) {
57 const FunctionProtoType *FnType = FD->getType()->castAs<FunctionProtoType>();
58 const SourceLocation FuncLoc = FD->getLocation();
59
60 ClassTemplateDecl *CoroTraits =
61 S.lookupCoroutineTraits(KwLoc, FuncLoc);
62 if (!CoroTraits)
63 return QualType();
64
65 // Form template argument list for coroutine_traits<R, P1, P2, ...> according
66 // to [dcl.fct.def.coroutine]3
67 TemplateArgumentListInfo Args(KwLoc, KwLoc);
68 auto AddArg = [&](QualType T) {
69 Args.addArgument(Loc: TemplateArgumentLoc(
70 TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, Loc: KwLoc)));
71 };
72 AddArg(FnType->getReturnType());
73 // If the function is a non-static member function, add the type
74 // of the implicit object parameter before the formal parameters.
75 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
76 if (MD->isImplicitObjectMemberFunction()) {
77 // [over.match.funcs]4
78 // For non-static member functions, the type of the implicit object
79 // parameter is
80 // -- "lvalue reference to cv X" for functions declared without a
81 // ref-qualifier or with the & ref-qualifier
82 // -- "rvalue reference to cv X" for functions declared with the &&
83 // ref-qualifier
84 QualType T = MD->getFunctionObjectParameterType();
85 T = FnType->getRefQualifier() == RQ_RValue
86 ? S.Context.getRValueReferenceType(T)
87 : S.Context.getLValueReferenceType(T, /*SpelledAsLValue*/ true);
88 AddArg(T);
89 }
90 }
91 for (QualType T : FnType->getParamTypes())
92 AddArg(T);
93
94 // Build the template-id.
95 QualType CoroTrait = S.CheckTemplateIdType(
96 Keyword: ElaboratedTypeKeyword::None, Template: TemplateName(CoroTraits), TemplateLoc: KwLoc, TemplateArgs&: Args,
97 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
98 if (CoroTrait.isNull())
99 return QualType();
100 if (S.RequireCompleteType(Loc: KwLoc, T: CoroTrait,
101 DiagID: diag::err_coroutine_type_missing_specialization))
102 return QualType();
103
104 auto *RD = CoroTrait->getAsCXXRecordDecl();
105 assert(RD && "specialization of class template is not a class?");
106
107 // Look up the ::promise_type member.
108 LookupResult R(S, &S.PP.getIdentifierTable().get(Name: "promise_type"), KwLoc,
109 Sema::LookupOrdinaryName);
110 S.LookupQualifiedName(R, LookupCtx: RD);
111 auto *Promise = R.getAsSingle<TypeDecl>();
112 if (!Promise) {
113 S.Diag(Loc: FuncLoc,
114 DiagID: diag::err_implied_std_coroutine_traits_promise_type_not_found)
115 << RD;
116 return QualType();
117 }
118
119 NestedNameSpecifier Qualifier(CoroTrait.getTypePtr());
120 QualType PromiseType = S.Context.getTypeDeclType(Keyword: ElaboratedTypeKeyword::None,
121 Qualifier, Decl: Promise);
122 // The promise type is required to be a class type.
123 if (!PromiseType->getAsCXXRecordDecl()) {
124 S.Diag(Loc: FuncLoc,
125 DiagID: diag::err_implied_std_coroutine_traits_promise_type_not_class)
126 << PromiseType;
127 return QualType();
128 }
129 if (S.RequireCompleteType(Loc: FuncLoc, T: PromiseType,
130 DiagID: diag::err_coroutine_promise_type_incomplete))
131 return QualType();
132
133 return PromiseType;
134}
135
136/// Look up the std::coroutine_handle<PromiseType>.
137static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
138 SourceLocation Loc) {
139 if (PromiseType.isNull())
140 return QualType();
141
142 NamespaceDecl *CoroNamespace = S.getStdNamespace();
143 assert(CoroNamespace && "Should already be diagnosed");
144
145 LookupResult Result(S, &S.PP.getIdentifierTable().get(Name: "coroutine_handle"),
146 Loc, Sema::LookupOrdinaryName);
147 if (!S.LookupQualifiedName(R&: Result, LookupCtx: CoroNamespace)) {
148 S.Diag(Loc, DiagID: diag::err_implied_coroutine_type_not_found)
149 << "std::coroutine_handle";
150 return QualType();
151 }
152
153 ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
154 if (!CoroHandle) {
155 Result.suppressDiagnostics();
156 // We found something weird. Complain about the first thing we found.
157 NamedDecl *Found = *Result.begin();
158 S.Diag(Loc: Found->getLocation(), DiagID: diag::err_malformed_std_coroutine_handle);
159 return QualType();
160 }
161
162 // Form template argument list for coroutine_handle<Promise>.
163 TemplateArgumentListInfo Args(Loc, Loc);
164 Args.addArgument(Loc: TemplateArgumentLoc(
165 TemplateArgument(PromiseType),
166 S.Context.getTrivialTypeSourceInfo(T: PromiseType, Loc)));
167
168 // Build the template-id.
169 QualType CoroHandleType = S.CheckTemplateIdType(
170 Keyword: ElaboratedTypeKeyword::None, Template: TemplateName(CoroHandle), TemplateLoc: Loc, TemplateArgs&: Args,
171 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
172 if (CoroHandleType.isNull())
173 return QualType();
174 if (S.RequireCompleteType(Loc, T: CoroHandleType,
175 DiagID: diag::err_coroutine_type_missing_specialization))
176 return QualType();
177
178 return CoroHandleType;
179}
180
181static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
182 StringRef Keyword) {
183 // [expr.await]p2 dictates that 'co_await' and 'co_yield' must be used within
184 // a function body.
185 // FIXME: This also covers [expr.await]p2: "An await-expression shall not
186 // appear in a default argument." But the diagnostic QoI here could be
187 // improved to inform the user that default arguments specifically are not
188 // allowed.
189 auto *FD = dyn_cast<FunctionDecl>(Val: S.CurContext);
190 if (!FD) {
191 S.Diag(Loc, DiagID: isa<ObjCMethodDecl>(Val: S.CurContext)
192 ? diag::err_coroutine_objc_method
193 : diag::err_coroutine_outside_function) << Keyword;
194 return false;
195 }
196
197 // An enumeration for mapping the diagnostic type to the correct diagnostic
198 // selection index.
199 enum InvalidFuncDiag {
200 DiagCtor = 0,
201 DiagDtor,
202 DiagMain,
203 DiagConstexpr,
204 DiagAutoRet,
205 DiagVarargs,
206 DiagConsteval,
207 };
208 bool Diagnosed = false;
209 auto DiagInvalid = [&](InvalidFuncDiag ID) {
210 S.Diag(Loc, DiagID: diag::err_coroutine_invalid_func_context) << ID << Keyword;
211 Diagnosed = true;
212 return false;
213 };
214
215 // Diagnose when a constructor, destructor
216 // or the function 'main' are declared as a coroutine.
217 auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
218 // [class.ctor]p11: "A constructor shall not be a coroutine."
219 if (MD && isa<CXXConstructorDecl>(Val: MD))
220 return DiagInvalid(DiagCtor);
221 // [class.dtor]p17: "A destructor shall not be a coroutine."
222 else if (MD && isa<CXXDestructorDecl>(Val: MD))
223 return DiagInvalid(DiagDtor);
224 // [basic.start.main]p3: "The function main shall not be a coroutine."
225 else if (FD->isMain())
226 return DiagInvalid(DiagMain);
227
228 // Emit a diagnostics for each of the following conditions which is not met.
229 // [expr.const]p2: "An expression e is a core constant expression unless the
230 // evaluation of e [...] would evaluate one of the following expressions:
231 // [...] an await-expression [...] a yield-expression."
232 if (FD->isConstexpr())
233 DiagInvalid(FD->isConsteval() ? DiagConsteval : DiagConstexpr);
234 // [dcl.spec.auto]p15: "A function declared with a return type that uses a
235 // placeholder type shall not be a coroutine."
236 if (FD->getReturnType()->isUndeducedType())
237 DiagInvalid(DiagAutoRet);
238 // [dcl.fct.def.coroutine]p1
239 // The parameter-declaration-clause of the coroutine shall not terminate with
240 // an ellipsis that is not part of a parameter-declaration.
241 if (FD->isVariadic())
242 DiagInvalid(DiagVarargs);
243
244 return !Diagnosed;
245}
246
247/// Build a call to 'operator co_await' if there is a suitable operator for
248/// the given expression.
249ExprResult Sema::BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E,
250 UnresolvedLookupExpr *Lookup) {
251 UnresolvedSet<16> Functions;
252 Functions.append(I: Lookup->decls_begin(), E: Lookup->decls_end());
253 return CreateOverloadedUnaryOp(OpLoc: Loc, Opc: UO_Coawait, Fns: Functions, input: E);
254}
255
256static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
257 SourceLocation Loc, Expr *E) {
258 ExprResult R = SemaRef.BuildOperatorCoawaitLookupExpr(S, Loc);
259 if (R.isInvalid())
260 return ExprError();
261 return SemaRef.BuildOperatorCoawaitCall(Loc, E,
262 Lookup: cast<UnresolvedLookupExpr>(Val: R.get()));
263}
264
265static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
266 SourceLocation Loc) {
267 QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
268 if (CoroHandleType.isNull())
269 return ExprError();
270
271 DeclContext *LookupCtx = S.computeDeclContext(T: CoroHandleType);
272 LookupResult Found(S, &S.PP.getIdentifierTable().get(Name: "from_address"), Loc,
273 Sema::LookupOrdinaryName);
274 if (!S.LookupQualifiedName(R&: Found, LookupCtx)) {
275 S.Diag(Loc, DiagID: diag::err_coroutine_handle_missing_member)
276 << "from_address";
277 return ExprError();
278 }
279
280 Expr *FramePtr =
281 S.BuildBuiltinCallExpr(Loc, Id: Builtin::BI__builtin_coro_frame, CallArgs: {});
282
283 CXXScopeSpec SS;
284 ExprResult FromAddr =
285 S.BuildDeclarationNameExpr(SS, R&: Found, /*NeedsADL=*/false);
286 if (FromAddr.isInvalid())
287 return ExprError();
288
289 return S.BuildCallExpr(S: nullptr, Fn: FromAddr.get(), LParenLoc: Loc, ArgExprs: FramePtr, RParenLoc: Loc);
290}
291
292struct ReadySuspendResumeResult {
293 enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume };
294 Expr *Results[3];
295 OpaqueValueExpr *OpaqueValue;
296 bool IsInvalid;
297};
298
299static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
300 StringRef Name, MultiExprArg Args) {
301 DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
302
303 // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
304 CXXScopeSpec SS;
305 ExprResult Result = S.BuildMemberReferenceExpr(
306 Base, BaseType: Base->getType(), OpLoc: Loc, /*IsPtr=*/IsArrow: false, SS,
307 TemplateKWLoc: SourceLocation(), FirstQualifierInScope: nullptr, NameInfo, /*TemplateArgs=*/nullptr,
308 /*Scope=*/S: nullptr);
309 if (Result.isInvalid())
310 return ExprError();
311
312 auto EndLoc = Args.empty() ? Loc : Args.back()->getEndLoc();
313 return S.BuildCallExpr(S: nullptr, Fn: Result.get(), LParenLoc: Loc, ArgExprs: Args, RParenLoc: EndLoc, ExecConfig: nullptr);
314}
315
316// See if return type is coroutine-handle and if so, invoke builtin coro-resume
317// on its address. This is to enable the support for coroutine-handle
318// returning await_suspend that results in a guaranteed tail call to the target
319// coroutine.
320static Expr *maybeTailCall(Sema &S, QualType RetType, Expr *E,
321 SourceLocation Loc) {
322 if (RetType->isReferenceType())
323 return nullptr;
324 Type const *T = RetType.getTypePtr();
325 if (!T->isClassType() && !T->isStructureType())
326 return nullptr;
327
328 // FIXME: Add convertability check to coroutine_handle<>. Possibly via
329 // EvaluateBinaryTypeTrait(BTT_IsConvertible, ...) which is at the moment
330 // a private function in SemaExprCXX.cpp
331
332 ExprResult AddressExpr = buildMemberCall(S, Base: E, Loc, Name: "address", Args: {});
333 if (AddressExpr.isInvalid())
334 return nullptr;
335
336 Expr *JustAddress = AddressExpr.get();
337
338 // Check that the type of AddressExpr is void*
339 if (!JustAddress->getType().getTypePtr()->isVoidPointerType())
340 S.Diag(Loc: cast<CallExpr>(Val: JustAddress)->getCalleeDecl()->getLocation(),
341 DiagID: diag::warn_coroutine_handle_address_invalid_return_type)
342 << JustAddress->getType();
343
344 // Clean up temporary objects, because the resulting expression
345 // will become the body of await_suspend wrapper.
346 return S.MaybeCreateExprWithCleanups(SubExpr: JustAddress);
347}
348
349/// Build calls to await_ready, await_suspend, and await_resume for a co_await
350/// expression.
351/// The generated AST tries to clean up temporary objects as early as
352/// possible so that they don't live across suspension points if possible.
353/// Having temporary objects living across suspension points unnecessarily can
354/// lead to large frame size, and also lead to memory corruptions if the
355/// coroutine frame is destroyed after coming back from suspension. This is done
356/// by wrapping both the await_ready call and the await_suspend call with
357/// ExprWithCleanups. In the end of this function, we also need to explicitly
358/// set cleanup state so that the CoawaitExpr is also wrapped with an
359/// ExprWithCleanups to clean up the awaiter associated with the co_await
360/// expression.
361static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
362 SourceLocation Loc, Expr *E) {
363 OpaqueValueExpr *Operand = new (S.Context)
364 OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
365
366 // Assume valid until we see otherwise.
367 // Further operations are responsible for setting IsInalid to true.
368 ReadySuspendResumeResult Calls = {.Results: {}, .OpaqueValue: Operand, /*IsInvalid=*/false};
369
370 using ACT = ReadySuspendResumeResult::AwaitCallType;
371
372 auto BuildSubExpr = [&](ACT CallType, StringRef Func,
373 MultiExprArg Arg) -> Expr * {
374 ExprResult Result = buildMemberCall(S, Base: Operand, Loc, Name: Func, Args: Arg);
375 if (Result.isInvalid()) {
376 Calls.IsInvalid = true;
377 return nullptr;
378 }
379 Calls.Results[CallType] = Result.get();
380 return Result.get();
381 };
382
383 CallExpr *AwaitReady =
384 cast_or_null<CallExpr>(Val: BuildSubExpr(ACT::ACT_Ready, "await_ready", {}));
385 if (!AwaitReady)
386 return Calls;
387 if (!AwaitReady->getType()->isDependentType()) {
388 // [expr.await]p3 [...]
389 // — await-ready is the expression e.await_ready(), contextually converted
390 // to bool.
391 ExprResult Conv = S.PerformContextuallyConvertToBool(From: AwaitReady);
392 if (Conv.isInvalid()) {
393 S.Diag(Loc: AwaitReady->getDirectCallee()->getBeginLoc(),
394 DiagID: diag::note_await_ready_no_bool_conversion);
395 S.Diag(Loc, DiagID: diag::note_coroutine_promise_call_implicitly_required)
396 << AwaitReady->getDirectCallee() << E->getSourceRange();
397 Calls.IsInvalid = true;
398 } else
399 Calls.Results[ACT::ACT_Ready] = S.MaybeCreateExprWithCleanups(SubExpr: Conv.get());
400 }
401
402 ExprResult CoroHandleRes =
403 buildCoroutineHandle(S, PromiseType: CoroPromise->getType(), Loc);
404 if (CoroHandleRes.isInvalid()) {
405 Calls.IsInvalid = true;
406 return Calls;
407 }
408 Expr *CoroHandle = CoroHandleRes.get();
409 CallExpr *AwaitSuspend = cast_or_null<CallExpr>(
410 Val: BuildSubExpr(ACT::ACT_Suspend, "await_suspend", CoroHandle));
411 if (!AwaitSuspend)
412 return Calls;
413 if (!AwaitSuspend->getType()->isDependentType()) {
414 // [expr.await]p3 [...]
415 // - await-suspend is the expression e.await_suspend(h), which shall be
416 // a prvalue of type void, bool, or std::coroutine_handle<Z> for some
417 // type Z.
418 QualType RetType = AwaitSuspend->getCallReturnType(Ctx: S.Context);
419
420 // Support for coroutine_handle returning await_suspend.
421 if (Expr *TailCallSuspend =
422 maybeTailCall(S, RetType, E: AwaitSuspend, Loc))
423 // Note that we don't wrap the expression with ExprWithCleanups here
424 // because that might interfere with tailcall contract (e.g. inserting
425 // clean up instructions in-between tailcall and return). Instead
426 // ExprWithCleanups is wrapped within maybeTailCall() prior to the resume
427 // call.
428 Calls.Results[ACT::ACT_Suspend] = TailCallSuspend;
429 else {
430 // non-class prvalues always have cv-unqualified types
431 if (RetType->isReferenceType() ||
432 (!RetType->isBooleanType() && !RetType->isVoidType())) {
433 S.Diag(Loc: AwaitSuspend->getCalleeDecl()->getLocation(),
434 DiagID: diag::err_await_suspend_invalid_return_type)
435 << RetType;
436 S.Diag(Loc, DiagID: diag::note_coroutine_promise_call_implicitly_required)
437 << AwaitSuspend->getDirectCallee();
438 Calls.IsInvalid = true;
439 } else
440 Calls.Results[ACT::ACT_Suspend] =
441 S.MaybeCreateExprWithCleanups(SubExpr: AwaitSuspend);
442 }
443 }
444
445 BuildSubExpr(ACT::ACT_Resume, "await_resume", {});
446
447 // Make sure the awaiter object gets a chance to be cleaned up.
448 S.Cleanup.setExprNeedsCleanups(true);
449
450 return Calls;
451}
452
453static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
454 SourceLocation Loc, StringRef Name,
455 MultiExprArg Args) {
456
457 // Form a reference to the promise.
458 ExprResult PromiseRef = S.BuildDeclRefExpr(
459 D: Promise, Ty: Promise->getType().getNonReferenceType(), VK: VK_LValue, Loc);
460 if (PromiseRef.isInvalid())
461 return ExprError();
462
463 return buildMemberCall(S, Base: PromiseRef.get(), Loc, Name, Args);
464}
465
466static void markCoroutineParametersReferenced(FunctionDecl &FD) {
467 for (auto *PD : FD.parameters())
468 if (!PD->getType()->isDependentType())
469 PD->setReferenced();
470}
471
472VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
473 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
474 auto *FD = cast<FunctionDecl>(Val: CurContext);
475 bool IsThisDependentType = [&] {
476 if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(Val: FD))
477 return MD->isImplicitObjectMemberFunction() &&
478 MD->getThisType()->isDependentType();
479 return false;
480 }();
481
482 QualType T = FD->getType()->isDependentType() || IsThisDependentType
483 ? Context.DependentTy
484 : lookupPromiseType(S&: *this, FD, KwLoc: Loc);
485 if (T.isNull())
486 return nullptr;
487
488 auto *VD = VarDecl::Create(C&: Context, DC: FD, StartLoc: FD->getLocation(), IdLoc: FD->getLocation(),
489 Id: &PP.getIdentifierTable().get(Name: "__promise"), T,
490 TInfo: Context.getTrivialTypeSourceInfo(T, Loc), S: SC_None);
491 VD->setImplicit();
492 CheckVariableDeclarationType(NewVD: VD);
493 if (VD->isInvalidDecl())
494 return nullptr;
495
496 auto *ScopeInfo = getCurFunction();
497
498 // Build a list of arguments, based on the coroutine function's arguments,
499 // that if present will be passed to the promise type's constructor.
500 llvm::SmallVector<Expr *, 4> CtorArgExprs;
501
502 // Add implicit object parameter.
503 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
504 if (MD->isImplicitObjectMemberFunction() && !isLambdaCallOperator(MD)) {
505 ExprResult ThisExpr = ActOnCXXThis(Loc);
506 if (ThisExpr.isInvalid())
507 return nullptr;
508 ThisExpr = CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: ThisExpr.get());
509 if (ThisExpr.isInvalid())
510 return nullptr;
511 CtorArgExprs.push_back(Elt: ThisExpr.get());
512 }
513 }
514
515 // Add the coroutine function's parameters.
516 auto &Moves = ScopeInfo->CoroutineParameterMoves;
517 for (auto *PD : FD->parameters()) {
518 if (PD->getType()->isDependentType())
519 continue;
520
521 auto RefExpr = ExprEmpty();
522 auto Move = Moves.find(Key: PD);
523 assert(Move != Moves.end() &&
524 "Coroutine function parameter not inserted into move map");
525 // If a reference to the function parameter exists in the coroutine
526 // frame, use that reference.
527 auto *MoveDecl =
528 cast<VarDecl>(Val: cast<DeclStmt>(Val: Move->second)->getSingleDecl());
529 RefExpr =
530 BuildDeclRefExpr(D: MoveDecl, Ty: MoveDecl->getType().getNonReferenceType(),
531 VK: ExprValueKind::VK_LValue, Loc: FD->getLocation());
532 if (RefExpr.isInvalid())
533 return nullptr;
534 CtorArgExprs.push_back(Elt: RefExpr.get());
535 }
536
537 // If we have a non-zero number of constructor arguments, try to use them.
538 // Otherwise, fall back to the promise type's default constructor.
539 if (!CtorArgExprs.empty()) {
540 // Create an initialization sequence for the promise type using the
541 // constructor arguments, wrapped in a parenthesized list expression.
542 Expr *PLE = ParenListExpr::Create(Ctx: Context, LParenLoc: FD->getLocation(),
543 Exprs: CtorArgExprs, RParenLoc: FD->getLocation());
544 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: VD);
545 InitializationKind Kind = InitializationKind::CreateForInit(
546 Loc: VD->getLocation(), /*DirectInit=*/true, Init: PLE);
547 InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs,
548 /*TopLevelOfInitList=*/false,
549 /*TreatUnavailableAsInvalid=*/false);
550
551 // [dcl.fct.def.coroutine]5.7
552 // promise-constructor-arguments is determined as follows: overload
553 // resolution is performed on a promise constructor call created by
554 // assembling an argument list q_1 ... q_n . If a viable constructor is
555 // found ([over.match.viable]), then promise-constructor-arguments is ( q_1
556 // , ..., q_n ), otherwise promise-constructor-arguments is empty.
557 if (InitSeq) {
558 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: CtorArgExprs);
559 if (Result.isInvalid()) {
560 VD->setInvalidDecl();
561 } else if (Result.get()) {
562 VD->setInit(MaybeCreateExprWithCleanups(SubExpr: Result.get()));
563 VD->setInitStyle(VarDecl::CallInit);
564 CheckCompleteVariableDeclaration(VD);
565 // The constructor is selected with the coroutine parameter copies as
566 // arguments. Mark the original parameters as referenced for
567 // -Wunused-parameter.
568 markCoroutineParametersReferenced(FD&: *FD);
569 }
570 } else
571 ActOnUninitializedDecl(dcl: VD);
572 } else
573 ActOnUninitializedDecl(dcl: VD);
574
575 FD->addDecl(D: VD);
576 return VD;
577}
578
579/// Check that this is a context in which a coroutine suspension can appear.
580static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
581 StringRef Keyword,
582 bool IsImplicit = false) {
583 if (!isValidCoroutineContext(S, Loc, Keyword))
584 return nullptr;
585
586 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
587
588 auto *ScopeInfo = S.getCurFunction();
589 assert(ScopeInfo && "missing function scope for function");
590
591 if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
592 ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
593
594 if (ScopeInfo->CoroutinePromise)
595 return ScopeInfo;
596
597 if (!S.buildCoroutineParameterMoves(Loc))
598 return nullptr;
599
600 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
601 if (!ScopeInfo->CoroutinePromise)
602 return nullptr;
603
604 return ScopeInfo;
605}
606
607/// Recursively check \p E and all its children to see if any call target
608/// (including constructor call) is declared noexcept. Also any value returned
609/// from the call has a noexcept destructor.
610static void checkNoThrow(Sema &S, const Stmt *E,
611 llvm::SmallPtrSetImpl<const Decl *> &ThrowingDecls) {
612 auto checkDeclNoexcept = [&](const Decl *D, bool IsDtor = false) {
613 // In the case of dtor, the call to dtor is implicit and hence we should
614 // pass nullptr to canCalleeThrow.
615 if (Sema::canCalleeThrow(S, E: IsDtor ? nullptr : cast<Expr>(Val: E), D)) {
616 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
617 // co_await promise.final_suspend() could end up calling
618 // __builtin_coro_resume for symmetric transfer if await_suspend()
619 // returns a handle. In that case, even __builtin_coro_resume is not
620 // declared as noexcept and may throw, it does not throw _into_ the
621 // coroutine that just suspended, but rather throws back out from
622 // whoever called coroutine_handle::resume(), hence we claim that
623 // logically it does not throw.
624 if (FD->getBuiltinID() == Builtin::BI__builtin_coro_resume)
625 return;
626 }
627 if (ThrowingDecls.empty()) {
628 // [dcl.fct.def.coroutine]p15
629 // The expression co_await promise.final_suspend() shall not be
630 // potentially-throwing ([except.spec]).
631 //
632 // First time seeing an error, emit the error message.
633 S.Diag(Loc: cast<FunctionDecl>(Val: S.CurContext)->getLocation(),
634 DiagID: diag::err_coroutine_promise_final_suspend_requires_nothrow);
635 }
636 ThrowingDecls.insert(Ptr: D);
637 }
638 };
639
640 if (auto *CE = dyn_cast<CXXConstructExpr>(Val: E)) {
641 CXXConstructorDecl *Ctor = CE->getConstructor();
642 checkDeclNoexcept(Ctor);
643 // Check the corresponding destructor of the constructor.
644 checkDeclNoexcept(Ctor->getParent()->getDestructor(), /*IsDtor=*/true);
645 } else if (auto *CE = dyn_cast<CallExpr>(Val: E)) {
646 if (CE->isTypeDependent())
647 return;
648
649 checkDeclNoexcept(CE->getCalleeDecl());
650 QualType ReturnType = CE->getCallReturnType(Ctx: S.getASTContext());
651 // Check the destructor of the call return type, if any.
652 if (ReturnType.isDestructedType() ==
653 QualType::DestructionKind::DK_cxx_destructor) {
654 const auto *T =
655 cast<RecordType>(Val: ReturnType.getCanonicalType().getTypePtr());
656 checkDeclNoexcept(
657 cast<CXXRecordDecl>(Val: T->getDecl())->getDefinition()->getDestructor(),
658 /*IsDtor=*/true);
659 }
660 } else
661 for (const auto *Child : E->children()) {
662 if (!Child)
663 continue;
664 checkNoThrow(S, E: Child, ThrowingDecls);
665 }
666}
667
668bool Sema::checkFinalSuspendNoThrow(const Stmt *FinalSuspend) {
669 llvm::SmallPtrSet<const Decl *, 4> ThrowingDecls;
670 // We first collect all declarations that should not throw but not declared
671 // 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 same
673 // declaration, and also provide a deterministic order for the messages.
674 checkNoThrow(S&: *this, E: FinalSuspend, ThrowingDecls);
675 auto SortedDecls = llvm::SmallVector<const Decl *, 4>{ThrowingDecls.begin(),
676 ThrowingDecls.end()};
677 sort(C&: SortedDecls, Comp: [](const Decl *A, const Decl *B) {
678 return A->getEndLoc() < B->getEndLoc();
679 });
680 for (const auto *D : SortedDecls) {
681 Diag(Loc: D->getEndLoc(), DiagID: diag::note_coroutine_function_declare_noexcept);
682 }
683 return ThrowingDecls.empty();
684}
685
686// [stmt.return.coroutine]p1:
687// A coroutine shall not enclose a return statement ([stmt.return]).
688static void checkReturnStmtInCoroutine(Sema &S, FunctionScopeInfo *FSI) {
689 assert(FSI && "FunctionScopeInfo is null");
690 assert(FSI->FirstCoroutineStmtLoc.isValid() &&
691 "first coroutine location not set");
692 if (FSI->FirstReturnLoc.isInvalid())
693 return;
694 S.Diag(Loc: FSI->FirstReturnLoc, DiagID: diag::err_return_in_coroutine);
695 S.Diag(Loc: FSI->FirstCoroutineStmtLoc, DiagID: diag::note_declared_coroutine_here)
696 << FSI->getFirstCoroutineStmtKeyword();
697}
698
699bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc,
700 StringRef Keyword) {
701 // Ignore previous expr evaluation contexts.
702 EnterExpressionEvaluationContextForFunction PotentiallyEvaluated(
703 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated,
704 dyn_cast_or_null<FunctionDecl>(Val: CurContext));
705
706 if (!checkCoroutineContext(S&: *this, Loc: KWLoc, Keyword))
707 return false;
708
709 // Support for coroutines is not stable on 32 bits windows
710 // Warn about it.
711 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
712 Context.getTargetInfo().getTriple().isX86_32())
713 Diag(Loc: KWLoc, DiagID: diag::warn_coroutines_x86_windows);
714
715 auto *ScopeInfo = getCurFunction();
716 assert(ScopeInfo->CoroutinePromise);
717
718 // Avoid duplicate errors, report only on first keyword.
719 if (ScopeInfo->FirstCoroutineStmtLoc == KWLoc)
720 checkReturnStmtInCoroutine(S&: *this, FSI: ScopeInfo);
721
722 // If we have existing coroutine statements then we have already built
723 // the initial and final suspend points.
724 if (!ScopeInfo->NeedsCoroutineSuspends)
725 return true;
726
727 ScopeInfo->setNeedsCoroutineSuspends(false);
728
729 auto *Fn = cast<FunctionDecl>(Val: CurContext);
730 SourceLocation Loc = Fn->getLocation();
731 // Build the initial suspend point
732 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
733 ExprResult Operand =
734 buildPromiseCall(S&: *this, Promise: ScopeInfo->CoroutinePromise, Loc, Name, Args: {});
735 if (Operand.isInvalid())
736 return StmtError();
737 ExprResult Suspend =
738 buildOperatorCoawaitCall(SemaRef&: *this, S: SC, Loc, E: Operand.get());
739 if (Suspend.isInvalid())
740 return StmtError();
741 Suspend = BuildResolvedCoawaitExpr(KwLoc: Loc, Operand: Operand.get(), Awaiter: Suspend.get(),
742 /*IsImplicit*/ true);
743 Suspend = ActOnFinishFullExpr(Expr: Suspend.get(), /*DiscardedValue*/ false);
744 if (Suspend.isInvalid()) {
745 Diag(Loc, DiagID: diag::note_coroutine_promise_suspend_implicitly_required)
746 << ((Name == "initial_suspend") ? 0 : 1);
747 Diag(Loc: KWLoc, DiagID: diag::note_declared_coroutine_here) << Keyword;
748 return StmtError();
749 }
750 return cast<Stmt>(Val: Suspend.get());
751 };
752
753 StmtResult InitSuspend = buildSuspends("initial_suspend");
754 if (InitSuspend.isInvalid())
755 return true;
756
757 StmtResult FinalSuspend = buildSuspends("final_suspend");
758 if (FinalSuspend.isInvalid() || !checkFinalSuspendNoThrow(FinalSuspend: FinalSuspend.get()))
759 return true;
760
761 ScopeInfo->setCoroutineSuspends(Initial: InitSuspend.get(), Final: FinalSuspend.get());
762
763 return true;
764}
765
766// Recursively walks up the scope hierarchy until either a 'catch' or a function
767// scope is found, whichever comes first.
768static bool isWithinCatchScope(Scope *S) {
769 // 'co_await' and 'co_yield' keywords are disallowed within catch blocks, but
770 // lambdas that use 'co_await' are allowed. The loop below ends when a
771 // function scope is found in order to ensure the following behavior:
772 //
773 // void foo() { // <- function scope
774 // try { //
775 // co_await x; // <- 'co_await' is OK within a function scope
776 // } catch { // <- catch scope
777 // co_await x; // <- 'co_await' is not OK within a catch scope
778 // []() { // <- function scope
779 // co_await x; // <- 'co_await' is OK within a function scope
780 // }();
781 // }
782 // }
783 while (S && !S->isFunctionScope()) {
784 if (S->isCatchScope())
785 return true;
786 S = S->getParent();
787 }
788 return false;
789}
790
791// [expr.await]p2, emphasis added: "An await-expression shall appear only in
792// a *potentially evaluated* expression within the compound-statement of a
793// function-body *outside of a handler* [...] A context within a function
794// where an await-expression can appear is called a suspension context of the
795// function."
796static bool checkSuspensionContext(Sema &S, SourceLocation Loc,
797 StringRef Keyword) {
798 // First emphasis of [expr.await]p2: must be a potentially evaluated context.
799 // That is, 'co_await' and 'co_yield' cannot appear in subexpressions of
800 // \c sizeof.
801 const auto ExprContext = S.currentEvaluationContext().ExprContext;
802 const bool BadContext =
803 S.isUnevaluatedContext() ||
804 (ExprContext != Sema::ExpressionEvaluationContextRecord::EK_Other &&
805 ExprContext != Sema::ExpressionEvaluationContextRecord::EK_VariableInit);
806 if (BadContext) {
807 S.Diag(Loc, DiagID: diag::err_coroutine_unevaluated_context) << Keyword;
808 return false;
809 }
810
811 // Second emphasis of [expr.await]p2: must be outside of an exception handler.
812 if (isWithinCatchScope(S: S.getCurScope())) {
813 S.Diag(Loc, DiagID: diag::err_coroutine_within_handler) << Keyword;
814 return false;
815 }
816 return true;
817}
818
819ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
820 if (!checkSuspensionContext(S&: *this, Loc, Keyword: "co_await"))
821 return ExprError();
822
823 if (!ActOnCoroutineBodyStart(SC: S, KWLoc: Loc, Keyword: "co_await")) {
824 return ExprError();
825 }
826
827 if (E->hasPlaceholderType()) {
828 ExprResult R = CheckPlaceholderExpr(E);
829 if (R.isInvalid()) return ExprError();
830 E = R.get();
831 }
832
833 ExprResult Lookup = BuildOperatorCoawaitLookupExpr(S, Loc);
834 if (Lookup.isInvalid())
835 return ExprError();
836 return BuildUnresolvedCoawaitExpr(KwLoc: Loc, Operand: E,
837 Lookup: cast<UnresolvedLookupExpr>(Val: Lookup.get()));
838}
839
840ExprResult Sema::BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc) {
841 DeclarationName OpName =
842 Context.DeclarationNames.getCXXOperatorName(Op: OO_Coawait);
843 LookupResult Operators(*this, OpName, SourceLocation(),
844 Sema::LookupOperatorName);
845 LookupName(R&: Operators, S);
846
847 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
848 const auto &Functions = Operators.asUnresolvedSet();
849 Expr *CoawaitOp = UnresolvedLookupExpr::Create(
850 Context, /*NamingClass*/ nullptr, QualifierLoc: NestedNameSpecifierLoc(),
851 NameInfo: DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, Begin: Functions.begin(),
852 End: Functions.end(), /*KnownDependent=*/false,
853 /*KnownInstantiationDependent=*/false);
854 assert(CoawaitOp);
855 return CoawaitOp;
856}
857
858static bool isAttributedCoroAwaitElidable(const QualType &QT) {
859 auto *Record = QT->getAsCXXRecordDecl();
860 return Record && Record->hasAttr<CoroAwaitElidableAttr>();
861}
862
863static void applySafeElideContext(Expr *Operand) {
864 // Strip both implicit nodes and parentheses to find the underlying CallExpr.
865 // The AST may have these in either order, so we apply both transformations
866 // iteratively until reaching a fixed point.
867 auto *Call = dyn_cast<CallExpr>(Val: IgnoreExprNodes(
868 E: Operand, Fns&: IgnoreImplicitSingleStep, Fns&: IgnoreParensSingleStep));
869 if (!Call || !Call->isPRValue())
870 return;
871
872 if (!isAttributedCoroAwaitElidable(QT: Call->getType()))
873 return;
874
875 Call->setCoroElideSafe();
876
877 // Check parameter
878 auto *Fn = llvm::dyn_cast_if_present<FunctionDecl>(Val: Call->getCalleeDecl());
879 if (!Fn)
880 return;
881
882 size_t ParmIdx = 0;
883 for (ParmVarDecl *PD : Fn->parameters()) {
884 if (PD->hasAttr<CoroAwaitElidableArgumentAttr>())
885 applySafeElideContext(Operand: Call->getArg(Arg: ParmIdx));
886
887 ParmIdx++;
888 }
889}
890
891// Attempts to resolve and build a CoawaitExpr from "raw" inputs, bailing out to
892// DependentCoawaitExpr if needed.
893ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *Operand,
894 UnresolvedLookupExpr *Lookup) {
895 auto *FSI = checkCoroutineContext(S&: *this, Loc, Keyword: "co_await");
896 if (!FSI)
897 return ExprError();
898
899 if (Operand->hasPlaceholderType()) {
900 ExprResult R = CheckPlaceholderExpr(E: Operand);
901 if (R.isInvalid())
902 return ExprError();
903 Operand = R.get();
904 }
905
906 auto *Promise = FSI->CoroutinePromise;
907 if (Promise->getType()->isDependentType()) {
908 Expr *Res = new (Context)
909 DependentCoawaitExpr(Loc, Context.DependentTy, Operand, Lookup);
910 return Res;
911 }
912
913 auto *RD = Promise->getType()->getAsCXXRecordDecl();
914
915 bool CurFnAwaitElidable = isAttributedCoroAwaitElidable(
916 QT: getCurFunctionDecl(/*AllowLambda=*/true)->getReturnType());
917
918 if (CurFnAwaitElidable)
919 applySafeElideContext(Operand);
920
921 Expr *Transformed = Operand;
922 if (lookupMember(S&: *this, Name: "await_transform", RD, Loc)) {
923 ExprResult R =
924 buildPromiseCall(S&: *this, Promise, Loc, Name: "await_transform", Args: Operand);
925 if (R.isInvalid()) {
926 Diag(Loc,
927 DiagID: diag::note_coroutine_promise_implicit_await_transform_required_here)
928 << Operand->getSourceRange();
929 return ExprError();
930 }
931 Transformed = R.get();
932 }
933 ExprResult Awaiter = BuildOperatorCoawaitCall(Loc, E: Transformed, Lookup);
934 if (Awaiter.isInvalid())
935 return ExprError();
936
937 return BuildResolvedCoawaitExpr(KwLoc: Loc, Operand, Awaiter: Awaiter.get());
938}
939
940ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *Operand,
941 Expr *Awaiter, bool IsImplicit) {
942 auto *Coroutine = checkCoroutineContext(S&: *this, Loc, Keyword: "co_await", IsImplicit);
943 if (!Coroutine)
944 return ExprError();
945
946 if (Awaiter->hasPlaceholderType()) {
947 ExprResult R = CheckPlaceholderExpr(E: Awaiter);
948 if (R.isInvalid()) return ExprError();
949 Awaiter = R.get();
950 }
951
952 if (Awaiter->getType()->isDependentType()) {
953 Expr *Res = new (Context)
954 CoawaitExpr(Loc, Context.DependentTy, Operand, Awaiter, IsImplicit);
955 return Res;
956 }
957
958 // If the expression is a temporary, materialize it as an lvalue so that we
959 // can use it multiple times.
960 if (Awaiter->isPRValue())
961 Awaiter = CreateMaterializeTemporaryExpr(T: Awaiter->getType(), Temporary: Awaiter, BoundToLvalueReference: true);
962
963 // The location of the `co_await` token cannot be used when constructing
964 // the member call expressions since it's before the location of `Expr`, which
965 // is used as the start of the member call expression.
966 SourceLocation CallLoc = Awaiter->getExprLoc();
967
968 // Build the await_ready, await_suspend, await_resume calls.
969 ReadySuspendResumeResult RSS =
970 buildCoawaitCalls(S&: *this, CoroPromise: Coroutine->CoroutinePromise, Loc: CallLoc, E: Awaiter);
971 if (RSS.IsInvalid)
972 return ExprError();
973
974 Expr *Res = new (Context)
975 CoawaitExpr(Loc, Operand, Awaiter, RSS.Results[0], RSS.Results[1],
976 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
977
978 return Res;
979}
980
981ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
982 if (!checkSuspensionContext(S&: *this, Loc, Keyword: "co_yield"))
983 return ExprError();
984
985 if (!ActOnCoroutineBodyStart(SC: S, KWLoc: Loc, Keyword: "co_yield")) {
986 return ExprError();
987 }
988
989 // Build yield_value call.
990 ExprResult Awaitable = buildPromiseCall(
991 S&: *this, Promise: getCurFunction()->CoroutinePromise, Loc, Name: "yield_value", Args: E);
992 if (Awaitable.isInvalid())
993 return ExprError();
994
995 // Build 'operator co_await' call.
996 Awaitable = buildOperatorCoawaitCall(SemaRef&: *this, S, Loc, E: Awaitable.get());
997 if (Awaitable.isInvalid())
998 return ExprError();
999
1000 return BuildCoyieldExpr(KwLoc: Loc, E: Awaitable.get());
1001}
1002ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
1003 auto *Coroutine = checkCoroutineContext(S&: *this, Loc, Keyword: "co_yield");
1004 if (!Coroutine)
1005 return ExprError();
1006
1007 if (E->hasPlaceholderType()) {
1008 ExprResult R = CheckPlaceholderExpr(E);
1009 if (R.isInvalid()) return ExprError();
1010 E = R.get();
1011 }
1012
1013 Expr *Operand = E;
1014
1015 if (E->getType()->isDependentType()) {
1016 Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, Operand, E);
1017 return Res;
1018 }
1019
1020 // If the expression is a temporary, materialize it as an lvalue so that we
1021 // can use it multiple times.
1022 if (E->isPRValue())
1023 E = CreateMaterializeTemporaryExpr(T: E->getType(), Temporary: E, BoundToLvalueReference: true);
1024
1025 // Build the await_ready, await_suspend, await_resume calls.
1026 ReadySuspendResumeResult RSS = buildCoawaitCalls(
1027 S&: *this, CoroPromise: Coroutine->CoroutinePromise, Loc, E);
1028 if (RSS.IsInvalid)
1029 return ExprError();
1030
1031 Expr *Res =
1032 new (Context) CoyieldExpr(Loc, Operand, E, RSS.Results[0], RSS.Results[1],
1033 RSS.Results[2], RSS.OpaqueValue);
1034
1035 return Res;
1036}
1037
1038StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
1039 if (!ActOnCoroutineBodyStart(SC: S, KWLoc: Loc, Keyword: "co_return")) {
1040 return StmtError();
1041 }
1042 return BuildCoreturnStmt(KwLoc: Loc, E);
1043}
1044
1045StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
1046 bool IsImplicit) {
1047 auto *FSI = checkCoroutineContext(S&: *this, Loc, Keyword: "co_return", IsImplicit);
1048 if (!FSI)
1049 return StmtError();
1050
1051 if (E && E->hasPlaceholderType() &&
1052 !E->hasPlaceholderType(K: BuiltinType::Overload)) {
1053 ExprResult R = CheckPlaceholderExpr(E);
1054 if (R.isInvalid()) return StmtError();
1055 E = R.get();
1056 }
1057
1058 VarDecl *Promise = FSI->CoroutinePromise;
1059 ExprResult PC;
1060 if (E && (isa<InitListExpr>(Val: E) || !E->getType()->isVoidType())) {
1061 getNamedReturnInfo(E, Mode: SimplerImplicitMoveMode::ForceOn);
1062 PC = buildPromiseCall(S&: *this, Promise, Loc, Name: "return_value", Args: E);
1063 } else {
1064 E = MakeFullDiscardedValueExpr(Arg: E).get();
1065 PC = buildPromiseCall(S&: *this, Promise, Loc, Name: "return_void", Args: {});
1066 }
1067 if (PC.isInvalid())
1068 return StmtError();
1069
1070 Expr *PCE = ActOnFinishFullExpr(Expr: PC.get(), /*DiscardedValue*/ false).get();
1071
1072 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
1073 return Res;
1074}
1075
1076/// Look up the std::nothrow object.
1077static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
1078 NamespaceDecl *Std = S.getStdNamespace();
1079 assert(Std && "Should already be diagnosed");
1080
1081 LookupResult Result(S, &S.PP.getIdentifierTable().get(Name: "nothrow"), Loc,
1082 Sema::LookupOrdinaryName);
1083 if (!S.LookupQualifiedName(R&: Result, LookupCtx: Std)) {
1084 // <coroutine> is not requred to include <new>, so we couldn't omit
1085 // the check here.
1086 S.Diag(Loc, DiagID: diag::err_implicit_coroutine_std_nothrow_type_not_found);
1087 return nullptr;
1088 }
1089
1090 auto *VD = Result.getAsSingle<VarDecl>();
1091 if (!VD) {
1092 Result.suppressDiagnostics();
1093 // We found something weird. Complain about the first thing we found.
1094 NamedDecl *Found = *Result.begin();
1095 S.Diag(Loc: Found->getLocation(), DiagID: diag::err_malformed_std_nothrow);
1096 return nullptr;
1097 }
1098
1099 ExprResult DR = S.BuildDeclRefExpr(D: VD, Ty: VD->getType(), VK: VK_LValue, Loc);
1100 if (DR.isInvalid())
1101 return nullptr;
1102
1103 return DR.get();
1104}
1105
1106static TypeSourceInfo *getTypeSourceInfoForStdAlignValT(Sema &S,
1107 SourceLocation Loc) {
1108 EnumDecl *StdAlignValDecl = S.getStdAlignValT();
1109 CanQualType StdAlignValT = S.Context.getCanonicalTagType(TD: StdAlignValDecl);
1110 return S.Context.getTrivialTypeSourceInfo(T: StdAlignValT);
1111}
1112
1113// When searching for custom allocators on the PromiseType we want to
1114// warn that we will ignore type aware allocators.
1115static bool DiagnoseTypeAwareAllocators(Sema &S, SourceLocation Loc,
1116 unsigned DiagnosticID,
1117 DeclarationName Name,
1118 QualType PromiseType) {
1119 assert(PromiseType->isRecordType());
1120
1121 LookupResult R(S, Name, Loc, Sema::LookupOrdinaryName);
1122 S.LookupQualifiedName(R, LookupCtx: PromiseType->getAsCXXRecordDecl());
1123 bool HaveIssuedWarning = false;
1124 for (auto Decl : R) {
1125 if (!Decl->getUnderlyingDecl()
1126 ->getAsFunction()
1127 ->isTypeAwareOperatorNewOrDelete())
1128 continue;
1129 if (!HaveIssuedWarning) {
1130 S.Diag(Loc, DiagID: DiagnosticID) << Name;
1131 HaveIssuedWarning = true;
1132 }
1133 S.Diag(Loc: Decl->getLocation(), DiagID: diag::note_type_aware_operator_declared)
1134 << /* isTypeAware=*/1 << Decl << Decl->getDeclContext();
1135 }
1136 R.suppressDiagnostics();
1137 return HaveIssuedWarning;
1138}
1139
1140// Find an appropriate delete for the promise.
1141static bool findDeleteForPromise(Sema &S, SourceLocation Loc, QualType PromiseType,
1142 FunctionDecl *&OperatorDelete) {
1143 DeclarationName DeleteName =
1144 S.Context.DeclarationNames.getCXXOperatorName(Op: OO_Delete);
1145 DiagnoseTypeAwareAllocators(S, Loc,
1146 DiagnosticID: diag::warn_coroutine_type_aware_allocator_ignored,
1147 Name: DeleteName, PromiseType);
1148 auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
1149 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
1150
1151 const bool Overaligned = S.getLangOpts().CoroAlignedAllocation;
1152
1153 // [dcl.fct.def.coroutine]p12
1154 // The deallocation function's name is looked up by searching for it in the
1155 // scope of the promise type. If nothing is found, a search is performed in
1156 // the global scope.
1157 ImplicitDeallocationParameters IDP = {
1158 alignedAllocationModeFromBool(IsAligned: Overaligned), SizedDeallocationMode::Yes};
1159 if (S.FindDeallocationFunction(StartLoc: Loc, RD: PointeeRD, Name: DeleteName, Operator&: OperatorDelete,
1160 IDP, /*Diagnose=*/true))
1161 return false;
1162
1163 // [dcl.fct.def.coroutine]p12
1164 // If both a usual deallocation function with only a pointer parameter and a
1165 // usual deallocation function with both a pointer parameter and a size
1166 // parameter are found, then the selected deallocation function shall be the
1167 // one with two parameters. Otherwise, the selected deallocation function
1168 // shall be the function with one parameter.
1169 if (!OperatorDelete) {
1170 // Look for a global declaration.
1171 // Sema::FindUsualDeallocationFunction will try to find the one with two
1172 // parameters first. It will return the deallocation function with one
1173 // parameter if failed.
1174 // Coroutines can always provide their required size.
1175 IDP.PassSize = SizedDeallocationMode::Yes;
1176 OperatorDelete = S.FindUsualDeallocationFunction(StartLoc: Loc, IDP, Name: DeleteName);
1177
1178 if (!OperatorDelete)
1179 return false;
1180 }
1181
1182 assert(!OperatorDelete->isTypeAwareOperatorNewOrDelete());
1183 S.MarkFunctionReferenced(Loc, Func: OperatorDelete);
1184 return true;
1185}
1186
1187
1188void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
1189 FunctionScopeInfo *Fn = getCurFunction();
1190 assert(Fn && Fn->isCoroutine() && "not a coroutine");
1191 if (!Body) {
1192 assert(FD->isInvalidDecl() &&
1193 "a null body is only allowed for invalid declarations");
1194 return;
1195 }
1196 // We have a function that uses coroutine keywords, but we failed to build
1197 // the promise type.
1198 if (!Fn->CoroutinePromise)
1199 return FD->setInvalidDecl();
1200
1201 if (isa<CoroutineBodyStmt>(Val: Body)) {
1202 // Nothing todo. the body is already a transformed coroutine body statement.
1203 return;
1204 }
1205
1206 // The always_inline attribute doesn't reliably apply to a coroutine,
1207 // because the coroutine will be split into pieces and some pieces
1208 // might be called indirectly, as in a virtual call. Even the ramp
1209 // function cannot be inlined at -O0, due to pipeline ordering
1210 // problems (see https://llvm.org/PR53413). Tell the user about it.
1211 if (FD->hasAttr<AlwaysInlineAttr>())
1212 Diag(Loc: FD->getLocation(), DiagID: diag::warn_always_inline_coroutine);
1213
1214 // The design of coroutines means we cannot allow use of VLAs within one, so
1215 // diagnose if we've seen a VLA in the body of this function.
1216 if (Fn->FirstVLALoc.isValid())
1217 Diag(Loc: Fn->FirstVLALoc, DiagID: diag::err_vla_in_coroutine_unsupported);
1218
1219 // Coroutines will get splitted into pieces. The GNU address of label
1220 // extension wouldn't be meaningful in coroutines.
1221 for (AddrLabelExpr *ALE : Fn->AddrLabels)
1222 Diag(Loc: ALE->getBeginLoc(), DiagID: diag::err_coro_invalid_addr_of_label);
1223
1224 // Coroutines always return a handle, so they can't be [[noreturn]].
1225 if (FD->isNoReturn())
1226 Diag(Loc: FD->getLocation(), DiagID: diag::warn_noreturn_coroutine) << FD;
1227
1228 CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
1229 if (Builder.isInvalid() || !Builder.buildStatements())
1230 return FD->setInvalidDecl();
1231
1232 // Build body for the coroutine wrapper statement.
1233 Body = CoroutineBodyStmt::Create(C: Context, Args: Builder);
1234}
1235
1236static CompoundStmt *buildCoroutineBody(Stmt *Body, ASTContext &Context) {
1237 if (auto *CS = dyn_cast<CompoundStmt>(Val: Body))
1238 return CS;
1239
1240 // The body of the coroutine may be a try statement if it is in
1241 // 'function-try-block' syntax. Here we wrap it into a compound
1242 // statement for consistency.
1243 assert(isa<CXXTryStmt>(Body) && "Unimaged coroutine body type");
1244 return CompoundStmt::Create(C: Context, Stmts: {Body}, FPFeatures: FPOptionsOverride(),
1245 LB: SourceLocation(), RB: SourceLocation());
1246}
1247
1248CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
1249 sema::FunctionScopeInfo &Fn,
1250 Stmt *Body)
1251 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
1252 IsPromiseDependentType(
1253 !Fn.CoroutinePromise ||
1254 Fn.CoroutinePromise->getType()->isDependentType()) {
1255 this->Body = buildCoroutineBody(Body, Context&: S.getASTContext());
1256
1257 for (auto KV : Fn.CoroutineParameterMoves)
1258 this->ParamMovesVector.push_back(Elt: KV.second);
1259 this->ParamMoves = this->ParamMovesVector;
1260
1261 if (!IsPromiseDependentType) {
1262 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
1263 assert(PromiseRecordDecl && "Type should have already been checked");
1264 }
1265 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
1266}
1267
1268bool CoroutineStmtBuilder::buildStatements() {
1269 assert(this->IsValid && "coroutine already invalid");
1270 this->IsValid = makeReturnObject();
1271 if (this->IsValid && !IsPromiseDependentType)
1272 buildDependentStatements();
1273 return this->IsValid;
1274}
1275
1276bool CoroutineStmtBuilder::buildDependentStatements() {
1277 assert(this->IsValid && "coroutine already invalid");
1278 assert(!this->IsPromiseDependentType &&
1279 "coroutine cannot have a dependent promise type");
1280 this->IsValid = makeOnException() && makeOnFallthrough() &&
1281 makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
1282 makeNewAndDeleteExpr();
1283 return this->IsValid;
1284}
1285
1286bool CoroutineStmtBuilder::makePromiseStmt() {
1287 // Form a declaration statement for the promise declaration, so that AST
1288 // visitors can more easily find it.
1289 StmtResult PromiseStmt =
1290 S.ActOnDeclStmt(Decl: S.ConvertDeclToDeclGroup(Ptr: Fn.CoroutinePromise), StartLoc: Loc, EndLoc: Loc);
1291 if (PromiseStmt.isInvalid())
1292 return false;
1293
1294 this->Promise = PromiseStmt.get();
1295 return true;
1296}
1297
1298bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
1299 if (Fn.hasInvalidCoroutineSuspends())
1300 return false;
1301 this->InitialSuspend = cast<Expr>(Val: Fn.CoroutineSuspends.first);
1302 this->FinalSuspend = cast<Expr>(Val: Fn.CoroutineSuspends.second);
1303 return true;
1304}
1305
1306static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
1307 CXXRecordDecl *PromiseRecordDecl,
1308 FunctionScopeInfo &Fn) {
1309 auto Loc = E->getExprLoc();
1310 if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(Val: E)) {
1311 auto *Decl = DeclRef->getDecl();
1312 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Val: Decl)) {
1313 if (Method->isStatic())
1314 return true;
1315 else
1316 Loc = Decl->getLocation();
1317 }
1318 }
1319
1320 S.Diag(
1321 Loc,
1322 DiagID: diag::err_coroutine_promise_get_return_object_on_allocation_failure)
1323 << PromiseRecordDecl;
1324 S.Diag(Loc: Fn.FirstCoroutineStmtLoc, DiagID: diag::note_declared_coroutine_here)
1325 << Fn.getFirstCoroutineStmtKeyword();
1326 return false;
1327}
1328
1329bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
1330 assert(!IsPromiseDependentType &&
1331 "cannot make statement while the promise type is dependent");
1332
1333 // [dcl.fct.def.coroutine]p10
1334 // If a search for the name get_return_object_on_allocation_failure in
1335 // the scope of the promise type ([class.member.lookup]) finds any
1336 // declarations, then the result of a call to an allocation function used to
1337 // obtain storage for the coroutine state is assumed to return nullptr if it
1338 // fails to obtain storage, ... If the allocation function returns nullptr,
1339 // ... and the return value is obtained by a call to
1340 // T::get_return_object_on_allocation_failure(), where T is the
1341 // promise type.
1342 DeclarationName DN =
1343 S.PP.getIdentifierInfo(Name: "get_return_object_on_allocation_failure");
1344 LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
1345 if (!S.LookupQualifiedName(R&: Found, LookupCtx: PromiseRecordDecl))
1346 return true;
1347
1348 CXXScopeSpec SS;
1349 ExprResult DeclNameExpr =
1350 S.BuildDeclarationNameExpr(SS, R&: Found, /*NeedsADL=*/false);
1351 if (DeclNameExpr.isInvalid())
1352 return false;
1353
1354 if (!diagReturnOnAllocFailure(S, E: DeclNameExpr.get(), PromiseRecordDecl, Fn))
1355 return false;
1356
1357 ExprResult ReturnObjectOnAllocationFailure =
1358 S.BuildCallExpr(S: nullptr, Fn: DeclNameExpr.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc);
1359 if (ReturnObjectOnAllocationFailure.isInvalid())
1360 return false;
1361
1362 StmtResult ReturnStmt =
1363 S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: ReturnObjectOnAllocationFailure.get());
1364 if (ReturnStmt.isInvalid()) {
1365 S.Diag(Loc: Found.getFoundDecl()->getLocation(), DiagID: diag::note_member_declared_here)
1366 << DN;
1367 S.Diag(Loc: Fn.FirstCoroutineStmtLoc, DiagID: diag::note_declared_coroutine_here)
1368 << Fn.getFirstCoroutineStmtKeyword();
1369 return false;
1370 }
1371
1372 this->ReturnStmtOnAllocFailure = ReturnStmt.get();
1373 return true;
1374}
1375
1376// Collect placement arguments for allocation function of coroutine FD.
1377// Return true if we collect placement arguments succesfully. Return false,
1378// otherwise.
1379static bool collectPlacementArgs(Sema &S, FunctionDecl &FD, SourceLocation Loc,
1380 SmallVectorImpl<Expr *> &PlacementArgs) {
1381 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: &FD)) {
1382 if (MD->isImplicitObjectMemberFunction() && !isLambdaCallOperator(MD)) {
1383 ExprResult ThisExpr = S.ActOnCXXThis(Loc);
1384 if (ThisExpr.isInvalid())
1385 return false;
1386 ThisExpr = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: ThisExpr.get());
1387 if (ThisExpr.isInvalid())
1388 return false;
1389 PlacementArgs.push_back(Elt: ThisExpr.get());
1390 }
1391 }
1392
1393 for (auto *PD : FD.parameters()) {
1394 if (PD->getType()->isDependentType())
1395 continue;
1396
1397 // Build a reference to the parameter.
1398 auto PDLoc = PD->getLocation();
1399 // Preserve the referenced state for unused parameter diagnostics.
1400 bool DeclReferenced = PD->isReferenced();
1401 ExprResult PDRefExpr =
1402 S.BuildDeclRefExpr(D: PD, Ty: PD->getOriginalType().getNonReferenceType(),
1403 VK: ExprValueKind::VK_LValue, Loc: PDLoc);
1404
1405 PD->setReferenced(DeclReferenced);
1406
1407 if (PDRefExpr.isInvalid())
1408 return false;
1409
1410 PlacementArgs.push_back(Elt: PDRefExpr.get());
1411 }
1412
1413 return true;
1414}
1415
1416bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
1417 // Form and check allocation and deallocation calls.
1418 assert(!IsPromiseDependentType &&
1419 "cannot make statement while the promise type is dependent");
1420 QualType PromiseType = Fn.CoroutinePromise->getType();
1421
1422 if (S.RequireCompleteType(Loc, T: PromiseType, DiagID: diag::err_incomplete_type))
1423 return false;
1424
1425 const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
1426
1427 // According to [dcl.fct.def.coroutine]p9, Lookup allocation functions using a
1428 // parameter list composed of the requested size of the coroutine state being
1429 // allocated, followed by the coroutine function's arguments. If a matching
1430 // allocation function exists, use it. Otherwise, use an allocation function
1431 // that just takes the requested size.
1432 //
1433 // [dcl.fct.def.coroutine]p9
1434 // An implementation may need to allocate additional storage for a
1435 // coroutine.
1436 // This storage is known as the coroutine state and is obtained by calling a
1437 // non-array allocation function ([basic.stc.dynamic.allocation]). The
1438 // allocation function's name is looked up by searching for it in the scope of
1439 // the promise type.
1440 // - If any declarations are found, overload resolution is performed on a
1441 // function call created by assembling an argument list. The first argument is
1442 // the amount of space requested, and has type std::size_t. The
1443 // lvalues p1 ... pn are the succeeding arguments.
1444 //
1445 // ...where "p1 ... pn" are defined earlier as:
1446 //
1447 // [dcl.fct.def.coroutine]p3
1448 // The promise type of a coroutine is `std::coroutine_traits<R, P1, ...,
1449 // Pn>`
1450 // , where R is the return type of the function, and `P1, ..., Pn` are the
1451 // sequence of types of the non-object function parameters, preceded by the
1452 // type of the object parameter ([dcl.fct]) if the coroutine is a non-static
1453 // member function. [dcl.fct.def.coroutine]p4 In the following, p_i is an
1454 // lvalue of type P_i, where p1 denotes the object parameter and p_i+1 denotes
1455 // the i-th non-object function parameter for a non-static member function,
1456 // and p_i denotes the i-th function parameter otherwise. For a non-static
1457 // member function, q_1 is an lvalue that denotes *this; any other q_i is an
1458 // lvalue that denotes the parameter copy corresponding to p_i.
1459
1460 FunctionDecl *OperatorNew = nullptr;
1461 SmallVector<Expr *, 1> PlacementArgs;
1462 // Track whether PlacementArgs still refer to the coroutine parameters.
1463 bool PlacementArgsFromCoroutine = false;
1464 DeclarationName NewName =
1465 S.getASTContext().DeclarationNames.getCXXOperatorName(Op: OO_New);
1466
1467 const bool PromiseContainsNew = [this, &PromiseType, NewName]() -> bool {
1468 LookupResult R(S, NewName, Loc, Sema::LookupOrdinaryName);
1469
1470 if (PromiseType->isRecordType())
1471 S.LookupQualifiedName(R, LookupCtx: PromiseType->getAsCXXRecordDecl());
1472
1473 return !R.empty() && !R.isAmbiguous();
1474 }();
1475
1476 // Helper function to indicate whether the last lookup found the aligned
1477 // allocation function.
1478 ImplicitAllocationParameters IAP(
1479 alignedAllocationModeFromBool(IsAligned: S.getLangOpts().CoroAlignedAllocation));
1480 auto LookupAllocationFunction = [&](AllocationFunctionScope NewScope =
1481 AllocationFunctionScope::Both,
1482 bool WithoutPlacementArgs = false,
1483 bool ForceNonAligned = false) {
1484 // [dcl.fct.def.coroutine]p9
1485 // The allocation function's name is looked up by searching for it in the
1486 // scope of the promise type.
1487 // - If any declarations are found, ...
1488 // - If no declarations are found in the scope of the promise type, a search
1489 // is performed in the global scope.
1490 if (NewScope == AllocationFunctionScope::Both)
1491 NewScope = PromiseContainsNew ? AllocationFunctionScope::Class
1492 : AllocationFunctionScope::Global;
1493
1494 bool ShouldUseAlignedAlloc =
1495 !ForceNonAligned && S.getLangOpts().CoroAlignedAllocation;
1496 IAP = ImplicitAllocationParameters(
1497 alignedAllocationModeFromBool(IsAligned: ShouldUseAlignedAlloc));
1498
1499 auto FoundAllocations = S.FindAllocationFunctions(
1500 StartLoc: Loc, Range: SourceRange(), NewScope,
1501 /*DeleteScope=*/AllocationFunctionScope::Both, AllocType: PromiseType,
1502 /*isArray=*/IsArray: false, IAP,
1503 PlaceArgs: WithoutPlacementArgs ? MultiExprArg{} : PlacementArgs,
1504 /*Diagnose=*/false);
1505 if (FoundAllocations) {
1506 IAP = FoundAllocations->IAP;
1507 OperatorNew = FoundAllocations->OperatorNew;
1508 } else {
1509 OperatorNew = nullptr;
1510 }
1511 assert(!OperatorNew || !OperatorNew->isTypeAwareOperatorNewOrDelete());
1512 };
1513
1514 // We don't expect to call to global operator new with (size, p0, …, pn).
1515 // So if we choose to lookup the allocation function in global scope, we
1516 // shouldn't lookup placement arguments.
1517 if (PromiseContainsNew) {
1518 if (!collectPlacementArgs(S, FD, Loc, PlacementArgs))
1519 return false;
1520 PlacementArgsFromCoroutine = true;
1521 }
1522
1523 LookupAllocationFunction();
1524
1525 if (PromiseContainsNew && !PlacementArgs.empty()) {
1526 // [dcl.fct.def.coroutine]p9
1527 // If no viable function is found ([over.match.viable]), overload
1528 // resolution
1529 // is performed again on a function call created by passing just the amount
1530 // of space required as an argument of type std::size_t.
1531 //
1532 // Proposed Change of [dcl.fct.def.coroutine]p9 in P2014R0:
1533 // Otherwise, overload resolution is performed again on a function call
1534 // created
1535 // by passing the amount of space requested as an argument of type
1536 // std::size_t as the first argument, and the requested alignment as
1537 // an argument of type std:align_val_t as the second argument.
1538 if (!OperatorNew || (S.getLangOpts().CoroAlignedAllocation &&
1539 !isAlignedAllocation(Mode: IAP.PassAlignment)))
1540 LookupAllocationFunction(/*NewScope*/ AllocationFunctionScope::Class,
1541 /*WithoutPlacementArgs*/ true);
1542 }
1543
1544 // Proposed Change of [dcl.fct.def.coroutine]p12 in P2014R0:
1545 // Otherwise, overload resolution is performed again on a function call
1546 // created
1547 // by passing the amount of space requested as an argument of type
1548 // std::size_t as the first argument, and the lvalues p1 ... pn as the
1549 // succeeding arguments. Otherwise, overload resolution is performed again
1550 // on a function call created by passing just the amount of space required as
1551 // an argument of type std::size_t.
1552 //
1553 // So within the proposed change in P2014RO, the priority order of aligned
1554 // allocation functions wiht promise_type is:
1555 //
1556 // void* operator new( std::size_t, std::align_val_t, placement_args... );
1557 // void* operator new( std::size_t, std::align_val_t);
1558 // void* operator new( std::size_t, placement_args... );
1559 // void* operator new( std::size_t);
1560
1561 // Helper variable to emit warnings.
1562 bool FoundNonAlignedInPromise = false;
1563 if (PromiseContainsNew && S.getLangOpts().CoroAlignedAllocation)
1564 if (!OperatorNew || !isAlignedAllocation(Mode: IAP.PassAlignment)) {
1565 FoundNonAlignedInPromise = OperatorNew;
1566
1567 LookupAllocationFunction(/*NewScope*/ AllocationFunctionScope::Class,
1568 /*WithoutPlacementArgs*/ false,
1569 /*ForceNonAligned*/ true);
1570
1571 if (!OperatorNew && !PlacementArgs.empty())
1572 LookupAllocationFunction(/*NewScope*/ AllocationFunctionScope::Class,
1573 /*WithoutPlacementArgs*/ true,
1574 /*ForceNonAligned*/ true);
1575 }
1576
1577 bool IsGlobalOverload =
1578 OperatorNew && !isa<CXXRecordDecl>(Val: OperatorNew->getDeclContext());
1579 // If we didn't find a class-local new declaration and non-throwing new
1580 // was is required then we need to lookup the non-throwing global operator
1581 // instead.
1582 if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
1583 auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
1584 if (!StdNoThrow)
1585 return false;
1586 PlacementArgs = {StdNoThrow};
1587 PlacementArgsFromCoroutine = false;
1588 OperatorNew = nullptr;
1589 LookupAllocationFunction(AllocationFunctionScope::Global);
1590 }
1591
1592 // If we found a non-aligned allocation function in the promise_type,
1593 // it indicates the user forgot to update the allocation function. Let's emit
1594 // a warning here.
1595 if (FoundNonAlignedInPromise) {
1596 S.Diag(Loc: OperatorNew->getLocation(),
1597 DiagID: diag::warn_non_aligned_allocation_function)
1598 << &FD;
1599 }
1600
1601 if (!OperatorNew) {
1602 if (PromiseContainsNew) {
1603 S.Diag(Loc, DiagID: diag::err_coroutine_unusable_new) << PromiseType << &FD;
1604 DiagnoseTypeAwareAllocators(
1605 S, Loc, DiagnosticID: diag::note_coroutine_unusable_type_aware_allocators, Name: NewName,
1606 PromiseType);
1607 } else if (RequiresNoThrowAlloc)
1608 S.Diag(Loc, DiagID: diag::err_coroutine_unfound_nothrow_new)
1609 << &FD << S.getLangOpts().CoroAlignedAllocation;
1610
1611 return false;
1612 }
1613 assert(!OperatorNew->isTypeAwareOperatorNewOrDelete());
1614
1615 DiagnoseTypeAwareAllocators(S, Loc,
1616 DiagnosticID: diag::warn_coroutine_type_aware_allocator_ignored,
1617 Name: NewName, PromiseType);
1618
1619 if (RequiresNoThrowAlloc) {
1620 const auto *FT = OperatorNew->getType()->castAs<FunctionProtoType>();
1621 if (!FT->isNothrow(/*ResultIfDependent*/ false)) {
1622 S.Diag(Loc: OperatorNew->getLocation(),
1623 DiagID: diag::err_coroutine_promise_new_requires_nothrow)
1624 << OperatorNew;
1625 S.Diag(Loc, DiagID: diag::note_coroutine_promise_call_implicitly_required)
1626 << OperatorNew;
1627 return false;
1628 }
1629 }
1630
1631 FunctionDecl *OperatorDelete = nullptr;
1632 if (!findDeleteForPromise(S, Loc, PromiseType, OperatorDelete)) {
1633 // FIXME: We should add an error here. According to:
1634 // [dcl.fct.def.coroutine]p12
1635 // If no usual deallocation function is found, the program is ill-formed.
1636 return false;
1637 }
1638
1639 assert(!OperatorDelete->isTypeAwareOperatorNewOrDelete());
1640
1641 Expr *FramePtr =
1642 S.BuildBuiltinCallExpr(Loc, Id: Builtin::BI__builtin_coro_frame, CallArgs: {});
1643
1644 Expr *FrameSize =
1645 S.BuildBuiltinCallExpr(Loc, Id: Builtin::BI__builtin_coro_size, CallArgs: {});
1646
1647 Expr *FrameAlignment = nullptr;
1648
1649 if (S.getLangOpts().CoroAlignedAllocation) {
1650 FrameAlignment =
1651 S.BuildBuiltinCallExpr(Loc, Id: Builtin::BI__builtin_coro_align, CallArgs: {});
1652
1653 TypeSourceInfo *AlignValTy = getTypeSourceInfoForStdAlignValT(S, Loc);
1654 if (!AlignValTy)
1655 return false;
1656
1657 FrameAlignment = S.BuildCXXNamedCast(OpLoc: Loc, Kind: tok::kw_static_cast, Ty: AlignValTy,
1658 E: FrameAlignment, AngleBrackets: SourceRange(Loc, Loc),
1659 Parens: SourceRange(Loc, Loc))
1660 .get();
1661 }
1662
1663 // Make new call.
1664 ExprResult NewRef =
1665 S.BuildDeclRefExpr(D: OperatorNew, Ty: OperatorNew->getType(), VK: VK_LValue, Loc);
1666 if (NewRef.isInvalid())
1667 return false;
1668
1669 SmallVector<Expr *, 2> NewArgs(1, FrameSize);
1670 if (S.getLangOpts().CoroAlignedAllocation &&
1671 isAlignedAllocation(Mode: IAP.PassAlignment))
1672 NewArgs.push_back(Elt: FrameAlignment);
1673
1674 // getNumParams() does not include an ellipsis, but a variadic allocation
1675 // function still receives the coroutine parameters as placement arguments.
1676 if (OperatorNew->isVariadic() ||
1677 OperatorNew->getNumParams() > NewArgs.size()) {
1678 llvm::append_range(C&: NewArgs, R&: PlacementArgs);
1679 if (PlacementArgsFromCoroutine)
1680 markCoroutineParametersReferenced(FD);
1681 }
1682
1683 ExprResult NewExpr =
1684 S.BuildCallExpr(S: S.getCurScope(), Fn: NewRef.get(), LParenLoc: Loc, ArgExprs: NewArgs, RParenLoc: Loc);
1685 NewExpr = S.ActOnFinishFullExpr(Expr: NewExpr.get(), /*DiscardedValue*/ false);
1686 if (NewExpr.isInvalid())
1687 return false;
1688
1689 // Make delete call.
1690
1691 QualType OpDeleteQualType = OperatorDelete->getType();
1692
1693 ExprResult DeleteRef =
1694 S.BuildDeclRefExpr(D: OperatorDelete, Ty: OpDeleteQualType, VK: VK_LValue, Loc);
1695 if (DeleteRef.isInvalid())
1696 return false;
1697
1698 Expr *CoroFree =
1699 S.BuildBuiltinCallExpr(Loc, Id: Builtin::BI__builtin_coro_free, CallArgs: {FramePtr});
1700
1701 SmallVector<Expr *, 2> DeleteArgs{CoroFree};
1702
1703 // [dcl.fct.def.coroutine]p12
1704 // The selected deallocation function shall be called with the address of
1705 // the block of storage to be reclaimed as its first argument. If a
1706 // deallocation function with a parameter of type std::size_t is
1707 // used, the size of the block is passed as the corresponding argument.
1708 const auto *OpDeleteType =
1709 OpDeleteQualType.getTypePtr()->castAs<FunctionProtoType>();
1710 if (OpDeleteType->getNumParams() > DeleteArgs.size() &&
1711 S.getASTContext().hasSameUnqualifiedType(
1712 T1: OpDeleteType->getParamType(i: DeleteArgs.size()), T2: FrameSize->getType()))
1713 DeleteArgs.push_back(Elt: FrameSize);
1714
1715 // Proposed Change of [dcl.fct.def.coroutine]p12 in P2014R0:
1716 // If deallocation function lookup finds a usual deallocation function with
1717 // a pointer parameter, size parameter and alignment parameter then this
1718 // will be the selected deallocation function, otherwise if lookup finds a
1719 // usual deallocation function with both a pointer parameter and a size
1720 // parameter, then this will be the selected deallocation function.
1721 // Otherwise, if lookup finds a usual deallocation function with only a
1722 // pointer parameter, then this will be the selected deallocation
1723 // function.
1724 //
1725 // So we are not forced to pass alignment to the deallocation function.
1726 if (S.getLangOpts().CoroAlignedAllocation &&
1727 OpDeleteType->getNumParams() > DeleteArgs.size() &&
1728 S.getASTContext().hasSameUnqualifiedType(
1729 T1: OpDeleteType->getParamType(i: DeleteArgs.size()),
1730 T2: FrameAlignment->getType()))
1731 DeleteArgs.push_back(Elt: FrameAlignment);
1732
1733 ExprResult DeleteExpr =
1734 S.BuildCallExpr(S: S.getCurScope(), Fn: DeleteRef.get(), LParenLoc: Loc, ArgExprs: DeleteArgs, RParenLoc: Loc);
1735 DeleteExpr =
1736 S.ActOnFinishFullExpr(Expr: DeleteExpr.get(), /*DiscardedValue*/ false);
1737 if (DeleteExpr.isInvalid())
1738 return false;
1739
1740 this->Allocate = NewExpr.get();
1741 this->Deallocate = DeleteExpr.get();
1742
1743 return true;
1744}
1745
1746bool CoroutineStmtBuilder::makeOnFallthrough() {
1747 assert(!IsPromiseDependentType &&
1748 "cannot make statement while the promise type is dependent");
1749
1750 // [dcl.fct.def.coroutine]/p6
1751 // If searches for the names return_void and return_value in the scope of
1752 // the promise type each find any declarations, the program is ill-formed.
1753 // [Note 1: If return_void is found, flowing off the end of a coroutine is
1754 // equivalent to a co_return with no operand. Otherwise, flowing off the end
1755 // of a coroutine results in undefined behavior ([stmt.return.coroutine]). —
1756 // end note]
1757 bool HasRVoid, HasRValue;
1758 LookupResult LRVoid =
1759 lookupMember(S, Name: "return_void", RD: PromiseRecordDecl, Loc, Res&: HasRVoid);
1760 LookupResult LRValue =
1761 lookupMember(S, Name: "return_value", RD: PromiseRecordDecl, Loc, Res&: HasRValue);
1762
1763 StmtResult Fallthrough;
1764 if (HasRVoid && HasRValue) {
1765 // FIXME Improve this diagnostic
1766 S.Diag(Loc: FD.getLocation(),
1767 DiagID: diag::err_coroutine_promise_incompatible_return_functions)
1768 << PromiseRecordDecl;
1769 S.Diag(Loc: LRVoid.getRepresentativeDecl()->getLocation(),
1770 DiagID: diag::note_member_first_declared_here)
1771 << LRVoid.getLookupName();
1772 S.Diag(Loc: LRValue.getRepresentativeDecl()->getLocation(),
1773 DiagID: diag::note_member_first_declared_here)
1774 << LRValue.getLookupName();
1775 return false;
1776 } else if (!HasRVoid && !HasRValue) {
1777 // We need to set 'Fallthrough'. Otherwise the other analysis part might
1778 // think the coroutine has defined a return_value method. So it might emit
1779 // **false** positive warning. e.g.,
1780 //
1781 // promise_without_return_func foo() {
1782 // co_await something();
1783 // }
1784 //
1785 // Then AnalysisBasedWarning would emit a warning about `foo()` lacking a
1786 // co_return statements, which isn't correct.
1787 Fallthrough = S.ActOnNullStmt(SemiLoc: PromiseRecordDecl->getLocation());
1788 if (Fallthrough.isInvalid())
1789 return false;
1790 } else if (HasRVoid) {
1791 Fallthrough = S.BuildCoreturnStmt(Loc: FD.getLocation(), E: nullptr,
1792 /*IsImplicit=*/true);
1793 Fallthrough = S.ActOnFinishFullStmt(Stmt: Fallthrough.get());
1794 if (Fallthrough.isInvalid())
1795 return false;
1796 }
1797
1798 this->OnFallthrough = Fallthrough.get();
1799 return true;
1800}
1801
1802bool CoroutineStmtBuilder::makeOnException() {
1803 // Try to form 'p.unhandled_exception();'
1804 assert(!IsPromiseDependentType &&
1805 "cannot make statement while the promise type is dependent");
1806
1807 const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1808
1809 if (!lookupMember(S, Name: "unhandled_exception", RD: PromiseRecordDecl, Loc)) {
1810 auto DiagID =
1811 RequireUnhandledException
1812 ? diag::err_coroutine_promise_unhandled_exception_required
1813 : diag::
1814 warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1815 S.Diag(Loc, DiagID) << PromiseRecordDecl;
1816 S.Diag(Loc: PromiseRecordDecl->getLocation(), DiagID: diag::note_defined_here)
1817 << PromiseRecordDecl;
1818 return !RequireUnhandledException;
1819 }
1820
1821 // If exceptions are disabled, don't try to build OnException.
1822 if (!S.getLangOpts().CXXExceptions)
1823 return true;
1824
1825 ExprResult UnhandledException =
1826 buildPromiseCall(S, Promise: Fn.CoroutinePromise, Loc, Name: "unhandled_exception", Args: {});
1827 UnhandledException = S.ActOnFinishFullExpr(Expr: UnhandledException.get(), CC: Loc,
1828 /*DiscardedValue*/ false);
1829 if (UnhandledException.isInvalid())
1830 return false;
1831
1832 // Since the body of the coroutine will be wrapped in try-catch, it will
1833 // be incompatible with SEH __try if present in a function.
1834 if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1835 S.Diag(Loc: Fn.FirstSEHTryLoc, DiagID: diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1836 S.Diag(Loc: Fn.FirstCoroutineStmtLoc, DiagID: diag::note_declared_coroutine_here)
1837 << Fn.getFirstCoroutineStmtKeyword();
1838 return false;
1839 }
1840
1841 this->OnException = UnhandledException.get();
1842 return true;
1843}
1844
1845bool CoroutineStmtBuilder::makeReturnObject() {
1846 // [dcl.fct.def.coroutine]p7
1847 // The expression promise.get_return_object() is used to initialize the
1848 // returned reference or prvalue result object of a call to a coroutine.
1849 ExprResult ReturnObject =
1850 buildPromiseCall(S, Promise: Fn.CoroutinePromise, Loc, Name: "get_return_object", Args: {});
1851 if (ReturnObject.isInvalid())
1852 return false;
1853
1854 this->ReturnValue = ReturnObject.get();
1855 return true;
1856}
1857
1858static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
1859 if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(Val: E)) {
1860 auto *MethodDecl = MbrRef->getMethodDecl();
1861 S.Diag(Loc: MethodDecl->getLocation(), DiagID: diag::note_member_declared_here)
1862 << MethodDecl;
1863 }
1864 S.Diag(Loc: Fn.FirstCoroutineStmtLoc, DiagID: diag::note_declared_coroutine_here)
1865 << Fn.getFirstCoroutineStmtKeyword();
1866}
1867
1868bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1869 assert(!IsPromiseDependentType &&
1870 "cannot make statement while the promise type is dependent");
1871 assert(this->ReturnValue && "ReturnValue must be already formed");
1872
1873 QualType const GroType = this->ReturnValue->getType();
1874 assert(!GroType->isDependentType() &&
1875 "get_return_object type must no longer be dependent");
1876
1877 QualType const FnRetType = FD.getReturnType();
1878 assert(!FnRetType->isDependentType() &&
1879 "get_return_object type must no longer be dependent");
1880
1881 // The call to get_­return_­object is sequenced before the call to
1882 // initial_­suspend and is invoked at most once, but there are caveats
1883 // regarding on whether the prvalue result object may be initialized
1884 // directly/eager or delayed, depending on the types involved.
1885 //
1886 // More info at https://github.com/cplusplus/papers/issues/1414
1887 bool GroMatchesRetType = S.getASTContext().hasSameType(T1: GroType, T2: FnRetType);
1888
1889 if (FnRetType->isVoidType()) {
1890 ExprResult Res =
1891 S.ActOnFinishFullExpr(Expr: this->ReturnValue, CC: Loc, /*DiscardedValue*/ false);
1892 if (Res.isInvalid())
1893 return false;
1894
1895 if (!GroMatchesRetType)
1896 this->ResultDecl = Res.get();
1897 return true;
1898 }
1899
1900 if (GroType->isVoidType()) {
1901 // Trigger a nice error message.
1902 InitializedEntity Entity =
1903 InitializedEntity::InitializeResult(ReturnLoc: Loc, Type: FnRetType);
1904 S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: ReturnValue);
1905 noteMemberDeclaredHere(S, E: ReturnValue, Fn);
1906 return false;
1907 }
1908
1909 StmtResult ReturnStmt;
1910 clang::VarDecl *GroDecl = nullptr;
1911 if (GroMatchesRetType) {
1912 ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: ReturnValue);
1913 } else {
1914 GroDecl = VarDecl::Create(
1915 C&: S.Context, DC: &FD, StartLoc: FD.getLocation(), IdLoc: FD.getLocation(),
1916 Id: &S.PP.getIdentifierTable().get(Name: "__coro_gro"),
1917 T: S.BuildDecltypeType(E: ReturnValue).getCanonicalType(),
1918 TInfo: S.Context.getTrivialTypeSourceInfo(T: GroType, Loc), S: SC_None);
1919 GroDecl->setImplicit();
1920
1921 S.CheckVariableDeclarationType(NewVD: GroDecl);
1922 if (GroDecl->isInvalidDecl())
1923 return false;
1924
1925 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: GroDecl);
1926 ExprResult Res =
1927 S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: ReturnValue);
1928 if (Res.isInvalid())
1929 return false;
1930
1931 Res = S.ActOnFinishFullExpr(Expr: Res.get(), /*DiscardedValue*/ false);
1932 if (Res.isInvalid())
1933 return false;
1934
1935 S.AddInitializerToDecl(dcl: GroDecl, init: Res.get(),
1936 /*DirectInit=*/false);
1937
1938 S.FinalizeDeclaration(D: GroDecl);
1939
1940 // Form a declaration statement for the return declaration, so that AST
1941 // visitors can more easily find it.
1942 StmtResult GroDeclStmt =
1943 S.ActOnDeclStmt(Decl: S.ConvertDeclToDeclGroup(Ptr: GroDecl), StartLoc: Loc, EndLoc: Loc);
1944 if (GroDeclStmt.isInvalid())
1945 return false;
1946
1947 this->ResultDecl = GroDeclStmt.get();
1948
1949 ExprResult declRef = S.BuildDeclRefExpr(D: GroDecl, Ty: GroType, VK: VK_LValue, Loc);
1950 if (declRef.isInvalid())
1951 return false;
1952
1953 ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: declRef.get());
1954 }
1955
1956 if (ReturnStmt.isInvalid()) {
1957 noteMemberDeclaredHere(S, E: ReturnValue, Fn);
1958 return false;
1959 }
1960
1961 if (!GroMatchesRetType &&
1962 cast<clang::ReturnStmt>(Val: ReturnStmt.get())->getNRVOCandidate() == GroDecl)
1963 GroDecl->setNRVOVariable(true);
1964
1965 this->ReturnStmt = ReturnStmt.get();
1966 return true;
1967}
1968
1969// Create a static_cast\<T&&>(expr).
1970static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
1971 if (T.isNull())
1972 T = E->getType();
1973 QualType TargetType = S.BuildReferenceType(
1974 T, /*SpelledAsLValue*/ LValueRef: false, Loc: SourceLocation(), Entity: DeclarationName());
1975 SourceLocation ExprLoc = E->getBeginLoc();
1976 TypeSourceInfo *TargetLoc =
1977 S.Context.getTrivialTypeSourceInfo(T: TargetType, Loc: ExprLoc);
1978
1979 return S
1980 .BuildCXXNamedCast(OpLoc: ExprLoc, Kind: tok::kw_static_cast, Ty: TargetLoc, E,
1981 AngleBrackets: SourceRange(ExprLoc, ExprLoc), Parens: E->getSourceRange())
1982 .get();
1983}
1984
1985/// Build a variable declaration for move parameter.
1986static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
1987 IdentifierInfo *II) {
1988 TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(T: Type, Loc);
1989 VarDecl *Decl = VarDecl::Create(C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, Id: II, T: Type,
1990 TInfo, S: SC_None);
1991 Decl->setImplicit();
1992 return Decl;
1993}
1994
1995// Build statements that move coroutine function parameters to the coroutine
1996// frame, and store them on the function scope info.
1997bool Sema::buildCoroutineParameterMoves(SourceLocation Loc) {
1998 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
1999 auto *FD = cast<FunctionDecl>(Val: CurContext);
2000
2001 auto *ScopeInfo = getCurFunction();
2002 if (!ScopeInfo->CoroutineParameterMoves.empty())
2003 return false;
2004
2005 // [dcl.fct.def.coroutine]p13
2006 // When a coroutine is invoked, after initializing its parameters
2007 // ([expr.call]), a copy is created for each coroutine parameter. For a
2008 // parameter of type cv T, the copy is a variable of type cv T with
2009 // automatic storage duration that is direct-initialized from an xvalue of
2010 // type T referring to the parameter.
2011 for (auto *PD : FD->parameters()) {
2012 if (PD->getType()->isDependentType())
2013 continue;
2014
2015 // Preserve the referenced state for unused parameter diagnostics.
2016 bool DeclReferenced = PD->isReferenced();
2017
2018 ExprResult PDRefExpr =
2019 BuildDeclRefExpr(D: PD, Ty: PD->getType().getNonReferenceType(),
2020 VK: ExprValueKind::VK_LValue, Loc); // FIXME: scope?
2021
2022 PD->setReferenced(DeclReferenced);
2023
2024 if (PDRefExpr.isInvalid())
2025 return false;
2026
2027 Expr *CExpr = nullptr;
2028 if (PD->getType()->getAsCXXRecordDecl() ||
2029 PD->getType()->isRValueReferenceType())
2030 CExpr = castForMoving(S&: *this, E: PDRefExpr.get());
2031 else
2032 CExpr = PDRefExpr.get();
2033 // [dcl.fct.def.coroutine]p13
2034 // The initialization and destruction of each parameter copy occurs in the
2035 // context of the called coroutine.
2036 auto *D = buildVarDecl(S&: *this, Loc, Type: PD->getType(), II: PD->getIdentifier());
2037 AddInitializerToDecl(dcl: D, init: CExpr, /*DirectInit=*/true);
2038
2039 // Convert decl to a statement.
2040 StmtResult Stmt = ActOnDeclStmt(Decl: ConvertDeclToDeclGroup(Ptr: D), StartLoc: Loc, EndLoc: Loc);
2041 if (Stmt.isInvalid())
2042 return false;
2043
2044 ScopeInfo->CoroutineParameterMoves.insert(KV: std::make_pair(x&: PD, y: Stmt.get()));
2045 }
2046 return true;
2047}
2048
2049StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
2050 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(C: Context, Args);
2051 if (!Res)
2052 return StmtError();
2053 return Res;
2054}
2055
2056ClassTemplateDecl *Sema::lookupCoroutineTraits(SourceLocation KwLoc,
2057 SourceLocation FuncLoc) {
2058 if (StdCoroutineTraitsCache)
2059 return StdCoroutineTraitsCache;
2060
2061 IdentifierInfo const &TraitIdent =
2062 PP.getIdentifierTable().get(Name: "coroutine_traits");
2063
2064 NamespaceDecl *StdSpace = getStdNamespace();
2065 LookupResult Result(*this, &TraitIdent, FuncLoc, LookupOrdinaryName);
2066 bool Found = StdSpace && LookupQualifiedName(R&: Result, LookupCtx: StdSpace);
2067
2068 if (!Found) {
2069 // The goggles, we found nothing!
2070 Diag(Loc: KwLoc, DiagID: diag::err_implied_coroutine_type_not_found)
2071 << "std::coroutine_traits";
2072 return nullptr;
2073 }
2074
2075 // coroutine_traits is required to be a class template.
2076 StdCoroutineTraitsCache = Result.getAsSingle<ClassTemplateDecl>();
2077 if (!StdCoroutineTraitsCache) {
2078 Result.suppressDiagnostics();
2079 NamedDecl *Found = *Result.begin();
2080 Diag(Loc: Found->getLocation(), DiagID: diag::err_malformed_std_coroutine_traits);
2081 return nullptr;
2082 }
2083
2084 return StdCoroutineTraitsCache;
2085}
2086