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