blob: 28386d49d2becda9f326c4e21bbbe9f8efb9a3fb [file] [log] [blame]
Richard Smithcfd53b42015-10-22 06:13:50 +00001//===--- SemaCoroutines.cpp - Semantic Analysis for Coroutines ------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Richard Smithcfd53b42015-10-22 06:13:50 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ Coroutines.
10//
Brian Gesiakc1b173a2018-06-23 18:01:02 +000011// This file contains references to sections of the Coroutines TS, which
12// can be found at http://wg21.link/coroutines.
13//
Richard Smithcfd53b42015-10-22 06:13:50 +000014//===----------------------------------------------------------------------===//
15
Eric Fiselierbee782b2017-04-03 19:21:00 +000016#include "CoroutineStmtBuilder.h"
Brian Gesiak98606222018-02-15 20:37:22 +000017#include "clang/AST/ASTLambda.h"
Richard Smith9f690bd2015-10-27 06:02:45 +000018#include "clang/AST/Decl.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/StmtCXX.h"
21#include "clang/Lex/Preprocessor.h"
Richard Smith2af65c42015-11-24 02:34:39 +000022#include "clang/Sema/Initialization.h"
Richard Smith9f690bd2015-10-27 06:02:45 +000023#include "clang/Sema/Overload.h"
Reid Kleckner04f9bca2018-03-07 22:48:35 +000024#include "clang/Sema/ScopeInfo.h"
Eric Fiselierbee782b2017-04-03 19:21:00 +000025#include "clang/Sema/SemaInternal.h"
26
Richard Smithcfd53b42015-10-22 06:13:50 +000027using namespace clang;
28using namespace sema;
29
Eric Fiselierfc50f622017-05-25 14:59:39 +000030static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
31 SourceLocation Loc, bool &Res) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +000032 DeclarationName DN = S.PP.getIdentifierInfo(Name);
33 LookupResult LR(S, DN, Loc, Sema::LookupMemberName);
34 // Suppress diagnostics when a private member is selected. The same warnings
35 // will be produced again when building the call.
36 LR.suppressDiagnostics();
Eric Fiselierfc50f622017-05-25 14:59:39 +000037 Res = S.LookupQualifiedName(LR, RD);
38 return LR;
39}
40
41static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
42 SourceLocation Loc) {
43 bool Res;
44 lookupMember(S, Name, RD, Loc, Res);
45 return Res;
Eric Fiselier20f25cb2017-03-06 23:38:15 +000046}
47
Richard Smith9f690bd2015-10-27 06:02:45 +000048/// Look up the std::coroutine_traits<...>::promise_type for the given
49/// function type.
Eric Fiselier166c6e62017-07-10 01:27:22 +000050static QualType lookupPromiseType(Sema &S, const FunctionDecl *FD,
51 SourceLocation KwLoc) {
52 const FunctionProtoType *FnType = FD->getType()->castAs<FunctionProtoType>();
53 const SourceLocation FuncLoc = FD->getLocation();
Richard Smith9f690bd2015-10-27 06:02:45 +000054 // FIXME: Cache std::coroutine_traits once we've found it.
Gor Nishanov3e048bb2016-10-04 00:31:16 +000055 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
56 if (!StdExp) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000057 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
58 << "std::experimental::coroutine_traits";
Richard Smith9f690bd2015-10-27 06:02:45 +000059 return QualType();
60 }
61
Brian Gesiak3e65d9a2018-07-14 18:21:44 +000062 ClassTemplateDecl *CoroTraits = S.lookupCoroutineTraits(KwLoc, FuncLoc);
Richard Smith9f690bd2015-10-27 06:02:45 +000063 if (!CoroTraits) {
Richard Smith9f690bd2015-10-27 06:02:45 +000064 return QualType();
65 }
66
Eric Fiselier166c6e62017-07-10 01:27:22 +000067 // Form template argument list for coroutine_traits<R, P1, P2, ...> according
68 // to [dcl.fct.def.coroutine]3
Eric Fiselier89bf0e72017-03-06 22:52:28 +000069 TemplateArgumentListInfo Args(KwLoc, KwLoc);
Eric Fiselier166c6e62017-07-10 01:27:22 +000070 auto AddArg = [&](QualType T) {
Richard Smith9f690bd2015-10-27 06:02:45 +000071 Args.addArgument(TemplateArgumentLoc(
Eric Fiselier89bf0e72017-03-06 22:52:28 +000072 TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));
Eric Fiselier166c6e62017-07-10 01:27:22 +000073 };
74 AddArg(FnType->getReturnType());
75 // If the function is a non-static member function, add the type
76 // of the implicit object parameter before the formal parameters.
77 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
78 if (MD->isInstance()) {
79 // [over.match.funcs]4
80 // For non-static member functions, the type of the implicit object
81 // parameter is
Eric Fiselierbf166ce2017-07-10 02:52:34 +000082 // -- "lvalue reference to cv X" for functions declared without a
83 // ref-qualifier or with the & ref-qualifier
84 // -- "rvalue reference to cv X" for functions declared with the &&
85 // ref-qualifier
Brian Gesiak5488ab42019-01-11 01:54:53 +000086 QualType T = MD->getThisType()->getAs<PointerType>()->getPointeeType();
Eric Fiselier166c6e62017-07-10 01:27:22 +000087 T = FnType->getRefQualifier() == RQ_RValue
88 ? S.Context.getRValueReferenceType(T)
89 : S.Context.getLValueReferenceType(T, /*SpelledAsLValue*/ true);
90 AddArg(T);
91 }
92 }
93 for (QualType T : FnType->getParamTypes())
94 AddArg(T);
Richard Smith9f690bd2015-10-27 06:02:45 +000095
96 // Build the template-id.
97 QualType CoroTrait =
Eric Fiselier89bf0e72017-03-06 22:52:28 +000098 S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
Richard Smith9f690bd2015-10-27 06:02:45 +000099 if (CoroTrait.isNull())
100 return QualType();
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000101 if (S.RequireCompleteType(KwLoc, CoroTrait,
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000102 diag::err_coroutine_type_missing_specialization))
Richard Smith9f690bd2015-10-27 06:02:45 +0000103 return QualType();
104
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000105 auto *RD = CoroTrait->getAsCXXRecordDecl();
Richard Smith9f690bd2015-10-27 06:02:45 +0000106 assert(RD && "specialization of class template is not a class?");
107
108 // Look up the ::promise_type member.
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000109 LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
Richard Smith9f690bd2015-10-27 06:02:45 +0000110 Sema::LookupOrdinaryName);
111 S.LookupQualifiedName(R, RD);
112 auto *Promise = R.getAsSingle<TypeDecl>();
113 if (!Promise) {
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000114 S.Diag(FuncLoc,
115 diag::err_implied_std_coroutine_traits_promise_type_not_found)
Gor Nishanov8df64e92016-10-27 16:28:31 +0000116 << RD;
Richard Smith9f690bd2015-10-27 06:02:45 +0000117 return QualType();
118 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000119 // The promise type is required to be a class type.
120 QualType PromiseType = S.Context.getTypeDeclType(Promise);
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000121
122 auto buildElaboratedType = [&]() {
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000123 auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, StdExp);
Richard Smith9b2f53e2015-11-19 02:36:35 +0000124 NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
125 CoroTrait.getTypePtr());
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000126 return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
127 };
Richard Smith9b2f53e2015-11-19 02:36:35 +0000128
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000129 if (!PromiseType->getAsCXXRecordDecl()) {
130 S.Diag(FuncLoc,
131 diag::err_implied_std_coroutine_traits_promise_type_not_class)
132 << buildElaboratedType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000133 return QualType();
134 }
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000135 if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
136 diag::err_coroutine_promise_type_incomplete))
137 return QualType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000138
139 return PromiseType;
140}
141
Gor Nishanov29ff6382017-05-24 14:34:19 +0000142/// Look up the std::experimental::coroutine_handle<PromiseType>.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000143static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
144 SourceLocation Loc) {
145 if (PromiseType.isNull())
146 return QualType();
147
148 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
149 assert(StdExp && "Should already be diagnosed");
150
151 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
152 Loc, Sema::LookupOrdinaryName);
153 if (!S.LookupQualifiedName(Result, StdExp)) {
154 S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
155 << "std::experimental::coroutine_handle";
156 return QualType();
157 }
158
159 ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
160 if (!CoroHandle) {
161 Result.suppressDiagnostics();
162 // We found something weird. Complain about the first thing we found.
163 NamedDecl *Found = *Result.begin();
164 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
165 return QualType();
166 }
167
168 // Form template argument list for coroutine_handle<Promise>.
169 TemplateArgumentListInfo Args(Loc, Loc);
170 Args.addArgument(TemplateArgumentLoc(
171 TemplateArgument(PromiseType),
172 S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
173
174 // Build the template-id.
175 QualType CoroHandleType =
176 S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
177 if (CoroHandleType.isNull())
178 return QualType();
179 if (S.RequireCompleteType(Loc, CoroHandleType,
180 diag::err_coroutine_type_missing_specialization))
181 return QualType();
182
183 return CoroHandleType;
184}
185
Eric Fiselierc8efda72016-10-27 18:43:28 +0000186static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
187 StringRef Keyword) {
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000188 // 'co_await' and 'co_yield' are not permitted in unevaluated operands,
189 // such as subexpressions of \c sizeof.
190 //
191 // [expr.await]p2, emphasis added: "An await-expression shall appear only in
192 // a *potentially evaluated* expression within the compound-statement of a
193 // function-body outside of a handler [...] A context within a function where
194 // an await-expression can appear is called a suspension context of the
195 // function." And per [expr.yield]p1: "A yield-expression shall appear only
196 // within a suspension context of a function."
Richard Smith744b2242015-11-20 02:54:01 +0000197 if (S.isUnevaluatedContext()) {
198 S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
Eric Fiselierc8efda72016-10-27 18:43:28 +0000199 return false;
Richard Smith744b2242015-11-20 02:54:01 +0000200 }
Richard Smithcfd53b42015-10-22 06:13:50 +0000201
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000202 // Per [expr.await]p2, any other usage must be within a function.
203 // FIXME: This also covers [expr.await]p2: "An await-expression shall not
204 // appear in a default argument." But the diagnostic QoI here could be
205 // improved to inform the user that default arguments specifically are not
206 // allowed.
Richard Smithcfd53b42015-10-22 06:13:50 +0000207 auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
208 if (!FD) {
209 S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
210 ? diag::err_coroutine_objc_method
211 : diag::err_coroutine_outside_function) << Keyword;
Eric Fiselierc8efda72016-10-27 18:43:28 +0000212 return false;
Richard Smithcfd53b42015-10-22 06:13:50 +0000213 }
214
Eric Fiselierc8efda72016-10-27 18:43:28 +0000215 // An enumeration for mapping the diagnostic type to the correct diagnostic
216 // selection index.
217 enum InvalidFuncDiag {
218 DiagCtor = 0,
219 DiagDtor,
220 DiagCopyAssign,
221 DiagMoveAssign,
222 DiagMain,
223 DiagConstexpr,
224 DiagAutoRet,
225 DiagVarargs,
226 };
227 bool Diagnosed = false;
228 auto DiagInvalid = [&](InvalidFuncDiag ID) {
229 S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
230 Diagnosed = true;
231 return false;
232 };
233
234 // Diagnose when a constructor, destructor, copy/move assignment operator,
235 // or the function 'main' are declared as a coroutine.
236 auto *MD = dyn_cast<CXXMethodDecl>(FD);
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000237 // [class.ctor]p6: "A constructor shall not be a coroutine."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000238 if (MD && isa<CXXConstructorDecl>(MD))
239 return DiagInvalid(DiagCtor);
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000240 // [class.dtor]p17: "A destructor shall not be a coroutine."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000241 else if (MD && isa<CXXDestructorDecl>(MD))
242 return DiagInvalid(DiagDtor);
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000243 // N4499 [special]p6: "A special member function shall not be a coroutine."
244 // Per C++ [special]p1, special member functions are the "default constructor,
245 // copy constructor and copy assignment operator, move constructor and move
246 // assignment operator, and destructor."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000247 else if (MD && MD->isCopyAssignmentOperator())
248 return DiagInvalid(DiagCopyAssign);
249 else if (MD && MD->isMoveAssignmentOperator())
250 return DiagInvalid(DiagMoveAssign);
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000251 // [basic.start.main]p3: "The function main shall not be a coroutine."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000252 else if (FD->isMain())
253 return DiagInvalid(DiagMain);
254
255 // Emit a diagnostics for each of the following conditions which is not met.
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000256 // [expr.const]p2: "An expression e is a core constant expression unless the
257 // evaluation of e [...] would evaluate one of the following expressions:
258 // [...] an await-expression [...] a yield-expression."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000259 if (FD->isConstexpr())
260 DiagInvalid(DiagConstexpr);
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000261 // [dcl.spec.auto]p15: "A function declared with a return type that uses a
262 // placeholder type shall not be a coroutine."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000263 if (FD->getReturnType()->isUndeducedType())
264 DiagInvalid(DiagAutoRet);
Brian Gesiakc1b173a2018-06-23 18:01:02 +0000265 // [dcl.fct.def.coroutine]p1: "The parameter-declaration-clause of the
266 // coroutine shall not terminate with an ellipsis that is not part of a
267 // parameter-declaration."
Eric Fiselierc8efda72016-10-27 18:43:28 +0000268 if (FD->isVariadic())
269 DiagInvalid(DiagVarargs);
270
271 return !Diagnosed;
272}
273
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000274static ExprResult buildOperatorCoawaitLookupExpr(Sema &SemaRef, Scope *S,
275 SourceLocation Loc) {
276 DeclarationName OpName =
277 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
278 LookupResult Operators(SemaRef, OpName, SourceLocation(),
279 Sema::LookupOperatorName);
280 SemaRef.LookupName(Operators, S);
Eric Fiselierc8efda72016-10-27 18:43:28 +0000281
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000282 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
283 const auto &Functions = Operators.asUnresolvedSet();
284 bool IsOverloaded =
285 Functions.size() > 1 ||
286 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
287 Expr *CoawaitOp = UnresolvedLookupExpr::Create(
288 SemaRef.Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
289 DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
290 Functions.begin(), Functions.end());
291 assert(CoawaitOp);
292 return CoawaitOp;
293}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000294
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000295/// Build a call to 'operator co_await' if there is a suitable operator for
296/// the given expression.
297static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, SourceLocation Loc,
298 Expr *E,
299 UnresolvedLookupExpr *Lookup) {
300 UnresolvedSet<16> Functions;
301 Functions.append(Lookup->decls_begin(), Lookup->decls_end());
302 return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
303}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000304
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000305static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
306 SourceLocation Loc, Expr *E) {
307 ExprResult R = buildOperatorCoawaitLookupExpr(SemaRef, S, Loc);
308 if (R.isInvalid())
309 return ExprError();
310 return buildOperatorCoawaitCall(SemaRef, Loc, E,
311 cast<UnresolvedLookupExpr>(R.get()));
Richard Smithcfd53b42015-10-22 06:13:50 +0000312}
313
Gor Nishanov8df64e92016-10-27 16:28:31 +0000314static Expr *buildBuiltinCall(Sema &S, SourceLocation Loc, Builtin::ID Id,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000315 MultiExprArg CallArgs) {
Gor Nishanov8df64e92016-10-27 16:28:31 +0000316 StringRef Name = S.Context.BuiltinInfo.getName(Id);
317 LookupResult R(S, &S.Context.Idents.get(Name), Loc, Sema::LookupOrdinaryName);
318 S.LookupName(R, S.TUScope, /*AllowBuiltinCreation=*/true);
319
320 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
321 assert(BuiltInDecl && "failed to find builtin declaration");
322
323 ExprResult DeclRef =
324 S.BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
325 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
326
327 ExprResult Call =
328 S.ActOnCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
329
330 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
331 return Call.get();
332}
333
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000334static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
335 SourceLocation Loc) {
336 QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
337 if (CoroHandleType.isNull())
338 return ExprError();
339
340 DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
341 LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
342 Sema::LookupOrdinaryName);
343 if (!S.LookupQualifiedName(Found, LookupCtx)) {
344 S.Diag(Loc, diag::err_coroutine_handle_missing_member)
345 << "from_address";
346 return ExprError();
347 }
348
349 Expr *FramePtr =
350 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
351
352 CXXScopeSpec SS;
353 ExprResult FromAddr =
354 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
355 if (FromAddr.isInvalid())
356 return ExprError();
357
358 return S.ActOnCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
359}
Richard Smithcfd53b42015-10-22 06:13:50 +0000360
Richard Smith9f690bd2015-10-27 06:02:45 +0000361struct ReadySuspendResumeResult {
Eric Fiselierd978e532017-05-28 18:21:12 +0000362 enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume };
Richard Smith9f690bd2015-10-27 06:02:45 +0000363 Expr *Results[3];
Gor Nishanovce43bd22017-03-11 01:30:17 +0000364 OpaqueValueExpr *OpaqueValue;
365 bool IsInvalid;
Richard Smith9f690bd2015-10-27 06:02:45 +0000366};
367
Richard Smith23da82c2015-11-20 22:40:06 +0000368static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000369 StringRef Name, MultiExprArg Args) {
Richard Smith23da82c2015-11-20 22:40:06 +0000370 DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
371
372 // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
373 CXXScopeSpec SS;
374 ExprResult Result = S.BuildMemberReferenceExpr(
375 Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
376 SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
377 /*Scope=*/nullptr);
378 if (Result.isInvalid())
379 return ExprError();
380
Gor Nishanovd4507262018-03-27 20:38:19 +0000381 // We meant exactly what we asked for. No need for typo correction.
382 if (auto *TE = dyn_cast<TypoExpr>(Result.get())) {
383 S.clearDelayedTypo(TE);
384 S.Diag(Loc, diag::err_no_member)
385 << NameInfo.getName() << Base->getType()->getAsCXXRecordDecl()
386 << Base->getSourceRange();
387 return ExprError();
388 }
389
Richard Smith23da82c2015-11-20 22:40:06 +0000390 return S.ActOnCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
391}
392
Gor Nishanov0f333002017-08-25 04:46:54 +0000393// See if return type is coroutine-handle and if so, invoke builtin coro-resume
394// on its address. This is to enable experimental support for coroutine-handle
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000395// returning await_suspend that results in a guaranteed tail call to the target
Gor Nishanov0f333002017-08-25 04:46:54 +0000396// coroutine.
397static Expr *maybeTailCall(Sema &S, QualType RetType, Expr *E,
398 SourceLocation Loc) {
399 if (RetType->isReferenceType())
400 return nullptr;
401 Type const *T = RetType.getTypePtr();
402 if (!T->isClassType() && !T->isStructureType())
403 return nullptr;
404
405 // FIXME: Add convertability check to coroutine_handle<>. Possibly via
406 // EvaluateBinaryTypeTrait(BTT_IsConvertible, ...) which is at the moment
407 // a private function in SemaExprCXX.cpp
408
409 ExprResult AddressExpr = buildMemberCall(S, E, Loc, "address", None);
410 if (AddressExpr.isInvalid())
411 return nullptr;
412
413 Expr *JustAddress = AddressExpr.get();
414 // FIXME: Check that the type of AddressExpr is void*
415 return buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_resume,
416 JustAddress);
417}
418
Richard Smith9f690bd2015-10-27 06:02:45 +0000419/// Build calls to await_ready, await_suspend, and await_resume for a co_await
420/// expression.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000421static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
422 SourceLocation Loc, Expr *E) {
Gor Nishanovce43bd22017-03-11 01:30:17 +0000423 OpaqueValueExpr *Operand = new (S.Context)
424 OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
425
Richard Smith9f690bd2015-10-27 06:02:45 +0000426 // Assume invalid until we see otherwise.
Gor Nishanovce43bd22017-03-11 01:30:17 +0000427 ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true};
Richard Smith9f690bd2015-10-27 06:02:45 +0000428
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000429 ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc);
430 if (CoroHandleRes.isInvalid())
431 return Calls;
432 Expr *CoroHandle = CoroHandleRes.get();
433
Richard Smith9f690bd2015-10-27 06:02:45 +0000434 const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000435 MultiExprArg Args[] = {None, CoroHandle, None};
Richard Smith9f690bd2015-10-27 06:02:45 +0000436 for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000437 ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]);
Richard Smith9f690bd2015-10-27 06:02:45 +0000438 if (Result.isInvalid())
439 return Calls;
440 Calls.Results[I] = Result.get();
441 }
442
Eric Fiselierd978e532017-05-28 18:21:12 +0000443 // Assume the calls are valid; all further checking should make them invalid.
Richard Smith9f690bd2015-10-27 06:02:45 +0000444 Calls.IsInvalid = false;
Eric Fiselierd978e532017-05-28 18:21:12 +0000445
446 using ACT = ReadySuspendResumeResult::AwaitCallType;
447 CallExpr *AwaitReady = cast<CallExpr>(Calls.Results[ACT::ACT_Ready]);
448 if (!AwaitReady->getType()->isDependentType()) {
449 // [expr.await]p3 [...]
450 // — await-ready is the expression e.await_ready(), contextually converted
451 // to bool.
452 ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady);
453 if (Conv.isInvalid()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000454 S.Diag(AwaitReady->getDirectCallee()->getBeginLoc(),
Eric Fiselierd978e532017-05-28 18:21:12 +0000455 diag::note_await_ready_no_bool_conversion);
456 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
457 << AwaitReady->getDirectCallee() << E->getSourceRange();
458 Calls.IsInvalid = true;
459 }
460 Calls.Results[ACT::ACT_Ready] = Conv.get();
461 }
462 CallExpr *AwaitSuspend = cast<CallExpr>(Calls.Results[ACT::ACT_Suspend]);
463 if (!AwaitSuspend->getType()->isDependentType()) {
464 // [expr.await]p3 [...]
465 // - await-suspend is the expression e.await_suspend(h), which shall be
466 // a prvalue of type void or bool.
Eric Fiselier84ee7ff2017-05-31 23:41:11 +0000467 QualType RetType = AwaitSuspend->getCallReturnType(S.Context);
Gor Nishanovdb419a62017-09-05 19:31:52 +0000468
Gor Nishanov0f333002017-08-25 04:46:54 +0000469 // Experimental support for coroutine_handle returning await_suspend.
470 if (Expr *TailCallSuspend = maybeTailCall(S, RetType, AwaitSuspend, Loc))
471 Calls.Results[ACT::ACT_Suspend] = TailCallSuspend;
472 else {
473 // non-class prvalues always have cv-unqualified types
Gor Nishanov0f333002017-08-25 04:46:54 +0000474 if (RetType->isReferenceType() ||
Gor Nishanovdb419a62017-09-05 19:31:52 +0000475 (!RetType->isBooleanType() && !RetType->isVoidType())) {
Gor Nishanov0f333002017-08-25 04:46:54 +0000476 S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
477 diag::err_await_suspend_invalid_return_type)
478 << RetType;
479 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
480 << AwaitSuspend->getDirectCallee();
481 Calls.IsInvalid = true;
482 }
Eric Fiselierd978e532017-05-28 18:21:12 +0000483 }
484 }
485
Richard Smith9f690bd2015-10-27 06:02:45 +0000486 return Calls;
487}
488
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000489static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
490 SourceLocation Loc, StringRef Name,
491 MultiExprArg Args) {
492
493 // Form a reference to the promise.
494 ExprResult PromiseRef = S.BuildDeclRefExpr(
495 Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
496 if (PromiseRef.isInvalid())
497 return ExprError();
498
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000499 return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
500}
501
502VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
503 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
504 auto *FD = cast<FunctionDecl>(CurContext);
Eric Fiselier166c6e62017-07-10 01:27:22 +0000505 bool IsThisDependentType = [&] {
506 if (auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD))
Brian Gesiak5488ab42019-01-11 01:54:53 +0000507 return MD->isInstance() && MD->getThisType()->isDependentType();
Eric Fiselier166c6e62017-07-10 01:27:22 +0000508 else
509 return false;
510 }();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000511
Eric Fiselier166c6e62017-07-10 01:27:22 +0000512 QualType T = FD->getType()->isDependentType() || IsThisDependentType
513 ? Context.DependentTy
514 : lookupPromiseType(*this, FD, Loc);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000515 if (T.isNull())
516 return nullptr;
517
518 auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
519 &PP.getIdentifierTable().get("__promise"), T,
520 Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
521 CheckVariableDeclarationType(VD);
522 if (VD->isInvalidDecl())
523 return nullptr;
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000524
525 auto *ScopeInfo = getCurFunction();
526 // Build a list of arguments, based on the coroutine functions arguments,
527 // that will be passed to the promise type's constructor.
528 llvm::SmallVector<Expr *, 4> CtorArgExprs;
Gor Nishanov07ac63f2018-05-28 18:08:47 +0000529
530 // Add implicit object parameter.
531 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
532 if (MD->isInstance() && !isLambdaCallOperator(MD)) {
533 ExprResult ThisExpr = ActOnCXXThis(Loc);
534 if (ThisExpr.isInvalid())
535 return nullptr;
536 ThisExpr = CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
537 if (ThisExpr.isInvalid())
538 return nullptr;
539 CtorArgExprs.push_back(ThisExpr.get());
540 }
541 }
542
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000543 auto &Moves = ScopeInfo->CoroutineParameterMoves;
544 for (auto *PD : FD->parameters()) {
545 if (PD->getType()->isDependentType())
546 continue;
547
548 auto RefExpr = ExprEmpty();
549 auto Move = Moves.find(PD);
Brian Gesiak98606222018-02-15 20:37:22 +0000550 assert(Move != Moves.end() &&
551 "Coroutine function parameter not inserted into move map");
552 // If a reference to the function parameter exists in the coroutine
553 // frame, use that reference.
554 auto *MoveDecl =
555 cast<VarDecl>(cast<DeclStmt>(Move->second)->getSingleDecl());
556 RefExpr =
557 BuildDeclRefExpr(MoveDecl, MoveDecl->getType().getNonReferenceType(),
558 ExprValueKind::VK_LValue, FD->getLocation());
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000559 if (RefExpr.isInvalid())
560 return nullptr;
561 CtorArgExprs.push_back(RefExpr.get());
562 }
563
564 // Create an initialization sequence for the promise type using the
565 // constructor arguments, wrapped in a parenthesized list expression.
Bruno Riccif49e1ca2018-11-20 16:20:40 +0000566 Expr *PLE = ParenListExpr::Create(Context, FD->getLocation(),
567 CtorArgExprs, FD->getLocation());
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000568 InitializedEntity Entity = InitializedEntity::InitializeVariable(VD);
569 InitializationKind Kind = InitializationKind::CreateForInit(
570 VD->getLocation(), /*DirectInit=*/true, PLE);
571 InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs,
572 /*TopLevelOfInitList=*/false,
573 /*TreatUnavailableAsInvalid=*/false);
574
575 // Attempt to initialize the promise type with the arguments.
576 // If that fails, fall back to the promise type's default constructor.
577 if (InitSeq) {
578 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, CtorArgExprs);
579 if (Result.isInvalid()) {
580 VD->setInvalidDecl();
581 } else if (Result.get()) {
582 VD->setInit(MaybeCreateExprWithCleanups(Result.get()));
583 VD->setInitStyle(VarDecl::CallInit);
584 CheckCompleteVariableDeclaration(VD);
585 }
586 } else
587 ActOnUninitializedDecl(VD);
588
Eric Fiselier37b8a372017-05-31 19:36:59 +0000589 FD->addDecl(VD);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000590 return VD;
591}
592
593/// Check that this is a context in which a coroutine suspension can appear.
594static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000595 StringRef Keyword,
596 bool IsImplicit = false) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000597 if (!isValidCoroutineContext(S, Loc, Keyword))
598 return nullptr;
599
600 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000601
602 auto *ScopeInfo = S.getCurFunction();
603 assert(ScopeInfo && "missing function scope for function");
604
Eric Fiseliercac0a592017-03-11 02:35:37 +0000605 if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
606 ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
607
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000608 if (ScopeInfo->CoroutinePromise)
609 return ScopeInfo;
610
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000611 if (!S.buildCoroutineParameterMoves(Loc))
612 return nullptr;
613
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000614 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
615 if (!ScopeInfo->CoroutinePromise)
616 return nullptr;
617
618 return ScopeInfo;
619}
620
Eric Fiselierb936a392017-06-14 03:24:55 +0000621bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc,
622 StringRef Keyword) {
623 if (!checkCoroutineContext(*this, KWLoc, Keyword))
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000624 return false;
Eric Fiselierb936a392017-06-14 03:24:55 +0000625 auto *ScopeInfo = getCurFunction();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000626 assert(ScopeInfo->CoroutinePromise);
627
628 // If we have existing coroutine statements then we have already built
629 // the initial and final suspend points.
630 if (!ScopeInfo->NeedsCoroutineSuspends)
631 return true;
632
633 ScopeInfo->setNeedsCoroutineSuspends(false);
634
Eric Fiselierb936a392017-06-14 03:24:55 +0000635 auto *Fn = cast<FunctionDecl>(CurContext);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000636 SourceLocation Loc = Fn->getLocation();
637 // Build the initial suspend point
638 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
639 ExprResult Suspend =
Eric Fiselierb936a392017-06-14 03:24:55 +0000640 buildPromiseCall(*this, ScopeInfo->CoroutinePromise, Loc, Name, None);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000641 if (Suspend.isInvalid())
642 return StmtError();
Eric Fiselierb936a392017-06-14 03:24:55 +0000643 Suspend = buildOperatorCoawaitCall(*this, SC, Loc, Suspend.get());
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000644 if (Suspend.isInvalid())
645 return StmtError();
Eric Fiselierb936a392017-06-14 03:24:55 +0000646 Suspend = BuildResolvedCoawaitExpr(Loc, Suspend.get(),
647 /*IsImplicit*/ true);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +0000648 Suspend = ActOnFinishFullExpr(Suspend.get(), /*DiscardedValue*/ false);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000649 if (Suspend.isInvalid()) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000650 Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000651 << ((Name == "initial_suspend") ? 0 : 1);
Eric Fiselierb936a392017-06-14 03:24:55 +0000652 Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000653 return StmtError();
654 }
655 return cast<Stmt>(Suspend.get());
656 };
657
658 StmtResult InitSuspend = buildSuspends("initial_suspend");
659 if (InitSuspend.isInvalid())
660 return true;
661
662 StmtResult FinalSuspend = buildSuspends("final_suspend");
663 if (FinalSuspend.isInvalid())
664 return true;
665
666 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
667
668 return true;
669}
670
Richard Smith9f690bd2015-10-27 06:02:45 +0000671ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000672 if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000673 CorrectDelayedTyposInExpr(E);
674 return ExprError();
675 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000676
Richard Smith10610f72015-11-20 22:57:24 +0000677 if (E->getType()->isPlaceholderType()) {
678 ExprResult R = CheckPlaceholderExpr(E);
679 if (R.isInvalid()) return ExprError();
680 E = R.get();
681 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000682 ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
683 if (Lookup.isInvalid())
684 return ExprError();
685 return BuildUnresolvedCoawaitExpr(Loc, E,
686 cast<UnresolvedLookupExpr>(Lookup.get()));
687}
Richard Smith10610f72015-11-20 22:57:24 +0000688
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000689ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000690 UnresolvedLookupExpr *Lookup) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000691 auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
692 if (!FSI)
693 return ExprError();
694
695 if (E->getType()->isPlaceholderType()) {
696 ExprResult R = CheckPlaceholderExpr(E);
697 if (R.isInvalid())
698 return ExprError();
699 E = R.get();
700 }
701
702 auto *Promise = FSI->CoroutinePromise;
703 if (Promise->getType()->isDependentType()) {
704 Expr *Res =
705 new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000706 return Res;
707 }
708
709 auto *RD = Promise->getType()->getAsCXXRecordDecl();
710 if (lookupMember(*this, "await_transform", RD, Loc)) {
711 ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
712 if (R.isInvalid()) {
713 Diag(Loc,
714 diag::note_coroutine_promise_implicit_await_transform_required_here)
715 << E->getSourceRange();
716 return ExprError();
717 }
718 E = R.get();
719 }
720 ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
Richard Smith9f690bd2015-10-27 06:02:45 +0000721 if (Awaitable.isInvalid())
722 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000723
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000724 return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
Richard Smith9f690bd2015-10-27 06:02:45 +0000725}
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000726
727ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E,
728 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000729 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
Richard Smith744b2242015-11-20 02:54:01 +0000730 if (!Coroutine)
731 return ExprError();
Richard Smith9f690bd2015-10-27 06:02:45 +0000732
Richard Smith9f690bd2015-10-27 06:02:45 +0000733 if (E->getType()->isPlaceholderType()) {
734 ExprResult R = CheckPlaceholderExpr(E);
735 if (R.isInvalid()) return ExprError();
736 E = R.get();
737 }
738
Richard Smith10610f72015-11-20 22:57:24 +0000739 if (E->getType()->isDependentType()) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000740 Expr *Res = new (Context)
741 CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
Richard Smith10610f72015-11-20 22:57:24 +0000742 return Res;
743 }
744
Richard Smith1f38edd2015-11-22 03:13:02 +0000745 // If the expression is a temporary, materialize it as an lvalue so that we
746 // can use it multiple times.
747 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000748 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smith9f690bd2015-10-27 06:02:45 +0000749
Eric Fiselierd2e30d32018-03-27 03:15:46 +0000750 // The location of the `co_await` token cannot be used when constructing
751 // the member call expressions since it's before the location of `Expr`, which
752 // is used as the start of the member call expression.
753 SourceLocation CallLoc = E->getExprLoc();
754
Richard Smith9f690bd2015-10-27 06:02:45 +0000755 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000756 ReadySuspendResumeResult RSS =
Eric Fiselierd2e30d32018-03-27 03:15:46 +0000757 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, CallLoc, E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000758 if (RSS.IsInvalid)
759 return ExprError();
760
Gor Nishanovce43bd22017-03-11 01:30:17 +0000761 Expr *Res =
762 new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
763 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000764
Richard Smithcfd53b42015-10-22 06:13:50 +0000765 return Res;
766}
767
Richard Smith9f690bd2015-10-27 06:02:45 +0000768ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000769 if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000770 CorrectDelayedTyposInExpr(E);
Richard Smith23da82c2015-11-20 22:40:06 +0000771 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000772 }
Richard Smith23da82c2015-11-20 22:40:06 +0000773
774 // Build yield_value call.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000775 ExprResult Awaitable = buildPromiseCall(
776 *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000777 if (Awaitable.isInvalid())
778 return ExprError();
Richard Smith23da82c2015-11-20 22:40:06 +0000779
780 // Build 'operator co_await' call.
781 Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
782 if (Awaitable.isInvalid())
783 return ExprError();
784
Richard Smith9f690bd2015-10-27 06:02:45 +0000785 return BuildCoyieldExpr(Loc, Awaitable.get());
786}
787ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
788 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
Richard Smith744b2242015-11-20 02:54:01 +0000789 if (!Coroutine)
790 return ExprError();
Richard Smithcfd53b42015-10-22 06:13:50 +0000791
Richard Smith10610f72015-11-20 22:57:24 +0000792 if (E->getType()->isPlaceholderType()) {
793 ExprResult R = CheckPlaceholderExpr(E);
794 if (R.isInvalid()) return ExprError();
795 E = R.get();
796 }
797
Richard Smithd7bed4d2015-11-22 02:57:17 +0000798 if (E->getType()->isDependentType()) {
799 Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000800 return Res;
801 }
802
Richard Smith1f38edd2015-11-22 03:13:02 +0000803 // If the expression is a temporary, materialize it as an lvalue so that we
804 // can use it multiple times.
805 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000806 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000807
808 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000809 ReadySuspendResumeResult RSS =
810 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000811 if (RSS.IsInvalid)
812 return ExprError();
813
Eric Fiselierb936a392017-06-14 03:24:55 +0000814 Expr *Res =
815 new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
816 RSS.Results[2], RSS.OpaqueValue);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000817
Richard Smithcfd53b42015-10-22 06:13:50 +0000818 return Res;
819}
820
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000821StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000822 if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000823 CorrectDelayedTyposInExpr(E);
824 return StmtError();
825 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000826 return BuildCoreturnStmt(Loc, E);
827}
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000828
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000829StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
830 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000831 auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000832 if (!FSI)
Richard Smith71d403e2015-11-22 07:33:28 +0000833 return StmtError();
834
835 if (E && E->getType()->isPlaceholderType() &&
836 !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
Richard Smith10610f72015-11-20 22:57:24 +0000837 ExprResult R = CheckPlaceholderExpr(E);
838 if (R.isInvalid()) return StmtError();
839 E = R.get();
840 }
841
Brian Gesiak0b568302018-10-08 03:08:39 +0000842 // Move the return value if we can
843 if (E) {
844 auto NRVOCandidate = this->getCopyElisionCandidate(E->getType(), E, CES_AsIfByStdMove);
845 if (NRVOCandidate) {
846 InitializedEntity Entity =
847 InitializedEntity::InitializeResult(Loc, E->getType(), NRVOCandidate);
848 ExprResult MoveResult = this->PerformMoveOrCopyInitialization(
849 Entity, NRVOCandidate, E->getType(), E);
850 if (MoveResult.get())
851 E = MoveResult.get();
852 }
853 }
854
Richard Smith4ba66602015-11-22 07:05:16 +0000855 // FIXME: If the operand is a reference to a variable that's about to go out
Richard Smith2af65c42015-11-24 02:34:39 +0000856 // of scope, we should treat the operand as an xvalue for this overload
Richard Smith4ba66602015-11-22 07:05:16 +0000857 // resolution.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000858 VarDecl *Promise = FSI->CoroutinePromise;
Richard Smith4ba66602015-11-22 07:05:16 +0000859 ExprResult PC;
Eric Fiselier98131312016-10-06 21:23:38 +0000860 if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000861 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
Richard Smith4ba66602015-11-22 07:05:16 +0000862 } else {
863 E = MakeFullDiscardedValueExpr(E).get();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000864 PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
Richard Smith4ba66602015-11-22 07:05:16 +0000865 }
866 if (PC.isInvalid())
867 return StmtError();
868
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +0000869 Expr *PCE = ActOnFinishFullExpr(PC.get(), /*DiscardedValue*/ false).get();
Richard Smith4ba66602015-11-22 07:05:16 +0000870
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000871 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
Richard Smithcfd53b42015-10-22 06:13:50 +0000872 return Res;
873}
874
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000875/// Look up the std::nothrow object.
876static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
877 NamespaceDecl *Std = S.getStdNamespace();
878 assert(Std && "Should already be diagnosed");
879
880 LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
881 Sema::LookupOrdinaryName);
882 if (!S.LookupQualifiedName(Result, Std)) {
883 // FIXME: <experimental/coroutine> should have been included already.
884 // If we require it to include <new> then this diagnostic is no longer
885 // needed.
886 S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
887 return nullptr;
888 }
889
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000890 auto *VD = Result.getAsSingle<VarDecl>();
891 if (!VD) {
892 Result.suppressDiagnostics();
893 // We found something weird. Complain about the first thing we found.
894 NamedDecl *Found = *Result.begin();
895 S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
896 return nullptr;
897 }
898
899 ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
900 if (DR.isInvalid())
901 return nullptr;
902
903 return DR.get();
904}
905
Gor Nishanov8df64e92016-10-27 16:28:31 +0000906// Find an appropriate delete for the promise.
907static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc,
908 QualType PromiseType) {
909 FunctionDecl *OperatorDelete = nullptr;
910
911 DeclarationName DeleteName =
912 S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
913
914 auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
915 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
916
917 if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
918 return nullptr;
919
920 if (!OperatorDelete) {
921 // Look for a global declaration.
922 const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
923 const bool Overaligned = false;
924 OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
925 Overaligned, DeleteName);
926 }
927 S.MarkFunctionReferenced(Loc, OperatorDelete);
928 return OperatorDelete;
929}
930
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000931
932void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
933 FunctionScopeInfo *Fn = getCurFunction();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000934 assert(Fn && Fn->isCoroutine() && "not a coroutine");
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000935 if (!Body) {
936 assert(FD->isInvalidDecl() &&
937 "a null body is only allowed for invalid declarations");
938 return;
939 }
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000940 // We have a function that uses coroutine keywords, but we failed to build
941 // the promise type.
942 if (!Fn->CoroutinePromise)
943 return FD->setInvalidDecl();
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000944
945 if (isa<CoroutineBodyStmt>(Body)) {
Gor Nishanov29ff6382017-05-24 14:34:19 +0000946 // Nothing todo. the body is already a transformed coroutine body statement.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000947 return;
948 }
949
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000950 // Coroutines [stmt.return]p1:
951 // A return statement shall not appear in a coroutine.
952 if (Fn->FirstReturnLoc.isValid()) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000953 assert(Fn->FirstCoroutineStmtLoc.isValid() &&
954 "first coroutine location not set");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000955 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000956 Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
957 << Fn->getFirstCoroutineStmtKeyword();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000958 }
Eric Fiselierbee782b2017-04-03 19:21:00 +0000959 CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
960 if (Builder.isInvalid() || !Builder.buildStatements())
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000961 return FD->setInvalidDecl();
962
963 // Build body for the coroutine wrapper statement.
964 Body = CoroutineBodyStmt::Create(Context, Builder);
965}
966
Eric Fiselierbee782b2017-04-03 19:21:00 +0000967CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
968 sema::FunctionScopeInfo &Fn,
969 Stmt *Body)
970 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
971 IsPromiseDependentType(
972 !Fn.CoroutinePromise ||
973 Fn.CoroutinePromise->getType()->isDependentType()) {
974 this->Body = Body;
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000975
976 for (auto KV : Fn.CoroutineParameterMoves)
977 this->ParamMovesVector.push_back(KV.second);
978 this->ParamMoves = this->ParamMovesVector;
979
Eric Fiselierbee782b2017-04-03 19:21:00 +0000980 if (!IsPromiseDependentType) {
981 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
982 assert(PromiseRecordDecl && "Type should have already been checked");
983 }
984 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
985}
986
987bool CoroutineStmtBuilder::buildStatements() {
988 assert(this->IsValid && "coroutine already invalid");
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000989 this->IsValid = makeReturnObject();
Eric Fiselierbee782b2017-04-03 19:21:00 +0000990 if (this->IsValid && !IsPromiseDependentType)
991 buildDependentStatements();
992 return this->IsValid;
993}
994
995bool CoroutineStmtBuilder::buildDependentStatements() {
996 assert(this->IsValid && "coroutine already invalid");
997 assert(!this->IsPromiseDependentType &&
998 "coroutine cannot have a dependent promise type");
999 this->IsValid = makeOnException() && makeOnFallthrough() &&
Gor Nishanov6a470682017-05-22 20:22:23 +00001000 makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
1001 makeNewAndDeleteExpr();
Eric Fiselierbee782b2017-04-03 19:21:00 +00001002 return this->IsValid;
1003}
1004
1005bool CoroutineStmtBuilder::makePromiseStmt() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001006 // Form a declaration statement for the promise declaration, so that AST
1007 // visitors can more easily find it.
1008 StmtResult PromiseStmt =
1009 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
1010 if (PromiseStmt.isInvalid())
1011 return false;
1012
1013 this->Promise = PromiseStmt.get();
1014 return true;
1015}
1016
Eric Fiselierbee782b2017-04-03 19:21:00 +00001017bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001018 if (Fn.hasInvalidCoroutineSuspends())
1019 return false;
1020 this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
1021 this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
1022 return true;
1023}
1024
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001025static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
1026 CXXRecordDecl *PromiseRecordDecl,
1027 FunctionScopeInfo &Fn) {
1028 auto Loc = E->getExprLoc();
1029 if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
1030 auto *Decl = DeclRef->getDecl();
1031 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
1032 if (Method->isStatic())
1033 return true;
1034 else
1035 Loc = Decl->getLocation();
1036 }
1037 }
1038
1039 S.Diag(
1040 Loc,
1041 diag::err_coroutine_promise_get_return_object_on_allocation_failure)
1042 << PromiseRecordDecl;
1043 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1044 << Fn.getFirstCoroutineStmtKeyword();
1045 return false;
1046}
1047
Eric Fiselierbee782b2017-04-03 19:21:00 +00001048bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
1049 assert(!IsPromiseDependentType &&
1050 "cannot make statement while the promise type is dependent");
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001051
1052 // [dcl.fct.def.coroutine]/8
1053 // The unqualified-id get_return_object_on_allocation_failure is looked up in
1054 // the scope of class P by class member access lookup (3.4.5). ...
1055 // If an allocation function returns nullptr, ... the coroutine return value
1056 // is obtained by a call to ... get_return_object_on_allocation_failure().
1057
1058 DeclarationName DN =
1059 S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
1060 LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
Eric Fiselierbee782b2017-04-03 19:21:00 +00001061 if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
1062 return true;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001063
1064 CXXScopeSpec SS;
1065 ExprResult DeclNameExpr =
1066 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
Eric Fiselierbee782b2017-04-03 19:21:00 +00001067 if (DeclNameExpr.isInvalid())
1068 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001069
1070 if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
1071 return false;
1072
1073 ExprResult ReturnObjectOnAllocationFailure =
1074 S.ActOnCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
Eric Fiselierbee782b2017-04-03 19:21:00 +00001075 if (ReturnObjectOnAllocationFailure.isInvalid())
1076 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001077
Gor Nishanovc4a19082017-03-28 02:51:45 +00001078 StmtResult ReturnStmt =
1079 S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
Gor Nishanov6a470682017-05-22 20:22:23 +00001080 if (ReturnStmt.isInvalid()) {
Eric Fiselierfc50f622017-05-25 14:59:39 +00001081 S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
1082 << DN;
Gor Nishanov6a470682017-05-22 20:22:23 +00001083 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1084 << Fn.getFirstCoroutineStmtKeyword();
Eric Fiselierbee782b2017-04-03 19:21:00 +00001085 return false;
Gor Nishanov6a470682017-05-22 20:22:23 +00001086 }
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001087
1088 this->ReturnStmtOnAllocFailure = ReturnStmt.get();
1089 return true;
1090}
1091
Eric Fiselierbee782b2017-04-03 19:21:00 +00001092bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001093 // Form and check allocation and deallocation calls.
Eric Fiselierbee782b2017-04-03 19:21:00 +00001094 assert(!IsPromiseDependentType &&
1095 "cannot make statement while the promise type is dependent");
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001096 QualType PromiseType = Fn.CoroutinePromise->getType();
Gor Nishanov8df64e92016-10-27 16:28:31 +00001097
1098 if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
1099 return false;
1100
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001101 const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
1102
Brian Gesiak98606222018-02-15 20:37:22 +00001103 // [dcl.fct.def.coroutine]/7
1104 // Lookup allocation functions using a parameter list composed of the
1105 // requested size of the coroutine state being allocated, followed by
1106 // the coroutine function's arguments. If a matching allocation function
1107 // exists, use it. Otherwise, use an allocation function that just takes
1108 // the requested size.
Gor Nishanov8df64e92016-10-27 16:28:31 +00001109
1110 FunctionDecl *OperatorNew = nullptr;
1111 FunctionDecl *OperatorDelete = nullptr;
1112 FunctionDecl *UnusedResult = nullptr;
1113 bool PassAlignment = false;
Eric Fiselierf747f532017-04-18 05:08:08 +00001114 SmallVector<Expr *, 1> PlacementArgs;
Gor Nishanov8df64e92016-10-27 16:28:31 +00001115
Brian Gesiak98606222018-02-15 20:37:22 +00001116 // [dcl.fct.def.coroutine]/7
1117 // "The allocation function’s name is looked up in the scope of P.
1118 // [...] If the lookup finds an allocation function in the scope of P,
1119 // overload resolution is performed on a function call created by assembling
1120 // an argument list. The first argument is the amount of space requested,
1121 // and has type std::size_t. The lvalues p1 ... pn are the succeeding
1122 // arguments."
1123 //
1124 // ...where "p1 ... pn" are defined earlier as:
1125 //
1126 // [dcl.fct.def.coroutine]/3
1127 // "For a coroutine f that is a non-static member function, let P1 denote the
1128 // type of the implicit object parameter (13.3.1) and P2 ... Pn be the types
1129 // of the function parameters; otherwise let P1 ... Pn be the types of the
1130 // function parameters. Let p1 ... pn be lvalues denoting those objects."
1131 if (auto *MD = dyn_cast<CXXMethodDecl>(&FD)) {
1132 if (MD->isInstance() && !isLambdaCallOperator(MD)) {
1133 ExprResult ThisExpr = S.ActOnCXXThis(Loc);
1134 if (ThisExpr.isInvalid())
1135 return false;
1136 ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
1137 if (ThisExpr.isInvalid())
1138 return false;
1139 PlacementArgs.push_back(ThisExpr.get());
1140 }
1141 }
1142 for (auto *PD : FD.parameters()) {
1143 if (PD->getType()->isDependentType())
1144 continue;
1145
1146 // Build a reference to the parameter.
1147 auto PDLoc = PD->getLocation();
1148 ExprResult PDRefExpr =
1149 S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),
1150 ExprValueKind::VK_LValue, PDLoc);
1151 if (PDRefExpr.isInvalid())
1152 return false;
1153
1154 PlacementArgs.push_back(PDRefExpr.get());
1155 }
Brian Gesiakcb024022018-04-01 22:59:22 +00001156 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class,
1157 /*DeleteScope*/ Sema::AFS_Both, PromiseType,
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001158 /*isArray*/ false, PassAlignment, PlacementArgs,
Brian Gesiak98606222018-02-15 20:37:22 +00001159 OperatorNew, UnusedResult, /*Diagnose*/ false);
1160
1161 // [dcl.fct.def.coroutine]/7
1162 // "If no matching function is found, overload resolution is performed again
1163 // on a function call created by passing just the amount of space required as
1164 // an argument of type std::size_t."
1165 if (!OperatorNew && !PlacementArgs.empty()) {
1166 PlacementArgs.clear();
Brian Gesiakcb024022018-04-01 22:59:22 +00001167 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class,
1168 /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1169 /*isArray*/ false, PassAlignment, PlacementArgs,
1170 OperatorNew, UnusedResult, /*Diagnose*/ false);
1171 }
1172
1173 // [dcl.fct.def.coroutine]/7
1174 // "The allocation function’s name is looked up in the scope of P. If this
1175 // lookup fails, the allocation function’s name is looked up in the global
1176 // scope."
1177 if (!OperatorNew) {
1178 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Global,
1179 /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1180 /*isArray*/ false, PassAlignment, PlacementArgs,
1181 OperatorNew, UnusedResult);
Brian Gesiak98606222018-02-15 20:37:22 +00001182 }
Gor Nishanov8df64e92016-10-27 16:28:31 +00001183
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001184 bool IsGlobalOverload =
1185 OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
1186 // If we didn't find a class-local new declaration and non-throwing new
1187 // was is required then we need to lookup the non-throwing global operator
1188 // instead.
1189 if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
1190 auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
1191 if (!StdNoThrow)
1192 return false;
Eric Fiselierf747f532017-04-18 05:08:08 +00001193 PlacementArgs = {StdNoThrow};
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001194 OperatorNew = nullptr;
Brian Gesiakcb024022018-04-01 22:59:22 +00001195 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Both,
1196 /*DeleteScope*/ Sema::AFS_Both, PromiseType,
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001197 /*isArray*/ false, PassAlignment, PlacementArgs,
1198 OperatorNew, UnusedResult);
1199 }
Gor Nishanov8df64e92016-10-27 16:28:31 +00001200
Brian Gesiak98606222018-02-15 20:37:22 +00001201 if (!OperatorNew)
1202 return false;
Eric Fiselierc5128752017-04-18 05:30:39 +00001203
1204 if (RequiresNoThrowAlloc) {
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001205 const auto *FT = OperatorNew->getType()->getAs<FunctionProtoType>();
Richard Smitheaf11ad2018-05-03 03:58:32 +00001206 if (!FT->isNothrow(/*ResultIfDependent*/ false)) {
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001207 S.Diag(OperatorNew->getLocation(),
1208 diag::err_coroutine_promise_new_requires_nothrow)
1209 << OperatorNew;
1210 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
1211 << OperatorNew;
1212 return false;
1213 }
1214 }
1215
1216 if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr)
Gor Nishanov8df64e92016-10-27 16:28:31 +00001217 return false;
1218
1219 Expr *FramePtr =
1220 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
1221
1222 Expr *FrameSize =
1223 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {});
1224
1225 // Make new call.
1226
1227 ExprResult NewRef =
1228 S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
1229 if (NewRef.isInvalid())
1230 return false;
1231
Eric Fiselierf747f532017-04-18 05:08:08 +00001232 SmallVector<Expr *, 2> NewArgs(1, FrameSize);
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001233 for (auto Arg : PlacementArgs)
1234 NewArgs.push_back(Arg);
1235
Gor Nishanov8df64e92016-10-27 16:28:31 +00001236 ExprResult NewExpr =
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001237 S.ActOnCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001238 NewExpr = S.ActOnFinishFullExpr(NewExpr.get(), /*DiscardedValue*/ false);
Gor Nishanov8df64e92016-10-27 16:28:31 +00001239 if (NewExpr.isInvalid())
1240 return false;
1241
Gor Nishanov8df64e92016-10-27 16:28:31 +00001242 // Make delete call.
1243
1244 QualType OpDeleteQualType = OperatorDelete->getType();
1245
1246 ExprResult DeleteRef =
1247 S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
1248 if (DeleteRef.isInvalid())
1249 return false;
1250
1251 Expr *CoroFree =
1252 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr});
1253
1254 SmallVector<Expr *, 2> DeleteArgs{CoroFree};
1255
1256 // Check if we need to pass the size.
1257 const auto *OpDeleteType =
1258 OpDeleteQualType.getTypePtr()->getAs<FunctionProtoType>();
1259 if (OpDeleteType->getNumParams() > 1)
1260 DeleteArgs.push_back(FrameSize);
1261
1262 ExprResult DeleteExpr =
1263 S.ActOnCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001264 DeleteExpr =
1265 S.ActOnFinishFullExpr(DeleteExpr.get(), /*DiscardedValue*/ false);
Gor Nishanov8df64e92016-10-27 16:28:31 +00001266 if (DeleteExpr.isInvalid())
1267 return false;
1268
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001269 this->Allocate = NewExpr.get();
1270 this->Deallocate = DeleteExpr.get();
Gor Nishanov8df64e92016-10-27 16:28:31 +00001271
1272 return true;
1273}
1274
Eric Fiselierbee782b2017-04-03 19:21:00 +00001275bool CoroutineStmtBuilder::makeOnFallthrough() {
1276 assert(!IsPromiseDependentType &&
1277 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001278
1279 // [dcl.fct.def.coroutine]/4
1280 // The unqualified-ids 'return_void' and 'return_value' are looked up in
1281 // the scope of class P. If both are found, the program is ill-formed.
Eric Fiselierfc50f622017-05-25 14:59:39 +00001282 bool HasRVoid, HasRValue;
1283 LookupResult LRVoid =
1284 lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
1285 LookupResult LRValue =
1286 lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001287
Eric Fiselier709d1b32016-10-27 07:30:31 +00001288 StmtResult Fallthrough;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001289 if (HasRVoid && HasRValue) {
1290 // FIXME Improve this diagnostic
Eric Fiselierfc50f622017-05-25 14:59:39 +00001291 S.Diag(FD.getLocation(),
1292 diag::err_coroutine_promise_incompatible_return_functions)
1293 << PromiseRecordDecl;
1294 S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
1295 diag::note_member_first_declared_here)
1296 << LRVoid.getLookupName();
1297 S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
1298 diag::note_member_first_declared_here)
1299 << LRValue.getLookupName();
1300 return false;
1301 } else if (!HasRVoid && !HasRValue) {
1302 // FIXME: The PDTS currently specifies this case as UB, not ill-formed.
1303 // However we still diagnose this as an error since until the PDTS is fixed.
1304 S.Diag(FD.getLocation(),
1305 diag::err_coroutine_promise_requires_return_function)
1306 << PromiseRecordDecl;
1307 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001308 << PromiseRecordDecl;
1309 return false;
1310 } else if (HasRVoid) {
1311 // If the unqualified-id return_void is found, flowing off the end of a
1312 // coroutine is equivalent to a co_return with no operand. Otherwise,
1313 // flowing off the end of a coroutine results in undefined behavior.
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001314 Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
1315 /*IsImplicit*/false);
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001316 Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
1317 if (Fallthrough.isInvalid())
1318 return false;
Eric Fiselier709d1b32016-10-27 07:30:31 +00001319 }
Richard Smith2af65c42015-11-24 02:34:39 +00001320
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001321 this->OnFallthrough = Fallthrough.get();
1322 return true;
1323}
1324
Eric Fiselierbee782b2017-04-03 19:21:00 +00001325bool CoroutineStmtBuilder::makeOnException() {
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001326 // Try to form 'p.unhandled_exception();'
Eric Fiselierbee782b2017-04-03 19:21:00 +00001327 assert(!IsPromiseDependentType &&
1328 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001329
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001330 const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1331
1332 if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
1333 auto DiagID =
1334 RequireUnhandledException
1335 ? diag::err_coroutine_promise_unhandled_exception_required
1336 : diag::
1337 warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1338 S.Diag(Loc, DiagID) << PromiseRecordDecl;
Gor Nishanov29ff6382017-05-24 14:34:19 +00001339 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1340 << PromiseRecordDecl;
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001341 return !RequireUnhandledException;
1342 }
1343
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001344 // If exceptions are disabled, don't try to build OnException.
1345 if (!S.getLangOpts().CXXExceptions)
1346 return true;
1347
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001348 ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
1349 "unhandled_exception", None);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001350 UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc,
1351 /*DiscardedValue*/ false);
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001352 if (UnhandledException.isInvalid())
1353 return false;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001354
Gor Nishanov5b050e42017-05-22 22:33:17 +00001355 // Since the body of the coroutine will be wrapped in try-catch, it will
1356 // be incompatible with SEH __try if present in a function.
1357 if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1358 S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1359 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1360 << Fn.getFirstCoroutineStmtKeyword();
1361 return false;
1362 }
1363
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001364 this->OnException = UnhandledException.get();
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001365 return true;
1366}
1367
Eric Fiselierbee782b2017-04-03 19:21:00 +00001368bool CoroutineStmtBuilder::makeReturnObject() {
Richard Smith2af65c42015-11-24 02:34:39 +00001369 // Build implicit 'p.get_return_object()' expression and form initialization
1370 // of return type from it.
1371 ExprResult ReturnObject =
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001372 buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
Richard Smith2af65c42015-11-24 02:34:39 +00001373 if (ReturnObject.isInvalid())
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001374 return false;
Richard Smith2af65c42015-11-24 02:34:39 +00001375
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001376 this->ReturnValue = ReturnObject.get();
1377 return true;
1378}
1379
Gor Nishanov6a470682017-05-22 20:22:23 +00001380static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
1381 if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
1382 auto *MethodDecl = MbrRef->getMethodDecl();
Eric Fiselierfc50f622017-05-25 14:59:39 +00001383 S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
1384 << MethodDecl;
Gor Nishanov6a470682017-05-22 20:22:23 +00001385 }
1386 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1387 << Fn.getFirstCoroutineStmtKeyword();
1388}
1389
1390bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1391 assert(!IsPromiseDependentType &&
1392 "cannot make statement while the promise type is dependent");
1393 assert(this->ReturnValue && "ReturnValue must be already formed");
1394
1395 QualType const GroType = this->ReturnValue->getType();
1396 assert(!GroType->isDependentType() &&
1397 "get_return_object type must no longer be dependent");
1398
1399 QualType const FnRetType = FD.getReturnType();
1400 assert(!FnRetType->isDependentType() &&
1401 "get_return_object type must no longer be dependent");
1402
1403 if (FnRetType->isVoidType()) {
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001404 ExprResult Res =
1405 S.ActOnFinishFullExpr(this->ReturnValue, Loc, /*DiscardedValue*/ false);
Gor Nishanov6a470682017-05-22 20:22:23 +00001406 if (Res.isInvalid())
1407 return false;
1408
1409 this->ResultDecl = Res.get();
1410 return true;
1411 }
1412
1413 if (GroType->isVoidType()) {
1414 // Trigger a nice error message.
1415 InitializedEntity Entity =
1416 InitializedEntity::InitializeResult(Loc, FnRetType, false);
1417 S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue);
1418 noteMemberDeclaredHere(S, ReturnValue, Fn);
1419 return false;
1420 }
1421
1422 auto *GroDecl = VarDecl::Create(
1423 S.Context, &FD, FD.getLocation(), FD.getLocation(),
1424 &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
1425 S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
1426
1427 S.CheckVariableDeclarationType(GroDecl);
1428 if (GroDecl->isInvalidDecl())
1429 return false;
1430
1431 InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
1432 ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType,
1433 this->ReturnValue);
1434 if (Res.isInvalid())
1435 return false;
1436
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00001437 Res = S.ActOnFinishFullExpr(Res.get(), /*DiscardedValue*/ false);
Gor Nishanov6a470682017-05-22 20:22:23 +00001438 if (Res.isInvalid())
1439 return false;
1440
Gor Nishanov6a470682017-05-22 20:22:23 +00001441 S.AddInitializerToDecl(GroDecl, Res.get(),
1442 /*DirectInit=*/false);
1443
1444 S.FinalizeDeclaration(GroDecl);
1445
1446 // Form a declaration statement for the return declaration, so that AST
1447 // visitors can more easily find it.
1448 StmtResult GroDeclStmt =
1449 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
1450 if (GroDeclStmt.isInvalid())
1451 return false;
1452
1453 this->ResultDecl = GroDeclStmt.get();
1454
1455 ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
1456 if (declRef.isInvalid())
1457 return false;
1458
1459 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
1460 if (ReturnStmt.isInvalid()) {
1461 noteMemberDeclaredHere(S, ReturnValue, Fn);
1462 return false;
1463 }
Eric Fiselier8ed97272018-02-01 23:47:54 +00001464 if (cast<clang::ReturnStmt>(ReturnStmt.get())->getNRVOCandidate() == GroDecl)
1465 GroDecl->setNRVOVariable(true);
Gor Nishanov6a470682017-05-22 20:22:23 +00001466
1467 this->ReturnStmt = ReturnStmt.get();
1468 return true;
1469}
1470
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001471// Create a static_cast\<T&&>(expr).
1472static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
1473 if (T.isNull())
1474 T = E->getType();
1475 QualType TargetType = S.BuildReferenceType(
1476 T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001477 SourceLocation ExprLoc = E->getBeginLoc();
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001478 TypeSourceInfo *TargetLoc =
1479 S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
1480
1481 return S
1482 .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1483 SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
1484 .get();
1485}
1486
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001487/// Build a variable declaration for move parameter.
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001488static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
Eric Fiselierde7943b2017-06-03 00:22:18 +00001489 IdentifierInfo *II) {
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001490 TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);
Brian Gesiak61f4ac92018-01-24 22:15:42 +00001491 VarDecl *Decl = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type,
1492 TInfo, SC_None);
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001493 Decl->setImplicit();
1494 return Decl;
1495}
1496
Brian Gesiak61f4ac92018-01-24 22:15:42 +00001497// Build statements that move coroutine function parameters to the coroutine
1498// frame, and store them on the function scope info.
1499bool Sema::buildCoroutineParameterMoves(SourceLocation Loc) {
1500 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
1501 auto *FD = cast<FunctionDecl>(CurContext);
1502
1503 auto *ScopeInfo = getCurFunction();
1504 assert(ScopeInfo->CoroutineParameterMoves.empty() &&
1505 "Should not build parameter moves twice");
1506
1507 for (auto *PD : FD->parameters()) {
1508 if (PD->getType()->isDependentType())
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001509 continue;
1510
Brian Gesiak98606222018-02-15 20:37:22 +00001511 ExprResult PDRefExpr =
1512 BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
1513 ExprValueKind::VK_LValue, Loc); // FIXME: scope?
1514 if (PDRefExpr.isInvalid())
1515 return false;
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001516
Brian Gesiak98606222018-02-15 20:37:22 +00001517 Expr *CExpr = nullptr;
1518 if (PD->getType()->getAsCXXRecordDecl() ||
1519 PD->getType()->isRValueReferenceType())
1520 CExpr = castForMoving(*this, PDRefExpr.get());
1521 else
1522 CExpr = PDRefExpr.get();
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001523
Brian Gesiak98606222018-02-15 20:37:22 +00001524 auto D = buildVarDecl(*this, Loc, PD->getType(), PD->getIdentifier());
1525 AddInitializerToDecl(D, CExpr, /*DirectInit=*/true);
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001526
Brian Gesiak98606222018-02-15 20:37:22 +00001527 // Convert decl to a statement.
1528 StmtResult Stmt = ActOnDeclStmt(ConvertDeclToDeclGroup(D), Loc, Loc);
1529 if (Stmt.isInvalid())
1530 return false;
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001531
Brian Gesiak98606222018-02-15 20:37:22 +00001532 ScopeInfo->CoroutineParameterMoves.insert(std::make_pair(PD, Stmt.get()));
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001533 }
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001534 return true;
Richard Smithcfd53b42015-10-22 06:13:50 +00001535}
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001536
1537StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1538 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
1539 if (!Res)
1540 return StmtError();
1541 return Res;
1542}
Brian Gesiak3e65d9a2018-07-14 18:21:44 +00001543
1544ClassTemplateDecl *Sema::lookupCoroutineTraits(SourceLocation KwLoc,
1545 SourceLocation FuncLoc) {
1546 if (!StdCoroutineTraitsCache) {
1547 if (auto StdExp = lookupStdExperimentalNamespace()) {
1548 LookupResult Result(*this,
1549 &PP.getIdentifierTable().get("coroutine_traits"),
1550 FuncLoc, LookupOrdinaryName);
1551 if (!LookupQualifiedName(Result, StdExp)) {
1552 Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
1553 << "std::experimental::coroutine_traits";
1554 return nullptr;
1555 }
1556 if (!(StdCoroutineTraitsCache =
1557 Result.getAsSingle<ClassTemplateDecl>())) {
1558 Result.suppressDiagnostics();
1559 NamedDecl *Found = *Result.begin();
1560 Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
1561 return nullptr;
1562 }
1563 }
1564 }
1565 return StdCoroutineTraitsCache;
1566}