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 return buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_resume, 402 JustAddress); 403 } 404 405 /// Build calls to await_ready, await_suspend, and await_resume for a co_await 406 /// expression. 407 static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise, 408 SourceLocation Loc, Expr *E) { 409 OpaqueValueExpr *Operand = new (S.Context) 410 OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E); 411 412 // Assume invalid until we see otherwise. 413 ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true}; 414 415 ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc); 416 if (CoroHandleRes.isInvalid()) 417 return Calls; 418 Expr *CoroHandle = CoroHandleRes.get(); 419 420 const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"}; 421 MultiExprArg Args[] = {None, CoroHandle, None}; 422 for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) { 423 ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]); 424 if (Result.isInvalid()) 425 return Calls; 426 Calls.Results[I] = Result.get(); 427 } 428 429 // Assume the calls are valid; all further checking should make them invalid. 430 Calls.IsInvalid = false; 431 432 using ACT = ReadySuspendResumeResult::AwaitCallType; 433 CallExpr *AwaitReady = cast<CallExpr>(Calls.Results[ACT::ACT_Ready]); 434 if (!AwaitReady->getType()->isDependentType()) { 435 // [expr.await]p3 [...] 436 // — await-ready is the expression e.await_ready(), contextually converted 437 // to bool. 438 ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady); 439 if (Conv.isInvalid()) { 440 S.Diag(AwaitReady->getDirectCallee()->getBeginLoc(), 441 diag::note_await_ready_no_bool_conversion); 442 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required) 443 << AwaitReady->getDirectCallee() << E->getSourceRange(); 444 Calls.IsInvalid = true; 445 } 446 Calls.Results[ACT::ACT_Ready] = Conv.get(); 447 } 448 CallExpr *AwaitSuspend = cast<CallExpr>(Calls.Results[ACT::ACT_Suspend]); 449 if (!AwaitSuspend->getType()->isDependentType()) { 450 // [expr.await]p3 [...] 451 // - await-suspend is the expression e.await_suspend(h), which shall be 452 // a prvalue of type void or bool. 453 QualType RetType = AwaitSuspend->getCallReturnType(S.Context); 454 455 // Experimental support for coroutine_handle returning await_suspend. 456 if (Expr *TailCallSuspend = maybeTailCall(S, RetType, AwaitSuspend, Loc)) 457 Calls.Results[ACT::ACT_Suspend] = TailCallSuspend; 458 else { 459 // non-class prvalues always have cv-unqualified types 460 if (RetType->isReferenceType() || 461 (!RetType->isBooleanType() && !RetType->isVoidType())) { 462 S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(), 463 diag::err_await_suspend_invalid_return_type) 464 << RetType; 465 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required) 466 << AwaitSuspend->getDirectCallee(); 467 Calls.IsInvalid = true; 468 } 469 } 470 } 471 472 return Calls; 473 } 474 475 static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise, 476 SourceLocation Loc, StringRef Name, 477 MultiExprArg Args) { 478 479 // Form a reference to the promise. 480 ExprResult PromiseRef = S.BuildDeclRefExpr( 481 Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc); 482 if (PromiseRef.isInvalid()) 483 return ExprError(); 484 485 return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args); 486 } 487 488 VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) { 489 assert(isa<FunctionDecl>(CurContext) && "not in a function scope"); 490 auto *FD = cast<FunctionDecl>(CurContext); 491 bool IsThisDependentType = [&] { 492 if (auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD)) 493 return MD->isInstance() && MD->getThisType()->isDependentType(); 494 else 495 return false; 496 }(); 497 498 QualType T = FD->getType()->isDependentType() || IsThisDependentType 499 ? Context.DependentTy 500 : lookupPromiseType(*this, FD, Loc); 501 if (T.isNull()) 502 return nullptr; 503 504 auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(), 505 &PP.getIdentifierTable().get("__promise"), T, 506 Context.getTrivialTypeSourceInfo(T, Loc), SC_None); 507 CheckVariableDeclarationType(VD); 508 if (VD->isInvalidDecl()) 509 return nullptr; 510 511 auto *ScopeInfo = getCurFunction(); 512 513 // Build a list of arguments, based on the coroutine function's arguments, 514 // that if present will be passed to the promise type's constructor. 515 llvm::SmallVector<Expr *, 4> CtorArgExprs; 516 517 // Add implicit object parameter. 518 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 519 if (MD->isInstance() && !isLambdaCallOperator(MD)) { 520 ExprResult ThisExpr = ActOnCXXThis(Loc); 521 if (ThisExpr.isInvalid()) 522 return nullptr; 523 ThisExpr = CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get()); 524 if (ThisExpr.isInvalid()) 525 return nullptr; 526 CtorArgExprs.push_back(ThisExpr.get()); 527 } 528 } 529 530 // Add the coroutine function's parameters. 531 auto &Moves = ScopeInfo->CoroutineParameterMoves; 532 for (auto *PD : FD->parameters()) { 533 if (PD->getType()->isDependentType()) 534 continue; 535 536 auto RefExpr = ExprEmpty(); 537 auto Move = Moves.find(PD); 538 assert(Move != Moves.end() && 539 "Coroutine function parameter not inserted into move map"); 540 // If a reference to the function parameter exists in the coroutine 541 // frame, use that reference. 542 auto *MoveDecl = 543 cast<VarDecl>(cast<DeclStmt>(Move->second)->getSingleDecl()); 544 RefExpr = 545 BuildDeclRefExpr(MoveDecl, MoveDecl->getType().getNonReferenceType(), 546 ExprValueKind::VK_LValue, FD->getLocation()); 547 if (RefExpr.isInvalid()) 548 return nullptr; 549 CtorArgExprs.push_back(RefExpr.get()); 550 } 551 552 // If we have a non-zero number of constructor arguments, try to use them. 553 // Otherwise, fall back to the promise type's default constructor. 554 if (!CtorArgExprs.empty()) { 555 // Create an initialization sequence for the promise type using the 556 // constructor arguments, wrapped in a parenthesized list expression. 557 Expr *PLE = ParenListExpr::Create(Context, FD->getLocation(), 558 CtorArgExprs, FD->getLocation()); 559 InitializedEntity Entity = InitializedEntity::InitializeVariable(VD); 560 InitializationKind Kind = InitializationKind::CreateForInit( 561 VD->getLocation(), /*DirectInit=*/true, PLE); 562 InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs, 563 /*TopLevelOfInitList=*/false, 564 /*TreatUnavailableAsInvalid=*/false); 565 566 // Attempt to initialize the promise type with the arguments. 567 // If that fails, fall back to the promise type's default constructor. 568 if (InitSeq) { 569 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, CtorArgExprs); 570 if (Result.isInvalid()) { 571 VD->setInvalidDecl(); 572 } else if (Result.get()) { 573 VD->setInit(MaybeCreateExprWithCleanups(Result.get())); 574 VD->setInitStyle(VarDecl::CallInit); 575 CheckCompleteVariableDeclaration(VD); 576 } 577 } else 578 ActOnUninitializedDecl(VD); 579 } else 580 ActOnUninitializedDecl(VD); 581 582 FD->addDecl(VD); 583 return VD; 584 } 585 586 /// Check that this is a context in which a coroutine suspension can appear. 587 static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc, 588 StringRef Keyword, 589 bool IsImplicit = false) { 590 if (!isValidCoroutineContext(S, Loc, Keyword)) 591 return nullptr; 592 593 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope"); 594 595 auto *ScopeInfo = S.getCurFunction(); 596 assert(ScopeInfo && "missing function scope for function"); 597 598 if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit) 599 ScopeInfo->setFirstCoroutineStmt(Loc, Keyword); 600 601 if (ScopeInfo->CoroutinePromise) 602 return ScopeInfo; 603 604 if (!S.buildCoroutineParameterMoves(Loc)) 605 return nullptr; 606 607 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc); 608 if (!ScopeInfo->CoroutinePromise) 609 return nullptr; 610 611 return ScopeInfo; 612 } 613 614 /// Recursively check \p E and all its children to see if any call target 615 /// (including constructor call) is declared noexcept. Also any value returned 616 /// from the call has a noexcept destructor. 617 static void checkNoThrow(Sema &S, const Stmt *E, 618 llvm::SmallPtrSetImpl<const Decl *> &ThrowingDecls) { 619 auto checkDeclNoexcept = [&](const Decl *D, bool IsDtor = false) { 620 // In the case of dtor, the call to dtor is implicit and hence we should 621 // pass nullptr to canCalleeThrow. 622 if (Sema::canCalleeThrow(S, IsDtor ? nullptr : cast<Expr>(E), D)) { 623 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 624 // co_await promise.final_suspend() could end up calling 625 // __builtin_coro_resume for symmetric transfer if await_suspend() 626 // returns a handle. In that case, even __builtin_coro_resume is not 627 // declared as noexcept and may throw, it does not throw _into_ the 628 // coroutine that just suspended, but rather throws back out from 629 // whoever called coroutine_handle::resume(), hence we claim that 630 // logically it does not throw. 631 if (FD->getBuiltinID() == Builtin::BI__builtin_coro_resume) 632 return; 633 } 634 if (ThrowingDecls.empty()) { 635 // First time seeing an error, emit the error message. 636 S.Diag(cast<FunctionDecl>(S.CurContext)->getLocation(), 637 diag::err_coroutine_promise_final_suspend_requires_nothrow); 638 } 639 ThrowingDecls.insert(D); 640 } 641 }; 642 auto SC = E->getStmtClass(); 643 if (SC == Expr::CXXConstructExprClass) { 644 auto const *Ctor = cast<CXXConstructExpr>(E)->getConstructor(); 645 checkDeclNoexcept(Ctor); 646 // Check the corresponding destructor of the constructor. 647 checkDeclNoexcept(Ctor->getParent()->getDestructor(), true); 648 } else if (SC == Expr::CallExprClass || SC == Expr::CXXMemberCallExprClass || 649 SC == Expr::CXXOperatorCallExprClass) { 650 if (!cast<CallExpr>(E)->isTypeDependent()) { 651 checkDeclNoexcept(cast<CallExpr>(E)->getCalleeDecl()); 652 auto ReturnType = cast<CallExpr>(E)->getCallReturnType(S.getASTContext()); 653 // Check the destructor of the call return type, if any. 654 if (ReturnType.isDestructedType() == 655 QualType::DestructionKind::DK_cxx_destructor) { 656 const auto *T = 657 cast<RecordType>(ReturnType.getCanonicalType().getTypePtr()); 658 checkDeclNoexcept( 659 dyn_cast<CXXRecordDecl>(T->getDecl())->getDestructor(), true); 660 } 661 } 662 } 663 for (const auto *Child : E->children()) { 664 if (!Child) 665 continue; 666 checkNoThrow(S, Child, ThrowingDecls); 667 } 668 } 669 670 bool Sema::checkFinalSuspendNoThrow(const Stmt *FinalSuspend) { 671 llvm::SmallPtrSet<const Decl *, 4> ThrowingDecls; 672 // We first collect all declarations that should not throw but not declared 673 // with noexcept. We then sort them based on the location before printing. 674 // This is to avoid emitting the same note multiple times on the same 675 // declaration, and also provide a deterministic order for the messages. 676 checkNoThrow(*this, FinalSuspend, ThrowingDecls); 677 auto SortedDecls = llvm::SmallVector<const Decl *, 4>{ThrowingDecls.begin(), 678 ThrowingDecls.end()}; 679 sort(SortedDecls, [](const Decl *A, const Decl *B) { 680 return A->getEndLoc() < B->getEndLoc(); 681 }); 682 for (const auto *D : SortedDecls) { 683 Diag(D->getEndLoc(), diag::note_coroutine_function_declare_noexcept); 684 } 685 return ThrowingDecls.empty(); 686 } 687 688 bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc, 689 StringRef Keyword) { 690 if (!checkCoroutineContext(*this, KWLoc, Keyword)) 691 return false; 692 auto *ScopeInfo = getCurFunction(); 693 assert(ScopeInfo->CoroutinePromise); 694 695 // If we have existing coroutine statements then we have already built 696 // the initial and final suspend points. 697 if (!ScopeInfo->NeedsCoroutineSuspends) 698 return true; 699 700 ScopeInfo->setNeedsCoroutineSuspends(false); 701 702 auto *Fn = cast<FunctionDecl>(CurContext); 703 SourceLocation Loc = Fn->getLocation(); 704 // Build the initial suspend point 705 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult { 706 ExprResult Suspend = 707 buildPromiseCall(*this, ScopeInfo->CoroutinePromise, Loc, Name, None); 708 if (Suspend.isInvalid()) 709 return StmtError(); 710 Suspend = buildOperatorCoawaitCall(*this, SC, Loc, Suspend.get()); 711 if (Suspend.isInvalid()) 712 return StmtError(); 713 Suspend = BuildResolvedCoawaitExpr(Loc, Suspend.get(), 714 /*IsImplicit*/ true); 715 Suspend = ActOnFinishFullExpr(Suspend.get(), /*DiscardedValue*/ false); 716 if (Suspend.isInvalid()) { 717 Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required) 718 << ((Name == "initial_suspend") ? 0 : 1); 719 Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword; 720 return StmtError(); 721 } 722 return cast<Stmt>(Suspend.get()); 723 }; 724 725 StmtResult InitSuspend = buildSuspends("initial_suspend"); 726 if (InitSuspend.isInvalid()) 727 return true; 728 729 StmtResult FinalSuspend = buildSuspends("final_suspend"); 730 if (FinalSuspend.isInvalid() || !checkFinalSuspendNoThrow(FinalSuspend.get())) 731 return true; 732 733 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get()); 734 735 return true; 736 } 737 738 // Recursively walks up the scope hierarchy until either a 'catch' or a function 739 // scope is found, whichever comes first. 740 static bool isWithinCatchScope(Scope *S) { 741 // 'co_await' and 'co_yield' keywords are disallowed within catch blocks, but 742 // lambdas that use 'co_await' are allowed. The loop below ends when a 743 // function scope is found in order to ensure the following behavior: 744 // 745 // void foo() { // <- function scope 746 // try { // 747 // co_await x; // <- 'co_await' is OK within a function scope 748 // } catch { // <- catch scope 749 // co_await x; // <- 'co_await' is not OK within a catch scope 750 // []() { // <- function scope 751 // co_await x; // <- 'co_await' is OK within a function scope 752 // }(); 753 // } 754 // } 755 while (S && !(S->getFlags() & Scope::FnScope)) { 756 if (S->getFlags() & Scope::CatchScope) 757 return true; 758 S = S->getParent(); 759 } 760 return false; 761 } 762 763 // [expr.await]p2, emphasis added: "An await-expression shall appear only in 764 // a *potentially evaluated* expression within the compound-statement of a 765 // function-body *outside of a handler* [...] A context within a function 766 // where an await-expression can appear is called a suspension context of the 767 // function." 768 static void checkSuspensionContext(Sema &S, SourceLocation Loc, 769 StringRef Keyword) { 770 // First emphasis of [expr.await]p2: must be a potentially evaluated context. 771 // That is, 'co_await' and 'co_yield' cannot appear in subexpressions of 772 // \c sizeof. 773 if (S.isUnevaluatedContext()) 774 S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword; 775 776 // Second emphasis of [expr.await]p2: must be outside of an exception handler. 777 if (isWithinCatchScope(S.getCurScope())) 778 S.Diag(Loc, diag::err_coroutine_within_handler) << Keyword; 779 } 780 781 ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) { 782 if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) { 783 CorrectDelayedTyposInExpr(E); 784 return ExprError(); 785 } 786 787 checkSuspensionContext(*this, Loc, "co_await"); 788 789 if (E->getType()->isPlaceholderType()) { 790 ExprResult R = CheckPlaceholderExpr(E); 791 if (R.isInvalid()) return ExprError(); 792 E = R.get(); 793 } 794 ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc); 795 if (Lookup.isInvalid()) 796 return ExprError(); 797 return BuildUnresolvedCoawaitExpr(Loc, E, 798 cast<UnresolvedLookupExpr>(Lookup.get())); 799 } 800 801 ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E, 802 UnresolvedLookupExpr *Lookup) { 803 auto *FSI = checkCoroutineContext(*this, Loc, "co_await"); 804 if (!FSI) 805 return ExprError(); 806 807 if (E->getType()->isPlaceholderType()) { 808 ExprResult R = CheckPlaceholderExpr(E); 809 if (R.isInvalid()) 810 return ExprError(); 811 E = R.get(); 812 } 813 814 auto *Promise = FSI->CoroutinePromise; 815 if (Promise->getType()->isDependentType()) { 816 Expr *Res = 817 new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup); 818 return Res; 819 } 820 821 auto *RD = Promise->getType()->getAsCXXRecordDecl(); 822 if (lookupMember(*this, "await_transform", RD, Loc)) { 823 ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E); 824 if (R.isInvalid()) { 825 Diag(Loc, 826 diag::note_coroutine_promise_implicit_await_transform_required_here) 827 << E->getSourceRange(); 828 return ExprError(); 829 } 830 E = R.get(); 831 } 832 ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup); 833 if (Awaitable.isInvalid()) 834 return ExprError(); 835 836 return BuildResolvedCoawaitExpr(Loc, Awaitable.get()); 837 } 838 839 ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E, 840 bool IsImplicit) { 841 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit); 842 if (!Coroutine) 843 return ExprError(); 844 845 if (E->getType()->isPlaceholderType()) { 846 ExprResult R = CheckPlaceholderExpr(E); 847 if (R.isInvalid()) return ExprError(); 848 E = R.get(); 849 } 850 851 if (E->getType()->isDependentType()) { 852 Expr *Res = new (Context) 853 CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit); 854 return Res; 855 } 856 857 // If the expression is a temporary, materialize it as an lvalue so that we 858 // can use it multiple times. 859 if (E->getValueKind() == VK_RValue) 860 E = CreateMaterializeTemporaryExpr(E->getType(), E, true); 861 862 // The location of the `co_await` token cannot be used when constructing 863 // the member call expressions since it's before the location of `Expr`, which 864 // is used as the start of the member call expression. 865 SourceLocation CallLoc = E->getExprLoc(); 866 867 // Build the await_ready, await_suspend, await_resume calls. 868 ReadySuspendResumeResult RSS = 869 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, CallLoc, E); 870 if (RSS.IsInvalid) 871 return ExprError(); 872 873 Expr *Res = 874 new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1], 875 RSS.Results[2], RSS.OpaqueValue, IsImplicit); 876 877 return Res; 878 } 879 880 ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) { 881 if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) { 882 CorrectDelayedTyposInExpr(E); 883 return ExprError(); 884 } 885 886 checkSuspensionContext(*this, Loc, "co_yield"); 887 888 // Build yield_value call. 889 ExprResult Awaitable = buildPromiseCall( 890 *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E); 891 if (Awaitable.isInvalid()) 892 return ExprError(); 893 894 // Build 'operator co_await' call. 895 Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get()); 896 if (Awaitable.isInvalid()) 897 return ExprError(); 898 899 return BuildCoyieldExpr(Loc, Awaitable.get()); 900 } 901 ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) { 902 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield"); 903 if (!Coroutine) 904 return ExprError(); 905 906 if (E->getType()->isPlaceholderType()) { 907 ExprResult R = CheckPlaceholderExpr(E); 908 if (R.isInvalid()) return ExprError(); 909 E = R.get(); 910 } 911 912 if (E->getType()->isDependentType()) { 913 Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E); 914 return Res; 915 } 916 917 // If the expression is a temporary, materialize it as an lvalue so that we 918 // can use it multiple times. 919 if (E->getValueKind() == VK_RValue) 920 E = CreateMaterializeTemporaryExpr(E->getType(), E, true); 921 922 // Build the await_ready, await_suspend, await_resume calls. 923 ReadySuspendResumeResult RSS = 924 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E); 925 if (RSS.IsInvalid) 926 return ExprError(); 927 928 Expr *Res = 929 new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1], 930 RSS.Results[2], RSS.OpaqueValue); 931 932 return Res; 933 } 934 935 StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) { 936 if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) { 937 CorrectDelayedTyposInExpr(E); 938 return StmtError(); 939 } 940 return BuildCoreturnStmt(Loc, E); 941 } 942 943 StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E, 944 bool IsImplicit) { 945 auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit); 946 if (!FSI) 947 return StmtError(); 948 949 if (E && E->getType()->isPlaceholderType() && 950 !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) { 951 ExprResult R = CheckPlaceholderExpr(E); 952 if (R.isInvalid()) return StmtError(); 953 E = R.get(); 954 } 955 956 // Move the return value if we can 957 if (E) { 958 auto NRVOCandidate = this->getCopyElisionCandidate(E->getType(), E, CES_AsIfByStdMove); 959 if (NRVOCandidate) { 960 InitializedEntity Entity = 961 InitializedEntity::InitializeResult(Loc, E->getType(), NRVOCandidate); 962 ExprResult MoveResult = this->PerformMoveOrCopyInitialization( 963 Entity, NRVOCandidate, E->getType(), E); 964 if (MoveResult.get()) 965 E = MoveResult.get(); 966 } 967 } 968 969 // FIXME: If the operand is a reference to a variable that's about to go out 970 // of scope, we should treat the operand as an xvalue for this overload 971 // resolution. 972 VarDecl *Promise = FSI->CoroutinePromise; 973 ExprResult PC; 974 if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) { 975 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E); 976 } else { 977 E = MakeFullDiscardedValueExpr(E).get(); 978 PC = buildPromiseCall(*this, Promise, Loc, "return_void", None); 979 } 980 if (PC.isInvalid()) 981 return StmtError(); 982 983 Expr *PCE = ActOnFinishFullExpr(PC.get(), /*DiscardedValue*/ false).get(); 984 985 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit); 986 return Res; 987 } 988 989 /// Look up the std::nothrow object. 990 static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) { 991 NamespaceDecl *Std = S.getStdNamespace(); 992 assert(Std && "Should already be diagnosed"); 993 994 LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc, 995 Sema::LookupOrdinaryName); 996 if (!S.LookupQualifiedName(Result, Std)) { 997 // FIXME: <experimental/coroutine> should have been included already. 998 // If we require it to include <new> then this diagnostic is no longer 999 // needed. 1000 S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found); 1001 return nullptr; 1002 } 1003 1004 auto *VD = Result.getAsSingle<VarDecl>(); 1005 if (!VD) { 1006 Result.suppressDiagnostics(); 1007 // We found something weird. Complain about the first thing we found. 1008 NamedDecl *Found = *Result.begin(); 1009 S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow); 1010 return nullptr; 1011 } 1012 1013 ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc); 1014 if (DR.isInvalid()) 1015 return nullptr; 1016 1017 return DR.get(); 1018 } 1019 1020 // Find an appropriate delete for the promise. 1021 static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc, 1022 QualType PromiseType) { 1023 FunctionDecl *OperatorDelete = nullptr; 1024 1025 DeclarationName DeleteName = 1026 S.Context.DeclarationNames.getCXXOperatorName(OO_Delete); 1027 1028 auto *PointeeRD = PromiseType->getAsCXXRecordDecl(); 1029 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type"); 1030 1031 if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete)) 1032 return nullptr; 1033 1034 if (!OperatorDelete) { 1035 // Look for a global declaration. 1036 const bool CanProvideSize = S.isCompleteType(Loc, PromiseType); 1037 const bool Overaligned = false; 1038 OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize, 1039 Overaligned, DeleteName); 1040 } 1041 S.MarkFunctionReferenced(Loc, OperatorDelete); 1042 return OperatorDelete; 1043 } 1044 1045 1046 void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) { 1047 FunctionScopeInfo *Fn = getCurFunction(); 1048 assert(Fn && Fn->isCoroutine() && "not a coroutine"); 1049 if (!Body) { 1050 assert(FD->isInvalidDecl() && 1051 "a null body is only allowed for invalid declarations"); 1052 return; 1053 } 1054 // We have a function that uses coroutine keywords, but we failed to build 1055 // the promise type. 1056 if (!Fn->CoroutinePromise) 1057 return FD->setInvalidDecl(); 1058 1059 if (isa<CoroutineBodyStmt>(Body)) { 1060 // Nothing todo. the body is already a transformed coroutine body statement. 1061 return; 1062 } 1063 1064 // Coroutines [stmt.return]p1: 1065 // A return statement shall not appear in a coroutine. 1066 if (Fn->FirstReturnLoc.isValid()) { 1067 assert(Fn->FirstCoroutineStmtLoc.isValid() && 1068 "first coroutine location not set"); 1069 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine); 1070 Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here) 1071 << Fn->getFirstCoroutineStmtKeyword(); 1072 } 1073 CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body); 1074 if (Builder.isInvalid() || !Builder.buildStatements()) 1075 return FD->setInvalidDecl(); 1076 1077 // Build body for the coroutine wrapper statement. 1078 Body = CoroutineBodyStmt::Create(Context, Builder); 1079 } 1080 1081 CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD, 1082 sema::FunctionScopeInfo &Fn, 1083 Stmt *Body) 1084 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()), 1085 IsPromiseDependentType( 1086 !Fn.CoroutinePromise || 1087 Fn.CoroutinePromise->getType()->isDependentType()) { 1088 this->Body = Body; 1089 1090 for (auto KV : Fn.CoroutineParameterMoves) 1091 this->ParamMovesVector.push_back(KV.second); 1092 this->ParamMoves = this->ParamMovesVector; 1093 1094 if (!IsPromiseDependentType) { 1095 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl(); 1096 assert(PromiseRecordDecl && "Type should have already been checked"); 1097 } 1098 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend(); 1099 } 1100 1101 bool CoroutineStmtBuilder::buildStatements() { 1102 assert(this->IsValid && "coroutine already invalid"); 1103 this->IsValid = makeReturnObject(); 1104 if (this->IsValid && !IsPromiseDependentType) 1105 buildDependentStatements(); 1106 return this->IsValid; 1107 } 1108 1109 bool CoroutineStmtBuilder::buildDependentStatements() { 1110 assert(this->IsValid && "coroutine already invalid"); 1111 assert(!this->IsPromiseDependentType && 1112 "coroutine cannot have a dependent promise type"); 1113 this->IsValid = makeOnException() && makeOnFallthrough() && 1114 makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() && 1115 makeNewAndDeleteExpr(); 1116 return this->IsValid; 1117 } 1118 1119 bool CoroutineStmtBuilder::makePromiseStmt() { 1120 // Form a declaration statement for the promise declaration, so that AST 1121 // visitors can more easily find it. 1122 StmtResult PromiseStmt = 1123 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc); 1124 if (PromiseStmt.isInvalid()) 1125 return false; 1126 1127 this->Promise = PromiseStmt.get(); 1128 return true; 1129 } 1130 1131 bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() { 1132 if (Fn.hasInvalidCoroutineSuspends()) 1133 return false; 1134 this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first); 1135 this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second); 1136 return true; 1137 } 1138 1139 static bool diagReturnOnAllocFailure(Sema &S, Expr *E, 1140 CXXRecordDecl *PromiseRecordDecl, 1141 FunctionScopeInfo &Fn) { 1142 auto Loc = E->getExprLoc(); 1143 if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) { 1144 auto *Decl = DeclRef->getDecl(); 1145 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) { 1146 if (Method->isStatic()) 1147 return true; 1148 else 1149 Loc = Decl->getLocation(); 1150 } 1151 } 1152 1153 S.Diag( 1154 Loc, 1155 diag::err_coroutine_promise_get_return_object_on_allocation_failure) 1156 << PromiseRecordDecl; 1157 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here) 1158 << Fn.getFirstCoroutineStmtKeyword(); 1159 return false; 1160 } 1161 1162 bool CoroutineStmtBuilder::makeReturnOnAllocFailure() { 1163 assert(!IsPromiseDependentType && 1164 "cannot make statement while the promise type is dependent"); 1165 1166 // [dcl.fct.def.coroutine]/8 1167 // The unqualified-id get_return_object_on_allocation_failure is looked up in 1168 // the scope of class P by class member access lookup (3.4.5). ... 1169 // If an allocation function returns nullptr, ... the coroutine return value 1170 // is obtained by a call to ... get_return_object_on_allocation_failure(). 1171 1172 DeclarationName DN = 1173 S.PP.getIdentifierInfo("get_return_object_on_allocation_failure"); 1174 LookupResult Found(S, DN, Loc, Sema::LookupMemberName); 1175 if (!S.LookupQualifiedName(Found, PromiseRecordDecl)) 1176 return true; 1177 1178 CXXScopeSpec SS; 1179 ExprResult DeclNameExpr = 1180 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false); 1181 if (DeclNameExpr.isInvalid()) 1182 return false; 1183 1184 if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn)) 1185 return false; 1186 1187 ExprResult ReturnObjectOnAllocationFailure = 1188 S.BuildCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc); 1189 if (ReturnObjectOnAllocationFailure.isInvalid()) 1190 return false; 1191 1192 StmtResult ReturnStmt = 1193 S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get()); 1194 if (ReturnStmt.isInvalid()) { 1195 S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here) 1196 << DN; 1197 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here) 1198 << Fn.getFirstCoroutineStmtKeyword(); 1199 return false; 1200 } 1201 1202 this->ReturnStmtOnAllocFailure = ReturnStmt.get(); 1203 return true; 1204 } 1205 1206 bool CoroutineStmtBuilder::makeNewAndDeleteExpr() { 1207 // Form and check allocation and deallocation calls. 1208 assert(!IsPromiseDependentType && 1209 "cannot make statement while the promise type is dependent"); 1210 QualType PromiseType = Fn.CoroutinePromise->getType(); 1211 1212 if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type)) 1213 return false; 1214 1215 const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr; 1216 1217 // [dcl.fct.def.coroutine]/7 1218 // Lookup allocation functions using a parameter list composed of the 1219 // requested size of the coroutine state being allocated, followed by 1220 // the coroutine function's arguments. If a matching allocation function 1221 // exists, use it. Otherwise, use an allocation function that just takes 1222 // the requested size. 1223 1224 FunctionDecl *OperatorNew = nullptr; 1225 FunctionDecl *OperatorDelete = nullptr; 1226 FunctionDecl *UnusedResult = nullptr; 1227 bool PassAlignment = false; 1228 SmallVector<Expr *, 1> PlacementArgs; 1229 1230 // [dcl.fct.def.coroutine]/7 1231 // "The allocation function’s name is looked up in the scope of P. 1232 // [...] If the lookup finds an allocation function in the scope of P, 1233 // overload resolution is performed on a function call created by assembling 1234 // an argument list. The first argument is the amount of space requested, 1235 // and has type std::size_t. The lvalues p1 ... pn are the succeeding 1236 // arguments." 1237 // 1238 // ...where "p1 ... pn" are defined earlier as: 1239 // 1240 // [dcl.fct.def.coroutine]/3 1241 // "For a coroutine f that is a non-static member function, let P1 denote the 1242 // type of the implicit object parameter (13.3.1) and P2 ... Pn be the types 1243 // of the function parameters; otherwise let P1 ... Pn be the types of the 1244 // function parameters. Let p1 ... pn be lvalues denoting those objects." 1245 if (auto *MD = dyn_cast<CXXMethodDecl>(&FD)) { 1246 if (MD->isInstance() && !isLambdaCallOperator(MD)) { 1247 ExprResult ThisExpr = S.ActOnCXXThis(Loc); 1248 if (ThisExpr.isInvalid()) 1249 return false; 1250 ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get()); 1251 if (ThisExpr.isInvalid()) 1252 return false; 1253 PlacementArgs.push_back(ThisExpr.get()); 1254 } 1255 } 1256 for (auto *PD : FD.parameters()) { 1257 if (PD->getType()->isDependentType()) 1258 continue; 1259 1260 // Build a reference to the parameter. 1261 auto PDLoc = PD->getLocation(); 1262 ExprResult PDRefExpr = 1263 S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(), 1264 ExprValueKind::VK_LValue, PDLoc); 1265 if (PDRefExpr.isInvalid()) 1266 return false; 1267 1268 PlacementArgs.push_back(PDRefExpr.get()); 1269 } 1270 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class, 1271 /*DeleteScope*/ Sema::AFS_Both, PromiseType, 1272 /*isArray*/ false, PassAlignment, PlacementArgs, 1273 OperatorNew, UnusedResult, /*Diagnose*/ false); 1274 1275 // [dcl.fct.def.coroutine]/7 1276 // "If no matching function is found, overload resolution is performed again 1277 // on a function call created by passing just the amount of space required as 1278 // an argument of type std::size_t." 1279 if (!OperatorNew && !PlacementArgs.empty()) { 1280 PlacementArgs.clear(); 1281 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class, 1282 /*DeleteScope*/ Sema::AFS_Both, PromiseType, 1283 /*isArray*/ false, PassAlignment, PlacementArgs, 1284 OperatorNew, UnusedResult, /*Diagnose*/ false); 1285 } 1286 1287 // [dcl.fct.def.coroutine]/7 1288 // "The allocation function’s name is looked up in the scope of P. If this 1289 // lookup fails, the allocation function’s name is looked up in the global 1290 // scope." 1291 if (!OperatorNew) { 1292 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Global, 1293 /*DeleteScope*/ Sema::AFS_Both, PromiseType, 1294 /*isArray*/ false, PassAlignment, PlacementArgs, 1295 OperatorNew, UnusedResult); 1296 } 1297 1298 bool IsGlobalOverload = 1299 OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext()); 1300 // If we didn't find a class-local new declaration and non-throwing new 1301 // was is required then we need to lookup the non-throwing global operator 1302 // instead. 1303 if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) { 1304 auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc); 1305 if (!StdNoThrow) 1306 return false; 1307 PlacementArgs = {StdNoThrow}; 1308 OperatorNew = nullptr; 1309 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Both, 1310 /*DeleteScope*/ Sema::AFS_Both, PromiseType, 1311 /*isArray*/ false, PassAlignment, PlacementArgs, 1312 OperatorNew, UnusedResult); 1313 } 1314 1315 if (!OperatorNew) 1316 return false; 1317 1318 if (RequiresNoThrowAlloc) { 1319 const auto *FT = OperatorNew->getType()->castAs<FunctionProtoType>(); 1320 if (!FT->isNothrow(/*ResultIfDependent*/ false)) { 1321 S.Diag(OperatorNew->getLocation(), 1322 diag::err_coroutine_promise_new_requires_nothrow) 1323 << OperatorNew; 1324 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required) 1325 << OperatorNew; 1326 return false; 1327 } 1328 } 1329 1330 if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr) 1331 return false; 1332 1333 Expr *FramePtr = 1334 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {}); 1335 1336 Expr *FrameSize = 1337 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {}); 1338 1339 // Make new call. 1340 1341 ExprResult NewRef = 1342 S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc); 1343 if (NewRef.isInvalid()) 1344 return false; 1345 1346 SmallVector<Expr *, 2> NewArgs(1, FrameSize); 1347 for (auto Arg : PlacementArgs) 1348 NewArgs.push_back(Arg); 1349 1350 ExprResult NewExpr = 1351 S.BuildCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc); 1352 NewExpr = S.ActOnFinishFullExpr(NewExpr.get(), /*DiscardedValue*/ false); 1353 if (NewExpr.isInvalid()) 1354 return false; 1355 1356 // Make delete call. 1357 1358 QualType OpDeleteQualType = OperatorDelete->getType(); 1359 1360 ExprResult DeleteRef = 1361 S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc); 1362 if (DeleteRef.isInvalid()) 1363 return false; 1364 1365 Expr *CoroFree = 1366 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr}); 1367 1368 SmallVector<Expr *, 2> DeleteArgs{CoroFree}; 1369 1370 // Check if we need to pass the size. 1371 const auto *OpDeleteType = 1372 OpDeleteQualType.getTypePtr()->castAs<FunctionProtoType>(); 1373 if (OpDeleteType->getNumParams() > 1) 1374 DeleteArgs.push_back(FrameSize); 1375 1376 ExprResult DeleteExpr = 1377 S.BuildCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc); 1378 DeleteExpr = 1379 S.ActOnFinishFullExpr(DeleteExpr.get(), /*DiscardedValue*/ false); 1380 if (DeleteExpr.isInvalid()) 1381 return false; 1382 1383 this->Allocate = NewExpr.get(); 1384 this->Deallocate = DeleteExpr.get(); 1385 1386 return true; 1387 } 1388 1389 bool CoroutineStmtBuilder::makeOnFallthrough() { 1390 assert(!IsPromiseDependentType && 1391 "cannot make statement while the promise type is dependent"); 1392 1393 // [dcl.fct.def.coroutine]/4 1394 // The unqualified-ids 'return_void' and 'return_value' are looked up in 1395 // the scope of class P. If both are found, the program is ill-formed. 1396 bool HasRVoid, HasRValue; 1397 LookupResult LRVoid = 1398 lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid); 1399 LookupResult LRValue = 1400 lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue); 1401 1402 StmtResult Fallthrough; 1403 if (HasRVoid && HasRValue) { 1404 // FIXME Improve this diagnostic 1405 S.Diag(FD.getLocation(), 1406 diag::err_coroutine_promise_incompatible_return_functions) 1407 << PromiseRecordDecl; 1408 S.Diag(LRVoid.getRepresentativeDecl()->getLocation(), 1409 diag::note_member_first_declared_here) 1410 << LRVoid.getLookupName(); 1411 S.Diag(LRValue.getRepresentativeDecl()->getLocation(), 1412 diag::note_member_first_declared_here) 1413 << LRValue.getLookupName(); 1414 return false; 1415 } else if (!HasRVoid && !HasRValue) { 1416 // FIXME: The PDTS currently specifies this case as UB, not ill-formed. 1417 // However we still diagnose this as an error since until the PDTS is fixed. 1418 S.Diag(FD.getLocation(), 1419 diag::err_coroutine_promise_requires_return_function) 1420 << PromiseRecordDecl; 1421 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here) 1422 << PromiseRecordDecl; 1423 return false; 1424 } else if (HasRVoid) { 1425 // If the unqualified-id return_void is found, flowing off the end of a 1426 // coroutine is equivalent to a co_return with no operand. Otherwise, 1427 // flowing off the end of a coroutine results in undefined behavior. 1428 Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr, 1429 /*IsImplicit*/false); 1430 Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get()); 1431 if (Fallthrough.isInvalid()) 1432 return false; 1433 } 1434 1435 this->OnFallthrough = Fallthrough.get(); 1436 return true; 1437 } 1438 1439 bool CoroutineStmtBuilder::makeOnException() { 1440 // Try to form 'p.unhandled_exception();' 1441 assert(!IsPromiseDependentType && 1442 "cannot make statement while the promise type is dependent"); 1443 1444 const bool RequireUnhandledException = S.getLangOpts().CXXExceptions; 1445 1446 if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) { 1447 auto DiagID = 1448 RequireUnhandledException 1449 ? diag::err_coroutine_promise_unhandled_exception_required 1450 : diag:: 1451 warn_coroutine_promise_unhandled_exception_required_with_exceptions; 1452 S.Diag(Loc, DiagID) << PromiseRecordDecl; 1453 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here) 1454 << PromiseRecordDecl; 1455 return !RequireUnhandledException; 1456 } 1457 1458 // If exceptions are disabled, don't try to build OnException. 1459 if (!S.getLangOpts().CXXExceptions) 1460 return true; 1461 1462 ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc, 1463 "unhandled_exception", None); 1464 UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc, 1465 /*DiscardedValue*/ false); 1466 if (UnhandledException.isInvalid()) 1467 return false; 1468 1469 // Since the body of the coroutine will be wrapped in try-catch, it will 1470 // be incompatible with SEH __try if present in a function. 1471 if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) { 1472 S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions); 1473 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here) 1474 << Fn.getFirstCoroutineStmtKeyword(); 1475 return false; 1476 } 1477 1478 this->OnException = UnhandledException.get(); 1479 return true; 1480 } 1481 1482 bool CoroutineStmtBuilder::makeReturnObject() { 1483 // Build implicit 'p.get_return_object()' expression and form initialization 1484 // of return type from it. 1485 ExprResult ReturnObject = 1486 buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None); 1487 if (ReturnObject.isInvalid()) 1488 return false; 1489 1490 this->ReturnValue = ReturnObject.get(); 1491 return true; 1492 } 1493 1494 static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) { 1495 if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) { 1496 auto *MethodDecl = MbrRef->getMethodDecl(); 1497 S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here) 1498 << MethodDecl; 1499 } 1500 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here) 1501 << Fn.getFirstCoroutineStmtKeyword(); 1502 } 1503 1504 bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() { 1505 assert(!IsPromiseDependentType && 1506 "cannot make statement while the promise type is dependent"); 1507 assert(this->ReturnValue && "ReturnValue must be already formed"); 1508 1509 QualType const GroType = this->ReturnValue->getType(); 1510 assert(!GroType->isDependentType() && 1511 "get_return_object type must no longer be dependent"); 1512 1513 QualType const FnRetType = FD.getReturnType(); 1514 assert(!FnRetType->isDependentType() && 1515 "get_return_object type must no longer be dependent"); 1516 1517 if (FnRetType->isVoidType()) { 1518 ExprResult Res = 1519 S.ActOnFinishFullExpr(this->ReturnValue, Loc, /*DiscardedValue*/ false); 1520 if (Res.isInvalid()) 1521 return false; 1522 1523 this->ResultDecl = Res.get(); 1524 return true; 1525 } 1526 1527 if (GroType->isVoidType()) { 1528 // Trigger a nice error message. 1529 InitializedEntity Entity = 1530 InitializedEntity::InitializeResult(Loc, FnRetType, false); 1531 S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue); 1532 noteMemberDeclaredHere(S, ReturnValue, Fn); 1533 return false; 1534 } 1535 1536 auto *GroDecl = VarDecl::Create( 1537 S.Context, &FD, FD.getLocation(), FD.getLocation(), 1538 &S.PP.getIdentifierTable().get("__coro_gro"), GroType, 1539 S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None); 1540 1541 S.CheckVariableDeclarationType(GroDecl); 1542 if (GroDecl->isInvalidDecl()) 1543 return false; 1544 1545 InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl); 1546 ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType, 1547 this->ReturnValue); 1548 if (Res.isInvalid()) 1549 return false; 1550 1551 Res = S.ActOnFinishFullExpr(Res.get(), /*DiscardedValue*/ false); 1552 if (Res.isInvalid()) 1553 return false; 1554 1555 S.AddInitializerToDecl(GroDecl, Res.get(), 1556 /*DirectInit=*/false); 1557 1558 S.FinalizeDeclaration(GroDecl); 1559 1560 // Form a declaration statement for the return declaration, so that AST 1561 // visitors can more easily find it. 1562 StmtResult GroDeclStmt = 1563 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc); 1564 if (GroDeclStmt.isInvalid()) 1565 return false; 1566 1567 this->ResultDecl = GroDeclStmt.get(); 1568 1569 ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc); 1570 if (declRef.isInvalid()) 1571 return false; 1572 1573 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get()); 1574 if (ReturnStmt.isInvalid()) { 1575 noteMemberDeclaredHere(S, ReturnValue, Fn); 1576 return false; 1577 } 1578 if (cast<clang::ReturnStmt>(ReturnStmt.get())->getNRVOCandidate() == GroDecl) 1579 GroDecl->setNRVOVariable(true); 1580 1581 this->ReturnStmt = ReturnStmt.get(); 1582 return true; 1583 } 1584 1585 // Create a static_cast\<T&&>(expr). 1586 static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) { 1587 if (T.isNull()) 1588 T = E->getType(); 1589 QualType TargetType = S.BuildReferenceType( 1590 T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName()); 1591 SourceLocation ExprLoc = E->getBeginLoc(); 1592 TypeSourceInfo *TargetLoc = 1593 S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc); 1594 1595 return S 1596 .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 1597 SourceRange(ExprLoc, ExprLoc), E->getSourceRange()) 1598 .get(); 1599 } 1600 1601 /// Build a variable declaration for move parameter. 1602 static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type, 1603 IdentifierInfo *II) { 1604 TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc); 1605 VarDecl *Decl = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type, 1606 TInfo, SC_None); 1607 Decl->setImplicit(); 1608 return Decl; 1609 } 1610 1611 // Build statements that move coroutine function parameters to the coroutine 1612 // frame, and store them on the function scope info. 1613 bool Sema::buildCoroutineParameterMoves(SourceLocation Loc) { 1614 assert(isa<FunctionDecl>(CurContext) && "not in a function scope"); 1615 auto *FD = cast<FunctionDecl>(CurContext); 1616 1617 auto *ScopeInfo = getCurFunction(); 1618 if (!ScopeInfo->CoroutineParameterMoves.empty()) 1619 return false; 1620 1621 for (auto *PD : FD->parameters()) { 1622 if (PD->getType()->isDependentType()) 1623 continue; 1624 1625 ExprResult PDRefExpr = 1626 BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 1627 ExprValueKind::VK_LValue, Loc); // FIXME: scope? 1628 if (PDRefExpr.isInvalid()) 1629 return false; 1630 1631 Expr *CExpr = nullptr; 1632 if (PD->getType()->getAsCXXRecordDecl() || 1633 PD->getType()->isRValueReferenceType()) 1634 CExpr = castForMoving(*this, PDRefExpr.get()); 1635 else 1636 CExpr = PDRefExpr.get(); 1637 1638 auto D = buildVarDecl(*this, Loc, PD->getType(), PD->getIdentifier()); 1639 AddInitializerToDecl(D, CExpr, /*DirectInit=*/true); 1640 1641 // Convert decl to a statement. 1642 StmtResult Stmt = ActOnDeclStmt(ConvertDeclToDeclGroup(D), Loc, Loc); 1643 if (Stmt.isInvalid()) 1644 return false; 1645 1646 ScopeInfo->CoroutineParameterMoves.insert(std::make_pair(PD, Stmt.get())); 1647 } 1648 return true; 1649 } 1650 1651 StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) { 1652 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args); 1653 if (!Res) 1654 return StmtError(); 1655 return Res; 1656 } 1657 1658 ClassTemplateDecl *Sema::lookupCoroutineTraits(SourceLocation KwLoc, 1659 SourceLocation FuncLoc) { 1660 if (!StdCoroutineTraitsCache) { 1661 if (auto StdExp = lookupStdExperimentalNamespace()) { 1662 LookupResult Result(*this, 1663 &PP.getIdentifierTable().get("coroutine_traits"), 1664 FuncLoc, LookupOrdinaryName); 1665 if (!LookupQualifiedName(Result, StdExp)) { 1666 Diag(KwLoc, diag::err_implied_coroutine_type_not_found) 1667 << "std::experimental::coroutine_traits"; 1668 return nullptr; 1669 } 1670 if (!(StdCoroutineTraitsCache = 1671 Result.getAsSingle<ClassTemplateDecl>())) { 1672 Result.suppressDiagnostics(); 1673 NamedDecl *Found = *Result.begin(); 1674 Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits); 1675 return nullptr; 1676 } 1677 } 1678 } 1679 return StdCoroutineTraitsCache; 1680 } 1681