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   return S.ActOnCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
366 }
367 
368 // See if return type is coroutine-handle and if so, invoke builtin coro-resume
369 // on its address. This is to enable experimental support for coroutine-handle
370 // returning await_suspend that results in a guranteed tail call to the target
371 // coroutine.
372 static Expr *maybeTailCall(Sema &S, QualType RetType, Expr *E,
373                            SourceLocation Loc) {
374   if (RetType->isReferenceType())
375     return nullptr;
376   Type const *T = RetType.getTypePtr();
377   if (!T->isClassType() && !T->isStructureType())
378     return nullptr;
379 
380   // FIXME: Add convertability check to coroutine_handle<>. Possibly via
381   // EvaluateBinaryTypeTrait(BTT_IsConvertible, ...) which is at the moment
382   // a private function in SemaExprCXX.cpp
383 
384   ExprResult AddressExpr = buildMemberCall(S, E, Loc, "address", None);
385   if (AddressExpr.isInvalid())
386     return nullptr;
387 
388   Expr *JustAddress = AddressExpr.get();
389   // FIXME: Check that the type of AddressExpr is void*
390   return buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_resume,
391                           JustAddress);
392 }
393 
394 /// Build calls to await_ready, await_suspend, and await_resume for a co_await
395 /// expression.
396 static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
397                                                   SourceLocation Loc, Expr *E) {
398   OpaqueValueExpr *Operand = new (S.Context)
399       OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
400 
401   // Assume invalid until we see otherwise.
402   ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true};
403 
404   ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc);
405   if (CoroHandleRes.isInvalid())
406     return Calls;
407   Expr *CoroHandle = CoroHandleRes.get();
408 
409   const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
410   MultiExprArg Args[] = {None, CoroHandle, None};
411   for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
412     ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]);
413     if (Result.isInvalid())
414       return Calls;
415     Calls.Results[I] = Result.get();
416   }
417 
418   // Assume the calls are valid; all further checking should make them invalid.
419   Calls.IsInvalid = false;
420 
421   using ACT = ReadySuspendResumeResult::AwaitCallType;
422   CallExpr *AwaitReady = cast<CallExpr>(Calls.Results[ACT::ACT_Ready]);
423   if (!AwaitReady->getType()->isDependentType()) {
424     // [expr.await]p3 [...]
425     // — await-ready is the expression e.await_ready(), contextually converted
426     // to bool.
427     ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady);
428     if (Conv.isInvalid()) {
429       S.Diag(AwaitReady->getDirectCallee()->getLocStart(),
430              diag::note_await_ready_no_bool_conversion);
431       S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
432           << AwaitReady->getDirectCallee() << E->getSourceRange();
433       Calls.IsInvalid = true;
434     }
435     Calls.Results[ACT::ACT_Ready] = Conv.get();
436   }
437   CallExpr *AwaitSuspend = cast<CallExpr>(Calls.Results[ACT::ACT_Suspend]);
438   if (!AwaitSuspend->getType()->isDependentType()) {
439     // [expr.await]p3 [...]
440     //   - await-suspend is the expression e.await_suspend(h), which shall be
441     //     a prvalue of type void or bool.
442     QualType RetType = AwaitSuspend->getCallReturnType(S.Context);
443 
444     // Experimental support for coroutine_handle returning await_suspend.
445     if (Expr *TailCallSuspend = maybeTailCall(S, RetType, AwaitSuspend, Loc))
446       Calls.Results[ACT::ACT_Suspend] = TailCallSuspend;
447     else {
448       // non-class prvalues always have cv-unqualified types
449       if (RetType->isReferenceType() ||
450           (!RetType->isBooleanType() && !RetType->isVoidType())) {
451         S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
452                diag::err_await_suspend_invalid_return_type)
453             << RetType;
454         S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
455             << AwaitSuspend->getDirectCallee();
456         Calls.IsInvalid = true;
457       }
458     }
459   }
460 
461   return Calls;
462 }
463 
464 static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
465                                    SourceLocation Loc, StringRef Name,
466                                    MultiExprArg Args) {
467 
468   // Form a reference to the promise.
469   ExprResult PromiseRef = S.BuildDeclRefExpr(
470       Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
471   if (PromiseRef.isInvalid())
472     return ExprError();
473 
474   return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
475 }
476 
477 VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
478   assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
479   auto *FD = cast<FunctionDecl>(CurContext);
480   bool IsThisDependentType = [&] {
481     if (auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD))
482       return MD->isInstance() && MD->getThisType(Context)->isDependentType();
483     else
484       return false;
485   }();
486 
487   QualType T = FD->getType()->isDependentType() || IsThisDependentType
488                    ? Context.DependentTy
489                    : lookupPromiseType(*this, FD, Loc);
490   if (T.isNull())
491     return nullptr;
492 
493   auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
494                              &PP.getIdentifierTable().get("__promise"), T,
495                              Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
496   CheckVariableDeclarationType(VD);
497   if (VD->isInvalidDecl())
498     return nullptr;
499 
500   auto *ScopeInfo = getCurFunction();
501   // Build a list of arguments, based on the coroutine functions arguments,
502   // that will be passed to the promise type's constructor.
503   llvm::SmallVector<Expr *, 4> CtorArgExprs;
504   auto &Moves = ScopeInfo->CoroutineParameterMoves;
505   for (auto *PD : FD->parameters()) {
506     if (PD->getType()->isDependentType())
507       continue;
508 
509     auto RefExpr = ExprEmpty();
510     auto Move = Moves.find(PD);
511     assert(Move != Moves.end() &&
512            "Coroutine function parameter not inserted into move map");
513     // If a reference to the function parameter exists in the coroutine
514     // frame, use that reference.
515     auto *MoveDecl =
516         cast<VarDecl>(cast<DeclStmt>(Move->second)->getSingleDecl());
517     RefExpr =
518         BuildDeclRefExpr(MoveDecl, MoveDecl->getType().getNonReferenceType(),
519                          ExprValueKind::VK_LValue, FD->getLocation());
520     if (RefExpr.isInvalid())
521       return nullptr;
522     CtorArgExprs.push_back(RefExpr.get());
523   }
524 
525   // Create an initialization sequence for the promise type using the
526   // constructor arguments, wrapped in a parenthesized list expression.
527   Expr *PLE = new (Context) ParenListExpr(Context, FD->getLocation(),
528                                           CtorArgExprs, FD->getLocation());
529   InitializedEntity Entity = InitializedEntity::InitializeVariable(VD);
530   InitializationKind Kind = InitializationKind::CreateForInit(
531       VD->getLocation(), /*DirectInit=*/true, PLE);
532   InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs,
533                                  /*TopLevelOfInitList=*/false,
534                                  /*TreatUnavailableAsInvalid=*/false);
535 
536   // Attempt to initialize the promise type with the arguments.
537   // If that fails, fall back to the promise type's default constructor.
538   if (InitSeq) {
539     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, CtorArgExprs);
540     if (Result.isInvalid()) {
541       VD->setInvalidDecl();
542     } else if (Result.get()) {
543       VD->setInit(MaybeCreateExprWithCleanups(Result.get()));
544       VD->setInitStyle(VarDecl::CallInit);
545       CheckCompleteVariableDeclaration(VD);
546     }
547   } else
548     ActOnUninitializedDecl(VD);
549 
550   FD->addDecl(VD);
551   return VD;
552 }
553 
554 /// Check that this is a context in which a coroutine suspension can appear.
555 static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
556                                                 StringRef Keyword,
557                                                 bool IsImplicit = false) {
558   if (!isValidCoroutineContext(S, Loc, Keyword))
559     return nullptr;
560 
561   assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
562 
563   auto *ScopeInfo = S.getCurFunction();
564   assert(ScopeInfo && "missing function scope for function");
565 
566   if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
567     ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
568 
569   if (ScopeInfo->CoroutinePromise)
570     return ScopeInfo;
571 
572   if (!S.buildCoroutineParameterMoves(Loc))
573     return nullptr;
574 
575   ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
576   if (!ScopeInfo->CoroutinePromise)
577     return nullptr;
578 
579   return ScopeInfo;
580 }
581 
582 bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc,
583                                    StringRef Keyword) {
584   if (!checkCoroutineContext(*this, KWLoc, Keyword))
585     return false;
586   auto *ScopeInfo = getCurFunction();
587   assert(ScopeInfo->CoroutinePromise);
588 
589   // If we have existing coroutine statements then we have already built
590   // the initial and final suspend points.
591   if (!ScopeInfo->NeedsCoroutineSuspends)
592     return true;
593 
594   ScopeInfo->setNeedsCoroutineSuspends(false);
595 
596   auto *Fn = cast<FunctionDecl>(CurContext);
597   SourceLocation Loc = Fn->getLocation();
598   // Build the initial suspend point
599   auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
600     ExprResult Suspend =
601         buildPromiseCall(*this, ScopeInfo->CoroutinePromise, Loc, Name, None);
602     if (Suspend.isInvalid())
603       return StmtError();
604     Suspend = buildOperatorCoawaitCall(*this, SC, Loc, Suspend.get());
605     if (Suspend.isInvalid())
606       return StmtError();
607     Suspend = BuildResolvedCoawaitExpr(Loc, Suspend.get(),
608                                        /*IsImplicit*/ true);
609     Suspend = ActOnFinishFullExpr(Suspend.get());
610     if (Suspend.isInvalid()) {
611       Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
612           << ((Name == "initial_suspend") ? 0 : 1);
613       Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
614       return StmtError();
615     }
616     return cast<Stmt>(Suspend.get());
617   };
618 
619   StmtResult InitSuspend = buildSuspends("initial_suspend");
620   if (InitSuspend.isInvalid())
621     return true;
622 
623   StmtResult FinalSuspend = buildSuspends("final_suspend");
624   if (FinalSuspend.isInvalid())
625     return true;
626 
627   ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
628 
629   return true;
630 }
631 
632 ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
633   if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) {
634     CorrectDelayedTyposInExpr(E);
635     return ExprError();
636   }
637 
638   if (E->getType()->isPlaceholderType()) {
639     ExprResult R = CheckPlaceholderExpr(E);
640     if (R.isInvalid()) return ExprError();
641     E = R.get();
642   }
643   ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
644   if (Lookup.isInvalid())
645     return ExprError();
646   return BuildUnresolvedCoawaitExpr(Loc, E,
647                                    cast<UnresolvedLookupExpr>(Lookup.get()));
648 }
649 
650 ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E,
651                                             UnresolvedLookupExpr *Lookup) {
652   auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
653   if (!FSI)
654     return ExprError();
655 
656   if (E->getType()->isPlaceholderType()) {
657     ExprResult R = CheckPlaceholderExpr(E);
658     if (R.isInvalid())
659       return ExprError();
660     E = R.get();
661   }
662 
663   auto *Promise = FSI->CoroutinePromise;
664   if (Promise->getType()->isDependentType()) {
665     Expr *Res =
666         new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
667     return Res;
668   }
669 
670   auto *RD = Promise->getType()->getAsCXXRecordDecl();
671   if (lookupMember(*this, "await_transform", RD, Loc)) {
672     ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
673     if (R.isInvalid()) {
674       Diag(Loc,
675            diag::note_coroutine_promise_implicit_await_transform_required_here)
676           << E->getSourceRange();
677       return ExprError();
678     }
679     E = R.get();
680   }
681   ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
682   if (Awaitable.isInvalid())
683     return ExprError();
684 
685   return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
686 }
687 
688 ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E,
689                                   bool IsImplicit) {
690   auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
691   if (!Coroutine)
692     return ExprError();
693 
694   if (E->getType()->isPlaceholderType()) {
695     ExprResult R = CheckPlaceholderExpr(E);
696     if (R.isInvalid()) return ExprError();
697     E = R.get();
698   }
699 
700   if (E->getType()->isDependentType()) {
701     Expr *Res = new (Context)
702         CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
703     return Res;
704   }
705 
706   // If the expression is a temporary, materialize it as an lvalue so that we
707   // can use it multiple times.
708   if (E->getValueKind() == VK_RValue)
709     E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
710 
711   // Build the await_ready, await_suspend, await_resume calls.
712   ReadySuspendResumeResult RSS =
713       buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
714   if (RSS.IsInvalid)
715     return ExprError();
716 
717   Expr *Res =
718       new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
719                                 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
720 
721   return Res;
722 }
723 
724 ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
725   if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) {
726     CorrectDelayedTyposInExpr(E);
727     return ExprError();
728   }
729 
730   // Build yield_value call.
731   ExprResult Awaitable = buildPromiseCall(
732       *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
733   if (Awaitable.isInvalid())
734     return ExprError();
735 
736   // Build 'operator co_await' call.
737   Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
738   if (Awaitable.isInvalid())
739     return ExprError();
740 
741   return BuildCoyieldExpr(Loc, Awaitable.get());
742 }
743 ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
744   auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
745   if (!Coroutine)
746     return ExprError();
747 
748   if (E->getType()->isPlaceholderType()) {
749     ExprResult R = CheckPlaceholderExpr(E);
750     if (R.isInvalid()) return ExprError();
751     E = R.get();
752   }
753 
754   if (E->getType()->isDependentType()) {
755     Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
756     return Res;
757   }
758 
759   // If the expression is a temporary, materialize it as an lvalue so that we
760   // can use it multiple times.
761   if (E->getValueKind() == VK_RValue)
762     E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
763 
764   // Build the await_ready, await_suspend, await_resume calls.
765   ReadySuspendResumeResult RSS =
766       buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
767   if (RSS.IsInvalid)
768     return ExprError();
769 
770   Expr *Res =
771       new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
772                                 RSS.Results[2], RSS.OpaqueValue);
773 
774   return Res;
775 }
776 
777 StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
778   if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) {
779     CorrectDelayedTyposInExpr(E);
780     return StmtError();
781   }
782   return BuildCoreturnStmt(Loc, E);
783 }
784 
785 StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
786                                    bool IsImplicit) {
787   auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
788   if (!FSI)
789     return StmtError();
790 
791   if (E && E->getType()->isPlaceholderType() &&
792       !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
793     ExprResult R = CheckPlaceholderExpr(E);
794     if (R.isInvalid()) return StmtError();
795     E = R.get();
796   }
797 
798   // FIXME: If the operand is a reference to a variable that's about to go out
799   // of scope, we should treat the operand as an xvalue for this overload
800   // resolution.
801   VarDecl *Promise = FSI->CoroutinePromise;
802   ExprResult PC;
803   if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
804     PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
805   } else {
806     E = MakeFullDiscardedValueExpr(E).get();
807     PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
808   }
809   if (PC.isInvalid())
810     return StmtError();
811 
812   Expr *PCE = ActOnFinishFullExpr(PC.get()).get();
813 
814   Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
815   return Res;
816 }
817 
818 /// Look up the std::nothrow object.
819 static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
820   NamespaceDecl *Std = S.getStdNamespace();
821   assert(Std && "Should already be diagnosed");
822 
823   LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
824                       Sema::LookupOrdinaryName);
825   if (!S.LookupQualifiedName(Result, Std)) {
826     // FIXME: <experimental/coroutine> should have been included already.
827     // If we require it to include <new> then this diagnostic is no longer
828     // needed.
829     S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
830     return nullptr;
831   }
832 
833   auto *VD = Result.getAsSingle<VarDecl>();
834   if (!VD) {
835     Result.suppressDiagnostics();
836     // We found something weird. Complain about the first thing we found.
837     NamedDecl *Found = *Result.begin();
838     S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
839     return nullptr;
840   }
841 
842   ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
843   if (DR.isInvalid())
844     return nullptr;
845 
846   return DR.get();
847 }
848 
849 // Find an appropriate delete for the promise.
850 static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc,
851                                           QualType PromiseType) {
852   FunctionDecl *OperatorDelete = nullptr;
853 
854   DeclarationName DeleteName =
855       S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
856 
857   auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
858   assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
859 
860   if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
861     return nullptr;
862 
863   if (!OperatorDelete) {
864     // Look for a global declaration.
865     const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
866     const bool Overaligned = false;
867     OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
868                                                      Overaligned, DeleteName);
869   }
870   S.MarkFunctionReferenced(Loc, OperatorDelete);
871   return OperatorDelete;
872 }
873 
874 
875 void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
876   FunctionScopeInfo *Fn = getCurFunction();
877   assert(Fn && Fn->isCoroutine() && "not a coroutine");
878   if (!Body) {
879     assert(FD->isInvalidDecl() &&
880            "a null body is only allowed for invalid declarations");
881     return;
882   }
883   // We have a function that uses coroutine keywords, but we failed to build
884   // the promise type.
885   if (!Fn->CoroutinePromise)
886     return FD->setInvalidDecl();
887 
888   if (isa<CoroutineBodyStmt>(Body)) {
889     // Nothing todo. the body is already a transformed coroutine body statement.
890     return;
891   }
892 
893   // Coroutines [stmt.return]p1:
894   //   A return statement shall not appear in a coroutine.
895   if (Fn->FirstReturnLoc.isValid()) {
896     assert(Fn->FirstCoroutineStmtLoc.isValid() &&
897                    "first coroutine location not set");
898     Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
899     Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
900             << Fn->getFirstCoroutineStmtKeyword();
901   }
902   CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
903   if (Builder.isInvalid() || !Builder.buildStatements())
904     return FD->setInvalidDecl();
905 
906   // Build body for the coroutine wrapper statement.
907   Body = CoroutineBodyStmt::Create(Context, Builder);
908 }
909 
910 CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
911                                            sema::FunctionScopeInfo &Fn,
912                                            Stmt *Body)
913     : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
914       IsPromiseDependentType(
915           !Fn.CoroutinePromise ||
916           Fn.CoroutinePromise->getType()->isDependentType()) {
917   this->Body = Body;
918 
919   for (auto KV : Fn.CoroutineParameterMoves)
920     this->ParamMovesVector.push_back(KV.second);
921   this->ParamMoves = this->ParamMovesVector;
922 
923   if (!IsPromiseDependentType) {
924     PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
925     assert(PromiseRecordDecl && "Type should have already been checked");
926   }
927   this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
928 }
929 
930 bool CoroutineStmtBuilder::buildStatements() {
931   assert(this->IsValid && "coroutine already invalid");
932   this->IsValid = makeReturnObject();
933   if (this->IsValid && !IsPromiseDependentType)
934     buildDependentStatements();
935   return this->IsValid;
936 }
937 
938 bool CoroutineStmtBuilder::buildDependentStatements() {
939   assert(this->IsValid && "coroutine already invalid");
940   assert(!this->IsPromiseDependentType &&
941          "coroutine cannot have a dependent promise type");
942   this->IsValid = makeOnException() && makeOnFallthrough() &&
943                   makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
944                   makeNewAndDeleteExpr();
945   return this->IsValid;
946 }
947 
948 bool CoroutineStmtBuilder::makePromiseStmt() {
949   // Form a declaration statement for the promise declaration, so that AST
950   // visitors can more easily find it.
951   StmtResult PromiseStmt =
952       S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
953   if (PromiseStmt.isInvalid())
954     return false;
955 
956   this->Promise = PromiseStmt.get();
957   return true;
958 }
959 
960 bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
961   if (Fn.hasInvalidCoroutineSuspends())
962     return false;
963   this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
964   this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
965   return true;
966 }
967 
968 static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
969                                      CXXRecordDecl *PromiseRecordDecl,
970                                      FunctionScopeInfo &Fn) {
971   auto Loc = E->getExprLoc();
972   if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
973     auto *Decl = DeclRef->getDecl();
974     if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
975       if (Method->isStatic())
976         return true;
977       else
978         Loc = Decl->getLocation();
979     }
980   }
981 
982   S.Diag(
983       Loc,
984       diag::err_coroutine_promise_get_return_object_on_allocation_failure)
985       << PromiseRecordDecl;
986   S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
987       << Fn.getFirstCoroutineStmtKeyword();
988   return false;
989 }
990 
991 bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
992   assert(!IsPromiseDependentType &&
993          "cannot make statement while the promise type is dependent");
994 
995   // [dcl.fct.def.coroutine]/8
996   // The unqualified-id get_return_object_on_allocation_failure is looked up in
997   // the scope of class P by class member access lookup (3.4.5). ...
998   // If an allocation function returns nullptr, ... the coroutine return value
999   // is obtained by a call to ... get_return_object_on_allocation_failure().
1000 
1001   DeclarationName DN =
1002       S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
1003   LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
1004   if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
1005     return true;
1006 
1007   CXXScopeSpec SS;
1008   ExprResult DeclNameExpr =
1009       S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
1010   if (DeclNameExpr.isInvalid())
1011     return false;
1012 
1013   if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
1014     return false;
1015 
1016   ExprResult ReturnObjectOnAllocationFailure =
1017       S.ActOnCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
1018   if (ReturnObjectOnAllocationFailure.isInvalid())
1019     return false;
1020 
1021   StmtResult ReturnStmt =
1022       S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
1023   if (ReturnStmt.isInvalid()) {
1024     S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
1025         << DN;
1026     S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1027         << Fn.getFirstCoroutineStmtKeyword();
1028     return false;
1029   }
1030 
1031   this->ReturnStmtOnAllocFailure = ReturnStmt.get();
1032   return true;
1033 }
1034 
1035 bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
1036   // Form and check allocation and deallocation calls.
1037   assert(!IsPromiseDependentType &&
1038          "cannot make statement while the promise type is dependent");
1039   QualType PromiseType = Fn.CoroutinePromise->getType();
1040 
1041   if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
1042     return false;
1043 
1044   const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
1045 
1046   // [dcl.fct.def.coroutine]/7
1047   // Lookup allocation functions using a parameter list composed of the
1048   // requested size of the coroutine state being allocated, followed by
1049   // the coroutine function's arguments. If a matching allocation function
1050   // exists, use it. Otherwise, use an allocation function that just takes
1051   // the requested size.
1052 
1053   FunctionDecl *OperatorNew = nullptr;
1054   FunctionDecl *OperatorDelete = nullptr;
1055   FunctionDecl *UnusedResult = nullptr;
1056   bool PassAlignment = false;
1057   SmallVector<Expr *, 1> PlacementArgs;
1058 
1059   // [dcl.fct.def.coroutine]/7
1060   // "The allocation function’s name is looked up in the scope of P.
1061   // [...] If the lookup finds an allocation function in the scope of P,
1062   // overload resolution is performed on a function call created by assembling
1063   // an argument list. The first argument is the amount of space requested,
1064   // and has type std::size_t. The lvalues p1 ... pn are the succeeding
1065   // arguments."
1066   //
1067   // ...where "p1 ... pn" are defined earlier as:
1068   //
1069   // [dcl.fct.def.coroutine]/3
1070   // "For a coroutine f that is a non-static member function, let P1 denote the
1071   // type of the implicit object parameter (13.3.1) and P2 ... Pn be the types
1072   // of the function parameters; otherwise let P1 ... Pn be the types of the
1073   // function parameters. Let p1 ... pn be lvalues denoting those objects."
1074   if (auto *MD = dyn_cast<CXXMethodDecl>(&FD)) {
1075     if (MD->isInstance() && !isLambdaCallOperator(MD)) {
1076       ExprResult ThisExpr = S.ActOnCXXThis(Loc);
1077       if (ThisExpr.isInvalid())
1078         return false;
1079       ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
1080       if (ThisExpr.isInvalid())
1081         return false;
1082       PlacementArgs.push_back(ThisExpr.get());
1083     }
1084   }
1085   for (auto *PD : FD.parameters()) {
1086     if (PD->getType()->isDependentType())
1087       continue;
1088 
1089     // Build a reference to the parameter.
1090     auto PDLoc = PD->getLocation();
1091     ExprResult PDRefExpr =
1092         S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),
1093                            ExprValueKind::VK_LValue, PDLoc);
1094     if (PDRefExpr.isInvalid())
1095       return false;
1096 
1097     PlacementArgs.push_back(PDRefExpr.get());
1098   }
1099   S.FindAllocationFunctions(Loc, SourceRange(),
1100                             /*UseGlobal*/ false, PromiseType,
1101                             /*isArray*/ false, PassAlignment, PlacementArgs,
1102                             OperatorNew, UnusedResult, /*Diagnose*/ false);
1103 
1104   // [dcl.fct.def.coroutine]/7
1105   // "If no matching function is found, overload resolution is performed again
1106   // on a function call created by passing just the amount of space required as
1107   // an argument of type std::size_t."
1108   if (!OperatorNew && !PlacementArgs.empty()) {
1109     PlacementArgs.clear();
1110     S.FindAllocationFunctions(Loc, SourceRange(),
1111                               /*UseGlobal*/ false, PromiseType,
1112                               /*isArray*/ false, PassAlignment,
1113                               PlacementArgs, OperatorNew, UnusedResult);
1114   }
1115 
1116   bool IsGlobalOverload =
1117       OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
1118   // If we didn't find a class-local new declaration and non-throwing new
1119   // was is required then we need to lookup the non-throwing global operator
1120   // instead.
1121   if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
1122     auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
1123     if (!StdNoThrow)
1124       return false;
1125     PlacementArgs = {StdNoThrow};
1126     OperatorNew = nullptr;
1127     S.FindAllocationFunctions(Loc, SourceRange(),
1128                               /*UseGlobal*/ true, PromiseType,
1129                               /*isArray*/ false, PassAlignment, PlacementArgs,
1130                               OperatorNew, UnusedResult);
1131   }
1132 
1133   if (!OperatorNew)
1134     return false;
1135 
1136   if (RequiresNoThrowAlloc) {
1137     const auto *FT = OperatorNew->getType()->getAs<FunctionProtoType>();
1138     if (!FT->isNothrow(S.Context, /*ResultIfDependent*/ false)) {
1139       S.Diag(OperatorNew->getLocation(),
1140              diag::err_coroutine_promise_new_requires_nothrow)
1141           << OperatorNew;
1142       S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
1143           << OperatorNew;
1144       return false;
1145     }
1146   }
1147 
1148   if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr)
1149     return false;
1150 
1151   Expr *FramePtr =
1152       buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
1153 
1154   Expr *FrameSize =
1155       buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {});
1156 
1157   // Make new call.
1158 
1159   ExprResult NewRef =
1160       S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
1161   if (NewRef.isInvalid())
1162     return false;
1163 
1164   SmallVector<Expr *, 2> NewArgs(1, FrameSize);
1165   for (auto Arg : PlacementArgs)
1166     NewArgs.push_back(Arg);
1167 
1168   ExprResult NewExpr =
1169       S.ActOnCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
1170   NewExpr = S.ActOnFinishFullExpr(NewExpr.get());
1171   if (NewExpr.isInvalid())
1172     return false;
1173 
1174   // Make delete call.
1175 
1176   QualType OpDeleteQualType = OperatorDelete->getType();
1177 
1178   ExprResult DeleteRef =
1179       S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
1180   if (DeleteRef.isInvalid())
1181     return false;
1182 
1183   Expr *CoroFree =
1184       buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr});
1185 
1186   SmallVector<Expr *, 2> DeleteArgs{CoroFree};
1187 
1188   // Check if we need to pass the size.
1189   const auto *OpDeleteType =
1190       OpDeleteQualType.getTypePtr()->getAs<FunctionProtoType>();
1191   if (OpDeleteType->getNumParams() > 1)
1192     DeleteArgs.push_back(FrameSize);
1193 
1194   ExprResult DeleteExpr =
1195       S.ActOnCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
1196   DeleteExpr = S.ActOnFinishFullExpr(DeleteExpr.get());
1197   if (DeleteExpr.isInvalid())
1198     return false;
1199 
1200   this->Allocate = NewExpr.get();
1201   this->Deallocate = DeleteExpr.get();
1202 
1203   return true;
1204 }
1205 
1206 bool CoroutineStmtBuilder::makeOnFallthrough() {
1207   assert(!IsPromiseDependentType &&
1208          "cannot make statement while the promise type is dependent");
1209 
1210   // [dcl.fct.def.coroutine]/4
1211   // The unqualified-ids 'return_void' and 'return_value' are looked up in
1212   // the scope of class P. If both are found, the program is ill-formed.
1213   bool HasRVoid, HasRValue;
1214   LookupResult LRVoid =
1215       lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
1216   LookupResult LRValue =
1217       lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
1218 
1219   StmtResult Fallthrough;
1220   if (HasRVoid && HasRValue) {
1221     // FIXME Improve this diagnostic
1222     S.Diag(FD.getLocation(),
1223            diag::err_coroutine_promise_incompatible_return_functions)
1224         << PromiseRecordDecl;
1225     S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
1226            diag::note_member_first_declared_here)
1227         << LRVoid.getLookupName();
1228     S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
1229            diag::note_member_first_declared_here)
1230         << LRValue.getLookupName();
1231     return false;
1232   } else if (!HasRVoid && !HasRValue) {
1233     // FIXME: The PDTS currently specifies this case as UB, not ill-formed.
1234     // However we still diagnose this as an error since until the PDTS is fixed.
1235     S.Diag(FD.getLocation(),
1236            diag::err_coroutine_promise_requires_return_function)
1237         << PromiseRecordDecl;
1238     S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1239         << PromiseRecordDecl;
1240     return false;
1241   } else if (HasRVoid) {
1242     // If the unqualified-id return_void is found, flowing off the end of a
1243     // coroutine is equivalent to a co_return with no operand. Otherwise,
1244     // flowing off the end of a coroutine results in undefined behavior.
1245     Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
1246                                       /*IsImplicit*/false);
1247     Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
1248     if (Fallthrough.isInvalid())
1249       return false;
1250   }
1251 
1252   this->OnFallthrough = Fallthrough.get();
1253   return true;
1254 }
1255 
1256 bool CoroutineStmtBuilder::makeOnException() {
1257   // Try to form 'p.unhandled_exception();'
1258   assert(!IsPromiseDependentType &&
1259          "cannot make statement while the promise type is dependent");
1260 
1261   const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1262 
1263   if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
1264     auto DiagID =
1265         RequireUnhandledException
1266             ? diag::err_coroutine_promise_unhandled_exception_required
1267             : diag::
1268                   warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1269     S.Diag(Loc, DiagID) << PromiseRecordDecl;
1270     S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1271         << PromiseRecordDecl;
1272     return !RequireUnhandledException;
1273   }
1274 
1275   // If exceptions are disabled, don't try to build OnException.
1276   if (!S.getLangOpts().CXXExceptions)
1277     return true;
1278 
1279   ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
1280                                                    "unhandled_exception", None);
1281   UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc);
1282   if (UnhandledException.isInvalid())
1283     return false;
1284 
1285   // Since the body of the coroutine will be wrapped in try-catch, it will
1286   // be incompatible with SEH __try if present in a function.
1287   if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1288     S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1289     S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1290         << Fn.getFirstCoroutineStmtKeyword();
1291     return false;
1292   }
1293 
1294   this->OnException = UnhandledException.get();
1295   return true;
1296 }
1297 
1298 bool CoroutineStmtBuilder::makeReturnObject() {
1299   // Build implicit 'p.get_return_object()' expression and form initialization
1300   // of return type from it.
1301   ExprResult ReturnObject =
1302       buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
1303   if (ReturnObject.isInvalid())
1304     return false;
1305 
1306   this->ReturnValue = ReturnObject.get();
1307   return true;
1308 }
1309 
1310 static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
1311   if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
1312     auto *MethodDecl = MbrRef->getMethodDecl();
1313     S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
1314         << MethodDecl;
1315   }
1316   S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1317       << Fn.getFirstCoroutineStmtKeyword();
1318 }
1319 
1320 bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1321   assert(!IsPromiseDependentType &&
1322          "cannot make statement while the promise type is dependent");
1323   assert(this->ReturnValue && "ReturnValue must be already formed");
1324 
1325   QualType const GroType = this->ReturnValue->getType();
1326   assert(!GroType->isDependentType() &&
1327          "get_return_object type must no longer be dependent");
1328 
1329   QualType const FnRetType = FD.getReturnType();
1330   assert(!FnRetType->isDependentType() &&
1331          "get_return_object type must no longer be dependent");
1332 
1333   if (FnRetType->isVoidType()) {
1334     ExprResult Res = S.ActOnFinishFullExpr(this->ReturnValue, Loc);
1335     if (Res.isInvalid())
1336       return false;
1337 
1338     this->ResultDecl = Res.get();
1339     return true;
1340   }
1341 
1342   if (GroType->isVoidType()) {
1343     // Trigger a nice error message.
1344     InitializedEntity Entity =
1345         InitializedEntity::InitializeResult(Loc, FnRetType, false);
1346     S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue);
1347     noteMemberDeclaredHere(S, ReturnValue, Fn);
1348     return false;
1349   }
1350 
1351   auto *GroDecl = VarDecl::Create(
1352       S.Context, &FD, FD.getLocation(), FD.getLocation(),
1353       &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
1354       S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
1355 
1356   S.CheckVariableDeclarationType(GroDecl);
1357   if (GroDecl->isInvalidDecl())
1358     return false;
1359 
1360   InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
1361   ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType,
1362                                                      this->ReturnValue);
1363   if (Res.isInvalid())
1364     return false;
1365 
1366   Res = S.ActOnFinishFullExpr(Res.get());
1367   if (Res.isInvalid())
1368     return false;
1369 
1370   S.AddInitializerToDecl(GroDecl, Res.get(),
1371                          /*DirectInit=*/false);
1372 
1373   S.FinalizeDeclaration(GroDecl);
1374 
1375   // Form a declaration statement for the return declaration, so that AST
1376   // visitors can more easily find it.
1377   StmtResult GroDeclStmt =
1378       S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
1379   if (GroDeclStmt.isInvalid())
1380     return false;
1381 
1382   this->ResultDecl = GroDeclStmt.get();
1383 
1384   ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
1385   if (declRef.isInvalid())
1386     return false;
1387 
1388   StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
1389   if (ReturnStmt.isInvalid()) {
1390     noteMemberDeclaredHere(S, ReturnValue, Fn);
1391     return false;
1392   }
1393   if (cast<clang::ReturnStmt>(ReturnStmt.get())->getNRVOCandidate() == GroDecl)
1394     GroDecl->setNRVOVariable(true);
1395 
1396   this->ReturnStmt = ReturnStmt.get();
1397   return true;
1398 }
1399 
1400 // Create a static_cast\<T&&>(expr).
1401 static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
1402   if (T.isNull())
1403     T = E->getType();
1404   QualType TargetType = S.BuildReferenceType(
1405       T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());
1406   SourceLocation ExprLoc = E->getLocStart();
1407   TypeSourceInfo *TargetLoc =
1408       S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
1409 
1410   return S
1411       .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1412                          SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
1413       .get();
1414 }
1415 
1416 /// \brief Build a variable declaration for move parameter.
1417 static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
1418                              IdentifierInfo *II) {
1419   TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);
1420   VarDecl *Decl = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type,
1421                                   TInfo, SC_None);
1422   Decl->setImplicit();
1423   return Decl;
1424 }
1425 
1426 // Build statements that move coroutine function parameters to the coroutine
1427 // frame, and store them on the function scope info.
1428 bool Sema::buildCoroutineParameterMoves(SourceLocation Loc) {
1429   assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
1430   auto *FD = cast<FunctionDecl>(CurContext);
1431 
1432   auto *ScopeInfo = getCurFunction();
1433   assert(ScopeInfo->CoroutineParameterMoves.empty() &&
1434          "Should not build parameter moves twice");
1435 
1436   for (auto *PD : FD->parameters()) {
1437     if (PD->getType()->isDependentType())
1438       continue;
1439 
1440     ExprResult PDRefExpr =
1441         BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
1442                          ExprValueKind::VK_LValue, Loc); // FIXME: scope?
1443     if (PDRefExpr.isInvalid())
1444       return false;
1445 
1446     Expr *CExpr = nullptr;
1447     if (PD->getType()->getAsCXXRecordDecl() ||
1448         PD->getType()->isRValueReferenceType())
1449       CExpr = castForMoving(*this, PDRefExpr.get());
1450     else
1451       CExpr = PDRefExpr.get();
1452 
1453     auto D = buildVarDecl(*this, Loc, PD->getType(), PD->getIdentifier());
1454     AddInitializerToDecl(D, CExpr, /*DirectInit=*/true);
1455 
1456     // Convert decl to a statement.
1457     StmtResult Stmt = ActOnDeclStmt(ConvertDeclToDeclGroup(D), Loc, Loc);
1458     if (Stmt.isInvalid())
1459       return false;
1460 
1461     ScopeInfo->CoroutineParameterMoves.insert(std::make_pair(PD, Stmt.get()));
1462   }
1463   return true;
1464 }
1465 
1466 StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1467   CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
1468   if (!Res)
1469     return StmtError();
1470   return Res;
1471 }
1472