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