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