SemaCoroutine.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297
  1. //===--- SemaCoroutines.cpp - Semantic Analysis for Coroutines ------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements semantic analysis for C++ Coroutines.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CoroutineStmtBuilder.h"
  14. #include "clang/AST/Decl.h"
  15. #include "clang/AST/ExprCXX.h"
  16. #include "clang/AST/StmtCXX.h"
  17. #include "clang/Lex/Preprocessor.h"
  18. #include "clang/Sema/Initialization.h"
  19. #include "clang/Sema/Overload.h"
  20. #include "clang/Sema/SemaInternal.h"
  21. using namespace clang;
  22. using namespace sema;
  23. static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
  24. SourceLocation Loc, bool &Res) {
  25. DeclarationName DN = S.PP.getIdentifierInfo(Name);
  26. LookupResult LR(S, DN, Loc, Sema::LookupMemberName);
  27. // Suppress diagnostics when a private member is selected. The same warnings
  28. // will be produced again when building the call.
  29. LR.suppressDiagnostics();
  30. Res = S.LookupQualifiedName(LR, RD);
  31. return LR;
  32. }
  33. static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
  34. SourceLocation Loc) {
  35. bool Res;
  36. lookupMember(S, Name, RD, Loc, Res);
  37. return Res;
  38. }
  39. /// Look up the std::coroutine_traits<...>::promise_type for the given
  40. /// function type.
  41. static QualType lookupPromiseType(Sema &S, const FunctionProtoType *FnType,
  42. SourceLocation KwLoc,
  43. SourceLocation FuncLoc) {
  44. // FIXME: Cache std::coroutine_traits once we've found it.
  45. NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
  46. if (!StdExp) {
  47. S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
  48. << "std::experimental::coroutine_traits";
  49. return QualType();
  50. }
  51. LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_traits"),
  52. FuncLoc, Sema::LookupOrdinaryName);
  53. if (!S.LookupQualifiedName(Result, StdExp)) {
  54. S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
  55. << "std::experimental::coroutine_traits";
  56. return QualType();
  57. }
  58. ClassTemplateDecl *CoroTraits = Result.getAsSingle<ClassTemplateDecl>();
  59. if (!CoroTraits) {
  60. Result.suppressDiagnostics();
  61. // We found something weird. Complain about the first thing we found.
  62. NamedDecl *Found = *Result.begin();
  63. S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
  64. return QualType();
  65. }
  66. // Form template argument list for coroutine_traits<R, P1, P2, ...>.
  67. TemplateArgumentListInfo Args(KwLoc, KwLoc);
  68. Args.addArgument(TemplateArgumentLoc(
  69. TemplateArgument(FnType->getReturnType()),
  70. S.Context.getTrivialTypeSourceInfo(FnType->getReturnType(), KwLoc)));
  71. // FIXME: If the function is a non-static member function, add the type
  72. // of the implicit object parameter before the formal parameters.
  73. for (QualType T : FnType->getParamTypes())
  74. Args.addArgument(TemplateArgumentLoc(
  75. TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));
  76. // Build the template-id.
  77. QualType CoroTrait =
  78. S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
  79. if (CoroTrait.isNull())
  80. return QualType();
  81. if (S.RequireCompleteType(KwLoc, CoroTrait,
  82. diag::err_coroutine_type_missing_specialization))
  83. return QualType();
  84. auto *RD = CoroTrait->getAsCXXRecordDecl();
  85. assert(RD && "specialization of class template is not a class?");
  86. // Look up the ::promise_type member.
  87. LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
  88. Sema::LookupOrdinaryName);
  89. S.LookupQualifiedName(R, RD);
  90. auto *Promise = R.getAsSingle<TypeDecl>();
  91. if (!Promise) {
  92. S.Diag(FuncLoc,
  93. diag::err_implied_std_coroutine_traits_promise_type_not_found)
  94. << RD;
  95. return QualType();
  96. }
  97. // The promise type is required to be a class type.
  98. QualType PromiseType = S.Context.getTypeDeclType(Promise);
  99. auto buildElaboratedType = [&]() {
  100. auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, StdExp);
  101. NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
  102. CoroTrait.getTypePtr());
  103. return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
  104. };
  105. if (!PromiseType->getAsCXXRecordDecl()) {
  106. S.Diag(FuncLoc,
  107. diag::err_implied_std_coroutine_traits_promise_type_not_class)
  108. << buildElaboratedType();
  109. return QualType();
  110. }
  111. if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
  112. diag::err_coroutine_promise_type_incomplete))
  113. return QualType();
  114. return PromiseType;
  115. }
  116. /// Look up the std::experimental::coroutine_handle<PromiseType>.
  117. static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
  118. SourceLocation Loc) {
  119. if (PromiseType.isNull())
  120. return QualType();
  121. NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
  122. assert(StdExp && "Should already be diagnosed");
  123. LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
  124. Loc, Sema::LookupOrdinaryName);
  125. if (!S.LookupQualifiedName(Result, StdExp)) {
  126. S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
  127. << "std::experimental::coroutine_handle";
  128. return QualType();
  129. }
  130. ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
  131. if (!CoroHandle) {
  132. Result.suppressDiagnostics();
  133. // We found something weird. Complain about the first thing we found.
  134. NamedDecl *Found = *Result.begin();
  135. S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
  136. return QualType();
  137. }
  138. // Form template argument list for coroutine_handle<Promise>.
  139. TemplateArgumentListInfo Args(Loc, Loc);
  140. Args.addArgument(TemplateArgumentLoc(
  141. TemplateArgument(PromiseType),
  142. S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
  143. // Build the template-id.
  144. QualType CoroHandleType =
  145. S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
  146. if (CoroHandleType.isNull())
  147. return QualType();
  148. if (S.RequireCompleteType(Loc, CoroHandleType,
  149. diag::err_coroutine_type_missing_specialization))
  150. return QualType();
  151. return CoroHandleType;
  152. }
  153. static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
  154. StringRef Keyword) {
  155. // 'co_await' and 'co_yield' are not permitted in unevaluated operands.
  156. if (S.isUnevaluatedContext()) {
  157. S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
  158. return false;
  159. }
  160. // Any other usage must be within a function.
  161. auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
  162. if (!FD) {
  163. S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
  164. ? diag::err_coroutine_objc_method
  165. : diag::err_coroutine_outside_function) << Keyword;
  166. return false;
  167. }
  168. // An enumeration for mapping the diagnostic type to the correct diagnostic
  169. // selection index.
  170. enum InvalidFuncDiag {
  171. DiagCtor = 0,
  172. DiagDtor,
  173. DiagCopyAssign,
  174. DiagMoveAssign,
  175. DiagMain,
  176. DiagConstexpr,
  177. DiagAutoRet,
  178. DiagVarargs,
  179. };
  180. bool Diagnosed = false;
  181. auto DiagInvalid = [&](InvalidFuncDiag ID) {
  182. S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
  183. Diagnosed = true;
  184. return false;
  185. };
  186. // Diagnose when a constructor, destructor, copy/move assignment operator,
  187. // or the function 'main' are declared as a coroutine.
  188. auto *MD = dyn_cast<CXXMethodDecl>(FD);
  189. if (MD && isa<CXXConstructorDecl>(MD))
  190. return DiagInvalid(DiagCtor);
  191. else if (MD && isa<CXXDestructorDecl>(MD))
  192. return DiagInvalid(DiagDtor);
  193. else if (MD && MD->isCopyAssignmentOperator())
  194. return DiagInvalid(DiagCopyAssign);
  195. else if (MD && MD->isMoveAssignmentOperator())
  196. return DiagInvalid(DiagMoveAssign);
  197. else if (FD->isMain())
  198. return DiagInvalid(DiagMain);
  199. // Emit a diagnostics for each of the following conditions which is not met.
  200. if (FD->isConstexpr())
  201. DiagInvalid(DiagConstexpr);
  202. if (FD->getReturnType()->isUndeducedType())
  203. DiagInvalid(DiagAutoRet);
  204. if (FD->isVariadic())
  205. DiagInvalid(DiagVarargs);
  206. return !Diagnosed;
  207. }
  208. static ExprResult buildOperatorCoawaitLookupExpr(Sema &SemaRef, Scope *S,
  209. SourceLocation Loc) {
  210. DeclarationName OpName =
  211. SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
  212. LookupResult Operators(SemaRef, OpName, SourceLocation(),
  213. Sema::LookupOperatorName);
  214. SemaRef.LookupName(Operators, S);
  215. assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
  216. const auto &Functions = Operators.asUnresolvedSet();
  217. bool IsOverloaded =
  218. Functions.size() > 1 ||
  219. (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
  220. Expr *CoawaitOp = UnresolvedLookupExpr::Create(
  221. SemaRef.Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
  222. DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
  223. Functions.begin(), Functions.end());
  224. assert(CoawaitOp);
  225. return CoawaitOp;
  226. }
  227. /// Build a call to 'operator co_await' if there is a suitable operator for
  228. /// the given expression.
  229. static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, SourceLocation Loc,
  230. Expr *E,
  231. UnresolvedLookupExpr *Lookup) {
  232. UnresolvedSet<16> Functions;
  233. Functions.append(Lookup->decls_begin(), Lookup->decls_end());
  234. return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
  235. }
  236. static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
  237. SourceLocation Loc, Expr *E) {
  238. ExprResult R = buildOperatorCoawaitLookupExpr(SemaRef, S, Loc);
  239. if (R.isInvalid())
  240. return ExprError();
  241. return buildOperatorCoawaitCall(SemaRef, Loc, E,
  242. cast<UnresolvedLookupExpr>(R.get()));
  243. }
  244. static Expr *buildBuiltinCall(Sema &S, SourceLocation Loc, Builtin::ID Id,
  245. MultiExprArg CallArgs) {
  246. StringRef Name = S.Context.BuiltinInfo.getName(Id);
  247. LookupResult R(S, &S.Context.Idents.get(Name), Loc, Sema::LookupOrdinaryName);
  248. S.LookupName(R, S.TUScope, /*AllowBuiltinCreation=*/true);
  249. auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
  250. assert(BuiltInDecl && "failed to find builtin declaration");
  251. ExprResult DeclRef =
  252. S.BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
  253. assert(DeclRef.isUsable() && "Builtin reference cannot fail");
  254. ExprResult Call =
  255. S.ActOnCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
  256. assert(!Call.isInvalid() && "Call to builtin cannot fail!");
  257. return Call.get();
  258. }
  259. static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
  260. SourceLocation Loc) {
  261. QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
  262. if (CoroHandleType.isNull())
  263. return ExprError();
  264. DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
  265. LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
  266. Sema::LookupOrdinaryName);
  267. if (!S.LookupQualifiedName(Found, LookupCtx)) {
  268. S.Diag(Loc, diag::err_coroutine_handle_missing_member)
  269. << "from_address";
  270. return ExprError();
  271. }
  272. Expr *FramePtr =
  273. buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
  274. CXXScopeSpec SS;
  275. ExprResult FromAddr =
  276. S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
  277. if (FromAddr.isInvalid())
  278. return ExprError();
  279. return S.ActOnCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
  280. }
  281. struct ReadySuspendResumeResult {
  282. enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume };
  283. Expr *Results[3];
  284. OpaqueValueExpr *OpaqueValue;
  285. bool IsInvalid;
  286. };
  287. static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
  288. StringRef Name, MultiExprArg Args) {
  289. DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
  290. // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
  291. CXXScopeSpec SS;
  292. ExprResult Result = S.BuildMemberReferenceExpr(
  293. Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
  294. SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
  295. /*Scope=*/nullptr);
  296. if (Result.isInvalid())
  297. return ExprError();
  298. return S.ActOnCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
  299. }
  300. /// Build calls to await_ready, await_suspend, and await_resume for a co_await
  301. /// expression.
  302. static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
  303. SourceLocation Loc, Expr *E) {
  304. OpaqueValueExpr *Operand = new (S.Context)
  305. OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
  306. // Assume invalid until we see otherwise.
  307. ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true};
  308. ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc);
  309. if (CoroHandleRes.isInvalid())
  310. return Calls;
  311. Expr *CoroHandle = CoroHandleRes.get();
  312. const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
  313. MultiExprArg Args[] = {None, CoroHandle, None};
  314. for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
  315. ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]);
  316. if (Result.isInvalid())
  317. return Calls;
  318. Calls.Results[I] = Result.get();
  319. }
  320. // Assume the calls are valid; all further checking should make them invalid.
  321. Calls.IsInvalid = false;
  322. using ACT = ReadySuspendResumeResult::AwaitCallType;
  323. CallExpr *AwaitReady = cast<CallExpr>(Calls.Results[ACT::ACT_Ready]);
  324. if (!AwaitReady->getType()->isDependentType()) {
  325. // [expr.await]p3 [...]
  326. // — await-ready is the expression e.await_ready(), contextually converted
  327. // to bool.
  328. ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady);
  329. if (Conv.isInvalid()) {
  330. S.Diag(AwaitReady->getDirectCallee()->getLocStart(),
  331. diag::note_await_ready_no_bool_conversion);
  332. S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
  333. << AwaitReady->getDirectCallee() << E->getSourceRange();
  334. Calls.IsInvalid = true;
  335. }
  336. Calls.Results[ACT::ACT_Ready] = Conv.get();
  337. }
  338. CallExpr *AwaitSuspend = cast<CallExpr>(Calls.Results[ACT::ACT_Suspend]);
  339. if (!AwaitSuspend->getType()->isDependentType()) {
  340. // [expr.await]p3 [...]
  341. // - await-suspend is the expression e.await_suspend(h), which shall be
  342. // a prvalue of type void or bool.
  343. QualType RetType = AwaitSuspend->getType();
  344. if (RetType != S.Context.BoolTy && RetType != S.Context.VoidTy) {
  345. S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
  346. diag::err_await_suspend_invalid_return_type)
  347. << RetType;
  348. S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
  349. << AwaitSuspend->getDirectCallee();
  350. Calls.IsInvalid = true;
  351. }
  352. }
  353. return Calls;
  354. }
  355. static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
  356. SourceLocation Loc, StringRef Name,
  357. MultiExprArg Args) {
  358. // Form a reference to the promise.
  359. ExprResult PromiseRef = S.BuildDeclRefExpr(
  360. Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
  361. if (PromiseRef.isInvalid())
  362. return ExprError();
  363. return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
  364. }
  365. VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
  366. assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
  367. auto *FD = cast<FunctionDecl>(CurContext);
  368. QualType T =
  369. FD->getType()->isDependentType()
  370. ? Context.DependentTy
  371. : lookupPromiseType(*this, FD->getType()->castAs<FunctionProtoType>(),
  372. Loc, FD->getLocation());
  373. if (T.isNull())
  374. return nullptr;
  375. auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
  376. &PP.getIdentifierTable().get("__promise"), T,
  377. Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
  378. CheckVariableDeclarationType(VD);
  379. if (VD->isInvalidDecl())
  380. return nullptr;
  381. ActOnUninitializedDecl(VD);
  382. assert(!VD->isInvalidDecl());
  383. return VD;
  384. }
  385. /// Check that this is a context in which a coroutine suspension can appear.
  386. static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
  387. StringRef Keyword,
  388. bool IsImplicit = false) {
  389. if (!isValidCoroutineContext(S, Loc, Keyword))
  390. return nullptr;
  391. assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
  392. auto *ScopeInfo = S.getCurFunction();
  393. assert(ScopeInfo && "missing function scope for function");
  394. if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
  395. ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
  396. if (ScopeInfo->CoroutinePromise)
  397. return ScopeInfo;
  398. ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
  399. if (!ScopeInfo->CoroutinePromise)
  400. return nullptr;
  401. return ScopeInfo;
  402. }
  403. static bool actOnCoroutineBodyStart(Sema &S, Scope *SC, SourceLocation KWLoc,
  404. StringRef Keyword) {
  405. if (!checkCoroutineContext(S, KWLoc, Keyword))
  406. return false;
  407. auto *ScopeInfo = S.getCurFunction();
  408. assert(ScopeInfo->CoroutinePromise);
  409. // If we have existing coroutine statements then we have already built
  410. // the initial and final suspend points.
  411. if (!ScopeInfo->NeedsCoroutineSuspends)
  412. return true;
  413. ScopeInfo->setNeedsCoroutineSuspends(false);
  414. auto *Fn = cast<FunctionDecl>(S.CurContext);
  415. SourceLocation Loc = Fn->getLocation();
  416. // Build the initial suspend point
  417. auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
  418. ExprResult Suspend =
  419. buildPromiseCall(S, ScopeInfo->CoroutinePromise, Loc, Name, None);
  420. if (Suspend.isInvalid())
  421. return StmtError();
  422. Suspend = buildOperatorCoawaitCall(S, SC, Loc, Suspend.get());
  423. if (Suspend.isInvalid())
  424. return StmtError();
  425. Suspend = S.BuildResolvedCoawaitExpr(Loc, Suspend.get(),
  426. /*IsImplicit*/ true);
  427. Suspend = S.ActOnFinishFullExpr(Suspend.get());
  428. if (Suspend.isInvalid()) {
  429. S.Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
  430. << ((Name == "initial_suspend") ? 0 : 1);
  431. S.Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
  432. return StmtError();
  433. }
  434. return cast<Stmt>(Suspend.get());
  435. };
  436. StmtResult InitSuspend = buildSuspends("initial_suspend");
  437. if (InitSuspend.isInvalid())
  438. return true;
  439. StmtResult FinalSuspend = buildSuspends("final_suspend");
  440. if (FinalSuspend.isInvalid())
  441. return true;
  442. ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
  443. return true;
  444. }
  445. ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
  446. if (!actOnCoroutineBodyStart(*this, S, Loc, "co_await")) {
  447. CorrectDelayedTyposInExpr(E);
  448. return ExprError();
  449. }
  450. if (E->getType()->isPlaceholderType()) {
  451. ExprResult R = CheckPlaceholderExpr(E);
  452. if (R.isInvalid()) return ExprError();
  453. E = R.get();
  454. }
  455. ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
  456. if (Lookup.isInvalid())
  457. return ExprError();
  458. return BuildUnresolvedCoawaitExpr(Loc, E,
  459. cast<UnresolvedLookupExpr>(Lookup.get()));
  460. }
  461. ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E,
  462. UnresolvedLookupExpr *Lookup) {
  463. auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
  464. if (!FSI)
  465. return ExprError();
  466. if (E->getType()->isPlaceholderType()) {
  467. ExprResult R = CheckPlaceholderExpr(E);
  468. if (R.isInvalid())
  469. return ExprError();
  470. E = R.get();
  471. }
  472. auto *Promise = FSI->CoroutinePromise;
  473. if (Promise->getType()->isDependentType()) {
  474. Expr *Res =
  475. new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
  476. return Res;
  477. }
  478. auto *RD = Promise->getType()->getAsCXXRecordDecl();
  479. if (lookupMember(*this, "await_transform", RD, Loc)) {
  480. ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
  481. if (R.isInvalid()) {
  482. Diag(Loc,
  483. diag::note_coroutine_promise_implicit_await_transform_required_here)
  484. << E->getSourceRange();
  485. return ExprError();
  486. }
  487. E = R.get();
  488. }
  489. ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
  490. if (Awaitable.isInvalid())
  491. return ExprError();
  492. return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
  493. }
  494. ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E,
  495. bool IsImplicit) {
  496. auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
  497. if (!Coroutine)
  498. return ExprError();
  499. if (E->getType()->isPlaceholderType()) {
  500. ExprResult R = CheckPlaceholderExpr(E);
  501. if (R.isInvalid()) return ExprError();
  502. E = R.get();
  503. }
  504. if (E->getType()->isDependentType()) {
  505. Expr *Res = new (Context)
  506. CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
  507. return Res;
  508. }
  509. // If the expression is a temporary, materialize it as an lvalue so that we
  510. // can use it multiple times.
  511. if (E->getValueKind() == VK_RValue)
  512. E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
  513. // Build the await_ready, await_suspend, await_resume calls.
  514. ReadySuspendResumeResult RSS =
  515. buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
  516. if (RSS.IsInvalid)
  517. return ExprError();
  518. Expr *Res =
  519. new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
  520. RSS.Results[2], RSS.OpaqueValue, IsImplicit);
  521. return Res;
  522. }
  523. ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
  524. if (!actOnCoroutineBodyStart(*this, S, Loc, "co_yield")) {
  525. CorrectDelayedTyposInExpr(E);
  526. return ExprError();
  527. }
  528. // Build yield_value call.
  529. ExprResult Awaitable = buildPromiseCall(
  530. *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
  531. if (Awaitable.isInvalid())
  532. return ExprError();
  533. // Build 'operator co_await' call.
  534. Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
  535. if (Awaitable.isInvalid())
  536. return ExprError();
  537. return BuildCoyieldExpr(Loc, Awaitable.get());
  538. }
  539. ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
  540. auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
  541. if (!Coroutine)
  542. return ExprError();
  543. if (E->getType()->isPlaceholderType()) {
  544. ExprResult R = CheckPlaceholderExpr(E);
  545. if (R.isInvalid()) return ExprError();
  546. E = R.get();
  547. }
  548. if (E->getType()->isDependentType()) {
  549. Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
  550. return Res;
  551. }
  552. // If the expression is a temporary, materialize it as an lvalue so that we
  553. // can use it multiple times.
  554. if (E->getValueKind() == VK_RValue)
  555. E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
  556. // Build the await_ready, await_suspend, await_resume calls.
  557. ReadySuspendResumeResult RSS =
  558. buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
  559. if (RSS.IsInvalid)
  560. return ExprError();
  561. Expr *Res = new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
  562. RSS.Results[2], RSS.OpaqueValue);
  563. return Res;
  564. }
  565. StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
  566. if (!actOnCoroutineBodyStart(*this, S, Loc, "co_return")) {
  567. CorrectDelayedTyposInExpr(E);
  568. return StmtError();
  569. }
  570. return BuildCoreturnStmt(Loc, E);
  571. }
  572. StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
  573. bool IsImplicit) {
  574. auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
  575. if (!FSI)
  576. return StmtError();
  577. if (E && E->getType()->isPlaceholderType() &&
  578. !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
  579. ExprResult R = CheckPlaceholderExpr(E);
  580. if (R.isInvalid()) return StmtError();
  581. E = R.get();
  582. }
  583. // FIXME: If the operand is a reference to a variable that's about to go out
  584. // of scope, we should treat the operand as an xvalue for this overload
  585. // resolution.
  586. VarDecl *Promise = FSI->CoroutinePromise;
  587. ExprResult PC;
  588. if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
  589. PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
  590. } else {
  591. E = MakeFullDiscardedValueExpr(E).get();
  592. PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
  593. }
  594. if (PC.isInvalid())
  595. return StmtError();
  596. Expr *PCE = ActOnFinishFullExpr(PC.get()).get();
  597. Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
  598. return Res;
  599. }
  600. /// Look up the std::nothrow object.
  601. static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
  602. NamespaceDecl *Std = S.getStdNamespace();
  603. assert(Std && "Should already be diagnosed");
  604. LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
  605. Sema::LookupOrdinaryName);
  606. if (!S.LookupQualifiedName(Result, Std)) {
  607. // FIXME: <experimental/coroutine> should have been included already.
  608. // If we require it to include <new> then this diagnostic is no longer
  609. // needed.
  610. S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
  611. return nullptr;
  612. }
  613. // FIXME: Mark the variable as ODR used. This currently does not work
  614. // likely due to the scope at in which this function is called.
  615. auto *VD = Result.getAsSingle<VarDecl>();
  616. if (!VD) {
  617. Result.suppressDiagnostics();
  618. // We found something weird. Complain about the first thing we found.
  619. NamedDecl *Found = *Result.begin();
  620. S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
  621. return nullptr;
  622. }
  623. ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
  624. if (DR.isInvalid())
  625. return nullptr;
  626. return DR.get();
  627. }
  628. // Find an appropriate delete for the promise.
  629. static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc,
  630. QualType PromiseType) {
  631. FunctionDecl *OperatorDelete = nullptr;
  632. DeclarationName DeleteName =
  633. S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
  634. auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
  635. assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
  636. if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
  637. return nullptr;
  638. if (!OperatorDelete) {
  639. // Look for a global declaration.
  640. const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
  641. const bool Overaligned = false;
  642. OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
  643. Overaligned, DeleteName);
  644. }
  645. S.MarkFunctionReferenced(Loc, OperatorDelete);
  646. return OperatorDelete;
  647. }
  648. void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
  649. FunctionScopeInfo *Fn = getCurFunction();
  650. assert(Fn && Fn->isCoroutine() && "not a coroutine");
  651. if (!Body) {
  652. assert(FD->isInvalidDecl() &&
  653. "a null body is only allowed for invalid declarations");
  654. return;
  655. }
  656. // We have a function that uses coroutine keywords, but we failed to build
  657. // the promise type.
  658. if (!Fn->CoroutinePromise)
  659. return FD->setInvalidDecl();
  660. if (isa<CoroutineBodyStmt>(Body)) {
  661. // Nothing todo. the body is already a transformed coroutine body statement.
  662. return;
  663. }
  664. // Coroutines [stmt.return]p1:
  665. // A return statement shall not appear in a coroutine.
  666. if (Fn->FirstReturnLoc.isValid()) {
  667. assert(Fn->FirstCoroutineStmtLoc.isValid() &&
  668. "first coroutine location not set");
  669. Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
  670. Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
  671. << Fn->getFirstCoroutineStmtKeyword();
  672. }
  673. CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
  674. if (Builder.isInvalid() || !Builder.buildStatements())
  675. return FD->setInvalidDecl();
  676. // Build body for the coroutine wrapper statement.
  677. Body = CoroutineBodyStmt::Create(Context, Builder);
  678. }
  679. CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
  680. sema::FunctionScopeInfo &Fn,
  681. Stmt *Body)
  682. : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
  683. IsPromiseDependentType(
  684. !Fn.CoroutinePromise ||
  685. Fn.CoroutinePromise->getType()->isDependentType()) {
  686. this->Body = Body;
  687. if (!IsPromiseDependentType) {
  688. PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
  689. assert(PromiseRecordDecl && "Type should have already been checked");
  690. }
  691. this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
  692. }
  693. bool CoroutineStmtBuilder::buildStatements() {
  694. assert(this->IsValid && "coroutine already invalid");
  695. this->IsValid = makeReturnObject() && makeParamMoves();
  696. if (this->IsValid && !IsPromiseDependentType)
  697. buildDependentStatements();
  698. return this->IsValid;
  699. }
  700. bool CoroutineStmtBuilder::buildDependentStatements() {
  701. assert(this->IsValid && "coroutine already invalid");
  702. assert(!this->IsPromiseDependentType &&
  703. "coroutine cannot have a dependent promise type");
  704. this->IsValid = makeOnException() && makeOnFallthrough() &&
  705. makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
  706. makeNewAndDeleteExpr();
  707. return this->IsValid;
  708. }
  709. bool CoroutineStmtBuilder::makePromiseStmt() {
  710. // Form a declaration statement for the promise declaration, so that AST
  711. // visitors can more easily find it.
  712. StmtResult PromiseStmt =
  713. S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
  714. if (PromiseStmt.isInvalid())
  715. return false;
  716. this->Promise = PromiseStmt.get();
  717. return true;
  718. }
  719. bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
  720. if (Fn.hasInvalidCoroutineSuspends())
  721. return false;
  722. this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
  723. this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
  724. return true;
  725. }
  726. static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
  727. CXXRecordDecl *PromiseRecordDecl,
  728. FunctionScopeInfo &Fn) {
  729. auto Loc = E->getExprLoc();
  730. if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
  731. auto *Decl = DeclRef->getDecl();
  732. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
  733. if (Method->isStatic())
  734. return true;
  735. else
  736. Loc = Decl->getLocation();
  737. }
  738. }
  739. S.Diag(
  740. Loc,
  741. diag::err_coroutine_promise_get_return_object_on_allocation_failure)
  742. << PromiseRecordDecl;
  743. S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
  744. << Fn.getFirstCoroutineStmtKeyword();
  745. return false;
  746. }
  747. bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
  748. assert(!IsPromiseDependentType &&
  749. "cannot make statement while the promise type is dependent");
  750. // [dcl.fct.def.coroutine]/8
  751. // The unqualified-id get_return_object_on_allocation_failure is looked up in
  752. // the scope of class P by class member access lookup (3.4.5). ...
  753. // If an allocation function returns nullptr, ... the coroutine return value
  754. // is obtained by a call to ... get_return_object_on_allocation_failure().
  755. DeclarationName DN =
  756. S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
  757. LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
  758. if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
  759. return true;
  760. CXXScopeSpec SS;
  761. ExprResult DeclNameExpr =
  762. S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
  763. if (DeclNameExpr.isInvalid())
  764. return false;
  765. if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
  766. return false;
  767. ExprResult ReturnObjectOnAllocationFailure =
  768. S.ActOnCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
  769. if (ReturnObjectOnAllocationFailure.isInvalid())
  770. return false;
  771. StmtResult ReturnStmt =
  772. S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
  773. if (ReturnStmt.isInvalid()) {
  774. S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
  775. << DN;
  776. S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
  777. << Fn.getFirstCoroutineStmtKeyword();
  778. return false;
  779. }
  780. this->ReturnStmtOnAllocFailure = ReturnStmt.get();
  781. return true;
  782. }
  783. bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
  784. // Form and check allocation and deallocation calls.
  785. assert(!IsPromiseDependentType &&
  786. "cannot make statement while the promise type is dependent");
  787. QualType PromiseType = Fn.CoroutinePromise->getType();
  788. if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
  789. return false;
  790. const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
  791. // FIXME: Add support for stateful allocators.
  792. FunctionDecl *OperatorNew = nullptr;
  793. FunctionDecl *OperatorDelete = nullptr;
  794. FunctionDecl *UnusedResult = nullptr;
  795. bool PassAlignment = false;
  796. SmallVector<Expr *, 1> PlacementArgs;
  797. S.FindAllocationFunctions(Loc, SourceRange(),
  798. /*UseGlobal*/ false, PromiseType,
  799. /*isArray*/ false, PassAlignment, PlacementArgs,
  800. OperatorNew, UnusedResult);
  801. bool IsGlobalOverload =
  802. OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
  803. // If we didn't find a class-local new declaration and non-throwing new
  804. // was is required then we need to lookup the non-throwing global operator
  805. // instead.
  806. if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
  807. auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
  808. if (!StdNoThrow)
  809. return false;
  810. PlacementArgs = {StdNoThrow};
  811. OperatorNew = nullptr;
  812. S.FindAllocationFunctions(Loc, SourceRange(),
  813. /*UseGlobal*/ true, PromiseType,
  814. /*isArray*/ false, PassAlignment, PlacementArgs,
  815. OperatorNew, UnusedResult);
  816. }
  817. assert(OperatorNew && "expected definition of operator new to be found");
  818. if (RequiresNoThrowAlloc) {
  819. const auto *FT = OperatorNew->getType()->getAs<FunctionProtoType>();
  820. if (!FT->isNothrow(S.Context, /*ResultIfDependent*/ false)) {
  821. S.Diag(OperatorNew->getLocation(),
  822. diag::err_coroutine_promise_new_requires_nothrow)
  823. << OperatorNew;
  824. S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
  825. << OperatorNew;
  826. return false;
  827. }
  828. }
  829. if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr)
  830. return false;
  831. Expr *FramePtr =
  832. buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
  833. Expr *FrameSize =
  834. buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {});
  835. // Make new call.
  836. ExprResult NewRef =
  837. S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
  838. if (NewRef.isInvalid())
  839. return false;
  840. SmallVector<Expr *, 2> NewArgs(1, FrameSize);
  841. for (auto Arg : PlacementArgs)
  842. NewArgs.push_back(Arg);
  843. ExprResult NewExpr =
  844. S.ActOnCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
  845. NewExpr = S.ActOnFinishFullExpr(NewExpr.get());
  846. if (NewExpr.isInvalid())
  847. return false;
  848. // Make delete call.
  849. QualType OpDeleteQualType = OperatorDelete->getType();
  850. ExprResult DeleteRef =
  851. S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
  852. if (DeleteRef.isInvalid())
  853. return false;
  854. Expr *CoroFree =
  855. buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr});
  856. SmallVector<Expr *, 2> DeleteArgs{CoroFree};
  857. // Check if we need to pass the size.
  858. const auto *OpDeleteType =
  859. OpDeleteQualType.getTypePtr()->getAs<FunctionProtoType>();
  860. if (OpDeleteType->getNumParams() > 1)
  861. DeleteArgs.push_back(FrameSize);
  862. ExprResult DeleteExpr =
  863. S.ActOnCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
  864. DeleteExpr = S.ActOnFinishFullExpr(DeleteExpr.get());
  865. if (DeleteExpr.isInvalid())
  866. return false;
  867. this->Allocate = NewExpr.get();
  868. this->Deallocate = DeleteExpr.get();
  869. return true;
  870. }
  871. bool CoroutineStmtBuilder::makeOnFallthrough() {
  872. assert(!IsPromiseDependentType &&
  873. "cannot make statement while the promise type is dependent");
  874. // [dcl.fct.def.coroutine]/4
  875. // The unqualified-ids 'return_void' and 'return_value' are looked up in
  876. // the scope of class P. If both are found, the program is ill-formed.
  877. bool HasRVoid, HasRValue;
  878. LookupResult LRVoid =
  879. lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
  880. LookupResult LRValue =
  881. lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
  882. StmtResult Fallthrough;
  883. if (HasRVoid && HasRValue) {
  884. // FIXME Improve this diagnostic
  885. S.Diag(FD.getLocation(),
  886. diag::err_coroutine_promise_incompatible_return_functions)
  887. << PromiseRecordDecl;
  888. S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
  889. diag::note_member_first_declared_here)
  890. << LRVoid.getLookupName();
  891. S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
  892. diag::note_member_first_declared_here)
  893. << LRValue.getLookupName();
  894. return false;
  895. } else if (!HasRVoid && !HasRValue) {
  896. // FIXME: The PDTS currently specifies this case as UB, not ill-formed.
  897. // However we still diagnose this as an error since until the PDTS is fixed.
  898. S.Diag(FD.getLocation(),
  899. diag::err_coroutine_promise_requires_return_function)
  900. << PromiseRecordDecl;
  901. S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
  902. << PromiseRecordDecl;
  903. return false;
  904. } else if (HasRVoid) {
  905. // If the unqualified-id return_void is found, flowing off the end of a
  906. // coroutine is equivalent to a co_return with no operand. Otherwise,
  907. // flowing off the end of a coroutine results in undefined behavior.
  908. Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
  909. /*IsImplicit*/false);
  910. Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
  911. if (Fallthrough.isInvalid())
  912. return false;
  913. }
  914. this->OnFallthrough = Fallthrough.get();
  915. return true;
  916. }
  917. bool CoroutineStmtBuilder::makeOnException() {
  918. // Try to form 'p.unhandled_exception();'
  919. assert(!IsPromiseDependentType &&
  920. "cannot make statement while the promise type is dependent");
  921. const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
  922. if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
  923. auto DiagID =
  924. RequireUnhandledException
  925. ? diag::err_coroutine_promise_unhandled_exception_required
  926. : diag::
  927. warn_coroutine_promise_unhandled_exception_required_with_exceptions;
  928. S.Diag(Loc, DiagID) << PromiseRecordDecl;
  929. S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
  930. << PromiseRecordDecl;
  931. return !RequireUnhandledException;
  932. }
  933. // If exceptions are disabled, don't try to build OnException.
  934. if (!S.getLangOpts().CXXExceptions)
  935. return true;
  936. ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
  937. "unhandled_exception", None);
  938. UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc);
  939. if (UnhandledException.isInvalid())
  940. return false;
  941. // Since the body of the coroutine will be wrapped in try-catch, it will
  942. // be incompatible with SEH __try if present in a function.
  943. if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
  944. S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
  945. S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
  946. << Fn.getFirstCoroutineStmtKeyword();
  947. return false;
  948. }
  949. this->OnException = UnhandledException.get();
  950. return true;
  951. }
  952. bool CoroutineStmtBuilder::makeReturnObject() {
  953. // Build implicit 'p.get_return_object()' expression and form initialization
  954. // of return type from it.
  955. ExprResult ReturnObject =
  956. buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
  957. if (ReturnObject.isInvalid())
  958. return false;
  959. this->ReturnValue = ReturnObject.get();
  960. return true;
  961. }
  962. static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
  963. if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
  964. auto *MethodDecl = MbrRef->getMethodDecl();
  965. S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
  966. << MethodDecl;
  967. }
  968. S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
  969. << Fn.getFirstCoroutineStmtKeyword();
  970. }
  971. bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
  972. assert(!IsPromiseDependentType &&
  973. "cannot make statement while the promise type is dependent");
  974. assert(this->ReturnValue && "ReturnValue must be already formed");
  975. QualType const GroType = this->ReturnValue->getType();
  976. assert(!GroType->isDependentType() &&
  977. "get_return_object type must no longer be dependent");
  978. QualType const FnRetType = FD.getReturnType();
  979. assert(!FnRetType->isDependentType() &&
  980. "get_return_object type must no longer be dependent");
  981. if (FnRetType->isVoidType()) {
  982. ExprResult Res = S.ActOnFinishFullExpr(this->ReturnValue, Loc);
  983. if (Res.isInvalid())
  984. return false;
  985. this->ResultDecl = Res.get();
  986. return true;
  987. }
  988. if (GroType->isVoidType()) {
  989. // Trigger a nice error message.
  990. InitializedEntity Entity =
  991. InitializedEntity::InitializeResult(Loc, FnRetType, false);
  992. S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue);
  993. noteMemberDeclaredHere(S, ReturnValue, Fn);
  994. return false;
  995. }
  996. auto *GroDecl = VarDecl::Create(
  997. S.Context, &FD, FD.getLocation(), FD.getLocation(),
  998. &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
  999. S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
  1000. S.CheckVariableDeclarationType(GroDecl);
  1001. if (GroDecl->isInvalidDecl())
  1002. return false;
  1003. InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
  1004. ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType,
  1005. this->ReturnValue);
  1006. if (Res.isInvalid())
  1007. return false;
  1008. Res = S.ActOnFinishFullExpr(Res.get());
  1009. if (Res.isInvalid())
  1010. return false;
  1011. if (GroType == FnRetType) {
  1012. GroDecl->setNRVOVariable(true);
  1013. }
  1014. S.AddInitializerToDecl(GroDecl, Res.get(),
  1015. /*DirectInit=*/false);
  1016. S.FinalizeDeclaration(GroDecl);
  1017. // Form a declaration statement for the return declaration, so that AST
  1018. // visitors can more easily find it.
  1019. StmtResult GroDeclStmt =
  1020. S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
  1021. if (GroDeclStmt.isInvalid())
  1022. return false;
  1023. this->ResultDecl = GroDeclStmt.get();
  1024. ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
  1025. if (declRef.isInvalid())
  1026. return false;
  1027. StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
  1028. if (ReturnStmt.isInvalid()) {
  1029. noteMemberDeclaredHere(S, ReturnValue, Fn);
  1030. return false;
  1031. }
  1032. this->ReturnStmt = ReturnStmt.get();
  1033. return true;
  1034. }
  1035. // Create a static_cast\<T&&>(expr).
  1036. static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
  1037. if (T.isNull())
  1038. T = E->getType();
  1039. QualType TargetType = S.BuildReferenceType(
  1040. T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());
  1041. SourceLocation ExprLoc = E->getLocStart();
  1042. TypeSourceInfo *TargetLoc =
  1043. S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
  1044. return S
  1045. .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
  1046. SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
  1047. .get();
  1048. }
  1049. /// \brief Build a variable declaration for move parameter.
  1050. static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
  1051. StringRef Name) {
  1052. DeclContext *DC = S.CurContext;
  1053. IdentifierInfo *II = &S.PP.getIdentifierTable().get(Name);
  1054. TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);
  1055. VarDecl *Decl =
  1056. VarDecl::Create(S.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
  1057. Decl->setImplicit();
  1058. return Decl;
  1059. }
  1060. bool CoroutineStmtBuilder::makeParamMoves() {
  1061. for (auto *paramDecl : FD.parameters()) {
  1062. auto Ty = paramDecl->getType();
  1063. if (Ty->isDependentType())
  1064. continue;
  1065. // No need to copy scalars, llvm will take care of them.
  1066. if (Ty->getAsCXXRecordDecl()) {
  1067. if (!paramDecl->getIdentifier())
  1068. continue;
  1069. ExprResult ParamRef =
  1070. S.BuildDeclRefExpr(paramDecl, paramDecl->getType(),
  1071. ExprValueKind::VK_LValue, Loc); // FIXME: scope?
  1072. if (ParamRef.isInvalid())
  1073. return false;
  1074. Expr *RCast = castForMoving(S, ParamRef.get());
  1075. auto D = buildVarDecl(S, Loc, Ty, paramDecl->getIdentifier()->getName());
  1076. S.AddInitializerToDecl(D, RCast, /*DirectInit=*/true);
  1077. // Convert decl to a statement.
  1078. StmtResult Stmt = S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(D), Loc, Loc);
  1079. if (Stmt.isInvalid())
  1080. return false;
  1081. ParamMovesVector.push_back(Stmt.get());
  1082. }
  1083. }
  1084. // Convert to ArrayRef in CtorArgs structure that builder inherits from.
  1085. ParamMoves = ParamMovesVector;
  1086. return true;
  1087. }
  1088. StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
  1089. CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
  1090. if (!Res)
  1091. return StmtError();
  1092. return Res;
  1093. }