SemaCoroutine.cpp 67 KB

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