1 //===--- SemaCoroutines.cpp - Semantic Analysis for Coroutines ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for C++ Coroutines.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CoroutineStmtBuilder.h"
15 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/ExprCXX.h"
18 #include "clang/AST/StmtCXX.h"
19 #include "clang/Lex/Preprocessor.h"
20 #include "clang/Sema/Initialization.h"
21 #include "clang/Sema/Overload.h"
22 #include "clang/Sema/ScopeInfo.h"
23 #include "clang/Sema/SemaInternal.h"
24 
25 using namespace clang;
26 using namespace sema;
27 
28 static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
29                                  SourceLocation Loc, bool &Res) {
30   DeclarationName DN = S.PP.getIdentifierInfo(Name);
31   LookupResult LR(S, DN, Loc, Sema::LookupMemberName);
32   // Suppress diagnostics when a private member is selected. The same warnings
33   // will be produced again when building the call.
34   LR.suppressDiagnostics();
35   Res = S.LookupQualifiedName(LR, RD);
36   return LR;
37 }
38 
39 static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
40                          SourceLocation Loc) {
41   bool Res;
42   lookupMember(S, Name, RD, Loc, Res);
43   return Res;
44 }
45 
46 /// Look up the std::coroutine_traits<...>::promise_type for the given
47 /// function type.
48 static QualType lookupPromiseType(Sema &S, const FunctionDecl *FD,
49                                   SourceLocation KwLoc) {
50   const FunctionProtoType *FnType = FD->getType()->castAs<FunctionProtoType>();
51   const SourceLocation FuncLoc = FD->getLocation();
52   // FIXME: Cache std::coroutine_traits once we've found it.
53   NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
54   if (!StdExp) {
55     S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
56         << "std::experimental::coroutine_traits";
57     return QualType();
58   }
59 
60   LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_traits"),
61                       FuncLoc, Sema::LookupOrdinaryName);
62   if (!S.LookupQualifiedName(Result, StdExp)) {
63     S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
64         << "std::experimental::coroutine_traits";
65     return QualType();
66   }
67 
68   ClassTemplateDecl *CoroTraits = Result.getAsSingle<ClassTemplateDecl>();
69   if (!CoroTraits) {
70     Result.suppressDiagnostics();
71     // We found something weird. Complain about the first thing we found.
72     NamedDecl *Found = *Result.begin();
73     S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
74     return QualType();
75   }
76 
77   // Form template argument list for coroutine_traits<R, P1, P2, ...> according
78   // to [dcl.fct.def.coroutine]3
79   TemplateArgumentListInfo Args(KwLoc, KwLoc);
80   auto AddArg = [&](QualType T) {
81     Args.addArgument(TemplateArgumentLoc(
82         TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));
83   };
84   AddArg(FnType->getReturnType());
85   // If the function is a non-static member function, add the type
86   // of the implicit object parameter before the formal parameters.
87   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
88     if (MD->isInstance()) {
89       // [over.match.funcs]4
90       // For non-static member functions, the type of the implicit object
91       // parameter is
92       //  -- "lvalue reference to cv X" for functions declared without a
93       //      ref-qualifier or with the & ref-qualifier
94       //  -- "rvalue reference to cv X" for functions declared with the &&
95       //      ref-qualifier
96       QualType T =
97           MD->getThisType(S.Context)->getAs<PointerType>()->getPointeeType();
98       T = FnType->getRefQualifier() == RQ_RValue
99               ? S.Context.getRValueReferenceType(T)
100               : S.Context.getLValueReferenceType(T, /*SpelledAsLValue*/ true);
101       AddArg(T);
102     }
103   }
104   for (QualType T : FnType->getParamTypes())
105     AddArg(T);
106 
107   // Build the template-id.
108   QualType CoroTrait =
109       S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
110   if (CoroTrait.isNull())
111     return QualType();
112   if (S.RequireCompleteType(KwLoc, CoroTrait,
113                             diag::err_coroutine_type_missing_specialization))
114     return QualType();
115 
116   auto *RD = CoroTrait->getAsCXXRecordDecl();
117   assert(RD && "specialization of class template is not a class?");
118 
119   // Look up the ::promise_type member.
120   LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
121                  Sema::LookupOrdinaryName);
122   S.LookupQualifiedName(R, RD);
123   auto *Promise = R.getAsSingle<TypeDecl>();
124   if (!Promise) {
125     S.Diag(FuncLoc,
126            diag::err_implied_std_coroutine_traits_promise_type_not_found)
127         << RD;
128     return QualType();
129   }
130   // The promise type is required to be a class type.
131   QualType PromiseType = S.Context.getTypeDeclType(Promise);
132 
133   auto buildElaboratedType = [&]() {
134     auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, StdExp);
135     NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
136                                       CoroTrait.getTypePtr());
137     return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
138   };
139 
140   if (!PromiseType->getAsCXXRecordDecl()) {
141     S.Diag(FuncLoc,
142            diag::err_implied_std_coroutine_traits_promise_type_not_class)
143         << buildElaboratedType();
144     return QualType();
145   }
146   if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
147                             diag::err_coroutine_promise_type_incomplete))
148     return QualType();
149 
150   return PromiseType;
151 }
152 
153 /// Look up the std::experimental::coroutine_handle<PromiseType>.
154 static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
155                                           SourceLocation Loc) {
156   if (PromiseType.isNull())
157     return QualType();
158 
159   NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
160   assert(StdExp && "Should already be diagnosed");
161 
162   LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
163                       Loc, Sema::LookupOrdinaryName);
164   if (!S.LookupQualifiedName(Result, StdExp)) {
165     S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
166         << "std::experimental::coroutine_handle";
167     return QualType();
168   }
169 
170   ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
171   if (!CoroHandle) {
172     Result.suppressDiagnostics();
173     // We found something weird. Complain about the first thing we found.
174     NamedDecl *Found = *Result.begin();
175     S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
176     return QualType();
177   }
178 
179   // Form template argument list for coroutine_handle<Promise>.
180   TemplateArgumentListInfo Args(Loc, Loc);
181   Args.addArgument(TemplateArgumentLoc(
182       TemplateArgument(PromiseType),
183       S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
184 
185   // Build the template-id.
186   QualType CoroHandleType =
187       S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
188   if (CoroHandleType.isNull())
189     return QualType();
190   if (S.RequireCompleteType(Loc, CoroHandleType,
191                             diag::err_coroutine_type_missing_specialization))
192     return QualType();
193 
194   return CoroHandleType;
195 }
196 
197 static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
198                                     StringRef Keyword) {
199   // 'co_await' and 'co_yield' are not permitted in unevaluated operands.
200   if (S.isUnevaluatedContext()) {
201     S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
202     return false;
203   }
204 
205   // Any other usage must be within a function.
206   auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
207   if (!FD) {
208     S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
209                     ? diag::err_coroutine_objc_method
210                     : diag::err_coroutine_outside_function) << Keyword;
211     return false;
212   }
213 
214   // An enumeration for mapping the diagnostic type to the correct diagnostic
215   // selection index.
216   enum InvalidFuncDiag {
217     DiagCtor = 0,
218     DiagDtor,
219     DiagCopyAssign,
220     DiagMoveAssign,
221     DiagMain,
222     DiagConstexpr,
223     DiagAutoRet,
224     DiagVarargs,
225   };
226   bool Diagnosed = false;
227   auto DiagInvalid = [&](InvalidFuncDiag ID) {
228     S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
229     Diagnosed = true;
230     return false;
231   };
232 
233   // Diagnose when a constructor, destructor, copy/move assignment operator,
234   // or the function 'main' are declared as a coroutine.
235   auto *MD = dyn_cast<CXXMethodDecl>(FD);
236   if (MD && isa<CXXConstructorDecl>(MD))
237     return DiagInvalid(DiagCtor);
238   else if (MD && isa<CXXDestructorDecl>(MD))
239     return DiagInvalid(DiagDtor);
240   else if (MD && MD->isCopyAssignmentOperator())
241     return DiagInvalid(DiagCopyAssign);
242   else if (MD && MD->isMoveAssignmentOperator())
243     return DiagInvalid(DiagMoveAssign);
244   else if (FD->isMain())
245     return DiagInvalid(DiagMain);
246 
247   // Emit a diagnostics for each of the following conditions which is not met.
248   if (FD->isConstexpr())
249     DiagInvalid(DiagConstexpr);
250   if (FD->getReturnType()->isUndeducedType())
251     DiagInvalid(DiagAutoRet);
252   if (FD->isVariadic())
253     DiagInvalid(DiagVarargs);
254 
255   return !Diagnosed;
256 }
257 
258 static ExprResult buildOperatorCoawaitLookupExpr(Sema &SemaRef, Scope *S,
259                                                  SourceLocation Loc) {
260   DeclarationName OpName =
261       SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
262   LookupResult Operators(SemaRef, OpName, SourceLocation(),
263                          Sema::LookupOperatorName);
264   SemaRef.LookupName(Operators, S);
265 
266   assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
267   const auto &Functions = Operators.asUnresolvedSet();
268   bool IsOverloaded =
269       Functions.size() > 1 ||
270       (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
271   Expr *CoawaitOp = UnresolvedLookupExpr::Create(
272       SemaRef.Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
273       DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
274       Functions.begin(), Functions.end());
275   assert(CoawaitOp);
276   return CoawaitOp;
277 }
278 
279 /// Build a call to 'operator co_await' if there is a suitable operator for
280 /// the given expression.
281 static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, SourceLocation Loc,
282                                            Expr *E,
283                                            UnresolvedLookupExpr *Lookup) {
284   UnresolvedSet<16> Functions;
285   Functions.append(Lookup->decls_begin(), Lookup->decls_end());
286   return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
287 }
288 
289 static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
290                                            SourceLocation Loc, Expr *E) {
291   ExprResult R = buildOperatorCoawaitLookupExpr(SemaRef, S, Loc);
292   if (R.isInvalid())
293     return ExprError();
294   return buildOperatorCoawaitCall(SemaRef, Loc, E,
295                                   cast<UnresolvedLookupExpr>(R.get()));
296 }
297 
298 static Expr *buildBuiltinCall(Sema &S, SourceLocation Loc, Builtin::ID Id,
299                               MultiExprArg CallArgs) {
300   StringRef Name = S.Context.BuiltinInfo.getName(Id);
301   LookupResult R(S, &S.Context.Idents.get(Name), Loc, Sema::LookupOrdinaryName);
302   S.LookupName(R, S.TUScope, /*AllowBuiltinCreation=*/true);
303 
304   auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
305   assert(BuiltInDecl && "failed to find builtin declaration");
306 
307   ExprResult DeclRef =
308       S.BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
309   assert(DeclRef.isUsable() && "Builtin reference cannot fail");
310 
311   ExprResult Call =
312       S.ActOnCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
313 
314   assert(!Call.isInvalid() && "Call to builtin cannot fail!");
315   return Call.get();
316 }
317 
318 static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
319                                        SourceLocation Loc) {
320   QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
321   if (CoroHandleType.isNull())
322     return ExprError();
323 
324   DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
325   LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
326                      Sema::LookupOrdinaryName);
327   if (!S.LookupQualifiedName(Found, LookupCtx)) {
328     S.Diag(Loc, diag::err_coroutine_handle_missing_member)
329         << "from_address";
330     return ExprError();
331   }
332 
333   Expr *FramePtr =
334       buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
335 
336   CXXScopeSpec SS;
337   ExprResult FromAddr =
338       S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
339   if (FromAddr.isInvalid())
340     return ExprError();
341 
342   return S.ActOnCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
343 }
344 
345 struct ReadySuspendResumeResult {
346   enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume };
347   Expr *Results[3];
348   OpaqueValueExpr *OpaqueValue;
349   bool IsInvalid;
350 };
351 
352 static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
353                                   StringRef Name, MultiExprArg Args) {
354   DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
355 
356   // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
357   CXXScopeSpec SS;
358   ExprResult Result = S.BuildMemberReferenceExpr(
359       Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
360       SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
361       /*Scope=*/nullptr);
362   if (Result.isInvalid())
363     return ExprError();
364 
365   // We meant exactly what we asked for. No need for typo correction.
366   if (auto *TE = dyn_cast<TypoExpr>(Result.get())) {
367     S.clearDelayedTypo(TE);
368     S.Diag(Loc, diag::err_no_member)
369         << NameInfo.getName() << Base->getType()->getAsCXXRecordDecl()
370         << Base->getSourceRange();
371     return ExprError();
372   }
373 
374   return S.ActOnCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
375 }
376 
377 // See if return type is coroutine-handle and if so, invoke builtin coro-resume
378 // on its address. This is to enable experimental support for coroutine-handle
379 // returning await_suspend that results in a guaranteed tail call to the target
380 // coroutine.
381 static Expr *maybeTailCall(Sema &S, QualType RetType, Expr *E,
382                            SourceLocation Loc) {
383   if (RetType->isReferenceType())
384     return nullptr;
385   Type const *T = RetType.getTypePtr();
386   if (!T->isClassType() && !T->isStructureType())
387     return nullptr;
388 
389   // FIXME: Add convertability check to coroutine_handle<>. Possibly via
390   // EvaluateBinaryTypeTrait(BTT_IsConvertible, ...) which is at the moment
391   // a private function in SemaExprCXX.cpp
392 
393   ExprResult AddressExpr = buildMemberCall(S, E, Loc, "address", None);
394   if (AddressExpr.isInvalid())
395     return nullptr;
396 
397   Expr *JustAddress = AddressExpr.get();
398   // FIXME: Check that the type of AddressExpr is void*
399   return buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_resume,
400                           JustAddress);
401 }
402 
403 /// Build calls to await_ready, await_suspend, and await_resume for a co_await
404 /// expression.
405 static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
406                                                   SourceLocation Loc, Expr *E) {
407   OpaqueValueExpr *Operand = new (S.Context)
408       OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
409 
410   // Assume invalid until we see otherwise.
411   ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true};
412 
413   ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc);
414   if (CoroHandleRes.isInvalid())
415     return Calls;
416   Expr *CoroHandle = CoroHandleRes.get();
417 
418   const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
419   MultiExprArg Args[] = {None, CoroHandle, None};
420   for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
421     ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]);
422     if (Result.isInvalid())
423       return Calls;
424     Calls.Results[I] = Result.get();
425   }
426 
427   // Assume the calls are valid; all further checking should make them invalid.
428   Calls.IsInvalid = false;
429 
430   using ACT = ReadySuspendResumeResult::AwaitCallType;
431   CallExpr *AwaitReady = cast<CallExpr>(Calls.Results[ACT::ACT_Ready]);
432   if (!AwaitReady->getType()->isDependentType()) {
433     // [expr.await]p3 [...]
434     // — await-ready is the expression e.await_ready(), contextually converted
435     // to bool.
436     ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady);
437     if (Conv.isInvalid()) {
438       S.Diag(AwaitReady->getDirectCallee()->getLocStart(),
439              diag::note_await_ready_no_bool_conversion);
440       S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
441           << AwaitReady->getDirectCallee() << E->getSourceRange();
442       Calls.IsInvalid = true;
443     }
444     Calls.Results[ACT::ACT_Ready] = Conv.get();
445   }
446   CallExpr *AwaitSuspend = cast<CallExpr>(Calls.Results[ACT::ACT_Suspend]);
447   if (!AwaitSuspend->getType()->isDependentType()) {
448     // [expr.await]p3 [...]
449     //   - await-suspend is the expression e.await_suspend(h), which shall be
450     //     a prvalue of type void or bool.
451     QualType RetType = AwaitSuspend->getCallReturnType(S.Context);
452 
453     // Experimental support for coroutine_handle returning await_suspend.
454     if (Expr *TailCallSuspend = maybeTailCall(S, RetType, AwaitSuspend, Loc))
455       Calls.Results[ACT::ACT_Suspend] = TailCallSuspend;
456     else {
457       // non-class prvalues always have cv-unqualified types
458       if (RetType->isReferenceType() ||
459           (!RetType->isBooleanType() && !RetType->isVoidType())) {
460         S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
461                diag::err_await_suspend_invalid_return_type)
462             << RetType;
463         S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
464             << AwaitSuspend->getDirectCallee();
465         Calls.IsInvalid = true;
466       }
467     }
468   }
469 
470   return Calls;
471 }
472 
473 static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
474                                    SourceLocation Loc, StringRef Name,
475                                    MultiExprArg Args) {
476 
477   // Form a reference to the promise.
478   ExprResult PromiseRef = S.BuildDeclRefExpr(
479       Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
480   if (PromiseRef.isInvalid())
481     return ExprError();
482 
483   return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
484 }
485 
486 VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
487   assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
488   auto *FD = cast<FunctionDecl>(CurContext);
489   bool IsThisDependentType = [&] {
490     if (auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD))
491       return MD->isInstance() && MD->getThisType(Context)->isDependentType();
492     else
493       return false;
494   }();
495 
496   QualType T = FD->getType()->isDependentType() || IsThisDependentType
497                    ? Context.DependentTy
498                    : lookupPromiseType(*this, FD, Loc);
499   if (T.isNull())
500     return nullptr;
501 
502   auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
503                              &PP.getIdentifierTable().get("__promise"), T,
504                              Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
505   CheckVariableDeclarationType(VD);
506   if (VD->isInvalidDecl())
507     return nullptr;
508 
509   auto *ScopeInfo = getCurFunction();
510   // Build a list of arguments, based on the coroutine functions arguments,
511   // that will be passed to the promise type's constructor.
512   llvm::SmallVector<Expr *, 4> CtorArgExprs;
513   auto &Moves = ScopeInfo->CoroutineParameterMoves;
514   for (auto *PD : FD->parameters()) {
515     if (PD->getType()->isDependentType())
516       continue;
517 
518     auto RefExpr = ExprEmpty();
519     auto Move = Moves.find(PD);
520     assert(Move != Moves.end() &&
521            "Coroutine function parameter not inserted into move map");
522     // If a reference to the function parameter exists in the coroutine
523     // frame, use that reference.
524     auto *MoveDecl =
525         cast<VarDecl>(cast<DeclStmt>(Move->second)->getSingleDecl());
526     RefExpr =
527         BuildDeclRefExpr(MoveDecl, MoveDecl->getType().getNonReferenceType(),
528                          ExprValueKind::VK_LValue, FD->getLocation());
529     if (RefExpr.isInvalid())
530       return nullptr;
531     CtorArgExprs.push_back(RefExpr.get());
532   }
533 
534   // Create an initialization sequence for the promise type using the
535   // constructor arguments, wrapped in a parenthesized list expression.
536   Expr *PLE = new (Context) ParenListExpr(Context, FD->getLocation(),
537                                           CtorArgExprs, FD->getLocation());
538   InitializedEntity Entity = InitializedEntity::InitializeVariable(VD);
539   InitializationKind Kind = InitializationKind::CreateForInit(
540       VD->getLocation(), /*DirectInit=*/true, PLE);
541   InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs,
542                                  /*TopLevelOfInitList=*/false,
543                                  /*TreatUnavailableAsInvalid=*/false);
544 
545   // Attempt to initialize the promise type with the arguments.
546   // If that fails, fall back to the promise type's default constructor.
547   if (InitSeq) {
548     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, CtorArgExprs);
549     if (Result.isInvalid()) {
550       VD->setInvalidDecl();
551     } else if (Result.get()) {
552       VD->setInit(MaybeCreateExprWithCleanups(Result.get()));
553       VD->setInitStyle(VarDecl::CallInit);
554       CheckCompleteVariableDeclaration(VD);
555     }
556   } else
557     ActOnUninitializedDecl(VD);
558 
559   FD->addDecl(VD);
560   return VD;
561 }
562 
563 /// Check that this is a context in which a coroutine suspension can appear.
564 static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
565                                                 StringRef Keyword,
566                                                 bool IsImplicit = false) {
567   if (!isValidCoroutineContext(S, Loc, Keyword))
568     return nullptr;
569 
570   assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
571 
572   auto *ScopeInfo = S.getCurFunction();
573   assert(ScopeInfo && "missing function scope for function");
574 
575   if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
576     ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
577 
578   if (ScopeInfo->CoroutinePromise)
579     return ScopeInfo;
580 
581   if (!S.buildCoroutineParameterMoves(Loc))
582     return nullptr;
583 
584   ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
585   if (!ScopeInfo->CoroutinePromise)
586     return nullptr;
587 
588   return ScopeInfo;
589 }
590 
591 bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc,
592                                    StringRef Keyword) {
593   if (!checkCoroutineContext(*this, KWLoc, Keyword))
594     return false;
595   auto *ScopeInfo = getCurFunction();
596   assert(ScopeInfo->CoroutinePromise);
597 
598   // If we have existing coroutine statements then we have already built
599   // the initial and final suspend points.
600   if (!ScopeInfo->NeedsCoroutineSuspends)
601     return true;
602 
603   ScopeInfo->setNeedsCoroutineSuspends(false);
604 
605   auto *Fn = cast<FunctionDecl>(CurContext);
606   SourceLocation Loc = Fn->getLocation();
607   // Build the initial suspend point
608   auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
609     ExprResult Suspend =
610         buildPromiseCall(*this, ScopeInfo->CoroutinePromise, Loc, Name, None);
611     if (Suspend.isInvalid())
612       return StmtError();
613     Suspend = buildOperatorCoawaitCall(*this, SC, Loc, Suspend.get());
614     if (Suspend.isInvalid())
615       return StmtError();
616     Suspend = BuildResolvedCoawaitExpr(Loc, Suspend.get(),
617                                        /*IsImplicit*/ true);
618     Suspend = ActOnFinishFullExpr(Suspend.get());
619     if (Suspend.isInvalid()) {
620       Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
621           << ((Name == "initial_suspend") ? 0 : 1);
622       Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
623       return StmtError();
624     }
625     return cast<Stmt>(Suspend.get());
626   };
627 
628   StmtResult InitSuspend = buildSuspends("initial_suspend");
629   if (InitSuspend.isInvalid())
630     return true;
631 
632   StmtResult FinalSuspend = buildSuspends("final_suspend");
633   if (FinalSuspend.isInvalid())
634     return true;
635 
636   ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
637 
638   return true;
639 }
640 
641 ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
642   if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) {
643     CorrectDelayedTyposInExpr(E);
644     return ExprError();
645   }
646 
647   if (E->getType()->isPlaceholderType()) {
648     ExprResult R = CheckPlaceholderExpr(E);
649     if (R.isInvalid()) return ExprError();
650     E = R.get();
651   }
652   ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
653   if (Lookup.isInvalid())
654     return ExprError();
655   return BuildUnresolvedCoawaitExpr(Loc, E,
656                                    cast<UnresolvedLookupExpr>(Lookup.get()));
657 }
658 
659 ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E,
660                                             UnresolvedLookupExpr *Lookup) {
661   auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
662   if (!FSI)
663     return ExprError();
664 
665   if (E->getType()->isPlaceholderType()) {
666     ExprResult R = CheckPlaceholderExpr(E);
667     if (R.isInvalid())
668       return ExprError();
669     E = R.get();
670   }
671 
672   auto *Promise = FSI->CoroutinePromise;
673   if (Promise->getType()->isDependentType()) {
674     Expr *Res =
675         new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
676     return Res;
677   }
678 
679   auto *RD = Promise->getType()->getAsCXXRecordDecl();
680   if (lookupMember(*this, "await_transform", RD, Loc)) {
681     ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
682     if (R.isInvalid()) {
683       Diag(Loc,
684            diag::note_coroutine_promise_implicit_await_transform_required_here)
685           << E->getSourceRange();
686       return ExprError();
687     }
688     E = R.get();
689   }
690   ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
691   if (Awaitable.isInvalid())
692     return ExprError();
693 
694   return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
695 }
696 
697 ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E,
698                                   bool IsImplicit) {
699   auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
700   if (!Coroutine)
701     return ExprError();
702 
703   if (E->getType()->isPlaceholderType()) {
704     ExprResult R = CheckPlaceholderExpr(E);
705     if (R.isInvalid()) return ExprError();
706     E = R.get();
707   }
708 
709   if (E->getType()->isDependentType()) {
710     Expr *Res = new (Context)
711         CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
712     return Res;
713   }
714 
715   // If the expression is a temporary, materialize it as an lvalue so that we
716   // can use it multiple times.
717   if (E->getValueKind() == VK_RValue)
718     E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
719 
720   // The location of the `co_await` token cannot be used when constructing
721   // the member call expressions since it's before the location of `Expr`, which
722   // is used as the start of the member call expression.
723   SourceLocation CallLoc = E->getExprLoc();
724 
725   // Build the await_ready, await_suspend, await_resume calls.
726   ReadySuspendResumeResult RSS =
727       buildCoawaitCalls(*this, Coroutine->CoroutinePromise, CallLoc, E);
728   if (RSS.IsInvalid)
729     return ExprError();
730 
731   Expr *Res =
732       new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
733                                 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
734 
735   return Res;
736 }
737 
738 ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
739   if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) {
740     CorrectDelayedTyposInExpr(E);
741     return ExprError();
742   }
743 
744   // Build yield_value call.
745   ExprResult Awaitable = buildPromiseCall(
746       *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
747   if (Awaitable.isInvalid())
748     return ExprError();
749 
750   // Build 'operator co_await' call.
751   Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
752   if (Awaitable.isInvalid())
753     return ExprError();
754 
755   return BuildCoyieldExpr(Loc, Awaitable.get());
756 }
757 ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
758   auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
759   if (!Coroutine)
760     return ExprError();
761 
762   if (E->getType()->isPlaceholderType()) {
763     ExprResult R = CheckPlaceholderExpr(E);
764     if (R.isInvalid()) return ExprError();
765     E = R.get();
766   }
767 
768   if (E->getType()->isDependentType()) {
769     Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
770     return Res;
771   }
772 
773   // If the expression is a temporary, materialize it as an lvalue so that we
774   // can use it multiple times.
775   if (E->getValueKind() == VK_RValue)
776     E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
777 
778   // Build the await_ready, await_suspend, await_resume calls.
779   ReadySuspendResumeResult RSS =
780       buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
781   if (RSS.IsInvalid)
782     return ExprError();
783 
784   Expr *Res =
785       new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
786                                 RSS.Results[2], RSS.OpaqueValue);
787 
788   return Res;
789 }
790 
791 StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
792   if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) {
793     CorrectDelayedTyposInExpr(E);
794     return StmtError();
795   }
796   return BuildCoreturnStmt(Loc, E);
797 }
798 
799 StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
800                                    bool IsImplicit) {
801   auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
802   if (!FSI)
803     return StmtError();
804 
805   if (E && E->getType()->isPlaceholderType() &&
806       !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
807     ExprResult R = CheckPlaceholderExpr(E);
808     if (R.isInvalid()) return StmtError();
809     E = R.get();
810   }
811 
812   // FIXME: If the operand is a reference to a variable that's about to go out
813   // of scope, we should treat the operand as an xvalue for this overload
814   // resolution.
815   VarDecl *Promise = FSI->CoroutinePromise;
816   ExprResult PC;
817   if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
818     PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
819   } else {
820     E = MakeFullDiscardedValueExpr(E).get();
821     PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
822   }
823   if (PC.isInvalid())
824     return StmtError();
825 
826   Expr *PCE = ActOnFinishFullExpr(PC.get()).get();
827 
828   Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
829   return Res;
830 }
831 
832 /// Look up the std::nothrow object.
833 static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
834   NamespaceDecl *Std = S.getStdNamespace();
835   assert(Std && "Should already be diagnosed");
836 
837   LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
838                       Sema::LookupOrdinaryName);
839   if (!S.LookupQualifiedName(Result, Std)) {
840     // FIXME: <experimental/coroutine> should have been included already.
841     // If we require it to include <new> then this diagnostic is no longer
842     // needed.
843     S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
844     return nullptr;
845   }
846 
847   auto *VD = Result.getAsSingle<VarDecl>();
848   if (!VD) {
849     Result.suppressDiagnostics();
850     // We found something weird. Complain about the first thing we found.
851     NamedDecl *Found = *Result.begin();
852     S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
853     return nullptr;
854   }
855 
856   ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
857   if (DR.isInvalid())
858     return nullptr;
859 
860   return DR.get();
861 }
862 
863 // Find an appropriate delete for the promise.
864 static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc,
865                                           QualType PromiseType) {
866   FunctionDecl *OperatorDelete = nullptr;
867 
868   DeclarationName DeleteName =
869       S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
870 
871   auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
872   assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
873 
874   if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
875     return nullptr;
876 
877   if (!OperatorDelete) {
878     // Look for a global declaration.
879     const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
880     const bool Overaligned = false;
881     OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
882                                                      Overaligned, DeleteName);
883   }
884   S.MarkFunctionReferenced(Loc, OperatorDelete);
885   return OperatorDelete;
886 }
887 
888 
889 void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
890   FunctionScopeInfo *Fn = getCurFunction();
891   assert(Fn && Fn->isCoroutine() && "not a coroutine");
892   if (!Body) {
893     assert(FD->isInvalidDecl() &&
894            "a null body is only allowed for invalid declarations");
895     return;
896   }
897   // We have a function that uses coroutine keywords, but we failed to build
898   // the promise type.
899   if (!Fn->CoroutinePromise)
900     return FD->setInvalidDecl();
901 
902   if (isa<CoroutineBodyStmt>(Body)) {
903     // Nothing todo. the body is already a transformed coroutine body statement.
904     return;
905   }
906 
907   // Coroutines [stmt.return]p1:
908   //   A return statement shall not appear in a coroutine.
909   if (Fn->FirstReturnLoc.isValid()) {
910     assert(Fn->FirstCoroutineStmtLoc.isValid() &&
911                    "first coroutine location not set");
912     Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
913     Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
914             << Fn->getFirstCoroutineStmtKeyword();
915   }
916   CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
917   if (Builder.isInvalid() || !Builder.buildStatements())
918     return FD->setInvalidDecl();
919 
920   // Build body for the coroutine wrapper statement.
921   Body = CoroutineBodyStmt::Create(Context, Builder);
922 }
923 
924 CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
925                                            sema::FunctionScopeInfo &Fn,
926                                            Stmt *Body)
927     : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
928       IsPromiseDependentType(
929           !Fn.CoroutinePromise ||
930           Fn.CoroutinePromise->getType()->isDependentType()) {
931   this->Body = Body;
932 
933   for (auto KV : Fn.CoroutineParameterMoves)
934     this->ParamMovesVector.push_back(KV.second);
935   this->ParamMoves = this->ParamMovesVector;
936 
937   if (!IsPromiseDependentType) {
938     PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
939     assert(PromiseRecordDecl && "Type should have already been checked");
940   }
941   this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
942 }
943 
944 bool CoroutineStmtBuilder::buildStatements() {
945   assert(this->IsValid && "coroutine already invalid");
946   this->IsValid = makeReturnObject();
947   if (this->IsValid && !IsPromiseDependentType)
948     buildDependentStatements();
949   return this->IsValid;
950 }
951 
952 bool CoroutineStmtBuilder::buildDependentStatements() {
953   assert(this->IsValid && "coroutine already invalid");
954   assert(!this->IsPromiseDependentType &&
955          "coroutine cannot have a dependent promise type");
956   this->IsValid = makeOnException() && makeOnFallthrough() &&
957                   makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
958                   makeNewAndDeleteExpr();
959   return this->IsValid;
960 }
961 
962 bool CoroutineStmtBuilder::makePromiseStmt() {
963   // Form a declaration statement for the promise declaration, so that AST
964   // visitors can more easily find it.
965   StmtResult PromiseStmt =
966       S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
967   if (PromiseStmt.isInvalid())
968     return false;
969 
970   this->Promise = PromiseStmt.get();
971   return true;
972 }
973 
974 bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
975   if (Fn.hasInvalidCoroutineSuspends())
976     return false;
977   this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
978   this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
979   return true;
980 }
981 
982 static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
983                                      CXXRecordDecl *PromiseRecordDecl,
984                                      FunctionScopeInfo &Fn) {
985   auto Loc = E->getExprLoc();
986   if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
987     auto *Decl = DeclRef->getDecl();
988     if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
989       if (Method->isStatic())
990         return true;
991       else
992         Loc = Decl->getLocation();
993     }
994   }
995 
996   S.Diag(
997       Loc,
998       diag::err_coroutine_promise_get_return_object_on_allocation_failure)
999       << PromiseRecordDecl;
1000   S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1001       << Fn.getFirstCoroutineStmtKeyword();
1002   return false;
1003 }
1004 
1005 bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
1006   assert(!IsPromiseDependentType &&
1007          "cannot make statement while the promise type is dependent");
1008 
1009   // [dcl.fct.def.coroutine]/8
1010   // The unqualified-id get_return_object_on_allocation_failure is looked up in
1011   // the scope of class P by class member access lookup (3.4.5). ...
1012   // If an allocation function returns nullptr, ... the coroutine return value
1013   // is obtained by a call to ... get_return_object_on_allocation_failure().
1014 
1015   DeclarationName DN =
1016       S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
1017   LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
1018   if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
1019     return true;
1020 
1021   CXXScopeSpec SS;
1022   ExprResult DeclNameExpr =
1023       S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
1024   if (DeclNameExpr.isInvalid())
1025     return false;
1026 
1027   if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
1028     return false;
1029 
1030   ExprResult ReturnObjectOnAllocationFailure =
1031       S.ActOnCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
1032   if (ReturnObjectOnAllocationFailure.isInvalid())
1033     return false;
1034 
1035   StmtResult ReturnStmt =
1036       S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
1037   if (ReturnStmt.isInvalid()) {
1038     S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
1039         << DN;
1040     S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1041         << Fn.getFirstCoroutineStmtKeyword();
1042     return false;
1043   }
1044 
1045   this->ReturnStmtOnAllocFailure = ReturnStmt.get();
1046   return true;
1047 }
1048 
1049 bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
1050   // Form and check allocation and deallocation calls.
1051   assert(!IsPromiseDependentType &&
1052          "cannot make statement while the promise type is dependent");
1053   QualType PromiseType = Fn.CoroutinePromise->getType();
1054 
1055   if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
1056     return false;
1057 
1058   const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
1059 
1060   // [dcl.fct.def.coroutine]/7
1061   // Lookup allocation functions using a parameter list composed of the
1062   // requested size of the coroutine state being allocated, followed by
1063   // the coroutine function's arguments. If a matching allocation function
1064   // exists, use it. Otherwise, use an allocation function that just takes
1065   // the requested size.
1066 
1067   FunctionDecl *OperatorNew = nullptr;
1068   FunctionDecl *OperatorDelete = nullptr;
1069   FunctionDecl *UnusedResult = nullptr;
1070   bool PassAlignment = false;
1071   SmallVector<Expr *, 1> PlacementArgs;
1072 
1073   // [dcl.fct.def.coroutine]/7
1074   // "The allocation function’s name is looked up in the scope of P.
1075   // [...] If the lookup finds an allocation function in the scope of P,
1076   // overload resolution is performed on a function call created by assembling
1077   // an argument list. The first argument is the amount of space requested,
1078   // and has type std::size_t. The lvalues p1 ... pn are the succeeding
1079   // arguments."
1080   //
1081   // ...where "p1 ... pn" are defined earlier as:
1082   //
1083   // [dcl.fct.def.coroutine]/3
1084   // "For a coroutine f that is a non-static member function, let P1 denote the
1085   // type of the implicit object parameter (13.3.1) and P2 ... Pn be the types
1086   // of the function parameters; otherwise let P1 ... Pn be the types of the
1087   // function parameters. Let p1 ... pn be lvalues denoting those objects."
1088   if (auto *MD = dyn_cast<CXXMethodDecl>(&FD)) {
1089     if (MD->isInstance() && !isLambdaCallOperator(MD)) {
1090       ExprResult ThisExpr = S.ActOnCXXThis(Loc);
1091       if (ThisExpr.isInvalid())
1092         return false;
1093       ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
1094       if (ThisExpr.isInvalid())
1095         return false;
1096       PlacementArgs.push_back(ThisExpr.get());
1097     }
1098   }
1099   for (auto *PD : FD.parameters()) {
1100     if (PD->getType()->isDependentType())
1101       continue;
1102 
1103     // Build a reference to the parameter.
1104     auto PDLoc = PD->getLocation();
1105     ExprResult PDRefExpr =
1106         S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),
1107                            ExprValueKind::VK_LValue, PDLoc);
1108     if (PDRefExpr.isInvalid())
1109       return false;
1110 
1111     PlacementArgs.push_back(PDRefExpr.get());
1112   }
1113   S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class,
1114                             /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1115                             /*isArray*/ false, PassAlignment, PlacementArgs,
1116                             OperatorNew, UnusedResult, /*Diagnose*/ false);
1117 
1118   // [dcl.fct.def.coroutine]/7
1119   // "If no matching function is found, overload resolution is performed again
1120   // on a function call created by passing just the amount of space required as
1121   // an argument of type std::size_t."
1122   if (!OperatorNew && !PlacementArgs.empty()) {
1123     PlacementArgs.clear();
1124     S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class,
1125                               /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1126                               /*isArray*/ false, PassAlignment, PlacementArgs,
1127                               OperatorNew, UnusedResult, /*Diagnose*/ false);
1128   }
1129 
1130   // [dcl.fct.def.coroutine]/7
1131   // "The allocation function’s name is looked up in the scope of P. If this
1132   // lookup fails, the allocation function’s name is looked up in the global
1133   // scope."
1134   if (!OperatorNew) {
1135     S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Global,
1136                               /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1137                               /*isArray*/ false, PassAlignment, PlacementArgs,
1138                               OperatorNew, UnusedResult);
1139   }
1140 
1141   bool IsGlobalOverload =
1142       OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
1143   // If we didn't find a class-local new declaration and non-throwing new
1144   // was is required then we need to lookup the non-throwing global operator
1145   // instead.
1146   if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
1147     auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
1148     if (!StdNoThrow)
1149       return false;
1150     PlacementArgs = {StdNoThrow};
1151     OperatorNew = nullptr;
1152     S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Both,
1153                               /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1154                               /*isArray*/ false, PassAlignment, PlacementArgs,
1155                               OperatorNew, UnusedResult);
1156   }
1157 
1158   if (!OperatorNew)
1159     return false;
1160 
1161   if (RequiresNoThrowAlloc) {
1162     const auto *FT = OperatorNew->getType()->getAs<FunctionProtoType>();
1163     if (!FT->isNothrow(/*ResultIfDependent*/ false)) {
1164       S.Diag(OperatorNew->getLocation(),
1165              diag::err_coroutine_promise_new_requires_nothrow)
1166           << OperatorNew;
1167       S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
1168           << OperatorNew;
1169       return false;
1170     }
1171   }
1172 
1173   if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr)
1174     return false;
1175 
1176   Expr *FramePtr =
1177       buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
1178 
1179   Expr *FrameSize =
1180       buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {});
1181 
1182   // Make new call.
1183 
1184   ExprResult NewRef =
1185       S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
1186   if (NewRef.isInvalid())
1187     return false;
1188 
1189   SmallVector<Expr *, 2> NewArgs(1, FrameSize);
1190   for (auto Arg : PlacementArgs)
1191     NewArgs.push_back(Arg);
1192 
1193   ExprResult NewExpr =
1194       S.ActOnCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
1195   NewExpr = S.ActOnFinishFullExpr(NewExpr.get());
1196   if (NewExpr.isInvalid())
1197     return false;
1198 
1199   // Make delete call.
1200 
1201   QualType OpDeleteQualType = OperatorDelete->getType();
1202 
1203   ExprResult DeleteRef =
1204       S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
1205   if (DeleteRef.isInvalid())
1206     return false;
1207 
1208   Expr *CoroFree =
1209       buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr});
1210 
1211   SmallVector<Expr *, 2> DeleteArgs{CoroFree};
1212 
1213   // Check if we need to pass the size.
1214   const auto *OpDeleteType =
1215       OpDeleteQualType.getTypePtr()->getAs<FunctionProtoType>();
1216   if (OpDeleteType->getNumParams() > 1)
1217     DeleteArgs.push_back(FrameSize);
1218 
1219   ExprResult DeleteExpr =
1220       S.ActOnCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
1221   DeleteExpr = S.ActOnFinishFullExpr(DeleteExpr.get());
1222   if (DeleteExpr.isInvalid())
1223     return false;
1224 
1225   this->Allocate = NewExpr.get();
1226   this->Deallocate = DeleteExpr.get();
1227 
1228   return true;
1229 }
1230 
1231 bool CoroutineStmtBuilder::makeOnFallthrough() {
1232   assert(!IsPromiseDependentType &&
1233          "cannot make statement while the promise type is dependent");
1234 
1235   // [dcl.fct.def.coroutine]/4
1236   // The unqualified-ids 'return_void' and 'return_value' are looked up in
1237   // the scope of class P. If both are found, the program is ill-formed.
1238   bool HasRVoid, HasRValue;
1239   LookupResult LRVoid =
1240       lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
1241   LookupResult LRValue =
1242       lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
1243 
1244   StmtResult Fallthrough;
1245   if (HasRVoid && HasRValue) {
1246     // FIXME Improve this diagnostic
1247     S.Diag(FD.getLocation(),
1248            diag::err_coroutine_promise_incompatible_return_functions)
1249         << PromiseRecordDecl;
1250     S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
1251            diag::note_member_first_declared_here)
1252         << LRVoid.getLookupName();
1253     S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
1254            diag::note_member_first_declared_here)
1255         << LRValue.getLookupName();
1256     return false;
1257   } else if (!HasRVoid && !HasRValue) {
1258     // FIXME: The PDTS currently specifies this case as UB, not ill-formed.
1259     // However we still diagnose this as an error since until the PDTS is fixed.
1260     S.Diag(FD.getLocation(),
1261            diag::err_coroutine_promise_requires_return_function)
1262         << PromiseRecordDecl;
1263     S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1264         << PromiseRecordDecl;
1265     return false;
1266   } else if (HasRVoid) {
1267     // If the unqualified-id return_void is found, flowing off the end of a
1268     // coroutine is equivalent to a co_return with no operand. Otherwise,
1269     // flowing off the end of a coroutine results in undefined behavior.
1270     Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
1271                                       /*IsImplicit*/false);
1272     Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
1273     if (Fallthrough.isInvalid())
1274       return false;
1275   }
1276 
1277   this->OnFallthrough = Fallthrough.get();
1278   return true;
1279 }
1280 
1281 bool CoroutineStmtBuilder::makeOnException() {
1282   // Try to form 'p.unhandled_exception();'
1283   assert(!IsPromiseDependentType &&
1284          "cannot make statement while the promise type is dependent");
1285 
1286   const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1287 
1288   if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
1289     auto DiagID =
1290         RequireUnhandledException
1291             ? diag::err_coroutine_promise_unhandled_exception_required
1292             : diag::
1293                   warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1294     S.Diag(Loc, DiagID) << PromiseRecordDecl;
1295     S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1296         << PromiseRecordDecl;
1297     return !RequireUnhandledException;
1298   }
1299 
1300   // If exceptions are disabled, don't try to build OnException.
1301   if (!S.getLangOpts().CXXExceptions)
1302     return true;
1303 
1304   ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
1305                                                    "unhandled_exception", None);
1306   UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc);
1307   if (UnhandledException.isInvalid())
1308     return false;
1309 
1310   // Since the body of the coroutine will be wrapped in try-catch, it will
1311   // be incompatible with SEH __try if present in a function.
1312   if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1313     S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1314     S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1315         << Fn.getFirstCoroutineStmtKeyword();
1316     return false;
1317   }
1318 
1319   this->OnException = UnhandledException.get();
1320   return true;
1321 }
1322 
1323 bool CoroutineStmtBuilder::makeReturnObject() {
1324   // Build implicit 'p.get_return_object()' expression and form initialization
1325   // of return type from it.
1326   ExprResult ReturnObject =
1327       buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
1328   if (ReturnObject.isInvalid())
1329     return false;
1330 
1331   this->ReturnValue = ReturnObject.get();
1332   return true;
1333 }
1334 
1335 static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
1336   if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
1337     auto *MethodDecl = MbrRef->getMethodDecl();
1338     S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
1339         << MethodDecl;
1340   }
1341   S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1342       << Fn.getFirstCoroutineStmtKeyword();
1343 }
1344 
1345 bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1346   assert(!IsPromiseDependentType &&
1347          "cannot make statement while the promise type is dependent");
1348   assert(this->ReturnValue && "ReturnValue must be already formed");
1349 
1350   QualType const GroType = this->ReturnValue->getType();
1351   assert(!GroType->isDependentType() &&
1352          "get_return_object type must no longer be dependent");
1353 
1354   QualType const FnRetType = FD.getReturnType();
1355   assert(!FnRetType->isDependentType() &&
1356          "get_return_object type must no longer be dependent");
1357 
1358   if (FnRetType->isVoidType()) {
1359     ExprResult Res = S.ActOnFinishFullExpr(this->ReturnValue, Loc);
1360     if (Res.isInvalid())
1361       return false;
1362 
1363     this->ResultDecl = Res.get();
1364     return true;
1365   }
1366 
1367   if (GroType->isVoidType()) {
1368     // Trigger a nice error message.
1369     InitializedEntity Entity =
1370         InitializedEntity::InitializeResult(Loc, FnRetType, false);
1371     S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue);
1372     noteMemberDeclaredHere(S, ReturnValue, Fn);
1373     return false;
1374   }
1375 
1376   auto *GroDecl = VarDecl::Create(
1377       S.Context, &FD, FD.getLocation(), FD.getLocation(),
1378       &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
1379       S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
1380 
1381   S.CheckVariableDeclarationType(GroDecl);
1382   if (GroDecl->isInvalidDecl())
1383     return false;
1384 
1385   InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
1386   ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType,
1387                                                      this->ReturnValue);
1388   if (Res.isInvalid())
1389     return false;
1390 
1391   Res = S.ActOnFinishFullExpr(Res.get());
1392   if (Res.isInvalid())
1393     return false;
1394 
1395   S.AddInitializerToDecl(GroDecl, Res.get(),
1396                          /*DirectInit=*/false);
1397 
1398   S.FinalizeDeclaration(GroDecl);
1399 
1400   // Form a declaration statement for the return declaration, so that AST
1401   // visitors can more easily find it.
1402   StmtResult GroDeclStmt =
1403       S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
1404   if (GroDeclStmt.isInvalid())
1405     return false;
1406 
1407   this->ResultDecl = GroDeclStmt.get();
1408 
1409   ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
1410   if (declRef.isInvalid())
1411     return false;
1412 
1413   StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
1414   if (ReturnStmt.isInvalid()) {
1415     noteMemberDeclaredHere(S, ReturnValue, Fn);
1416     return false;
1417   }
1418   if (cast<clang::ReturnStmt>(ReturnStmt.get())->getNRVOCandidate() == GroDecl)
1419     GroDecl->setNRVOVariable(true);
1420 
1421   this->ReturnStmt = ReturnStmt.get();
1422   return true;
1423 }
1424 
1425 // Create a static_cast\<T&&>(expr).
1426 static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
1427   if (T.isNull())
1428     T = E->getType();
1429   QualType TargetType = S.BuildReferenceType(
1430       T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());
1431   SourceLocation ExprLoc = E->getLocStart();
1432   TypeSourceInfo *TargetLoc =
1433       S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
1434 
1435   return S
1436       .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1437                          SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
1438       .get();
1439 }
1440 
1441 /// Build a variable declaration for move parameter.
1442 static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
1443                              IdentifierInfo *II) {
1444   TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);
1445   VarDecl *Decl = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type,
1446                                   TInfo, SC_None);
1447   Decl->setImplicit();
1448   return Decl;
1449 }
1450 
1451 // Build statements that move coroutine function parameters to the coroutine
1452 // frame, and store them on the function scope info.
1453 bool Sema::buildCoroutineParameterMoves(SourceLocation Loc) {
1454   assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
1455   auto *FD = cast<FunctionDecl>(CurContext);
1456 
1457   auto *ScopeInfo = getCurFunction();
1458   assert(ScopeInfo->CoroutineParameterMoves.empty() &&
1459          "Should not build parameter moves twice");
1460 
1461   for (auto *PD : FD->parameters()) {
1462     if (PD->getType()->isDependentType())
1463       continue;
1464 
1465     ExprResult PDRefExpr =
1466         BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
1467                          ExprValueKind::VK_LValue, Loc); // FIXME: scope?
1468     if (PDRefExpr.isInvalid())
1469       return false;
1470 
1471     Expr *CExpr = nullptr;
1472     if (PD->getType()->getAsCXXRecordDecl() ||
1473         PD->getType()->isRValueReferenceType())
1474       CExpr = castForMoving(*this, PDRefExpr.get());
1475     else
1476       CExpr = PDRefExpr.get();
1477 
1478     auto D = buildVarDecl(*this, Loc, PD->getType(), PD->getIdentifier());
1479     AddInitializerToDecl(D, CExpr, /*DirectInit=*/true);
1480 
1481     // Convert decl to a statement.
1482     StmtResult Stmt = ActOnDeclStmt(ConvertDeclToDeclGroup(D), Loc, Loc);
1483     if (Stmt.isInvalid())
1484       return false;
1485 
1486     ScopeInfo->CoroutineParameterMoves.insert(std::make_pair(PD, Stmt.get()));
1487   }
1488   return true;
1489 }
1490 
1491 StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1492   CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
1493   if (!Res)
1494     return StmtError();
1495   return Res;
1496 }
1497