SemaCoroutine.cpp 43 KB

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