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