SemaCoroutine.cpp 58 KB

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