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 
lookupMember(Sema & S,const char * Name,CXXRecordDecl * RD,SourceLocation Loc,bool & Res)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 
lookupMember(Sema & S,const char * Name,CXXRecordDecl * RD,SourceLocation Loc)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.
lookupPromiseType(Sema & S,const FunctionDecl * FD,SourceLocation KwLoc)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>.
lookupCoroutineHandleType(Sema & S,QualType PromiseType,SourceLocation Loc)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 
isValidCoroutineContext(Sema & S,SourceLocation Loc,StringRef Keyword)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 
buildOperatorCoawaitLookupExpr(Sema & SemaRef,Scope * S,SourceLocation Loc)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.
buildOperatorCoawaitCall(Sema & SemaRef,SourceLocation Loc,Expr * E,UnresolvedLookupExpr * Lookup)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 
buildOperatorCoawaitCall(Sema & SemaRef,Scope * S,SourceLocation Loc,Expr * E)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 
buildBuiltinCall(Sema & S,SourceLocation Loc,Builtin::ID Id,MultiExprArg CallArgs)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 
buildCoroutineHandle(Sema & S,QualType PromiseType,SourceLocation Loc)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 
buildMemberCall(Sema & S,Expr * Base,SourceLocation Loc,StringRef Name,MultiExprArg Args)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.
maybeTailCall(Sema & S,QualType RetType,Expr * E,SourceLocation Loc)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 
395   // Check that the type of AddressExpr is void*
396   if (!JustAddress->getType().getTypePtr()->isVoidPointerType())
397     S.Diag(cast<CallExpr>(JustAddress)->getCalleeDecl()->getLocation(),
398            diag::warn_coroutine_handle_address_invalid_return_type)
399         << JustAddress->getType();
400 
401   // Clean up temporary objects so that they don't live across suspension points
402   // unnecessarily. We choose to clean up before the call to
403   // __builtin_coro_resume so that the cleanup code are not inserted in-between
404   // the resume call and return instruction, which would interfere with the
405   // musttail call contract.
406   JustAddress = S.MaybeCreateExprWithCleanups(JustAddress);
407   return buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_resume,
408                           JustAddress);
409 }
410 
411 /// Build calls to await_ready, await_suspend, and await_resume for a co_await
412 /// expression.
413 /// The generated AST tries to clean up temporary objects as early as
414 /// possible so that they don't live across suspension points if possible.
415 /// Having temporary objects living across suspension points unnecessarily can
416 /// lead to large frame size, and also lead to memory corruptions if the
417 /// coroutine frame is destroyed after coming back from suspension. This is done
418 /// by wrapping both the await_ready call and the await_suspend call with
419 /// ExprWithCleanups. In the end of this function, we also need to explicitly
420 /// set cleanup state so that the CoawaitExpr is also wrapped with an
421 /// ExprWithCleanups to clean up the awaiter associated with the co_await
422 /// expression.
buildCoawaitCalls(Sema & S,VarDecl * CoroPromise,SourceLocation Loc,Expr * E)423 static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
424                                                   SourceLocation Loc, Expr *E) {
425   OpaqueValueExpr *Operand = new (S.Context)
426       OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
427 
428   // Assume valid until we see otherwise.
429   // Further operations are responsible for setting IsInalid to true.
430   ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/false};
431 
432   using ACT = ReadySuspendResumeResult::AwaitCallType;
433 
434   auto BuildSubExpr = [&](ACT CallType, StringRef Func,
435                           MultiExprArg Arg) -> Expr * {
436     ExprResult Result = buildMemberCall(S, Operand, Loc, Func, Arg);
437     if (Result.isInvalid()) {
438       Calls.IsInvalid = true;
439       return nullptr;
440     }
441     Calls.Results[CallType] = Result.get();
442     return Result.get();
443   };
444 
445   CallExpr *AwaitReady =
446       cast_or_null<CallExpr>(BuildSubExpr(ACT::ACT_Ready, "await_ready", None));
447   if (!AwaitReady)
448     return Calls;
449   if (!AwaitReady->getType()->isDependentType()) {
450     // [expr.await]p3 [...]
451     // — await-ready is the expression e.await_ready(), contextually converted
452     // to bool.
453     ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady);
454     if (Conv.isInvalid()) {
455       S.Diag(AwaitReady->getDirectCallee()->getBeginLoc(),
456              diag::note_await_ready_no_bool_conversion);
457       S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
458           << AwaitReady->getDirectCallee() << E->getSourceRange();
459       Calls.IsInvalid = true;
460     } else
461       Calls.Results[ACT::ACT_Ready] = S.MaybeCreateExprWithCleanups(Conv.get());
462   }
463 
464   ExprResult CoroHandleRes =
465       buildCoroutineHandle(S, CoroPromise->getType(), Loc);
466   if (CoroHandleRes.isInvalid()) {
467     Calls.IsInvalid = true;
468     return Calls;
469   }
470   Expr *CoroHandle = CoroHandleRes.get();
471   CallExpr *AwaitSuspend = cast_or_null<CallExpr>(
472       BuildSubExpr(ACT::ACT_Suspend, "await_suspend", CoroHandle));
473   if (!AwaitSuspend)
474     return Calls;
475   if (!AwaitSuspend->getType()->isDependentType()) {
476     // [expr.await]p3 [...]
477     //   - await-suspend is the expression e.await_suspend(h), which shall be
478     //     a prvalue of type void, bool, or std::coroutine_handle<Z> for some
479     //     type Z.
480     QualType RetType = AwaitSuspend->getCallReturnType(S.Context);
481 
482     // Experimental support for coroutine_handle returning await_suspend.
483     if (Expr *TailCallSuspend =
484             maybeTailCall(S, RetType, AwaitSuspend, Loc))
485       // Note that we don't wrap the expression with ExprWithCleanups here
486       // because that might interfere with tailcall contract (e.g. inserting
487       // clean up instructions in-between tailcall and return). Instead
488       // ExprWithCleanups is wrapped within maybeTailCall() prior to the resume
489       // call.
490       Calls.Results[ACT::ACT_Suspend] = TailCallSuspend;
491     else {
492       // non-class prvalues always have cv-unqualified types
493       if (RetType->isReferenceType() ||
494           (!RetType->isBooleanType() && !RetType->isVoidType())) {
495         S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
496                diag::err_await_suspend_invalid_return_type)
497             << RetType;
498         S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
499             << AwaitSuspend->getDirectCallee();
500         Calls.IsInvalid = true;
501       } else
502         Calls.Results[ACT::ACT_Suspend] =
503             S.MaybeCreateExprWithCleanups(AwaitSuspend);
504     }
505   }
506 
507   BuildSubExpr(ACT::ACT_Resume, "await_resume", None);
508 
509   // Make sure the awaiter object gets a chance to be cleaned up.
510   S.Cleanup.setExprNeedsCleanups(true);
511 
512   return Calls;
513 }
514 
buildPromiseCall(Sema & S,VarDecl * Promise,SourceLocation Loc,StringRef Name,MultiExprArg Args)515 static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
516                                    SourceLocation Loc, StringRef Name,
517                                    MultiExprArg Args) {
518 
519   // Form a reference to the promise.
520   ExprResult PromiseRef = S.BuildDeclRefExpr(
521       Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
522   if (PromiseRef.isInvalid())
523     return ExprError();
524 
525   return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
526 }
527 
buildCoroutinePromise(SourceLocation Loc)528 VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
529   assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
530   auto *FD = cast<FunctionDecl>(CurContext);
531   bool IsThisDependentType = [&] {
532     if (auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD))
533       return MD->isInstance() && MD->getThisType()->isDependentType();
534     else
535       return false;
536   }();
537 
538   QualType T = FD->getType()->isDependentType() || IsThisDependentType
539                    ? Context.DependentTy
540                    : lookupPromiseType(*this, FD, Loc);
541   if (T.isNull())
542     return nullptr;
543 
544   auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
545                              &PP.getIdentifierTable().get("__promise"), T,
546                              Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
547   CheckVariableDeclarationType(VD);
548   if (VD->isInvalidDecl())
549     return nullptr;
550 
551   auto *ScopeInfo = getCurFunction();
552 
553   // Build a list of arguments, based on the coroutine function's arguments,
554   // that if present will be passed to the promise type's constructor.
555   llvm::SmallVector<Expr *, 4> CtorArgExprs;
556 
557   // Add implicit object parameter.
558   if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
559     if (MD->isInstance() && !isLambdaCallOperator(MD)) {
560       ExprResult ThisExpr = ActOnCXXThis(Loc);
561       if (ThisExpr.isInvalid())
562         return nullptr;
563       ThisExpr = CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
564       if (ThisExpr.isInvalid())
565         return nullptr;
566       CtorArgExprs.push_back(ThisExpr.get());
567     }
568   }
569 
570   // Add the coroutine function's parameters.
571   auto &Moves = ScopeInfo->CoroutineParameterMoves;
572   for (auto *PD : FD->parameters()) {
573     if (PD->getType()->isDependentType())
574       continue;
575 
576     auto RefExpr = ExprEmpty();
577     auto Move = Moves.find(PD);
578     assert(Move != Moves.end() &&
579            "Coroutine function parameter not inserted into move map");
580     // If a reference to the function parameter exists in the coroutine
581     // frame, use that reference.
582     auto *MoveDecl =
583         cast<VarDecl>(cast<DeclStmt>(Move->second)->getSingleDecl());
584     RefExpr =
585         BuildDeclRefExpr(MoveDecl, MoveDecl->getType().getNonReferenceType(),
586                          ExprValueKind::VK_LValue, FD->getLocation());
587     if (RefExpr.isInvalid())
588       return nullptr;
589     CtorArgExprs.push_back(RefExpr.get());
590   }
591 
592   // If we have a non-zero number of constructor arguments, try to use them.
593   // Otherwise, fall back to the promise type's default constructor.
594   if (!CtorArgExprs.empty()) {
595     // Create an initialization sequence for the promise type using the
596     // constructor arguments, wrapped in a parenthesized list expression.
597     Expr *PLE = ParenListExpr::Create(Context, FD->getLocation(),
598                                       CtorArgExprs, FD->getLocation());
599     InitializedEntity Entity = InitializedEntity::InitializeVariable(VD);
600     InitializationKind Kind = InitializationKind::CreateForInit(
601         VD->getLocation(), /*DirectInit=*/true, PLE);
602     InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs,
603                                    /*TopLevelOfInitList=*/false,
604                                    /*TreatUnavailableAsInvalid=*/false);
605 
606     // Attempt to initialize the promise type with the arguments.
607     // If that fails, fall back to the promise type's default constructor.
608     if (InitSeq) {
609       ExprResult Result = InitSeq.Perform(*this, Entity, Kind, CtorArgExprs);
610       if (Result.isInvalid()) {
611         VD->setInvalidDecl();
612       } else if (Result.get()) {
613         VD->setInit(MaybeCreateExprWithCleanups(Result.get()));
614         VD->setInitStyle(VarDecl::CallInit);
615         CheckCompleteVariableDeclaration(VD);
616       }
617     } else
618       ActOnUninitializedDecl(VD);
619   } else
620     ActOnUninitializedDecl(VD);
621 
622   FD->addDecl(VD);
623   return VD;
624 }
625 
626 /// Check that this is a context in which a coroutine suspension can appear.
checkCoroutineContext(Sema & S,SourceLocation Loc,StringRef Keyword,bool IsImplicit=false)627 static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
628                                                 StringRef Keyword,
629                                                 bool IsImplicit = false) {
630   if (!isValidCoroutineContext(S, Loc, Keyword))
631     return nullptr;
632 
633   assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
634 
635   auto *ScopeInfo = S.getCurFunction();
636   assert(ScopeInfo && "missing function scope for function");
637 
638   if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
639     ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
640 
641   if (ScopeInfo->CoroutinePromise)
642     return ScopeInfo;
643 
644   if (!S.buildCoroutineParameterMoves(Loc))
645     return nullptr;
646 
647   ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
648   if (!ScopeInfo->CoroutinePromise)
649     return nullptr;
650 
651   return ScopeInfo;
652 }
653 
654 /// Recursively check \p E and all its children to see if any call target
655 /// (including constructor call) is declared noexcept. Also any value returned
656 /// from the call has a noexcept destructor.
checkNoThrow(Sema & S,const Stmt * E,llvm::SmallPtrSetImpl<const Decl * > & ThrowingDecls)657 static void checkNoThrow(Sema &S, const Stmt *E,
658                          llvm::SmallPtrSetImpl<const Decl *> &ThrowingDecls) {
659   auto checkDeclNoexcept = [&](const Decl *D, bool IsDtor = false) {
660     // In the case of dtor, the call to dtor is implicit and hence we should
661     // pass nullptr to canCalleeThrow.
662     if (Sema::canCalleeThrow(S, IsDtor ? nullptr : cast<Expr>(E), D)) {
663       if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
664         // co_await promise.final_suspend() could end up calling
665         // __builtin_coro_resume for symmetric transfer if await_suspend()
666         // returns a handle. In that case, even __builtin_coro_resume is not
667         // declared as noexcept and may throw, it does not throw _into_ the
668         // coroutine that just suspended, but rather throws back out from
669         // whoever called coroutine_handle::resume(), hence we claim that
670         // logically it does not throw.
671         if (FD->getBuiltinID() == Builtin::BI__builtin_coro_resume)
672           return;
673       }
674       if (ThrowingDecls.empty()) {
675         // First time seeing an error, emit the error message.
676         S.Diag(cast<FunctionDecl>(S.CurContext)->getLocation(),
677                diag::err_coroutine_promise_final_suspend_requires_nothrow);
678       }
679       ThrowingDecls.insert(D);
680     }
681   };
682   auto SC = E->getStmtClass();
683   if (SC == Expr::CXXConstructExprClass) {
684     auto const *Ctor = cast<CXXConstructExpr>(E)->getConstructor();
685     checkDeclNoexcept(Ctor);
686     // Check the corresponding destructor of the constructor.
687     checkDeclNoexcept(Ctor->getParent()->getDestructor(), true);
688   } else if (SC == Expr::CallExprClass || SC == Expr::CXXMemberCallExprClass ||
689              SC == Expr::CXXOperatorCallExprClass) {
690     if (!cast<CallExpr>(E)->isTypeDependent()) {
691       checkDeclNoexcept(cast<CallExpr>(E)->getCalleeDecl());
692       auto ReturnType = cast<CallExpr>(E)->getCallReturnType(S.getASTContext());
693       // Check the destructor of the call return type, if any.
694       if (ReturnType.isDestructedType() ==
695           QualType::DestructionKind::DK_cxx_destructor) {
696         const auto *T =
697             cast<RecordType>(ReturnType.getCanonicalType().getTypePtr());
698         checkDeclNoexcept(
699             dyn_cast<CXXRecordDecl>(T->getDecl())->getDestructor(), true);
700       }
701     }
702   }
703   for (const auto *Child : E->children()) {
704     if (!Child)
705       continue;
706     checkNoThrow(S, Child, ThrowingDecls);
707   }
708 }
709 
checkFinalSuspendNoThrow(const Stmt * FinalSuspend)710 bool Sema::checkFinalSuspendNoThrow(const Stmt *FinalSuspend) {
711   llvm::SmallPtrSet<const Decl *, 4> ThrowingDecls;
712   // We first collect all declarations that should not throw but not declared
713   // with noexcept. We then sort them based on the location before printing.
714   // This is to avoid emitting the same note multiple times on the same
715   // declaration, and also provide a deterministic order for the messages.
716   checkNoThrow(*this, FinalSuspend, ThrowingDecls);
717   auto SortedDecls = llvm::SmallVector<const Decl *, 4>{ThrowingDecls.begin(),
718                                                         ThrowingDecls.end()};
719   sort(SortedDecls, [](const Decl *A, const Decl *B) {
720     return A->getEndLoc() < B->getEndLoc();
721   });
722   for (const auto *D : SortedDecls) {
723     Diag(D->getEndLoc(), diag::note_coroutine_function_declare_noexcept);
724   }
725   return ThrowingDecls.empty();
726 }
727 
ActOnCoroutineBodyStart(Scope * SC,SourceLocation KWLoc,StringRef Keyword)728 bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc,
729                                    StringRef Keyword) {
730   if (!checkCoroutineContext(*this, KWLoc, Keyword))
731     return false;
732   auto *ScopeInfo = getCurFunction();
733   assert(ScopeInfo->CoroutinePromise);
734 
735   // If we have existing coroutine statements then we have already built
736   // the initial and final suspend points.
737   if (!ScopeInfo->NeedsCoroutineSuspends)
738     return true;
739 
740   ScopeInfo->setNeedsCoroutineSuspends(false);
741 
742   auto *Fn = cast<FunctionDecl>(CurContext);
743   SourceLocation Loc = Fn->getLocation();
744   // Build the initial suspend point
745   auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
746     ExprResult Suspend =
747         buildPromiseCall(*this, ScopeInfo->CoroutinePromise, Loc, Name, None);
748     if (Suspend.isInvalid())
749       return StmtError();
750     Suspend = buildOperatorCoawaitCall(*this, SC, Loc, Suspend.get());
751     if (Suspend.isInvalid())
752       return StmtError();
753     Suspend = BuildResolvedCoawaitExpr(Loc, Suspend.get(),
754                                        /*IsImplicit*/ true);
755     Suspend = ActOnFinishFullExpr(Suspend.get(), /*DiscardedValue*/ false);
756     if (Suspend.isInvalid()) {
757       Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
758           << ((Name == "initial_suspend") ? 0 : 1);
759       Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
760       return StmtError();
761     }
762     return cast<Stmt>(Suspend.get());
763   };
764 
765   StmtResult InitSuspend = buildSuspends("initial_suspend");
766   if (InitSuspend.isInvalid())
767     return true;
768 
769   StmtResult FinalSuspend = buildSuspends("final_suspend");
770   if (FinalSuspend.isInvalid() || !checkFinalSuspendNoThrow(FinalSuspend.get()))
771     return true;
772 
773   ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
774 
775   return true;
776 }
777 
778 // Recursively walks up the scope hierarchy until either a 'catch' or a function
779 // scope is found, whichever comes first.
isWithinCatchScope(Scope * S)780 static bool isWithinCatchScope(Scope *S) {
781   // 'co_await' and 'co_yield' keywords are disallowed within catch blocks, but
782   // lambdas that use 'co_await' are allowed. The loop below ends when a
783   // function scope is found in order to ensure the following behavior:
784   //
785   // void foo() {      // <- function scope
786   //   try {           //
787   //     co_await x;   // <- 'co_await' is OK within a function scope
788   //   } catch {       // <- catch scope
789   //     co_await x;   // <- 'co_await' is not OK within a catch scope
790   //     []() {        // <- function scope
791   //       co_await x; // <- 'co_await' is OK within a function scope
792   //     }();
793   //   }
794   // }
795   while (S && !(S->getFlags() & Scope::FnScope)) {
796     if (S->getFlags() & Scope::CatchScope)
797       return true;
798     S = S->getParent();
799   }
800   return false;
801 }
802 
803 // [expr.await]p2, emphasis added: "An await-expression shall appear only in
804 // a *potentially evaluated* expression within the compound-statement of a
805 // function-body *outside of a handler* [...] A context within a function
806 // where an await-expression can appear is called a suspension context of the
807 // function."
checkSuspensionContext(Sema & S,SourceLocation Loc,StringRef Keyword)808 static void checkSuspensionContext(Sema &S, SourceLocation Loc,
809                                    StringRef Keyword) {
810   // First emphasis of [expr.await]p2: must be a potentially evaluated context.
811   // That is, 'co_await' and 'co_yield' cannot appear in subexpressions of
812   // \c sizeof.
813   if (S.isUnevaluatedContext())
814     S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
815 
816   // Second emphasis of [expr.await]p2: must be outside of an exception handler.
817   if (isWithinCatchScope(S.getCurScope()))
818     S.Diag(Loc, diag::err_coroutine_within_handler) << Keyword;
819 }
820 
ActOnCoawaitExpr(Scope * S,SourceLocation Loc,Expr * E)821 ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
822   if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) {
823     CorrectDelayedTyposInExpr(E);
824     return ExprError();
825   }
826 
827   checkSuspensionContext(*this, Loc, "co_await");
828 
829   if (E->getType()->isPlaceholderType()) {
830     ExprResult R = CheckPlaceholderExpr(E);
831     if (R.isInvalid()) return ExprError();
832     E = R.get();
833   }
834   ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
835   if (Lookup.isInvalid())
836     return ExprError();
837   return BuildUnresolvedCoawaitExpr(Loc, E,
838                                    cast<UnresolvedLookupExpr>(Lookup.get()));
839 }
840 
BuildUnresolvedCoawaitExpr(SourceLocation Loc,Expr * E,UnresolvedLookupExpr * Lookup)841 ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E,
842                                             UnresolvedLookupExpr *Lookup) {
843   auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
844   if (!FSI)
845     return ExprError();
846 
847   if (E->getType()->isPlaceholderType()) {
848     ExprResult R = CheckPlaceholderExpr(E);
849     if (R.isInvalid())
850       return ExprError();
851     E = R.get();
852   }
853 
854   auto *Promise = FSI->CoroutinePromise;
855   if (Promise->getType()->isDependentType()) {
856     Expr *Res =
857         new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
858     return Res;
859   }
860 
861   auto *RD = Promise->getType()->getAsCXXRecordDecl();
862   if (lookupMember(*this, "await_transform", RD, Loc)) {
863     ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
864     if (R.isInvalid()) {
865       Diag(Loc,
866            diag::note_coroutine_promise_implicit_await_transform_required_here)
867           << E->getSourceRange();
868       return ExprError();
869     }
870     E = R.get();
871   }
872   ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
873   if (Awaitable.isInvalid())
874     return ExprError();
875 
876   return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
877 }
878 
BuildResolvedCoawaitExpr(SourceLocation Loc,Expr * E,bool IsImplicit)879 ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E,
880                                   bool IsImplicit) {
881   auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
882   if (!Coroutine)
883     return ExprError();
884 
885   if (E->getType()->isPlaceholderType()) {
886     ExprResult R = CheckPlaceholderExpr(E);
887     if (R.isInvalid()) return ExprError();
888     E = R.get();
889   }
890 
891   if (E->getType()->isDependentType()) {
892     Expr *Res = new (Context)
893         CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
894     return Res;
895   }
896 
897   // If the expression is a temporary, materialize it as an lvalue so that we
898   // can use it multiple times.
899   if (E->getValueKind() == VK_RValue)
900     E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
901 
902   // The location of the `co_await` token cannot be used when constructing
903   // the member call expressions since it's before the location of `Expr`, which
904   // is used as the start of the member call expression.
905   SourceLocation CallLoc = E->getExprLoc();
906 
907   // Build the await_ready, await_suspend, await_resume calls.
908   ReadySuspendResumeResult RSS = buildCoawaitCalls(
909       *this, Coroutine->CoroutinePromise, CallLoc, E);
910   if (RSS.IsInvalid)
911     return ExprError();
912 
913   Expr *Res =
914       new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
915                                 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
916 
917   return Res;
918 }
919 
ActOnCoyieldExpr(Scope * S,SourceLocation Loc,Expr * E)920 ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
921   if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) {
922     CorrectDelayedTyposInExpr(E);
923     return ExprError();
924   }
925 
926   checkSuspensionContext(*this, Loc, "co_yield");
927 
928   // Build yield_value call.
929   ExprResult Awaitable = buildPromiseCall(
930       *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
931   if (Awaitable.isInvalid())
932     return ExprError();
933 
934   // Build 'operator co_await' call.
935   Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
936   if (Awaitable.isInvalid())
937     return ExprError();
938 
939   return BuildCoyieldExpr(Loc, Awaitable.get());
940 }
BuildCoyieldExpr(SourceLocation Loc,Expr * E)941 ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
942   auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
943   if (!Coroutine)
944     return ExprError();
945 
946   if (E->getType()->isPlaceholderType()) {
947     ExprResult R = CheckPlaceholderExpr(E);
948     if (R.isInvalid()) return ExprError();
949     E = R.get();
950   }
951 
952   if (E->getType()->isDependentType()) {
953     Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
954     return Res;
955   }
956 
957   // If the expression is a temporary, materialize it as an lvalue so that we
958   // can use it multiple times.
959   if (E->getValueKind() == VK_RValue)
960     E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
961 
962   // Build the await_ready, await_suspend, await_resume calls.
963   ReadySuspendResumeResult RSS = buildCoawaitCalls(
964       *this, Coroutine->CoroutinePromise, Loc, E);
965   if (RSS.IsInvalid)
966     return ExprError();
967 
968   Expr *Res =
969       new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
970                                 RSS.Results[2], RSS.OpaqueValue);
971 
972   return Res;
973 }
974 
ActOnCoreturnStmt(Scope * S,SourceLocation Loc,Expr * E)975 StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
976   if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) {
977     CorrectDelayedTyposInExpr(E);
978     return StmtError();
979   }
980   return BuildCoreturnStmt(Loc, E);
981 }
982 
BuildCoreturnStmt(SourceLocation Loc,Expr * E,bool IsImplicit)983 StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
984                                    bool IsImplicit) {
985   auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
986   if (!FSI)
987     return StmtError();
988 
989   if (E && E->getType()->isPlaceholderType() &&
990       !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
991     ExprResult R = CheckPlaceholderExpr(E);
992     if (R.isInvalid()) return StmtError();
993     E = R.get();
994   }
995 
996   // Move the return value if we can
997   if (E) {
998     auto NRVOCandidate = this->getCopyElisionCandidate(E->getType(), E, CES_AsIfByStdMove);
999     if (NRVOCandidate) {
1000       InitializedEntity Entity =
1001           InitializedEntity::InitializeResult(Loc, E->getType(), NRVOCandidate);
1002       ExprResult MoveResult = this->PerformMoveOrCopyInitialization(
1003           Entity, NRVOCandidate, E->getType(), E);
1004       if (MoveResult.get())
1005         E = MoveResult.get();
1006     }
1007   }
1008 
1009   // FIXME: If the operand is a reference to a variable that's about to go out
1010   // of scope, we should treat the operand as an xvalue for this overload
1011   // resolution.
1012   VarDecl *Promise = FSI->CoroutinePromise;
1013   ExprResult PC;
1014   if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
1015     PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
1016   } else {
1017     E = MakeFullDiscardedValueExpr(E).get();
1018     PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
1019   }
1020   if (PC.isInvalid())
1021     return StmtError();
1022 
1023   Expr *PCE = ActOnFinishFullExpr(PC.get(), /*DiscardedValue*/ false).get();
1024 
1025   Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
1026   return Res;
1027 }
1028 
1029 /// Look up the std::nothrow object.
buildStdNoThrowDeclRef(Sema & S,SourceLocation Loc)1030 static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
1031   NamespaceDecl *Std = S.getStdNamespace();
1032   assert(Std && "Should already be diagnosed");
1033 
1034   LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
1035                       Sema::LookupOrdinaryName);
1036   if (!S.LookupQualifiedName(Result, Std)) {
1037     // FIXME: <experimental/coroutine> should have been included already.
1038     // If we require it to include <new> then this diagnostic is no longer
1039     // needed.
1040     S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
1041     return nullptr;
1042   }
1043 
1044   auto *VD = Result.getAsSingle<VarDecl>();
1045   if (!VD) {
1046     Result.suppressDiagnostics();
1047     // We found something weird. Complain about the first thing we found.
1048     NamedDecl *Found = *Result.begin();
1049     S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
1050     return nullptr;
1051   }
1052 
1053   ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
1054   if (DR.isInvalid())
1055     return nullptr;
1056 
1057   return DR.get();
1058 }
1059 
1060 // Find an appropriate delete for the promise.
findDeleteForPromise(Sema & S,SourceLocation Loc,QualType PromiseType)1061 static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc,
1062                                           QualType PromiseType) {
1063   FunctionDecl *OperatorDelete = nullptr;
1064 
1065   DeclarationName DeleteName =
1066       S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
1067 
1068   auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
1069   assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
1070 
1071   if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
1072     return nullptr;
1073 
1074   if (!OperatorDelete) {
1075     // Look for a global declaration.
1076     const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
1077     const bool Overaligned = false;
1078     OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
1079                                                      Overaligned, DeleteName);
1080   }
1081   S.MarkFunctionReferenced(Loc, OperatorDelete);
1082   return OperatorDelete;
1083 }
1084 
1085 
CheckCompletedCoroutineBody(FunctionDecl * FD,Stmt * & Body)1086 void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
1087   FunctionScopeInfo *Fn = getCurFunction();
1088   assert(Fn && Fn->isCoroutine() && "not a coroutine");
1089   if (!Body) {
1090     assert(FD->isInvalidDecl() &&
1091            "a null body is only allowed for invalid declarations");
1092     return;
1093   }
1094   // We have a function that uses coroutine keywords, but we failed to build
1095   // the promise type.
1096   if (!Fn->CoroutinePromise)
1097     return FD->setInvalidDecl();
1098 
1099   if (isa<CoroutineBodyStmt>(Body)) {
1100     // Nothing todo. the body is already a transformed coroutine body statement.
1101     return;
1102   }
1103 
1104   // Coroutines [stmt.return]p1:
1105   //   A return statement shall not appear in a coroutine.
1106   if (Fn->FirstReturnLoc.isValid()) {
1107     assert(Fn->FirstCoroutineStmtLoc.isValid() &&
1108                    "first coroutine location not set");
1109     Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
1110     Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1111             << Fn->getFirstCoroutineStmtKeyword();
1112   }
1113   CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
1114   if (Builder.isInvalid() || !Builder.buildStatements())
1115     return FD->setInvalidDecl();
1116 
1117   // Build body for the coroutine wrapper statement.
1118   Body = CoroutineBodyStmt::Create(Context, Builder);
1119 }
1120 
CoroutineStmtBuilder(Sema & S,FunctionDecl & FD,sema::FunctionScopeInfo & Fn,Stmt * Body)1121 CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
1122                                            sema::FunctionScopeInfo &Fn,
1123                                            Stmt *Body)
1124     : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
1125       IsPromiseDependentType(
1126           !Fn.CoroutinePromise ||
1127           Fn.CoroutinePromise->getType()->isDependentType()) {
1128   this->Body = Body;
1129 
1130   for (auto KV : Fn.CoroutineParameterMoves)
1131     this->ParamMovesVector.push_back(KV.second);
1132   this->ParamMoves = this->ParamMovesVector;
1133 
1134   if (!IsPromiseDependentType) {
1135     PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
1136     assert(PromiseRecordDecl && "Type should have already been checked");
1137   }
1138   this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
1139 }
1140 
buildStatements()1141 bool CoroutineStmtBuilder::buildStatements() {
1142   assert(this->IsValid && "coroutine already invalid");
1143   this->IsValid = makeReturnObject();
1144   if (this->IsValid && !IsPromiseDependentType)
1145     buildDependentStatements();
1146   return this->IsValid;
1147 }
1148 
buildDependentStatements()1149 bool CoroutineStmtBuilder::buildDependentStatements() {
1150   assert(this->IsValid && "coroutine already invalid");
1151   assert(!this->IsPromiseDependentType &&
1152          "coroutine cannot have a dependent promise type");
1153   this->IsValid = makeOnException() && makeOnFallthrough() &&
1154                   makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
1155                   makeNewAndDeleteExpr();
1156   return this->IsValid;
1157 }
1158 
makePromiseStmt()1159 bool CoroutineStmtBuilder::makePromiseStmt() {
1160   // Form a declaration statement for the promise declaration, so that AST
1161   // visitors can more easily find it.
1162   StmtResult PromiseStmt =
1163       S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
1164   if (PromiseStmt.isInvalid())
1165     return false;
1166 
1167   this->Promise = PromiseStmt.get();
1168   return true;
1169 }
1170 
makeInitialAndFinalSuspend()1171 bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
1172   if (Fn.hasInvalidCoroutineSuspends())
1173     return false;
1174   this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
1175   this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
1176   return true;
1177 }
1178 
diagReturnOnAllocFailure(Sema & S,Expr * E,CXXRecordDecl * PromiseRecordDecl,FunctionScopeInfo & Fn)1179 static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
1180                                      CXXRecordDecl *PromiseRecordDecl,
1181                                      FunctionScopeInfo &Fn) {
1182   auto Loc = E->getExprLoc();
1183   if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
1184     auto *Decl = DeclRef->getDecl();
1185     if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
1186       if (Method->isStatic())
1187         return true;
1188       else
1189         Loc = Decl->getLocation();
1190     }
1191   }
1192 
1193   S.Diag(
1194       Loc,
1195       diag::err_coroutine_promise_get_return_object_on_allocation_failure)
1196       << PromiseRecordDecl;
1197   S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1198       << Fn.getFirstCoroutineStmtKeyword();
1199   return false;
1200 }
1201 
makeReturnOnAllocFailure()1202 bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
1203   assert(!IsPromiseDependentType &&
1204          "cannot make statement while the promise type is dependent");
1205 
1206   // [dcl.fct.def.coroutine]/8
1207   // The unqualified-id get_return_object_on_allocation_failure is looked up in
1208   // the scope of class P by class member access lookup (3.4.5). ...
1209   // If an allocation function returns nullptr, ... the coroutine return value
1210   // is obtained by a call to ... get_return_object_on_allocation_failure().
1211 
1212   DeclarationName DN =
1213       S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
1214   LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
1215   if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
1216     return true;
1217 
1218   CXXScopeSpec SS;
1219   ExprResult DeclNameExpr =
1220       S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
1221   if (DeclNameExpr.isInvalid())
1222     return false;
1223 
1224   if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
1225     return false;
1226 
1227   ExprResult ReturnObjectOnAllocationFailure =
1228       S.BuildCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
1229   if (ReturnObjectOnAllocationFailure.isInvalid())
1230     return false;
1231 
1232   StmtResult ReturnStmt =
1233       S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
1234   if (ReturnStmt.isInvalid()) {
1235     S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
1236         << DN;
1237     S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1238         << Fn.getFirstCoroutineStmtKeyword();
1239     return false;
1240   }
1241 
1242   this->ReturnStmtOnAllocFailure = ReturnStmt.get();
1243   return true;
1244 }
1245 
makeNewAndDeleteExpr()1246 bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
1247   // Form and check allocation and deallocation calls.
1248   assert(!IsPromiseDependentType &&
1249          "cannot make statement while the promise type is dependent");
1250   QualType PromiseType = Fn.CoroutinePromise->getType();
1251 
1252   if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
1253     return false;
1254 
1255   const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
1256 
1257   // [dcl.fct.def.coroutine]/7
1258   // Lookup allocation functions using a parameter list composed of the
1259   // requested size of the coroutine state being allocated, followed by
1260   // the coroutine function's arguments. If a matching allocation function
1261   // exists, use it. Otherwise, use an allocation function that just takes
1262   // the requested size.
1263 
1264   FunctionDecl *OperatorNew = nullptr;
1265   FunctionDecl *OperatorDelete = nullptr;
1266   FunctionDecl *UnusedResult = nullptr;
1267   bool PassAlignment = false;
1268   SmallVector<Expr *, 1> PlacementArgs;
1269 
1270   // [dcl.fct.def.coroutine]/7
1271   // "The allocation function’s name is looked up in the scope of P.
1272   // [...] If the lookup finds an allocation function in the scope of P,
1273   // overload resolution is performed on a function call created by assembling
1274   // an argument list. The first argument is the amount of space requested,
1275   // and has type std::size_t. The lvalues p1 ... pn are the succeeding
1276   // arguments."
1277   //
1278   // ...where "p1 ... pn" are defined earlier as:
1279   //
1280   // [dcl.fct.def.coroutine]/3
1281   // "For a coroutine f that is a non-static member function, let P1 denote the
1282   // type of the implicit object parameter (13.3.1) and P2 ... Pn be the types
1283   // of the function parameters; otherwise let P1 ... Pn be the types of the
1284   // function parameters. Let p1 ... pn be lvalues denoting those objects."
1285   if (auto *MD = dyn_cast<CXXMethodDecl>(&FD)) {
1286     if (MD->isInstance() && !isLambdaCallOperator(MD)) {
1287       ExprResult ThisExpr = S.ActOnCXXThis(Loc);
1288       if (ThisExpr.isInvalid())
1289         return false;
1290       ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
1291       if (ThisExpr.isInvalid())
1292         return false;
1293       PlacementArgs.push_back(ThisExpr.get());
1294     }
1295   }
1296   for (auto *PD : FD.parameters()) {
1297     if (PD->getType()->isDependentType())
1298       continue;
1299 
1300     // Build a reference to the parameter.
1301     auto PDLoc = PD->getLocation();
1302     ExprResult PDRefExpr =
1303         S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),
1304                            ExprValueKind::VK_LValue, PDLoc);
1305     if (PDRefExpr.isInvalid())
1306       return false;
1307 
1308     PlacementArgs.push_back(PDRefExpr.get());
1309   }
1310   S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class,
1311                             /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1312                             /*isArray*/ false, PassAlignment, PlacementArgs,
1313                             OperatorNew, UnusedResult, /*Diagnose*/ false);
1314 
1315   // [dcl.fct.def.coroutine]/7
1316   // "If no matching function is found, overload resolution is performed again
1317   // on a function call created by passing just the amount of space required as
1318   // an argument of type std::size_t."
1319   if (!OperatorNew && !PlacementArgs.empty()) {
1320     PlacementArgs.clear();
1321     S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class,
1322                               /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1323                               /*isArray*/ false, PassAlignment, PlacementArgs,
1324                               OperatorNew, UnusedResult, /*Diagnose*/ false);
1325   }
1326 
1327   // [dcl.fct.def.coroutine]/7
1328   // "The allocation function’s name is looked up in the scope of P. If this
1329   // lookup fails, the allocation function’s name is looked up in the global
1330   // scope."
1331   if (!OperatorNew) {
1332     S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Global,
1333                               /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1334                               /*isArray*/ false, PassAlignment, PlacementArgs,
1335                               OperatorNew, UnusedResult);
1336   }
1337 
1338   bool IsGlobalOverload =
1339       OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
1340   // If we didn't find a class-local new declaration and non-throwing new
1341   // was is required then we need to lookup the non-throwing global operator
1342   // instead.
1343   if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
1344     auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
1345     if (!StdNoThrow)
1346       return false;
1347     PlacementArgs = {StdNoThrow};
1348     OperatorNew = nullptr;
1349     S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Both,
1350                               /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1351                               /*isArray*/ false, PassAlignment, PlacementArgs,
1352                               OperatorNew, UnusedResult);
1353   }
1354 
1355   if (!OperatorNew)
1356     return false;
1357 
1358   if (RequiresNoThrowAlloc) {
1359     const auto *FT = OperatorNew->getType()->castAs<FunctionProtoType>();
1360     if (!FT->isNothrow(/*ResultIfDependent*/ false)) {
1361       S.Diag(OperatorNew->getLocation(),
1362              diag::err_coroutine_promise_new_requires_nothrow)
1363           << OperatorNew;
1364       S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
1365           << OperatorNew;
1366       return false;
1367     }
1368   }
1369 
1370   if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr)
1371     return false;
1372 
1373   Expr *FramePtr =
1374       buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
1375 
1376   Expr *FrameSize =
1377       buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {});
1378 
1379   // Make new call.
1380 
1381   ExprResult NewRef =
1382       S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
1383   if (NewRef.isInvalid())
1384     return false;
1385 
1386   SmallVector<Expr *, 2> NewArgs(1, FrameSize);
1387   for (auto Arg : PlacementArgs)
1388     NewArgs.push_back(Arg);
1389 
1390   ExprResult NewExpr =
1391       S.BuildCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
1392   NewExpr = S.ActOnFinishFullExpr(NewExpr.get(), /*DiscardedValue*/ false);
1393   if (NewExpr.isInvalid())
1394     return false;
1395 
1396   // Make delete call.
1397 
1398   QualType OpDeleteQualType = OperatorDelete->getType();
1399 
1400   ExprResult DeleteRef =
1401       S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
1402   if (DeleteRef.isInvalid())
1403     return false;
1404 
1405   Expr *CoroFree =
1406       buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr});
1407 
1408   SmallVector<Expr *, 2> DeleteArgs{CoroFree};
1409 
1410   // Check if we need to pass the size.
1411   const auto *OpDeleteType =
1412       OpDeleteQualType.getTypePtr()->castAs<FunctionProtoType>();
1413   if (OpDeleteType->getNumParams() > 1)
1414     DeleteArgs.push_back(FrameSize);
1415 
1416   ExprResult DeleteExpr =
1417       S.BuildCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
1418   DeleteExpr =
1419       S.ActOnFinishFullExpr(DeleteExpr.get(), /*DiscardedValue*/ false);
1420   if (DeleteExpr.isInvalid())
1421     return false;
1422 
1423   this->Allocate = NewExpr.get();
1424   this->Deallocate = DeleteExpr.get();
1425 
1426   return true;
1427 }
1428 
makeOnFallthrough()1429 bool CoroutineStmtBuilder::makeOnFallthrough() {
1430   assert(!IsPromiseDependentType &&
1431          "cannot make statement while the promise type is dependent");
1432 
1433   // [dcl.fct.def.coroutine]/4
1434   // The unqualified-ids 'return_void' and 'return_value' are looked up in
1435   // the scope of class P. If both are found, the program is ill-formed.
1436   bool HasRVoid, HasRValue;
1437   LookupResult LRVoid =
1438       lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
1439   LookupResult LRValue =
1440       lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
1441 
1442   StmtResult Fallthrough;
1443   if (HasRVoid && HasRValue) {
1444     // FIXME Improve this diagnostic
1445     S.Diag(FD.getLocation(),
1446            diag::err_coroutine_promise_incompatible_return_functions)
1447         << PromiseRecordDecl;
1448     S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
1449            diag::note_member_first_declared_here)
1450         << LRVoid.getLookupName();
1451     S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
1452            diag::note_member_first_declared_here)
1453         << LRValue.getLookupName();
1454     return false;
1455   } else if (!HasRVoid && !HasRValue) {
1456     // FIXME: The PDTS currently specifies this case as UB, not ill-formed.
1457     // However we still diagnose this as an error since until the PDTS is fixed.
1458     S.Diag(FD.getLocation(),
1459            diag::err_coroutine_promise_requires_return_function)
1460         << PromiseRecordDecl;
1461     S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1462         << PromiseRecordDecl;
1463     return false;
1464   } else if (HasRVoid) {
1465     // If the unqualified-id return_void is found, flowing off the end of a
1466     // coroutine is equivalent to a co_return with no operand. Otherwise,
1467     // flowing off the end of a coroutine results in undefined behavior.
1468     Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
1469                                       /*IsImplicit*/false);
1470     Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
1471     if (Fallthrough.isInvalid())
1472       return false;
1473   }
1474 
1475   this->OnFallthrough = Fallthrough.get();
1476   return true;
1477 }
1478 
makeOnException()1479 bool CoroutineStmtBuilder::makeOnException() {
1480   // Try to form 'p.unhandled_exception();'
1481   assert(!IsPromiseDependentType &&
1482          "cannot make statement while the promise type is dependent");
1483 
1484   const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1485 
1486   if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
1487     auto DiagID =
1488         RequireUnhandledException
1489             ? diag::err_coroutine_promise_unhandled_exception_required
1490             : diag::
1491                   warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1492     S.Diag(Loc, DiagID) << PromiseRecordDecl;
1493     S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1494         << PromiseRecordDecl;
1495     return !RequireUnhandledException;
1496   }
1497 
1498   // If exceptions are disabled, don't try to build OnException.
1499   if (!S.getLangOpts().CXXExceptions)
1500     return true;
1501 
1502   ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
1503                                                    "unhandled_exception", None);
1504   UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc,
1505                                              /*DiscardedValue*/ false);
1506   if (UnhandledException.isInvalid())
1507     return false;
1508 
1509   // Since the body of the coroutine will be wrapped in try-catch, it will
1510   // be incompatible with SEH __try if present in a function.
1511   if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1512     S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1513     S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1514         << Fn.getFirstCoroutineStmtKeyword();
1515     return false;
1516   }
1517 
1518   this->OnException = UnhandledException.get();
1519   return true;
1520 }
1521 
makeReturnObject()1522 bool CoroutineStmtBuilder::makeReturnObject() {
1523   // Build implicit 'p.get_return_object()' expression and form initialization
1524   // of return type from it.
1525   ExprResult ReturnObject =
1526       buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
1527   if (ReturnObject.isInvalid())
1528     return false;
1529 
1530   this->ReturnValue = ReturnObject.get();
1531   return true;
1532 }
1533 
noteMemberDeclaredHere(Sema & S,Expr * E,FunctionScopeInfo & Fn)1534 static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
1535   if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
1536     auto *MethodDecl = MbrRef->getMethodDecl();
1537     S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
1538         << MethodDecl;
1539   }
1540   S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1541       << Fn.getFirstCoroutineStmtKeyword();
1542 }
1543 
makeGroDeclAndReturnStmt()1544 bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1545   assert(!IsPromiseDependentType &&
1546          "cannot make statement while the promise type is dependent");
1547   assert(this->ReturnValue && "ReturnValue must be already formed");
1548 
1549   QualType const GroType = this->ReturnValue->getType();
1550   assert(!GroType->isDependentType() &&
1551          "get_return_object type must no longer be dependent");
1552 
1553   QualType const FnRetType = FD.getReturnType();
1554   assert(!FnRetType->isDependentType() &&
1555          "get_return_object type must no longer be dependent");
1556 
1557   if (FnRetType->isVoidType()) {
1558     ExprResult Res =
1559         S.ActOnFinishFullExpr(this->ReturnValue, Loc, /*DiscardedValue*/ false);
1560     if (Res.isInvalid())
1561       return false;
1562 
1563     this->ResultDecl = Res.get();
1564     return true;
1565   }
1566 
1567   if (GroType->isVoidType()) {
1568     // Trigger a nice error message.
1569     InitializedEntity Entity =
1570         InitializedEntity::InitializeResult(Loc, FnRetType, false);
1571     S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue);
1572     noteMemberDeclaredHere(S, ReturnValue, Fn);
1573     return false;
1574   }
1575 
1576   auto *GroDecl = VarDecl::Create(
1577       S.Context, &FD, FD.getLocation(), FD.getLocation(),
1578       &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
1579       S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
1580 
1581   S.CheckVariableDeclarationType(GroDecl);
1582   if (GroDecl->isInvalidDecl())
1583     return false;
1584 
1585   InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
1586   ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType,
1587                                                      this->ReturnValue);
1588   if (Res.isInvalid())
1589     return false;
1590 
1591   Res = S.ActOnFinishFullExpr(Res.get(), /*DiscardedValue*/ false);
1592   if (Res.isInvalid())
1593     return false;
1594 
1595   S.AddInitializerToDecl(GroDecl, Res.get(),
1596                          /*DirectInit=*/false);
1597 
1598   S.FinalizeDeclaration(GroDecl);
1599 
1600   // Form a declaration statement for the return declaration, so that AST
1601   // visitors can more easily find it.
1602   StmtResult GroDeclStmt =
1603       S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
1604   if (GroDeclStmt.isInvalid())
1605     return false;
1606 
1607   this->ResultDecl = GroDeclStmt.get();
1608 
1609   ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
1610   if (declRef.isInvalid())
1611     return false;
1612 
1613   StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
1614   if (ReturnStmt.isInvalid()) {
1615     noteMemberDeclaredHere(S, ReturnValue, Fn);
1616     return false;
1617   }
1618   if (cast<clang::ReturnStmt>(ReturnStmt.get())->getNRVOCandidate() == GroDecl)
1619     GroDecl->setNRVOVariable(true);
1620 
1621   this->ReturnStmt = ReturnStmt.get();
1622   return true;
1623 }
1624 
1625 // Create a static_cast\<T&&>(expr).
castForMoving(Sema & S,Expr * E,QualType T=QualType ())1626 static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
1627   if (T.isNull())
1628     T = E->getType();
1629   QualType TargetType = S.BuildReferenceType(
1630       T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());
1631   SourceLocation ExprLoc = E->getBeginLoc();
1632   TypeSourceInfo *TargetLoc =
1633       S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
1634 
1635   return S
1636       .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1637                          SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
1638       .get();
1639 }
1640 
1641 /// Build a variable declaration for move parameter.
buildVarDecl(Sema & S,SourceLocation Loc,QualType Type,IdentifierInfo * II)1642 static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
1643                              IdentifierInfo *II) {
1644   TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);
1645   VarDecl *Decl = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type,
1646                                   TInfo, SC_None);
1647   Decl->setImplicit();
1648   return Decl;
1649 }
1650 
1651 // Build statements that move coroutine function parameters to the coroutine
1652 // frame, and store them on the function scope info.
buildCoroutineParameterMoves(SourceLocation Loc)1653 bool Sema::buildCoroutineParameterMoves(SourceLocation Loc) {
1654   assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
1655   auto *FD = cast<FunctionDecl>(CurContext);
1656 
1657   auto *ScopeInfo = getCurFunction();
1658   if (!ScopeInfo->CoroutineParameterMoves.empty())
1659     return false;
1660 
1661   for (auto *PD : FD->parameters()) {
1662     if (PD->getType()->isDependentType())
1663       continue;
1664 
1665     ExprResult PDRefExpr =
1666         BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
1667                          ExprValueKind::VK_LValue, Loc); // FIXME: scope?
1668     if (PDRefExpr.isInvalid())
1669       return false;
1670 
1671     Expr *CExpr = nullptr;
1672     if (PD->getType()->getAsCXXRecordDecl() ||
1673         PD->getType()->isRValueReferenceType())
1674       CExpr = castForMoving(*this, PDRefExpr.get());
1675     else
1676       CExpr = PDRefExpr.get();
1677 
1678     auto D = buildVarDecl(*this, Loc, PD->getType(), PD->getIdentifier());
1679     AddInitializerToDecl(D, CExpr, /*DirectInit=*/true);
1680 
1681     // Convert decl to a statement.
1682     StmtResult Stmt = ActOnDeclStmt(ConvertDeclToDeclGroup(D), Loc, Loc);
1683     if (Stmt.isInvalid())
1684       return false;
1685 
1686     ScopeInfo->CoroutineParameterMoves.insert(std::make_pair(PD, Stmt.get()));
1687   }
1688   return true;
1689 }
1690 
BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args)1691 StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1692   CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
1693   if (!Res)
1694     return StmtError();
1695   return Res;
1696 }
1697 
lookupCoroutineTraits(SourceLocation KwLoc,SourceLocation FuncLoc)1698 ClassTemplateDecl *Sema::lookupCoroutineTraits(SourceLocation KwLoc,
1699                                                SourceLocation FuncLoc) {
1700   if (!StdCoroutineTraitsCache) {
1701     if (auto StdExp = lookupStdExperimentalNamespace()) {
1702       LookupResult Result(*this,
1703                           &PP.getIdentifierTable().get("coroutine_traits"),
1704                           FuncLoc, LookupOrdinaryName);
1705       if (!LookupQualifiedName(Result, StdExp)) {
1706         Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
1707             << "std::experimental::coroutine_traits";
1708         return nullptr;
1709       }
1710       if (!(StdCoroutineTraitsCache =
1711                 Result.getAsSingle<ClassTemplateDecl>())) {
1712         Result.suppressDiagnostics();
1713         NamedDecl *Found = *Result.begin();
1714         Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
1715         return nullptr;
1716       }
1717     }
1718   }
1719   return StdCoroutineTraitsCache;
1720 }
1721