SemaCoroutine.cpp 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908
  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. /// Build a call to 'operator co_await' if there is a suitable operator for
  224. /// the given expression.
  225. ExprResult Sema::BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E,
  226. UnresolvedLookupExpr *Lookup) {
  227. UnresolvedSet<16> Functions;
  228. Functions.append(Lookup->decls_begin(), Lookup->decls_end());
  229. return CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
  230. }
  231. static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
  232. SourceLocation Loc, Expr *E) {
  233. ExprResult R = SemaRef.BuildOperatorCoawaitLookupExpr(S, Loc);
  234. if (R.isInvalid())
  235. return ExprError();
  236. return SemaRef.BuildOperatorCoawaitCall(Loc, E,
  237. cast<UnresolvedLookupExpr>(R.get()));
  238. }
  239. static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
  240. SourceLocation Loc) {
  241. QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
  242. if (CoroHandleType.isNull())
  243. return ExprError();
  244. DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
  245. LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
  246. Sema::LookupOrdinaryName);
  247. if (!S.LookupQualifiedName(Found, LookupCtx)) {
  248. S.Diag(Loc, diag::err_coroutine_handle_missing_member)
  249. << "from_address";
  250. return ExprError();
  251. }
  252. Expr *FramePtr =
  253. S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_frame, {});
  254. CXXScopeSpec SS;
  255. ExprResult FromAddr =
  256. S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
  257. if (FromAddr.isInvalid())
  258. return ExprError();
  259. return S.BuildCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
  260. }
  261. struct ReadySuspendResumeResult {
  262. enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume };
  263. Expr *Results[3];
  264. OpaqueValueExpr *OpaqueValue;
  265. bool IsInvalid;
  266. };
  267. static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
  268. StringRef Name, MultiExprArg Args) {
  269. DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
  270. // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
  271. CXXScopeSpec SS;
  272. ExprResult Result = S.BuildMemberReferenceExpr(
  273. Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
  274. SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
  275. /*Scope=*/nullptr);
  276. if (Result.isInvalid())
  277. return ExprError();
  278. // We meant exactly what we asked for. No need for typo correction.
  279. if (auto *TE = dyn_cast<TypoExpr>(Result.get())) {
  280. S.clearDelayedTypo(TE);
  281. S.Diag(Loc, diag::err_no_member)
  282. << NameInfo.getName() << Base->getType()->getAsCXXRecordDecl()
  283. << Base->getSourceRange();
  284. return ExprError();
  285. }
  286. return S.BuildCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
  287. }
  288. // See if return type is coroutine-handle and if so, invoke builtin coro-resume
  289. // on its address. This is to enable experimental support for coroutine-handle
  290. // returning await_suspend that results in a guaranteed tail call to the target
  291. // coroutine.
  292. static Expr *maybeTailCall(Sema &S, QualType RetType, Expr *E,
  293. SourceLocation Loc) {
  294. if (RetType->isReferenceType())
  295. return nullptr;
  296. Type const *T = RetType.getTypePtr();
  297. if (!T->isClassType() && !T->isStructureType())
  298. return nullptr;
  299. // FIXME: Add convertability check to coroutine_handle<>. Possibly via
  300. // EvaluateBinaryTypeTrait(BTT_IsConvertible, ...) which is at the moment
  301. // a private function in SemaExprCXX.cpp
  302. ExprResult AddressExpr = buildMemberCall(S, E, Loc, "address", std::nullopt);
  303. if (AddressExpr.isInvalid())
  304. return nullptr;
  305. Expr *JustAddress = AddressExpr.get();
  306. // Check that the type of AddressExpr is void*
  307. if (!JustAddress->getType().getTypePtr()->isVoidPointerType())
  308. S.Diag(cast<CallExpr>(JustAddress)->getCalleeDecl()->getLocation(),
  309. diag::warn_coroutine_handle_address_invalid_return_type)
  310. << JustAddress->getType();
  311. // Clean up temporary objects so that they don't live across suspension points
  312. // unnecessarily. We choose to clean up before the call to
  313. // __builtin_coro_resume so that the cleanup code are not inserted in-between
  314. // the resume call and return instruction, which would interfere with the
  315. // musttail call contract.
  316. JustAddress = S.MaybeCreateExprWithCleanups(JustAddress);
  317. return S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_resume,
  318. JustAddress);
  319. }
  320. /// Build calls to await_ready, await_suspend, and await_resume for a co_await
  321. /// expression.
  322. /// The generated AST tries to clean up temporary objects as early as
  323. /// possible so that they don't live across suspension points if possible.
  324. /// Having temporary objects living across suspension points unnecessarily can
  325. /// lead to large frame size, and also lead to memory corruptions if the
  326. /// coroutine frame is destroyed after coming back from suspension. This is done
  327. /// by wrapping both the await_ready call and the await_suspend call with
  328. /// ExprWithCleanups. In the end of this function, we also need to explicitly
  329. /// set cleanup state so that the CoawaitExpr is also wrapped with an
  330. /// ExprWithCleanups to clean up the awaiter associated with the co_await
  331. /// expression.
  332. static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
  333. SourceLocation Loc, Expr *E) {
  334. OpaqueValueExpr *Operand = new (S.Context)
  335. OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
  336. // Assume valid until we see otherwise.
  337. // Further operations are responsible for setting IsInalid to true.
  338. ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/false};
  339. using ACT = ReadySuspendResumeResult::AwaitCallType;
  340. auto BuildSubExpr = [&](ACT CallType, StringRef Func,
  341. MultiExprArg Arg) -> Expr * {
  342. ExprResult Result = buildMemberCall(S, Operand, Loc, Func, Arg);
  343. if (Result.isInvalid()) {
  344. Calls.IsInvalid = true;
  345. return nullptr;
  346. }
  347. Calls.Results[CallType] = Result.get();
  348. return Result.get();
  349. };
  350. CallExpr *AwaitReady = cast_or_null<CallExpr>(
  351. BuildSubExpr(ACT::ACT_Ready, "await_ready", std::nullopt));
  352. if (!AwaitReady)
  353. return Calls;
  354. if (!AwaitReady->getType()->isDependentType()) {
  355. // [expr.await]p3 [...]
  356. // — await-ready is the expression e.await_ready(), contextually converted
  357. // to bool.
  358. ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady);
  359. if (Conv.isInvalid()) {
  360. S.Diag(AwaitReady->getDirectCallee()->getBeginLoc(),
  361. diag::note_await_ready_no_bool_conversion);
  362. S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
  363. << AwaitReady->getDirectCallee() << E->getSourceRange();
  364. Calls.IsInvalid = true;
  365. } else
  366. Calls.Results[ACT::ACT_Ready] = S.MaybeCreateExprWithCleanups(Conv.get());
  367. }
  368. ExprResult CoroHandleRes =
  369. buildCoroutineHandle(S, CoroPromise->getType(), Loc);
  370. if (CoroHandleRes.isInvalid()) {
  371. Calls.IsInvalid = true;
  372. return Calls;
  373. }
  374. Expr *CoroHandle = CoroHandleRes.get();
  375. CallExpr *AwaitSuspend = cast_or_null<CallExpr>(
  376. BuildSubExpr(ACT::ACT_Suspend, "await_suspend", CoroHandle));
  377. if (!AwaitSuspend)
  378. return Calls;
  379. if (!AwaitSuspend->getType()->isDependentType()) {
  380. // [expr.await]p3 [...]
  381. // - await-suspend is the expression e.await_suspend(h), which shall be
  382. // a prvalue of type void, bool, or std::coroutine_handle<Z> for some
  383. // type Z.
  384. QualType RetType = AwaitSuspend->getCallReturnType(S.Context);
  385. // Experimental support for coroutine_handle returning await_suspend.
  386. if (Expr *TailCallSuspend =
  387. maybeTailCall(S, RetType, AwaitSuspend, Loc))
  388. // Note that we don't wrap the expression with ExprWithCleanups here
  389. // because that might interfere with tailcall contract (e.g. inserting
  390. // clean up instructions in-between tailcall and return). Instead
  391. // ExprWithCleanups is wrapped within maybeTailCall() prior to the resume
  392. // call.
  393. Calls.Results[ACT::ACT_Suspend] = TailCallSuspend;
  394. else {
  395. // non-class prvalues always have cv-unqualified types
  396. if (RetType->isReferenceType() ||
  397. (!RetType->isBooleanType() && !RetType->isVoidType())) {
  398. S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
  399. diag::err_await_suspend_invalid_return_type)
  400. << RetType;
  401. S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
  402. << AwaitSuspend->getDirectCallee();
  403. Calls.IsInvalid = true;
  404. } else
  405. Calls.Results[ACT::ACT_Suspend] =
  406. S.MaybeCreateExprWithCleanups(AwaitSuspend);
  407. }
  408. }
  409. BuildSubExpr(ACT::ACT_Resume, "await_resume", std::nullopt);
  410. // Make sure the awaiter object gets a chance to be cleaned up.
  411. S.Cleanup.setExprNeedsCleanups(true);
  412. return Calls;
  413. }
  414. static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
  415. SourceLocation Loc, StringRef Name,
  416. MultiExprArg Args) {
  417. // Form a reference to the promise.
  418. ExprResult PromiseRef = S.BuildDeclRefExpr(
  419. Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
  420. if (PromiseRef.isInvalid())
  421. return ExprError();
  422. return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
  423. }
  424. VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
  425. assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
  426. auto *FD = cast<FunctionDecl>(CurContext);
  427. bool IsThisDependentType = [&] {
  428. if (auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD))
  429. return MD->isInstance() && MD->getThisType()->isDependentType();
  430. else
  431. return false;
  432. }();
  433. QualType T = FD->getType()->isDependentType() || IsThisDependentType
  434. ? Context.DependentTy
  435. : lookupPromiseType(*this, FD, Loc);
  436. if (T.isNull())
  437. return nullptr;
  438. auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
  439. &PP.getIdentifierTable().get("__promise"), T,
  440. Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
  441. VD->setImplicit();
  442. CheckVariableDeclarationType(VD);
  443. if (VD->isInvalidDecl())
  444. return nullptr;
  445. auto *ScopeInfo = getCurFunction();
  446. // Build a list of arguments, based on the coroutine function's arguments,
  447. // that if present will be passed to the promise type's constructor.
  448. llvm::SmallVector<Expr *, 4> CtorArgExprs;
  449. // Add implicit object parameter.
  450. if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  451. if (MD->isInstance() && !isLambdaCallOperator(MD)) {
  452. ExprResult ThisExpr = ActOnCXXThis(Loc);
  453. if (ThisExpr.isInvalid())
  454. return nullptr;
  455. ThisExpr = CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
  456. if (ThisExpr.isInvalid())
  457. return nullptr;
  458. CtorArgExprs.push_back(ThisExpr.get());
  459. }
  460. }
  461. // Add the coroutine function's parameters.
  462. auto &Moves = ScopeInfo->CoroutineParameterMoves;
  463. for (auto *PD : FD->parameters()) {
  464. if (PD->getType()->isDependentType())
  465. continue;
  466. auto RefExpr = ExprEmpty();
  467. auto Move = Moves.find(PD);
  468. assert(Move != Moves.end() &&
  469. "Coroutine function parameter not inserted into move map");
  470. // If a reference to the function parameter exists in the coroutine
  471. // frame, use that reference.
  472. auto *MoveDecl =
  473. cast<VarDecl>(cast<DeclStmt>(Move->second)->getSingleDecl());
  474. RefExpr =
  475. BuildDeclRefExpr(MoveDecl, MoveDecl->getType().getNonReferenceType(),
  476. ExprValueKind::VK_LValue, FD->getLocation());
  477. if (RefExpr.isInvalid())
  478. return nullptr;
  479. CtorArgExprs.push_back(RefExpr.get());
  480. }
  481. // If we have a non-zero number of constructor arguments, try to use them.
  482. // Otherwise, fall back to the promise type's default constructor.
  483. if (!CtorArgExprs.empty()) {
  484. // Create an initialization sequence for the promise type using the
  485. // constructor arguments, wrapped in a parenthesized list expression.
  486. Expr *PLE = ParenListExpr::Create(Context, FD->getLocation(),
  487. CtorArgExprs, FD->getLocation());
  488. InitializedEntity Entity = InitializedEntity::InitializeVariable(VD);
  489. InitializationKind Kind = InitializationKind::CreateForInit(
  490. VD->getLocation(), /*DirectInit=*/true, PLE);
  491. InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs,
  492. /*TopLevelOfInitList=*/false,
  493. /*TreatUnavailableAsInvalid=*/false);
  494. // [dcl.fct.def.coroutine]5.7
  495. // promise-constructor-arguments is determined as follows: overload
  496. // resolution is performed on a promise constructor call created by
  497. // assembling an argument list q_1 ... q_n . If a viable constructor is
  498. // found ([over.match.viable]), then promise-constructor-arguments is ( q_1
  499. // , ..., q_n ), otherwise promise-constructor-arguments is empty.
  500. if (InitSeq) {
  501. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, CtorArgExprs);
  502. if (Result.isInvalid()) {
  503. VD->setInvalidDecl();
  504. } else if (Result.get()) {
  505. VD->setInit(MaybeCreateExprWithCleanups(Result.get()));
  506. VD->setInitStyle(VarDecl::CallInit);
  507. CheckCompleteVariableDeclaration(VD);
  508. }
  509. } else
  510. ActOnUninitializedDecl(VD);
  511. } else
  512. ActOnUninitializedDecl(VD);
  513. FD->addDecl(VD);
  514. return VD;
  515. }
  516. /// Check that this is a context in which a coroutine suspension can appear.
  517. static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
  518. StringRef Keyword,
  519. bool IsImplicit = false) {
  520. if (!isValidCoroutineContext(S, Loc, Keyword))
  521. return nullptr;
  522. assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
  523. auto *ScopeInfo = S.getCurFunction();
  524. assert(ScopeInfo && "missing function scope for function");
  525. if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
  526. ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
  527. if (ScopeInfo->CoroutinePromise)
  528. return ScopeInfo;
  529. if (!S.buildCoroutineParameterMoves(Loc))
  530. return nullptr;
  531. ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
  532. if (!ScopeInfo->CoroutinePromise)
  533. return nullptr;
  534. return ScopeInfo;
  535. }
  536. /// Recursively check \p E and all its children to see if any call target
  537. /// (including constructor call) is declared noexcept. Also any value returned
  538. /// from the call has a noexcept destructor.
  539. static void checkNoThrow(Sema &S, const Stmt *E,
  540. llvm::SmallPtrSetImpl<const Decl *> &ThrowingDecls) {
  541. auto checkDeclNoexcept = [&](const Decl *D, bool IsDtor = false) {
  542. // In the case of dtor, the call to dtor is implicit and hence we should
  543. // pass nullptr to canCalleeThrow.
  544. if (Sema::canCalleeThrow(S, IsDtor ? nullptr : cast<Expr>(E), D)) {
  545. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  546. // co_await promise.final_suspend() could end up calling
  547. // __builtin_coro_resume for symmetric transfer if await_suspend()
  548. // returns a handle. In that case, even __builtin_coro_resume is not
  549. // declared as noexcept and may throw, it does not throw _into_ the
  550. // coroutine that just suspended, but rather throws back out from
  551. // whoever called coroutine_handle::resume(), hence we claim that
  552. // logically it does not throw.
  553. if (FD->getBuiltinID() == Builtin::BI__builtin_coro_resume)
  554. return;
  555. }
  556. if (ThrowingDecls.empty()) {
  557. // [dcl.fct.def.coroutine]p15
  558. // The expression co_await promise.final_suspend() shall not be
  559. // potentially-throwing ([except.spec]).
  560. //
  561. // First time seeing an error, emit the error message.
  562. S.Diag(cast<FunctionDecl>(S.CurContext)->getLocation(),
  563. diag::err_coroutine_promise_final_suspend_requires_nothrow);
  564. }
  565. ThrowingDecls.insert(D);
  566. }
  567. };
  568. if (auto *CE = dyn_cast<CXXConstructExpr>(E)) {
  569. CXXConstructorDecl *Ctor = CE->getConstructor();
  570. checkDeclNoexcept(Ctor);
  571. // Check the corresponding destructor of the constructor.
  572. checkDeclNoexcept(Ctor->getParent()->getDestructor(), /*IsDtor=*/true);
  573. } else if (auto *CE = dyn_cast<CallExpr>(E)) {
  574. if (CE->isTypeDependent())
  575. return;
  576. checkDeclNoexcept(CE->getCalleeDecl());
  577. QualType ReturnType = CE->getCallReturnType(S.getASTContext());
  578. // Check the destructor of the call return type, if any.
  579. if (ReturnType.isDestructedType() ==
  580. QualType::DestructionKind::DK_cxx_destructor) {
  581. const auto *T =
  582. cast<RecordType>(ReturnType.getCanonicalType().getTypePtr());
  583. checkDeclNoexcept(cast<CXXRecordDecl>(T->getDecl())->getDestructor(),
  584. /*IsDtor=*/true);
  585. }
  586. } else
  587. for (const auto *Child : E->children()) {
  588. if (!Child)
  589. continue;
  590. checkNoThrow(S, Child, ThrowingDecls);
  591. }
  592. }
  593. bool Sema::checkFinalSuspendNoThrow(const Stmt *FinalSuspend) {
  594. llvm::SmallPtrSet<const Decl *, 4> ThrowingDecls;
  595. // We first collect all declarations that should not throw but not declared
  596. // with noexcept. We then sort them based on the location before printing.
  597. // This is to avoid emitting the same note multiple times on the same
  598. // declaration, and also provide a deterministic order for the messages.
  599. checkNoThrow(*this, FinalSuspend, ThrowingDecls);
  600. auto SortedDecls = llvm::SmallVector<const Decl *, 4>{ThrowingDecls.begin(),
  601. ThrowingDecls.end()};
  602. sort(SortedDecls, [](const Decl *A, const Decl *B) {
  603. return A->getEndLoc() < B->getEndLoc();
  604. });
  605. for (const auto *D : SortedDecls) {
  606. Diag(D->getEndLoc(), diag::note_coroutine_function_declare_noexcept);
  607. }
  608. return ThrowingDecls.empty();
  609. }
  610. bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc,
  611. StringRef Keyword) {
  612. if (!checkCoroutineContext(*this, KWLoc, Keyword))
  613. return false;
  614. auto *ScopeInfo = getCurFunction();
  615. assert(ScopeInfo->CoroutinePromise);
  616. // If we have existing coroutine statements then we have already built
  617. // the initial and final suspend points.
  618. if (!ScopeInfo->NeedsCoroutineSuspends)
  619. return true;
  620. ScopeInfo->setNeedsCoroutineSuspends(false);
  621. auto *Fn = cast<FunctionDecl>(CurContext);
  622. SourceLocation Loc = Fn->getLocation();
  623. // Build the initial suspend point
  624. auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
  625. ExprResult Operand = buildPromiseCall(*this, ScopeInfo->CoroutinePromise,
  626. Loc, Name, std::nullopt);
  627. if (Operand.isInvalid())
  628. return StmtError();
  629. ExprResult Suspend =
  630. buildOperatorCoawaitCall(*this, SC, Loc, Operand.get());
  631. if (Suspend.isInvalid())
  632. return StmtError();
  633. Suspend = BuildResolvedCoawaitExpr(Loc, Operand.get(), Suspend.get(),
  634. /*IsImplicit*/ true);
  635. Suspend = ActOnFinishFullExpr(Suspend.get(), /*DiscardedValue*/ false);
  636. if (Suspend.isInvalid()) {
  637. Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
  638. << ((Name == "initial_suspend") ? 0 : 1);
  639. Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
  640. return StmtError();
  641. }
  642. return cast<Stmt>(Suspend.get());
  643. };
  644. StmtResult InitSuspend = buildSuspends("initial_suspend");
  645. if (InitSuspend.isInvalid())
  646. return true;
  647. StmtResult FinalSuspend = buildSuspends("final_suspend");
  648. if (FinalSuspend.isInvalid() || !checkFinalSuspendNoThrow(FinalSuspend.get()))
  649. return true;
  650. ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
  651. return true;
  652. }
  653. // Recursively walks up the scope hierarchy until either a 'catch' or a function
  654. // scope is found, whichever comes first.
  655. static bool isWithinCatchScope(Scope *S) {
  656. // 'co_await' and 'co_yield' keywords are disallowed within catch blocks, but
  657. // lambdas that use 'co_await' are allowed. The loop below ends when a
  658. // function scope is found in order to ensure the following behavior:
  659. //
  660. // void foo() { // <- function scope
  661. // try { //
  662. // co_await x; // <- 'co_await' is OK within a function scope
  663. // } catch { // <- catch scope
  664. // co_await x; // <- 'co_await' is not OK within a catch scope
  665. // []() { // <- function scope
  666. // co_await x; // <- 'co_await' is OK within a function scope
  667. // }();
  668. // }
  669. // }
  670. while (S && !S->isFunctionScope()) {
  671. if (S->isCatchScope())
  672. return true;
  673. S = S->getParent();
  674. }
  675. return false;
  676. }
  677. // [expr.await]p2, emphasis added: "An await-expression shall appear only in
  678. // a *potentially evaluated* expression within the compound-statement of a
  679. // function-body *outside of a handler* [...] A context within a function
  680. // where an await-expression can appear is called a suspension context of the
  681. // function."
  682. static bool checkSuspensionContext(Sema &S, SourceLocation Loc,
  683. StringRef Keyword) {
  684. // First emphasis of [expr.await]p2: must be a potentially evaluated context.
  685. // That is, 'co_await' and 'co_yield' cannot appear in subexpressions of
  686. // \c sizeof.
  687. if (S.isUnevaluatedContext()) {
  688. S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
  689. return false;
  690. }
  691. // Second emphasis of [expr.await]p2: must be outside of an exception handler.
  692. if (isWithinCatchScope(S.getCurScope())) {
  693. S.Diag(Loc, diag::err_coroutine_within_handler) << Keyword;
  694. return false;
  695. }
  696. return true;
  697. }
  698. ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
  699. if (!checkSuspensionContext(*this, Loc, "co_await"))
  700. return ExprError();
  701. if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) {
  702. CorrectDelayedTyposInExpr(E);
  703. return ExprError();
  704. }
  705. if (E->hasPlaceholderType()) {
  706. ExprResult R = CheckPlaceholderExpr(E);
  707. if (R.isInvalid()) return ExprError();
  708. E = R.get();
  709. }
  710. ExprResult Lookup = BuildOperatorCoawaitLookupExpr(S, Loc);
  711. if (Lookup.isInvalid())
  712. return ExprError();
  713. return BuildUnresolvedCoawaitExpr(Loc, E,
  714. cast<UnresolvedLookupExpr>(Lookup.get()));
  715. }
  716. ExprResult Sema::BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc) {
  717. DeclarationName OpName =
  718. Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
  719. LookupResult Operators(*this, OpName, SourceLocation(),
  720. Sema::LookupOperatorName);
  721. LookupName(Operators, S);
  722. assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
  723. const auto &Functions = Operators.asUnresolvedSet();
  724. bool IsOverloaded =
  725. Functions.size() > 1 ||
  726. (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
  727. Expr *CoawaitOp = UnresolvedLookupExpr::Create(
  728. Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
  729. DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
  730. Functions.begin(), Functions.end());
  731. assert(CoawaitOp);
  732. return CoawaitOp;
  733. }
  734. // Attempts to resolve and build a CoawaitExpr from "raw" inputs, bailing out to
  735. // DependentCoawaitExpr if needed.
  736. ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *Operand,
  737. UnresolvedLookupExpr *Lookup) {
  738. auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
  739. if (!FSI)
  740. return ExprError();
  741. if (Operand->hasPlaceholderType()) {
  742. ExprResult R = CheckPlaceholderExpr(Operand);
  743. if (R.isInvalid())
  744. return ExprError();
  745. Operand = R.get();
  746. }
  747. auto *Promise = FSI->CoroutinePromise;
  748. if (Promise->getType()->isDependentType()) {
  749. Expr *Res = new (Context)
  750. DependentCoawaitExpr(Loc, Context.DependentTy, Operand, Lookup);
  751. return Res;
  752. }
  753. auto *RD = Promise->getType()->getAsCXXRecordDecl();
  754. auto *Transformed = Operand;
  755. if (lookupMember(*this, "await_transform", RD, Loc)) {
  756. ExprResult R =
  757. buildPromiseCall(*this, Promise, Loc, "await_transform", Operand);
  758. if (R.isInvalid()) {
  759. Diag(Loc,
  760. diag::note_coroutine_promise_implicit_await_transform_required_here)
  761. << Operand->getSourceRange();
  762. return ExprError();
  763. }
  764. Transformed = R.get();
  765. }
  766. ExprResult Awaiter = BuildOperatorCoawaitCall(Loc, Transformed, Lookup);
  767. if (Awaiter.isInvalid())
  768. return ExprError();
  769. return BuildResolvedCoawaitExpr(Loc, Operand, Awaiter.get());
  770. }
  771. ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *Operand,
  772. Expr *Awaiter, bool IsImplicit) {
  773. auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
  774. if (!Coroutine)
  775. return ExprError();
  776. if (Awaiter->hasPlaceholderType()) {
  777. ExprResult R = CheckPlaceholderExpr(Awaiter);
  778. if (R.isInvalid()) return ExprError();
  779. Awaiter = R.get();
  780. }
  781. if (Awaiter->getType()->isDependentType()) {
  782. Expr *Res = new (Context)
  783. CoawaitExpr(Loc, Context.DependentTy, Operand, Awaiter, IsImplicit);
  784. return Res;
  785. }
  786. // If the expression is a temporary, materialize it as an lvalue so that we
  787. // can use it multiple times.
  788. if (Awaiter->isPRValue())
  789. Awaiter = CreateMaterializeTemporaryExpr(Awaiter->getType(), Awaiter, true);
  790. // The location of the `co_await` token cannot be used when constructing
  791. // the member call expressions since it's before the location of `Expr`, which
  792. // is used as the start of the member call expression.
  793. SourceLocation CallLoc = Awaiter->getExprLoc();
  794. // Build the await_ready, await_suspend, await_resume calls.
  795. ReadySuspendResumeResult RSS =
  796. buildCoawaitCalls(*this, Coroutine->CoroutinePromise, CallLoc, Awaiter);
  797. if (RSS.IsInvalid)
  798. return ExprError();
  799. Expr *Res = new (Context)
  800. CoawaitExpr(Loc, Operand, Awaiter, RSS.Results[0], RSS.Results[1],
  801. RSS.Results[2], RSS.OpaqueValue, IsImplicit);
  802. return Res;
  803. }
  804. ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
  805. if (!checkSuspensionContext(*this, Loc, "co_yield"))
  806. return ExprError();
  807. if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) {
  808. CorrectDelayedTyposInExpr(E);
  809. return ExprError();
  810. }
  811. // Build yield_value call.
  812. ExprResult Awaitable = buildPromiseCall(
  813. *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
  814. if (Awaitable.isInvalid())
  815. return ExprError();
  816. // Build 'operator co_await' call.
  817. Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
  818. if (Awaitable.isInvalid())
  819. return ExprError();
  820. return BuildCoyieldExpr(Loc, Awaitable.get());
  821. }
  822. ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
  823. auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
  824. if (!Coroutine)
  825. return ExprError();
  826. if (E->hasPlaceholderType()) {
  827. ExprResult R = CheckPlaceholderExpr(E);
  828. if (R.isInvalid()) return ExprError();
  829. E = R.get();
  830. }
  831. Expr *Operand = E;
  832. if (E->getType()->isDependentType()) {
  833. Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, Operand, E);
  834. return Res;
  835. }
  836. // If the expression is a temporary, materialize it as an lvalue so that we
  837. // can use it multiple times.
  838. if (E->isPRValue())
  839. E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
  840. // Build the await_ready, await_suspend, await_resume calls.
  841. ReadySuspendResumeResult RSS = buildCoawaitCalls(
  842. *this, Coroutine->CoroutinePromise, Loc, E);
  843. if (RSS.IsInvalid)
  844. return ExprError();
  845. Expr *Res =
  846. new (Context) CoyieldExpr(Loc, Operand, E, RSS.Results[0], RSS.Results[1],
  847. RSS.Results[2], RSS.OpaqueValue);
  848. return Res;
  849. }
  850. StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
  851. if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) {
  852. CorrectDelayedTyposInExpr(E);
  853. return StmtError();
  854. }
  855. return BuildCoreturnStmt(Loc, E);
  856. }
  857. StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
  858. bool IsImplicit) {
  859. auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
  860. if (!FSI)
  861. return StmtError();
  862. if (E && E->hasPlaceholderType() &&
  863. !E->hasPlaceholderType(BuiltinType::Overload)) {
  864. ExprResult R = CheckPlaceholderExpr(E);
  865. if (R.isInvalid()) return StmtError();
  866. E = R.get();
  867. }
  868. VarDecl *Promise = FSI->CoroutinePromise;
  869. ExprResult PC;
  870. if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
  871. getNamedReturnInfo(E, SimplerImplicitMoveMode::ForceOn);
  872. PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
  873. } else {
  874. E = MakeFullDiscardedValueExpr(E).get();
  875. PC = buildPromiseCall(*this, Promise, Loc, "return_void", std::nullopt);
  876. }
  877. if (PC.isInvalid())
  878. return StmtError();
  879. Expr *PCE = ActOnFinishFullExpr(PC.get(), /*DiscardedValue*/ false).get();
  880. Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
  881. return Res;
  882. }
  883. /// Look up the std::nothrow object.
  884. static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
  885. NamespaceDecl *Std = S.getStdNamespace();
  886. assert(Std && "Should already be diagnosed");
  887. LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
  888. Sema::LookupOrdinaryName);
  889. if (!S.LookupQualifiedName(Result, Std)) {
  890. // <coroutine> is not requred to include <new>, so we couldn't omit
  891. // the check here.
  892. S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
  893. return nullptr;
  894. }
  895. auto *VD = Result.getAsSingle<VarDecl>();
  896. if (!VD) {
  897. Result.suppressDiagnostics();
  898. // We found something weird. Complain about the first thing we found.
  899. NamedDecl *Found = *Result.begin();
  900. S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
  901. return nullptr;
  902. }
  903. ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
  904. if (DR.isInvalid())
  905. return nullptr;
  906. return DR.get();
  907. }
  908. static TypeSourceInfo *getTypeSourceInfoForStdAlignValT(Sema &S,
  909. SourceLocation Loc) {
  910. EnumDecl *StdAlignValT = S.getStdAlignValT();
  911. QualType StdAlignValDecl = S.Context.getTypeDeclType(StdAlignValT);
  912. return S.Context.getTrivialTypeSourceInfo(StdAlignValDecl);
  913. }
  914. // Find an appropriate delete for the promise.
  915. static bool findDeleteForPromise(Sema &S, SourceLocation Loc, QualType PromiseType,
  916. FunctionDecl *&OperatorDelete) {
  917. DeclarationName DeleteName =
  918. S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
  919. auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
  920. assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
  921. const bool Overaligned = S.getLangOpts().CoroAlignedAllocation;
  922. // [dcl.fct.def.coroutine]p12
  923. // The deallocation function's name is looked up by searching for it in the
  924. // scope of the promise type. If nothing is found, a search is performed in
  925. // the global scope.
  926. if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete,
  927. /*Diagnose*/ true, /*WantSize*/ true,
  928. /*WantAligned*/ Overaligned))
  929. return false;
  930. // [dcl.fct.def.coroutine]p12
  931. // If both a usual deallocation function with only a pointer parameter and a
  932. // usual deallocation function with both a pointer parameter and a size
  933. // parameter are found, then the selected deallocation function shall be the
  934. // one with two parameters. Otherwise, the selected deallocation function
  935. // shall be the function with one parameter.
  936. if (!OperatorDelete) {
  937. // Look for a global declaration.
  938. // Coroutines can always provide their required size.
  939. const bool CanProvideSize = true;
  940. // Sema::FindUsualDeallocationFunction will try to find the one with two
  941. // parameters first. It will return the deallocation function with one
  942. // parameter if failed.
  943. OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
  944. Overaligned, DeleteName);
  945. if (!OperatorDelete)
  946. return false;
  947. }
  948. S.MarkFunctionReferenced(Loc, OperatorDelete);
  949. return true;
  950. }
  951. void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
  952. FunctionScopeInfo *Fn = getCurFunction();
  953. assert(Fn && Fn->isCoroutine() && "not a coroutine");
  954. if (!Body) {
  955. assert(FD->isInvalidDecl() &&
  956. "a null body is only allowed for invalid declarations");
  957. return;
  958. }
  959. // We have a function that uses coroutine keywords, but we failed to build
  960. // the promise type.
  961. if (!Fn->CoroutinePromise)
  962. return FD->setInvalidDecl();
  963. if (isa<CoroutineBodyStmt>(Body)) {
  964. // Nothing todo. the body is already a transformed coroutine body statement.
  965. return;
  966. }
  967. // The always_inline attribute doesn't reliably apply to a coroutine,
  968. // because the coroutine will be split into pieces and some pieces
  969. // might be called indirectly, as in a virtual call. Even the ramp
  970. // function cannot be inlined at -O0, due to pipeline ordering
  971. // problems (see https://llvm.org/PR53413). Tell the user about it.
  972. if (FD->hasAttr<AlwaysInlineAttr>())
  973. Diag(FD->getLocation(), diag::warn_always_inline_coroutine);
  974. // [stmt.return.coroutine]p1:
  975. // A coroutine shall not enclose a return statement ([stmt.return]).
  976. if (Fn->FirstReturnLoc.isValid()) {
  977. assert(Fn->FirstCoroutineStmtLoc.isValid() &&
  978. "first coroutine location not set");
  979. Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
  980. Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
  981. << Fn->getFirstCoroutineStmtKeyword();
  982. }
  983. // Coroutines will get splitted into pieces. The GNU address of label
  984. // extension wouldn't be meaningful in coroutines.
  985. for (AddrLabelExpr *ALE : Fn->AddrLabels)
  986. Diag(ALE->getBeginLoc(), diag::err_coro_invalid_addr_of_label);
  987. CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
  988. if (Builder.isInvalid() || !Builder.buildStatements())
  989. return FD->setInvalidDecl();
  990. // Build body for the coroutine wrapper statement.
  991. Body = CoroutineBodyStmt::Create(Context, Builder);
  992. }
  993. CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
  994. sema::FunctionScopeInfo &Fn,
  995. Stmt *Body)
  996. : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
  997. IsPromiseDependentType(
  998. !Fn.CoroutinePromise ||
  999. Fn.CoroutinePromise->getType()->isDependentType()) {
  1000. this->Body = Body;
  1001. for (auto KV : Fn.CoroutineParameterMoves)
  1002. this->ParamMovesVector.push_back(KV.second);
  1003. this->ParamMoves = this->ParamMovesVector;
  1004. if (!IsPromiseDependentType) {
  1005. PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
  1006. assert(PromiseRecordDecl && "Type should have already been checked");
  1007. }
  1008. this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
  1009. }
  1010. bool CoroutineStmtBuilder::buildStatements() {
  1011. assert(this->IsValid && "coroutine already invalid");
  1012. this->IsValid = makeReturnObject();
  1013. if (this->IsValid && !IsPromiseDependentType)
  1014. buildDependentStatements();
  1015. return this->IsValid;
  1016. }
  1017. bool CoroutineStmtBuilder::buildDependentStatements() {
  1018. assert(this->IsValid && "coroutine already invalid");
  1019. assert(!this->IsPromiseDependentType &&
  1020. "coroutine cannot have a dependent promise type");
  1021. this->IsValid = makeOnException() && makeOnFallthrough() &&
  1022. makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
  1023. makeNewAndDeleteExpr();
  1024. return this->IsValid;
  1025. }
  1026. bool CoroutineStmtBuilder::makePromiseStmt() {
  1027. // Form a declaration statement for the promise declaration, so that AST
  1028. // visitors can more easily find it.
  1029. StmtResult PromiseStmt =
  1030. S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
  1031. if (PromiseStmt.isInvalid())
  1032. return false;
  1033. this->Promise = PromiseStmt.get();
  1034. return true;
  1035. }
  1036. bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
  1037. if (Fn.hasInvalidCoroutineSuspends())
  1038. return false;
  1039. this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
  1040. this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
  1041. return true;
  1042. }
  1043. static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
  1044. CXXRecordDecl *PromiseRecordDecl,
  1045. FunctionScopeInfo &Fn) {
  1046. auto Loc = E->getExprLoc();
  1047. if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
  1048. auto *Decl = DeclRef->getDecl();
  1049. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
  1050. if (Method->isStatic())
  1051. return true;
  1052. else
  1053. Loc = Decl->getLocation();
  1054. }
  1055. }
  1056. S.Diag(
  1057. Loc,
  1058. diag::err_coroutine_promise_get_return_object_on_allocation_failure)
  1059. << PromiseRecordDecl;
  1060. S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
  1061. << Fn.getFirstCoroutineStmtKeyword();
  1062. return false;
  1063. }
  1064. bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
  1065. assert(!IsPromiseDependentType &&
  1066. "cannot make statement while the promise type is dependent");
  1067. // [dcl.fct.def.coroutine]p10
  1068. // If a search for the name get_return_object_on_allocation_failure in
  1069. // the scope of the promise type ([class.member.lookup]) finds any
  1070. // declarations, then the result of a call to an allocation function used to
  1071. // obtain storage for the coroutine state is assumed to return nullptr if it
  1072. // fails to obtain storage, ... If the allocation function returns nullptr,
  1073. // ... and the return value is obtained by a call to
  1074. // T::get_return_object_on_allocation_failure(), where T is the
  1075. // promise type.
  1076. DeclarationName DN =
  1077. S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
  1078. LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
  1079. if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
  1080. return true;
  1081. CXXScopeSpec SS;
  1082. ExprResult DeclNameExpr =
  1083. S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
  1084. if (DeclNameExpr.isInvalid())
  1085. return false;
  1086. if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
  1087. return false;
  1088. ExprResult ReturnObjectOnAllocationFailure =
  1089. S.BuildCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
  1090. if (ReturnObjectOnAllocationFailure.isInvalid())
  1091. return false;
  1092. StmtResult ReturnStmt =
  1093. S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
  1094. if (ReturnStmt.isInvalid()) {
  1095. S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
  1096. << DN;
  1097. S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
  1098. << Fn.getFirstCoroutineStmtKeyword();
  1099. return false;
  1100. }
  1101. this->ReturnStmtOnAllocFailure = ReturnStmt.get();
  1102. return true;
  1103. }
  1104. // Collect placement arguments for allocation function of coroutine FD.
  1105. // Return true if we collect placement arguments succesfully. Return false,
  1106. // otherwise.
  1107. static bool collectPlacementArgs(Sema &S, FunctionDecl &FD, SourceLocation Loc,
  1108. SmallVectorImpl<Expr *> &PlacementArgs) {
  1109. if (auto *MD = dyn_cast<CXXMethodDecl>(&FD)) {
  1110. if (MD->isInstance() && !isLambdaCallOperator(MD)) {
  1111. ExprResult ThisExpr = S.ActOnCXXThis(Loc);
  1112. if (ThisExpr.isInvalid())
  1113. return false;
  1114. ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
  1115. if (ThisExpr.isInvalid())
  1116. return false;
  1117. PlacementArgs.push_back(ThisExpr.get());
  1118. }
  1119. }
  1120. for (auto *PD : FD.parameters()) {
  1121. if (PD->getType()->isDependentType())
  1122. continue;
  1123. // Build a reference to the parameter.
  1124. auto PDLoc = PD->getLocation();
  1125. ExprResult PDRefExpr =
  1126. S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),
  1127. ExprValueKind::VK_LValue, PDLoc);
  1128. if (PDRefExpr.isInvalid())
  1129. return false;
  1130. PlacementArgs.push_back(PDRefExpr.get());
  1131. }
  1132. return true;
  1133. }
  1134. bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
  1135. // Form and check allocation and deallocation calls.
  1136. assert(!IsPromiseDependentType &&
  1137. "cannot make statement while the promise type is dependent");
  1138. QualType PromiseType = Fn.CoroutinePromise->getType();
  1139. if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
  1140. return false;
  1141. const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
  1142. // According to [dcl.fct.def.coroutine]p9, Lookup allocation functions using a
  1143. // parameter list composed of the requested size of the coroutine state being
  1144. // allocated, followed by the coroutine function's arguments. If a matching
  1145. // allocation function exists, use it. Otherwise, use an allocation function
  1146. // that just takes the requested size.
  1147. //
  1148. // [dcl.fct.def.coroutine]p9
  1149. // An implementation may need to allocate additional storage for a
  1150. // coroutine.
  1151. // This storage is known as the coroutine state and is obtained by calling a
  1152. // non-array allocation function ([basic.stc.dynamic.allocation]). The
  1153. // allocation function's name is looked up by searching for it in the scope of
  1154. // the promise type.
  1155. // - If any declarations are found, overload resolution is performed on a
  1156. // function call created by assembling an argument list. The first argument is
  1157. // the amount of space requested, and has type std::size_t. The
  1158. // lvalues p1 ... pn are the succeeding arguments.
  1159. //
  1160. // ...where "p1 ... pn" are defined earlier as:
  1161. //
  1162. // [dcl.fct.def.coroutine]p3
  1163. // The promise type of a coroutine is `std::coroutine_traits<R, P1, ...,
  1164. // Pn>`
  1165. // , where R is the return type of the function, and `P1, ..., Pn` are the
  1166. // sequence of types of the non-object function parameters, preceded by the
  1167. // type of the object parameter ([dcl.fct]) if the coroutine is a non-static
  1168. // member function. [dcl.fct.def.coroutine]p4 In the following, p_i is an
  1169. // lvalue of type P_i, where p1 denotes the object parameter and p_i+1 denotes
  1170. // the i-th non-object function parameter for a non-static member function,
  1171. // and p_i denotes the i-th function parameter otherwise. For a non-static
  1172. // member function, q_1 is an lvalue that denotes *this; any other q_i is an
  1173. // lvalue that denotes the parameter copy corresponding to p_i.
  1174. FunctionDecl *OperatorNew = nullptr;
  1175. SmallVector<Expr *, 1> PlacementArgs;
  1176. const bool PromiseContainsNew = [this, &PromiseType]() -> bool {
  1177. DeclarationName NewName =
  1178. S.getASTContext().DeclarationNames.getCXXOperatorName(OO_New);
  1179. LookupResult R(S, NewName, Loc, Sema::LookupOrdinaryName);
  1180. if (PromiseType->isRecordType())
  1181. S.LookupQualifiedName(R, PromiseType->getAsCXXRecordDecl());
  1182. return !R.empty() && !R.isAmbiguous();
  1183. }();
  1184. // Helper function to indicate whether the last lookup found the aligned
  1185. // allocation function.
  1186. bool PassAlignment = S.getLangOpts().CoroAlignedAllocation;
  1187. auto LookupAllocationFunction = [&](Sema::AllocationFunctionScope NewScope =
  1188. Sema::AFS_Both,
  1189. bool WithoutPlacementArgs = false,
  1190. bool ForceNonAligned = false) {
  1191. // [dcl.fct.def.coroutine]p9
  1192. // The allocation function's name is looked up by searching for it in the
  1193. // scope of the promise type.
  1194. // - If any declarations are found, ...
  1195. // - If no declarations are found in the scope of the promise type, a search
  1196. // is performed in the global scope.
  1197. if (NewScope == Sema::AFS_Both)
  1198. NewScope = PromiseContainsNew ? Sema::AFS_Class : Sema::AFS_Global;
  1199. PassAlignment = !ForceNonAligned && S.getLangOpts().CoroAlignedAllocation;
  1200. FunctionDecl *UnusedResult = nullptr;
  1201. S.FindAllocationFunctions(Loc, SourceRange(), NewScope,
  1202. /*DeleteScope*/ Sema::AFS_Both, PromiseType,
  1203. /*isArray*/ false, PassAlignment,
  1204. WithoutPlacementArgs ? MultiExprArg{}
  1205. : PlacementArgs,
  1206. OperatorNew, UnusedResult, /*Diagnose*/ false);
  1207. };
  1208. // We don't expect to call to global operator new with (size, p0, …, pn).
  1209. // So if we choose to lookup the allocation function in global scope, we
  1210. // shouldn't lookup placement arguments.
  1211. if (PromiseContainsNew && !collectPlacementArgs(S, FD, Loc, PlacementArgs))
  1212. return false;
  1213. LookupAllocationFunction();
  1214. if (PromiseContainsNew && !PlacementArgs.empty()) {
  1215. // [dcl.fct.def.coroutine]p9
  1216. // If no viable function is found ([over.match.viable]), overload
  1217. // resolution
  1218. // is performed again on a function call created by passing just the amount
  1219. // of space required as an argument of type std::size_t.
  1220. //
  1221. // Proposed Change of [dcl.fct.def.coroutine]p9 in P2014R0:
  1222. // Otherwise, overload resolution is performed again on a function call
  1223. // created
  1224. // by passing the amount of space requested as an argument of type
  1225. // std::size_t as the first argument, and the requested alignment as
  1226. // an argument of type std:align_val_t as the second argument.
  1227. if (!OperatorNew ||
  1228. (S.getLangOpts().CoroAlignedAllocation && !PassAlignment))
  1229. LookupAllocationFunction(/*NewScope*/ Sema::AFS_Class,
  1230. /*WithoutPlacementArgs*/ true);
  1231. }
  1232. // Proposed Change of [dcl.fct.def.coroutine]p12 in P2014R0:
  1233. // Otherwise, overload resolution is performed again on a function call
  1234. // created
  1235. // by passing the amount of space requested as an argument of type
  1236. // std::size_t as the first argument, and the lvalues p1 ... pn as the
  1237. // succeeding arguments. Otherwise, overload resolution is performed again
  1238. // on a function call created by passing just the amount of space required as
  1239. // an argument of type std::size_t.
  1240. //
  1241. // So within the proposed change in P2014RO, the priority order of aligned
  1242. // allocation functions wiht promise_type is:
  1243. //
  1244. // void* operator new( std::size_t, std::align_val_t, placement_args... );
  1245. // void* operator new( std::size_t, std::align_val_t);
  1246. // void* operator new( std::size_t, placement_args... );
  1247. // void* operator new( std::size_t);
  1248. // Helper variable to emit warnings.
  1249. bool FoundNonAlignedInPromise = false;
  1250. if (PromiseContainsNew && S.getLangOpts().CoroAlignedAllocation)
  1251. if (!OperatorNew || !PassAlignment) {
  1252. FoundNonAlignedInPromise = OperatorNew;
  1253. LookupAllocationFunction(/*NewScope*/ Sema::AFS_Class,
  1254. /*WithoutPlacementArgs*/ false,
  1255. /*ForceNonAligned*/ true);
  1256. if (!OperatorNew && !PlacementArgs.empty())
  1257. LookupAllocationFunction(/*NewScope*/ Sema::AFS_Class,
  1258. /*WithoutPlacementArgs*/ true,
  1259. /*ForceNonAligned*/ true);
  1260. }
  1261. bool IsGlobalOverload =
  1262. OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
  1263. // If we didn't find a class-local new declaration and non-throwing new
  1264. // was is required then we need to lookup the non-throwing global operator
  1265. // instead.
  1266. if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
  1267. auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
  1268. if (!StdNoThrow)
  1269. return false;
  1270. PlacementArgs = {StdNoThrow};
  1271. OperatorNew = nullptr;
  1272. LookupAllocationFunction(Sema::AFS_Global);
  1273. }
  1274. // If we found a non-aligned allocation function in the promise_type,
  1275. // it indicates the user forgot to update the allocation function. Let's emit
  1276. // a warning here.
  1277. if (FoundNonAlignedInPromise) {
  1278. S.Diag(OperatorNew->getLocation(),
  1279. diag::warn_non_aligned_allocation_function)
  1280. << &FD;
  1281. }
  1282. if (!OperatorNew) {
  1283. if (PromiseContainsNew)
  1284. S.Diag(Loc, diag::err_coroutine_unusable_new) << PromiseType << &FD;
  1285. else if (RequiresNoThrowAlloc)
  1286. S.Diag(Loc, diag::err_coroutine_unfound_nothrow_new)
  1287. << &FD << S.getLangOpts().CoroAlignedAllocation;
  1288. return false;
  1289. }
  1290. if (RequiresNoThrowAlloc) {
  1291. const auto *FT = OperatorNew->getType()->castAs<FunctionProtoType>();
  1292. if (!FT->isNothrow(/*ResultIfDependent*/ false)) {
  1293. S.Diag(OperatorNew->getLocation(),
  1294. diag::err_coroutine_promise_new_requires_nothrow)
  1295. << OperatorNew;
  1296. S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
  1297. << OperatorNew;
  1298. return false;
  1299. }
  1300. }
  1301. FunctionDecl *OperatorDelete = nullptr;
  1302. if (!findDeleteForPromise(S, Loc, PromiseType, OperatorDelete)) {
  1303. // FIXME: We should add an error here. According to:
  1304. // [dcl.fct.def.coroutine]p12
  1305. // If no usual deallocation function is found, the program is ill-formed.
  1306. return false;
  1307. }
  1308. Expr *FramePtr =
  1309. S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_frame, {});
  1310. Expr *FrameSize =
  1311. S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_size, {});
  1312. Expr *FrameAlignment = nullptr;
  1313. if (S.getLangOpts().CoroAlignedAllocation) {
  1314. FrameAlignment =
  1315. S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_align, {});
  1316. TypeSourceInfo *AlignValTy = getTypeSourceInfoForStdAlignValT(S, Loc);
  1317. if (!AlignValTy)
  1318. return false;
  1319. FrameAlignment = S.BuildCXXNamedCast(Loc, tok::kw_static_cast, AlignValTy,
  1320. FrameAlignment, SourceRange(Loc, Loc),
  1321. SourceRange(Loc, Loc))
  1322. .get();
  1323. }
  1324. // Make new call.
  1325. ExprResult NewRef =
  1326. S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
  1327. if (NewRef.isInvalid())
  1328. return false;
  1329. SmallVector<Expr *, 2> NewArgs(1, FrameSize);
  1330. if (S.getLangOpts().CoroAlignedAllocation && PassAlignment)
  1331. NewArgs.push_back(FrameAlignment);
  1332. if (OperatorNew->getNumParams() > NewArgs.size())
  1333. llvm::append_range(NewArgs, PlacementArgs);
  1334. ExprResult NewExpr =
  1335. S.BuildCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
  1336. NewExpr = S.ActOnFinishFullExpr(NewExpr.get(), /*DiscardedValue*/ false);
  1337. if (NewExpr.isInvalid())
  1338. return false;
  1339. // Make delete call.
  1340. QualType OpDeleteQualType = OperatorDelete->getType();
  1341. ExprResult DeleteRef =
  1342. S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
  1343. if (DeleteRef.isInvalid())
  1344. return false;
  1345. Expr *CoroFree =
  1346. S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_free, {FramePtr});
  1347. SmallVector<Expr *, 2> DeleteArgs{CoroFree};
  1348. // [dcl.fct.def.coroutine]p12
  1349. // The selected deallocation function shall be called with the address of
  1350. // the block of storage to be reclaimed as its first argument. If a
  1351. // deallocation function with a parameter of type std::size_t is
  1352. // used, the size of the block is passed as the corresponding argument.
  1353. const auto *OpDeleteType =
  1354. OpDeleteQualType.getTypePtr()->castAs<FunctionProtoType>();
  1355. if (OpDeleteType->getNumParams() > DeleteArgs.size() &&
  1356. S.getASTContext().hasSameType(
  1357. OpDeleteType->getParamType(DeleteArgs.size()), FrameSize->getType()))
  1358. DeleteArgs.push_back(FrameSize);
  1359. // Proposed Change of [dcl.fct.def.coroutine]p12 in P2014R0:
  1360. // If deallocation function lookup finds a usual deallocation function with
  1361. // a pointer parameter, size parameter and alignment parameter then this
  1362. // will be the selected deallocation function, otherwise if lookup finds a
  1363. // usual deallocation function with both a pointer parameter and a size
  1364. // parameter, then this will be the selected deallocation function.
  1365. // Otherwise, if lookup finds a usual deallocation function with only a
  1366. // pointer parameter, then this will be the selected deallocation
  1367. // function.
  1368. //
  1369. // So we are not forced to pass alignment to the deallocation function.
  1370. if (S.getLangOpts().CoroAlignedAllocation &&
  1371. OpDeleteType->getNumParams() > DeleteArgs.size() &&
  1372. S.getASTContext().hasSameType(
  1373. OpDeleteType->getParamType(DeleteArgs.size()),
  1374. FrameAlignment->getType()))
  1375. DeleteArgs.push_back(FrameAlignment);
  1376. ExprResult DeleteExpr =
  1377. S.BuildCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
  1378. DeleteExpr =
  1379. S.ActOnFinishFullExpr(DeleteExpr.get(), /*DiscardedValue*/ false);
  1380. if (DeleteExpr.isInvalid())
  1381. return false;
  1382. this->Allocate = NewExpr.get();
  1383. this->Deallocate = DeleteExpr.get();
  1384. return true;
  1385. }
  1386. bool CoroutineStmtBuilder::makeOnFallthrough() {
  1387. assert(!IsPromiseDependentType &&
  1388. "cannot make statement while the promise type is dependent");
  1389. // [dcl.fct.def.coroutine]/p6
  1390. // If searches for the names return_void and return_value in the scope of
  1391. // the promise type each find any declarations, the program is ill-formed.
  1392. // [Note 1: If return_void is found, flowing off the end of a coroutine is
  1393. // equivalent to a co_return with no operand. Otherwise, flowing off the end
  1394. // of a coroutine results in undefined behavior ([stmt.return.coroutine]). —
  1395. // end note]
  1396. bool HasRVoid, HasRValue;
  1397. LookupResult LRVoid =
  1398. lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
  1399. LookupResult LRValue =
  1400. lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
  1401. StmtResult Fallthrough;
  1402. if (HasRVoid && HasRValue) {
  1403. // FIXME Improve this diagnostic
  1404. S.Diag(FD.getLocation(),
  1405. diag::err_coroutine_promise_incompatible_return_functions)
  1406. << PromiseRecordDecl;
  1407. S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
  1408. diag::note_member_first_declared_here)
  1409. << LRVoid.getLookupName();
  1410. S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
  1411. diag::note_member_first_declared_here)
  1412. << LRValue.getLookupName();
  1413. return false;
  1414. } else if (!HasRVoid && !HasRValue) {
  1415. // We need to set 'Fallthrough'. Otherwise the other analysis part might
  1416. // think the coroutine has defined a return_value method. So it might emit
  1417. // **false** positive warning. e.g.,
  1418. //
  1419. // promise_without_return_func foo() {
  1420. // co_await something();
  1421. // }
  1422. //
  1423. // Then AnalysisBasedWarning would emit a warning about `foo()` lacking a
  1424. // co_return statements, which isn't correct.
  1425. Fallthrough = S.ActOnNullStmt(PromiseRecordDecl->getLocation());
  1426. if (Fallthrough.isInvalid())
  1427. return false;
  1428. } else if (HasRVoid) {
  1429. Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
  1430. /*IsImplicit*/false);
  1431. Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
  1432. if (Fallthrough.isInvalid())
  1433. return false;
  1434. }
  1435. this->OnFallthrough = Fallthrough.get();
  1436. return true;
  1437. }
  1438. bool CoroutineStmtBuilder::makeOnException() {
  1439. // Try to form 'p.unhandled_exception();'
  1440. assert(!IsPromiseDependentType &&
  1441. "cannot make statement while the promise type is dependent");
  1442. const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
  1443. if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
  1444. auto DiagID =
  1445. RequireUnhandledException
  1446. ? diag::err_coroutine_promise_unhandled_exception_required
  1447. : diag::
  1448. warn_coroutine_promise_unhandled_exception_required_with_exceptions;
  1449. S.Diag(Loc, DiagID) << PromiseRecordDecl;
  1450. S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
  1451. << PromiseRecordDecl;
  1452. return !RequireUnhandledException;
  1453. }
  1454. // If exceptions are disabled, don't try to build OnException.
  1455. if (!S.getLangOpts().CXXExceptions)
  1456. return true;
  1457. ExprResult UnhandledException = buildPromiseCall(
  1458. S, Fn.CoroutinePromise, Loc, "unhandled_exception", std::nullopt);
  1459. UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc,
  1460. /*DiscardedValue*/ false);
  1461. if (UnhandledException.isInvalid())
  1462. return false;
  1463. // Since the body of the coroutine will be wrapped in try-catch, it will
  1464. // be incompatible with SEH __try if present in a function.
  1465. if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
  1466. S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
  1467. S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
  1468. << Fn.getFirstCoroutineStmtKeyword();
  1469. return false;
  1470. }
  1471. this->OnException = UnhandledException.get();
  1472. return true;
  1473. }
  1474. bool CoroutineStmtBuilder::makeReturnObject() {
  1475. // [dcl.fct.def.coroutine]p7
  1476. // The expression promise.get_return_object() is used to initialize the
  1477. // returned reference or prvalue result object of a call to a coroutine.
  1478. ExprResult ReturnObject = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
  1479. "get_return_object", std::nullopt);
  1480. if (ReturnObject.isInvalid())
  1481. return false;
  1482. this->ReturnValue = ReturnObject.get();
  1483. return true;
  1484. }
  1485. static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
  1486. if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
  1487. auto *MethodDecl = MbrRef->getMethodDecl();
  1488. S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
  1489. << MethodDecl;
  1490. }
  1491. S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
  1492. << Fn.getFirstCoroutineStmtKeyword();
  1493. }
  1494. bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
  1495. assert(!IsPromiseDependentType &&
  1496. "cannot make statement while the promise type is dependent");
  1497. assert(this->ReturnValue && "ReturnValue must be already formed");
  1498. QualType const GroType = this->ReturnValue->getType();
  1499. assert(!GroType->isDependentType() &&
  1500. "get_return_object type must no longer be dependent");
  1501. QualType const FnRetType = FD.getReturnType();
  1502. assert(!FnRetType->isDependentType() &&
  1503. "get_return_object type must no longer be dependent");
  1504. if (FnRetType->isVoidType()) {
  1505. ExprResult Res =
  1506. S.ActOnFinishFullExpr(this->ReturnValue, Loc, /*DiscardedValue*/ false);
  1507. if (Res.isInvalid())
  1508. return false;
  1509. return true;
  1510. }
  1511. if (GroType->isVoidType()) {
  1512. // Trigger a nice error message.
  1513. InitializedEntity Entity =
  1514. InitializedEntity::InitializeResult(Loc, FnRetType);
  1515. S.PerformCopyInitialization(Entity, SourceLocation(), ReturnValue);
  1516. noteMemberDeclaredHere(S, ReturnValue, Fn);
  1517. return false;
  1518. }
  1519. StmtResult ReturnStmt = S.BuildReturnStmt(Loc, ReturnValue);
  1520. if (ReturnStmt.isInvalid()) {
  1521. noteMemberDeclaredHere(S, ReturnValue, Fn);
  1522. return false;
  1523. }
  1524. this->ReturnStmt = ReturnStmt.get();
  1525. return true;
  1526. }
  1527. // Create a static_cast\<T&&>(expr).
  1528. static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
  1529. if (T.isNull())
  1530. T = E->getType();
  1531. QualType TargetType = S.BuildReferenceType(
  1532. T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());
  1533. SourceLocation ExprLoc = E->getBeginLoc();
  1534. TypeSourceInfo *TargetLoc =
  1535. S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
  1536. return S
  1537. .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
  1538. SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
  1539. .get();
  1540. }
  1541. /// Build a variable declaration for move parameter.
  1542. static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
  1543. IdentifierInfo *II) {
  1544. TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);
  1545. VarDecl *Decl = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type,
  1546. TInfo, SC_None);
  1547. Decl->setImplicit();
  1548. return Decl;
  1549. }
  1550. // Build statements that move coroutine function parameters to the coroutine
  1551. // frame, and store them on the function scope info.
  1552. bool Sema::buildCoroutineParameterMoves(SourceLocation Loc) {
  1553. assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
  1554. auto *FD = cast<FunctionDecl>(CurContext);
  1555. auto *ScopeInfo = getCurFunction();
  1556. if (!ScopeInfo->CoroutineParameterMoves.empty())
  1557. return false;
  1558. // [dcl.fct.def.coroutine]p13
  1559. // When a coroutine is invoked, after initializing its parameters
  1560. // ([expr.call]), a copy is created for each coroutine parameter. For a
  1561. // parameter of type cv T, the copy is a variable of type cv T with
  1562. // automatic storage duration that is direct-initialized from an xvalue of
  1563. // type T referring to the parameter.
  1564. for (auto *PD : FD->parameters()) {
  1565. if (PD->getType()->isDependentType())
  1566. continue;
  1567. ExprResult PDRefExpr =
  1568. BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
  1569. ExprValueKind::VK_LValue, Loc); // FIXME: scope?
  1570. if (PDRefExpr.isInvalid())
  1571. return false;
  1572. Expr *CExpr = nullptr;
  1573. if (PD->getType()->getAsCXXRecordDecl() ||
  1574. PD->getType()->isRValueReferenceType())
  1575. CExpr = castForMoving(*this, PDRefExpr.get());
  1576. else
  1577. CExpr = PDRefExpr.get();
  1578. // [dcl.fct.def.coroutine]p13
  1579. // The initialization and destruction of each parameter copy occurs in the
  1580. // context of the called coroutine.
  1581. auto *D = buildVarDecl(*this, Loc, PD->getType(), PD->getIdentifier());
  1582. AddInitializerToDecl(D, CExpr, /*DirectInit=*/true);
  1583. // Convert decl to a statement.
  1584. StmtResult Stmt = ActOnDeclStmt(ConvertDeclToDeclGroup(D), Loc, Loc);
  1585. if (Stmt.isInvalid())
  1586. return false;
  1587. ScopeInfo->CoroutineParameterMoves.insert(std::make_pair(PD, Stmt.get()));
  1588. }
  1589. return true;
  1590. }
  1591. StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
  1592. CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
  1593. if (!Res)
  1594. return StmtError();
  1595. return Res;
  1596. }
  1597. ClassTemplateDecl *Sema::lookupCoroutineTraits(SourceLocation KwLoc,
  1598. SourceLocation FuncLoc,
  1599. NamespaceDecl *&Namespace) {
  1600. if (!StdCoroutineTraitsCache) {
  1601. // Because coroutines moved from std::experimental in the TS to std in
  1602. // C++20, we look in both places to give users time to transition their
  1603. // TS-specific code to C++20. Diagnostics are given when the TS usage is
  1604. // discovered.
  1605. // TODO: Become stricter when <experimental/coroutine> is removed.
  1606. IdentifierInfo const &TraitIdent =
  1607. PP.getIdentifierTable().get("coroutine_traits");
  1608. NamespaceDecl *StdSpace = getStdNamespace();
  1609. LookupResult ResStd(*this, &TraitIdent, FuncLoc, LookupOrdinaryName);
  1610. bool InStd = StdSpace && LookupQualifiedName(ResStd, StdSpace);
  1611. NamespaceDecl *ExpSpace = lookupStdExperimentalNamespace();
  1612. LookupResult ResExp(*this, &TraitIdent, FuncLoc, LookupOrdinaryName);
  1613. bool InExp = ExpSpace && LookupQualifiedName(ResExp, ExpSpace);
  1614. if (!InStd && !InExp) {
  1615. // The goggles, they found nothing!
  1616. Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
  1617. << "std::coroutine_traits";
  1618. return nullptr;
  1619. }
  1620. // Prefer ::std to std::experimental.
  1621. LookupResult &Result = InStd ? ResStd : ResExp;
  1622. CoroTraitsNamespaceCache = InStd ? StdSpace : ExpSpace;
  1623. // coroutine_traits is required to be a class template.
  1624. StdCoroutineTraitsCache = Result.getAsSingle<ClassTemplateDecl>();
  1625. if (!StdCoroutineTraitsCache) {
  1626. Result.suppressDiagnostics();
  1627. NamedDecl *Found = *Result.begin();
  1628. Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
  1629. return nullptr;
  1630. }
  1631. if (InExp) {
  1632. // Found in std::experimental
  1633. Diag(KwLoc, diag::warn_deprecated_coroutine_namespace)
  1634. << "coroutine_traits";
  1635. ResExp.suppressDiagnostics();
  1636. NamedDecl *Found = *ResExp.begin();
  1637. Diag(Found->getLocation(), diag::note_entity_declared_at) << Found;
  1638. if (InStd &&
  1639. StdCoroutineTraitsCache != ResExp.getAsSingle<ClassTemplateDecl>()) {
  1640. // Also found something different in std
  1641. Diag(KwLoc,
  1642. diag::err_mixed_use_std_and_experimental_namespace_for_coroutine);
  1643. Diag(StdCoroutineTraitsCache->getLocation(),
  1644. diag::note_entity_declared_at)
  1645. << StdCoroutineTraitsCache;
  1646. return nullptr;
  1647. }
  1648. }
  1649. }
  1650. Namespace = CoroTraitsNamespaceCache;
  1651. return StdCoroutineTraitsCache;
  1652. }