blob: 139a21014d1dd29f9d8be68d9f94c0e3753a1a3a [file] [log] [blame]
Richard Smithcfd53b42015-10-22 06:13:50 +00001//===--- SemaCoroutines.cpp - Semantic Analysis for Coroutines ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ Coroutines.
11//
12//===----------------------------------------------------------------------===//
13
Eric Fiselierbee782b2017-04-03 19:21:00 +000014#include "CoroutineStmtBuilder.h"
Brian Gesiak98606222018-02-15 20:37:22 +000015#include "clang/AST/ASTLambda.h"
Richard Smith9f690bd2015-10-27 06:02:45 +000016#include "clang/AST/Decl.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/StmtCXX.h"
19#include "clang/Lex/Preprocessor.h"
Richard Smith2af65c42015-11-24 02:34:39 +000020#include "clang/Sema/Initialization.h"
Richard Smith9f690bd2015-10-27 06:02:45 +000021#include "clang/Sema/Overload.h"
Reid Kleckner04f9bca2018-03-07 22:48:35 +000022#include "clang/Sema/ScopeInfo.h"
Eric Fiselierbee782b2017-04-03 19:21:00 +000023#include "clang/Sema/SemaInternal.h"
24
Richard Smithcfd53b42015-10-22 06:13:50 +000025using namespace clang;
26using namespace sema;
27
Eric Fiselierfc50f622017-05-25 14:59:39 +000028static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
29 SourceLocation Loc, bool &Res) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +000030 DeclarationName DN = S.PP.getIdentifierInfo(Name);
31 LookupResult LR(S, DN, Loc, Sema::LookupMemberName);
32 // Suppress diagnostics when a private member is selected. The same warnings
33 // will be produced again when building the call.
34 LR.suppressDiagnostics();
Eric Fiselierfc50f622017-05-25 14:59:39 +000035 Res = S.LookupQualifiedName(LR, RD);
36 return LR;
37}
38
39static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
40 SourceLocation Loc) {
41 bool Res;
42 lookupMember(S, Name, RD, Loc, Res);
43 return Res;
Eric Fiselier20f25cb2017-03-06 23:38:15 +000044}
45
Richard Smith9f690bd2015-10-27 06:02:45 +000046/// Look up the std::coroutine_traits<...>::promise_type for the given
47/// function type.
Eric Fiselier166c6e62017-07-10 01:27:22 +000048static QualType lookupPromiseType(Sema &S, const FunctionDecl *FD,
49 SourceLocation KwLoc) {
50 const FunctionProtoType *FnType = FD->getType()->castAs<FunctionProtoType>();
51 const SourceLocation FuncLoc = FD->getLocation();
Richard Smith9f690bd2015-10-27 06:02:45 +000052 // FIXME: Cache std::coroutine_traits once we've found it.
Gor Nishanov3e048bb2016-10-04 00:31:16 +000053 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
54 if (!StdExp) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000055 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
56 << "std::experimental::coroutine_traits";
Richard Smith9f690bd2015-10-27 06:02:45 +000057 return QualType();
58 }
59
60 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_traits"),
Eric Fiselier89bf0e72017-03-06 22:52:28 +000061 FuncLoc, Sema::LookupOrdinaryName);
Gor Nishanov3e048bb2016-10-04 00:31:16 +000062 if (!S.LookupQualifiedName(Result, StdExp)) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000063 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
64 << "std::experimental::coroutine_traits";
Richard Smith9f690bd2015-10-27 06:02:45 +000065 return QualType();
66 }
67
68 ClassTemplateDecl *CoroTraits = Result.getAsSingle<ClassTemplateDecl>();
69 if (!CoroTraits) {
70 Result.suppressDiagnostics();
71 // We found something weird. Complain about the first thing we found.
72 NamedDecl *Found = *Result.begin();
73 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
74 return QualType();
75 }
76
Eric Fiselier166c6e62017-07-10 01:27:22 +000077 // Form template argument list for coroutine_traits<R, P1, P2, ...> according
78 // to [dcl.fct.def.coroutine]3
Eric Fiselier89bf0e72017-03-06 22:52:28 +000079 TemplateArgumentListInfo Args(KwLoc, KwLoc);
Eric Fiselier166c6e62017-07-10 01:27:22 +000080 auto AddArg = [&](QualType T) {
Richard Smith9f690bd2015-10-27 06:02:45 +000081 Args.addArgument(TemplateArgumentLoc(
Eric Fiselier89bf0e72017-03-06 22:52:28 +000082 TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));
Eric Fiselier166c6e62017-07-10 01:27:22 +000083 };
84 AddArg(FnType->getReturnType());
85 // If the function is a non-static member function, add the type
86 // of the implicit object parameter before the formal parameters.
87 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
88 if (MD->isInstance()) {
89 // [over.match.funcs]4
90 // For non-static member functions, the type of the implicit object
91 // parameter is
Eric Fiselierbf166ce2017-07-10 02:52:34 +000092 // -- "lvalue reference to cv X" for functions declared without a
93 // ref-qualifier or with the & ref-qualifier
94 // -- "rvalue reference to cv X" for functions declared with the &&
95 // ref-qualifier
Eric Fiselier166c6e62017-07-10 01:27:22 +000096 QualType T =
97 MD->getThisType(S.Context)->getAs<PointerType>()->getPointeeType();
98 T = FnType->getRefQualifier() == RQ_RValue
99 ? S.Context.getRValueReferenceType(T)
100 : S.Context.getLValueReferenceType(T, /*SpelledAsLValue*/ true);
101 AddArg(T);
102 }
103 }
104 for (QualType T : FnType->getParamTypes())
105 AddArg(T);
Richard Smith9f690bd2015-10-27 06:02:45 +0000106
107 // Build the template-id.
108 QualType CoroTrait =
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000109 S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
Richard Smith9f690bd2015-10-27 06:02:45 +0000110 if (CoroTrait.isNull())
111 return QualType();
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000112 if (S.RequireCompleteType(KwLoc, CoroTrait,
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000113 diag::err_coroutine_type_missing_specialization))
Richard Smith9f690bd2015-10-27 06:02:45 +0000114 return QualType();
115
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000116 auto *RD = CoroTrait->getAsCXXRecordDecl();
Richard Smith9f690bd2015-10-27 06:02:45 +0000117 assert(RD && "specialization of class template is not a class?");
118
119 // Look up the ::promise_type member.
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000120 LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
Richard Smith9f690bd2015-10-27 06:02:45 +0000121 Sema::LookupOrdinaryName);
122 S.LookupQualifiedName(R, RD);
123 auto *Promise = R.getAsSingle<TypeDecl>();
124 if (!Promise) {
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000125 S.Diag(FuncLoc,
126 diag::err_implied_std_coroutine_traits_promise_type_not_found)
Gor Nishanov8df64e92016-10-27 16:28:31 +0000127 << RD;
Richard Smith9f690bd2015-10-27 06:02:45 +0000128 return QualType();
129 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000130 // The promise type is required to be a class type.
131 QualType PromiseType = S.Context.getTypeDeclType(Promise);
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000132
133 auto buildElaboratedType = [&]() {
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000134 auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, StdExp);
Richard Smith9b2f53e2015-11-19 02:36:35 +0000135 NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
136 CoroTrait.getTypePtr());
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000137 return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
138 };
Richard Smith9b2f53e2015-11-19 02:36:35 +0000139
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000140 if (!PromiseType->getAsCXXRecordDecl()) {
141 S.Diag(FuncLoc,
142 diag::err_implied_std_coroutine_traits_promise_type_not_class)
143 << buildElaboratedType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000144 return QualType();
145 }
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000146 if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
147 diag::err_coroutine_promise_type_incomplete))
148 return QualType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000149
150 return PromiseType;
151}
152
Gor Nishanov29ff6382017-05-24 14:34:19 +0000153/// Look up the std::experimental::coroutine_handle<PromiseType>.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000154static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
155 SourceLocation Loc) {
156 if (PromiseType.isNull())
157 return QualType();
158
159 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
160 assert(StdExp && "Should already be diagnosed");
161
162 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
163 Loc, Sema::LookupOrdinaryName);
164 if (!S.LookupQualifiedName(Result, StdExp)) {
165 S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
166 << "std::experimental::coroutine_handle";
167 return QualType();
168 }
169
170 ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
171 if (!CoroHandle) {
172 Result.suppressDiagnostics();
173 // We found something weird. Complain about the first thing we found.
174 NamedDecl *Found = *Result.begin();
175 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
176 return QualType();
177 }
178
179 // Form template argument list for coroutine_handle<Promise>.
180 TemplateArgumentListInfo Args(Loc, Loc);
181 Args.addArgument(TemplateArgumentLoc(
182 TemplateArgument(PromiseType),
183 S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
184
185 // Build the template-id.
186 QualType CoroHandleType =
187 S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
188 if (CoroHandleType.isNull())
189 return QualType();
190 if (S.RequireCompleteType(Loc, CoroHandleType,
191 diag::err_coroutine_type_missing_specialization))
192 return QualType();
193
194 return CoroHandleType;
195}
196
Eric Fiselierc8efda72016-10-27 18:43:28 +0000197static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
198 StringRef Keyword) {
Richard Smith744b2242015-11-20 02:54:01 +0000199 // 'co_await' and 'co_yield' are not permitted in unevaluated operands.
200 if (S.isUnevaluatedContext()) {
201 S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
Eric Fiselierc8efda72016-10-27 18:43:28 +0000202 return false;
Richard Smith744b2242015-11-20 02:54:01 +0000203 }
Richard Smithcfd53b42015-10-22 06:13:50 +0000204
205 // Any other usage must be within a function.
206 auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
207 if (!FD) {
208 S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
209 ? diag::err_coroutine_objc_method
210 : diag::err_coroutine_outside_function) << Keyword;
Eric Fiselierc8efda72016-10-27 18:43:28 +0000211 return false;
Richard Smithcfd53b42015-10-22 06:13:50 +0000212 }
213
Eric Fiselierc8efda72016-10-27 18:43:28 +0000214 // An enumeration for mapping the diagnostic type to the correct diagnostic
215 // selection index.
216 enum InvalidFuncDiag {
217 DiagCtor = 0,
218 DiagDtor,
219 DiagCopyAssign,
220 DiagMoveAssign,
221 DiagMain,
222 DiagConstexpr,
223 DiagAutoRet,
224 DiagVarargs,
225 };
226 bool Diagnosed = false;
227 auto DiagInvalid = [&](InvalidFuncDiag ID) {
228 S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
229 Diagnosed = true;
230 return false;
231 };
232
233 // Diagnose when a constructor, destructor, copy/move assignment operator,
234 // or the function 'main' are declared as a coroutine.
235 auto *MD = dyn_cast<CXXMethodDecl>(FD);
236 if (MD && isa<CXXConstructorDecl>(MD))
237 return DiagInvalid(DiagCtor);
238 else if (MD && isa<CXXDestructorDecl>(MD))
239 return DiagInvalid(DiagDtor);
240 else if (MD && MD->isCopyAssignmentOperator())
241 return DiagInvalid(DiagCopyAssign);
242 else if (MD && MD->isMoveAssignmentOperator())
243 return DiagInvalid(DiagMoveAssign);
244 else if (FD->isMain())
245 return DiagInvalid(DiagMain);
246
247 // Emit a diagnostics for each of the following conditions which is not met.
248 if (FD->isConstexpr())
249 DiagInvalid(DiagConstexpr);
250 if (FD->getReturnType()->isUndeducedType())
251 DiagInvalid(DiagAutoRet);
252 if (FD->isVariadic())
253 DiagInvalid(DiagVarargs);
254
255 return !Diagnosed;
256}
257
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000258static ExprResult buildOperatorCoawaitLookupExpr(Sema &SemaRef, Scope *S,
259 SourceLocation Loc) {
260 DeclarationName OpName =
261 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
262 LookupResult Operators(SemaRef, OpName, SourceLocation(),
263 Sema::LookupOperatorName);
264 SemaRef.LookupName(Operators, S);
Eric Fiselierc8efda72016-10-27 18:43:28 +0000265
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000266 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
267 const auto &Functions = Operators.asUnresolvedSet();
268 bool IsOverloaded =
269 Functions.size() > 1 ||
270 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
271 Expr *CoawaitOp = UnresolvedLookupExpr::Create(
272 SemaRef.Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
273 DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
274 Functions.begin(), Functions.end());
275 assert(CoawaitOp);
276 return CoawaitOp;
277}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000278
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000279/// Build a call to 'operator co_await' if there is a suitable operator for
280/// the given expression.
281static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, SourceLocation Loc,
282 Expr *E,
283 UnresolvedLookupExpr *Lookup) {
284 UnresolvedSet<16> Functions;
285 Functions.append(Lookup->decls_begin(), Lookup->decls_end());
286 return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
287}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000288
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000289static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
290 SourceLocation Loc, Expr *E) {
291 ExprResult R = buildOperatorCoawaitLookupExpr(SemaRef, S, Loc);
292 if (R.isInvalid())
293 return ExprError();
294 return buildOperatorCoawaitCall(SemaRef, Loc, E,
295 cast<UnresolvedLookupExpr>(R.get()));
Richard Smithcfd53b42015-10-22 06:13:50 +0000296}
297
Gor Nishanov8df64e92016-10-27 16:28:31 +0000298static Expr *buildBuiltinCall(Sema &S, SourceLocation Loc, Builtin::ID Id,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000299 MultiExprArg CallArgs) {
Gor Nishanov8df64e92016-10-27 16:28:31 +0000300 StringRef Name = S.Context.BuiltinInfo.getName(Id);
301 LookupResult R(S, &S.Context.Idents.get(Name), Loc, Sema::LookupOrdinaryName);
302 S.LookupName(R, S.TUScope, /*AllowBuiltinCreation=*/true);
303
304 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
305 assert(BuiltInDecl && "failed to find builtin declaration");
306
307 ExprResult DeclRef =
308 S.BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
309 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
310
311 ExprResult Call =
312 S.ActOnCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
313
314 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
315 return Call.get();
316}
317
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000318static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
319 SourceLocation Loc) {
320 QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
321 if (CoroHandleType.isNull())
322 return ExprError();
323
324 DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
325 LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
326 Sema::LookupOrdinaryName);
327 if (!S.LookupQualifiedName(Found, LookupCtx)) {
328 S.Diag(Loc, diag::err_coroutine_handle_missing_member)
329 << "from_address";
330 return ExprError();
331 }
332
333 Expr *FramePtr =
334 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
335
336 CXXScopeSpec SS;
337 ExprResult FromAddr =
338 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
339 if (FromAddr.isInvalid())
340 return ExprError();
341
342 return S.ActOnCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
343}
Richard Smithcfd53b42015-10-22 06:13:50 +0000344
Richard Smith9f690bd2015-10-27 06:02:45 +0000345struct ReadySuspendResumeResult {
Eric Fiselierd978e532017-05-28 18:21:12 +0000346 enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume };
Richard Smith9f690bd2015-10-27 06:02:45 +0000347 Expr *Results[3];
Gor Nishanovce43bd22017-03-11 01:30:17 +0000348 OpaqueValueExpr *OpaqueValue;
349 bool IsInvalid;
Richard Smith9f690bd2015-10-27 06:02:45 +0000350};
351
Richard Smith23da82c2015-11-20 22:40:06 +0000352static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000353 StringRef Name, MultiExprArg Args) {
Richard Smith23da82c2015-11-20 22:40:06 +0000354 DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
355
356 // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
357 CXXScopeSpec SS;
358 ExprResult Result = S.BuildMemberReferenceExpr(
359 Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
360 SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
361 /*Scope=*/nullptr);
362 if (Result.isInvalid())
363 return ExprError();
364
Gor Nishanovd4507262018-03-27 20:38:19 +0000365 // We meant exactly what we asked for. No need for typo correction.
366 if (auto *TE = dyn_cast<TypoExpr>(Result.get())) {
367 S.clearDelayedTypo(TE);
368 S.Diag(Loc, diag::err_no_member)
369 << NameInfo.getName() << Base->getType()->getAsCXXRecordDecl()
370 << Base->getSourceRange();
371 return ExprError();
372 }
373
Richard Smith23da82c2015-11-20 22:40:06 +0000374 return S.ActOnCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
375}
376
Gor Nishanov0f333002017-08-25 04:46:54 +0000377// See if return type is coroutine-handle and if so, invoke builtin coro-resume
378// on its address. This is to enable experimental support for coroutine-handle
379// returning await_suspend that results in a guranteed tail call to the target
380// coroutine.
381static Expr *maybeTailCall(Sema &S, QualType RetType, Expr *E,
382 SourceLocation Loc) {
383 if (RetType->isReferenceType())
384 return nullptr;
385 Type const *T = RetType.getTypePtr();
386 if (!T->isClassType() && !T->isStructureType())
387 return nullptr;
388
389 // FIXME: Add convertability check to coroutine_handle<>. Possibly via
390 // EvaluateBinaryTypeTrait(BTT_IsConvertible, ...) which is at the moment
391 // a private function in SemaExprCXX.cpp
392
393 ExprResult AddressExpr = buildMemberCall(S, E, Loc, "address", None);
394 if (AddressExpr.isInvalid())
395 return nullptr;
396
397 Expr *JustAddress = AddressExpr.get();
398 // FIXME: Check that the type of AddressExpr is void*
399 return buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_resume,
400 JustAddress);
401}
402
Richard Smith9f690bd2015-10-27 06:02:45 +0000403/// Build calls to await_ready, await_suspend, and await_resume for a co_await
404/// expression.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000405static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
406 SourceLocation Loc, Expr *E) {
Gor Nishanovce43bd22017-03-11 01:30:17 +0000407 OpaqueValueExpr *Operand = new (S.Context)
408 OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
409
Richard Smith9f690bd2015-10-27 06:02:45 +0000410 // Assume invalid until we see otherwise.
Gor Nishanovce43bd22017-03-11 01:30:17 +0000411 ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true};
Richard Smith9f690bd2015-10-27 06:02:45 +0000412
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000413 ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc);
414 if (CoroHandleRes.isInvalid())
415 return Calls;
416 Expr *CoroHandle = CoroHandleRes.get();
417
Richard Smith9f690bd2015-10-27 06:02:45 +0000418 const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000419 MultiExprArg Args[] = {None, CoroHandle, None};
Richard Smith9f690bd2015-10-27 06:02:45 +0000420 for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000421 ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]);
Richard Smith9f690bd2015-10-27 06:02:45 +0000422 if (Result.isInvalid())
423 return Calls;
424 Calls.Results[I] = Result.get();
425 }
426
Eric Fiselierd978e532017-05-28 18:21:12 +0000427 // Assume the calls are valid; all further checking should make them invalid.
Richard Smith9f690bd2015-10-27 06:02:45 +0000428 Calls.IsInvalid = false;
Eric Fiselierd978e532017-05-28 18:21:12 +0000429
430 using ACT = ReadySuspendResumeResult::AwaitCallType;
431 CallExpr *AwaitReady = cast<CallExpr>(Calls.Results[ACT::ACT_Ready]);
432 if (!AwaitReady->getType()->isDependentType()) {
433 // [expr.await]p3 [...]
434 // — await-ready is the expression e.await_ready(), contextually converted
435 // to bool.
436 ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady);
437 if (Conv.isInvalid()) {
438 S.Diag(AwaitReady->getDirectCallee()->getLocStart(),
439 diag::note_await_ready_no_bool_conversion);
440 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
441 << AwaitReady->getDirectCallee() << E->getSourceRange();
442 Calls.IsInvalid = true;
443 }
444 Calls.Results[ACT::ACT_Ready] = Conv.get();
445 }
446 CallExpr *AwaitSuspend = cast<CallExpr>(Calls.Results[ACT::ACT_Suspend]);
447 if (!AwaitSuspend->getType()->isDependentType()) {
448 // [expr.await]p3 [...]
449 // - await-suspend is the expression e.await_suspend(h), which shall be
450 // a prvalue of type void or bool.
Eric Fiselier84ee7ff2017-05-31 23:41:11 +0000451 QualType RetType = AwaitSuspend->getCallReturnType(S.Context);
Gor Nishanovdb419a62017-09-05 19:31:52 +0000452
Gor Nishanov0f333002017-08-25 04:46:54 +0000453 // Experimental support for coroutine_handle returning await_suspend.
454 if (Expr *TailCallSuspend = maybeTailCall(S, RetType, AwaitSuspend, Loc))
455 Calls.Results[ACT::ACT_Suspend] = TailCallSuspend;
456 else {
457 // non-class prvalues always have cv-unqualified types
Gor Nishanov0f333002017-08-25 04:46:54 +0000458 if (RetType->isReferenceType() ||
Gor Nishanovdb419a62017-09-05 19:31:52 +0000459 (!RetType->isBooleanType() && !RetType->isVoidType())) {
Gor Nishanov0f333002017-08-25 04:46:54 +0000460 S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
461 diag::err_await_suspend_invalid_return_type)
462 << RetType;
463 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
464 << AwaitSuspend->getDirectCallee();
465 Calls.IsInvalid = true;
466 }
Eric Fiselierd978e532017-05-28 18:21:12 +0000467 }
468 }
469
Richard Smith9f690bd2015-10-27 06:02:45 +0000470 return Calls;
471}
472
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000473static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
474 SourceLocation Loc, StringRef Name,
475 MultiExprArg Args) {
476
477 // Form a reference to the promise.
478 ExprResult PromiseRef = S.BuildDeclRefExpr(
479 Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
480 if (PromiseRef.isInvalid())
481 return ExprError();
482
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000483 return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
484}
485
486VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
487 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
488 auto *FD = cast<FunctionDecl>(CurContext);
Eric Fiselier166c6e62017-07-10 01:27:22 +0000489 bool IsThisDependentType = [&] {
490 if (auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD))
491 return MD->isInstance() && MD->getThisType(Context)->isDependentType();
492 else
493 return false;
494 }();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000495
Eric Fiselier166c6e62017-07-10 01:27:22 +0000496 QualType T = FD->getType()->isDependentType() || IsThisDependentType
497 ? Context.DependentTy
498 : lookupPromiseType(*this, FD, Loc);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000499 if (T.isNull())
500 return nullptr;
501
502 auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
503 &PP.getIdentifierTable().get("__promise"), T,
504 Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
505 CheckVariableDeclarationType(VD);
506 if (VD->isInvalidDecl())
507 return nullptr;
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000508
509 auto *ScopeInfo = getCurFunction();
510 // Build a list of arguments, based on the coroutine functions arguments,
511 // that will be passed to the promise type's constructor.
512 llvm::SmallVector<Expr *, 4> CtorArgExprs;
513 auto &Moves = ScopeInfo->CoroutineParameterMoves;
514 for (auto *PD : FD->parameters()) {
515 if (PD->getType()->isDependentType())
516 continue;
517
518 auto RefExpr = ExprEmpty();
519 auto Move = Moves.find(PD);
Brian Gesiak98606222018-02-15 20:37:22 +0000520 assert(Move != Moves.end() &&
521 "Coroutine function parameter not inserted into move map");
522 // If a reference to the function parameter exists in the coroutine
523 // frame, use that reference.
524 auto *MoveDecl =
525 cast<VarDecl>(cast<DeclStmt>(Move->second)->getSingleDecl());
526 RefExpr =
527 BuildDeclRefExpr(MoveDecl, MoveDecl->getType().getNonReferenceType(),
528 ExprValueKind::VK_LValue, FD->getLocation());
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000529 if (RefExpr.isInvalid())
530 return nullptr;
531 CtorArgExprs.push_back(RefExpr.get());
532 }
533
534 // Create an initialization sequence for the promise type using the
535 // constructor arguments, wrapped in a parenthesized list expression.
536 Expr *PLE = new (Context) ParenListExpr(Context, FD->getLocation(),
537 CtorArgExprs, FD->getLocation());
538 InitializedEntity Entity = InitializedEntity::InitializeVariable(VD);
539 InitializationKind Kind = InitializationKind::CreateForInit(
540 VD->getLocation(), /*DirectInit=*/true, PLE);
541 InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs,
542 /*TopLevelOfInitList=*/false,
543 /*TreatUnavailableAsInvalid=*/false);
544
545 // Attempt to initialize the promise type with the arguments.
546 // If that fails, fall back to the promise type's default constructor.
547 if (InitSeq) {
548 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, CtorArgExprs);
549 if (Result.isInvalid()) {
550 VD->setInvalidDecl();
551 } else if (Result.get()) {
552 VD->setInit(MaybeCreateExprWithCleanups(Result.get()));
553 VD->setInitStyle(VarDecl::CallInit);
554 CheckCompleteVariableDeclaration(VD);
555 }
556 } else
557 ActOnUninitializedDecl(VD);
558
Eric Fiselier37b8a372017-05-31 19:36:59 +0000559 FD->addDecl(VD);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000560 return VD;
561}
562
563/// Check that this is a context in which a coroutine suspension can appear.
564static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000565 StringRef Keyword,
566 bool IsImplicit = false) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000567 if (!isValidCoroutineContext(S, Loc, Keyword))
568 return nullptr;
569
570 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000571
572 auto *ScopeInfo = S.getCurFunction();
573 assert(ScopeInfo && "missing function scope for function");
574
Eric Fiseliercac0a592017-03-11 02:35:37 +0000575 if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
576 ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
577
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000578 if (ScopeInfo->CoroutinePromise)
579 return ScopeInfo;
580
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000581 if (!S.buildCoroutineParameterMoves(Loc))
582 return nullptr;
583
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000584 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
585 if (!ScopeInfo->CoroutinePromise)
586 return nullptr;
587
588 return ScopeInfo;
589}
590
Eric Fiselierb936a392017-06-14 03:24:55 +0000591bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc,
592 StringRef Keyword) {
593 if (!checkCoroutineContext(*this, KWLoc, Keyword))
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000594 return false;
Eric Fiselierb936a392017-06-14 03:24:55 +0000595 auto *ScopeInfo = getCurFunction();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000596 assert(ScopeInfo->CoroutinePromise);
597
598 // If we have existing coroutine statements then we have already built
599 // the initial and final suspend points.
600 if (!ScopeInfo->NeedsCoroutineSuspends)
601 return true;
602
603 ScopeInfo->setNeedsCoroutineSuspends(false);
604
Eric Fiselierb936a392017-06-14 03:24:55 +0000605 auto *Fn = cast<FunctionDecl>(CurContext);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000606 SourceLocation Loc = Fn->getLocation();
607 // Build the initial suspend point
608 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
609 ExprResult Suspend =
Eric Fiselierb936a392017-06-14 03:24:55 +0000610 buildPromiseCall(*this, ScopeInfo->CoroutinePromise, Loc, Name, None);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000611 if (Suspend.isInvalid())
612 return StmtError();
Eric Fiselierb936a392017-06-14 03:24:55 +0000613 Suspend = buildOperatorCoawaitCall(*this, SC, Loc, Suspend.get());
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000614 if (Suspend.isInvalid())
615 return StmtError();
Eric Fiselierb936a392017-06-14 03:24:55 +0000616 Suspend = BuildResolvedCoawaitExpr(Loc, Suspend.get(),
617 /*IsImplicit*/ true);
618 Suspend = ActOnFinishFullExpr(Suspend.get());
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000619 if (Suspend.isInvalid()) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000620 Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000621 << ((Name == "initial_suspend") ? 0 : 1);
Eric Fiselierb936a392017-06-14 03:24:55 +0000622 Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000623 return StmtError();
624 }
625 return cast<Stmt>(Suspend.get());
626 };
627
628 StmtResult InitSuspend = buildSuspends("initial_suspend");
629 if (InitSuspend.isInvalid())
630 return true;
631
632 StmtResult FinalSuspend = buildSuspends("final_suspend");
633 if (FinalSuspend.isInvalid())
634 return true;
635
636 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
637
638 return true;
639}
640
Richard Smith9f690bd2015-10-27 06:02:45 +0000641ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000642 if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000643 CorrectDelayedTyposInExpr(E);
644 return ExprError();
645 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000646
Richard Smith10610f72015-11-20 22:57:24 +0000647 if (E->getType()->isPlaceholderType()) {
648 ExprResult R = CheckPlaceholderExpr(E);
649 if (R.isInvalid()) return ExprError();
650 E = R.get();
651 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000652 ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
653 if (Lookup.isInvalid())
654 return ExprError();
655 return BuildUnresolvedCoawaitExpr(Loc, E,
656 cast<UnresolvedLookupExpr>(Lookup.get()));
657}
Richard Smith10610f72015-11-20 22:57:24 +0000658
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000659ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000660 UnresolvedLookupExpr *Lookup) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000661 auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
662 if (!FSI)
663 return ExprError();
664
665 if (E->getType()->isPlaceholderType()) {
666 ExprResult R = CheckPlaceholderExpr(E);
667 if (R.isInvalid())
668 return ExprError();
669 E = R.get();
670 }
671
672 auto *Promise = FSI->CoroutinePromise;
673 if (Promise->getType()->isDependentType()) {
674 Expr *Res =
675 new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000676 return Res;
677 }
678
679 auto *RD = Promise->getType()->getAsCXXRecordDecl();
680 if (lookupMember(*this, "await_transform", RD, Loc)) {
681 ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
682 if (R.isInvalid()) {
683 Diag(Loc,
684 diag::note_coroutine_promise_implicit_await_transform_required_here)
685 << E->getSourceRange();
686 return ExprError();
687 }
688 E = R.get();
689 }
690 ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
Richard Smith9f690bd2015-10-27 06:02:45 +0000691 if (Awaitable.isInvalid())
692 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000693
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000694 return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
Richard Smith9f690bd2015-10-27 06:02:45 +0000695}
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000696
697ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E,
698 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000699 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
Richard Smith744b2242015-11-20 02:54:01 +0000700 if (!Coroutine)
701 return ExprError();
Richard Smith9f690bd2015-10-27 06:02:45 +0000702
Richard Smith9f690bd2015-10-27 06:02:45 +0000703 if (E->getType()->isPlaceholderType()) {
704 ExprResult R = CheckPlaceholderExpr(E);
705 if (R.isInvalid()) return ExprError();
706 E = R.get();
707 }
708
Richard Smith10610f72015-11-20 22:57:24 +0000709 if (E->getType()->isDependentType()) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000710 Expr *Res = new (Context)
711 CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
Richard Smith10610f72015-11-20 22:57:24 +0000712 return Res;
713 }
714
Richard Smith1f38edd2015-11-22 03:13:02 +0000715 // If the expression is a temporary, materialize it as an lvalue so that we
716 // can use it multiple times.
717 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000718 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smith9f690bd2015-10-27 06:02:45 +0000719
Eric Fiselierd2e30d32018-03-27 03:15:46 +0000720 // The location of the `co_await` token cannot be used when constructing
721 // the member call expressions since it's before the location of `Expr`, which
722 // is used as the start of the member call expression.
723 SourceLocation CallLoc = E->getExprLoc();
724
Richard Smith9f690bd2015-10-27 06:02:45 +0000725 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000726 ReadySuspendResumeResult RSS =
Eric Fiselierd2e30d32018-03-27 03:15:46 +0000727 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, CallLoc, E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000728 if (RSS.IsInvalid)
729 return ExprError();
730
Gor Nishanovce43bd22017-03-11 01:30:17 +0000731 Expr *Res =
732 new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
733 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000734
Richard Smithcfd53b42015-10-22 06:13:50 +0000735 return Res;
736}
737
Richard Smith9f690bd2015-10-27 06:02:45 +0000738ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000739 if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000740 CorrectDelayedTyposInExpr(E);
Richard Smith23da82c2015-11-20 22:40:06 +0000741 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000742 }
Richard Smith23da82c2015-11-20 22:40:06 +0000743
744 // Build yield_value call.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000745 ExprResult Awaitable = buildPromiseCall(
746 *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000747 if (Awaitable.isInvalid())
748 return ExprError();
Richard Smith23da82c2015-11-20 22:40:06 +0000749
750 // Build 'operator co_await' call.
751 Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
752 if (Awaitable.isInvalid())
753 return ExprError();
754
Richard Smith9f690bd2015-10-27 06:02:45 +0000755 return BuildCoyieldExpr(Loc, Awaitable.get());
756}
757ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
758 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
Richard Smith744b2242015-11-20 02:54:01 +0000759 if (!Coroutine)
760 return ExprError();
Richard Smithcfd53b42015-10-22 06:13:50 +0000761
Richard Smith10610f72015-11-20 22:57:24 +0000762 if (E->getType()->isPlaceholderType()) {
763 ExprResult R = CheckPlaceholderExpr(E);
764 if (R.isInvalid()) return ExprError();
765 E = R.get();
766 }
767
Richard Smithd7bed4d2015-11-22 02:57:17 +0000768 if (E->getType()->isDependentType()) {
769 Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000770 return Res;
771 }
772
Richard Smith1f38edd2015-11-22 03:13:02 +0000773 // If the expression is a temporary, materialize it as an lvalue so that we
774 // can use it multiple times.
775 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000776 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000777
778 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000779 ReadySuspendResumeResult RSS =
780 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000781 if (RSS.IsInvalid)
782 return ExprError();
783
Eric Fiselierb936a392017-06-14 03:24:55 +0000784 Expr *Res =
785 new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
786 RSS.Results[2], RSS.OpaqueValue);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000787
Richard Smithcfd53b42015-10-22 06:13:50 +0000788 return Res;
789}
790
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000791StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000792 if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000793 CorrectDelayedTyposInExpr(E);
794 return StmtError();
795 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000796 return BuildCoreturnStmt(Loc, E);
797}
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000798
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000799StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
800 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000801 auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000802 if (!FSI)
Richard Smith71d403e2015-11-22 07:33:28 +0000803 return StmtError();
804
805 if (E && E->getType()->isPlaceholderType() &&
806 !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
Richard Smith10610f72015-11-20 22:57:24 +0000807 ExprResult R = CheckPlaceholderExpr(E);
808 if (R.isInvalid()) return StmtError();
809 E = R.get();
810 }
811
Richard Smith4ba66602015-11-22 07:05:16 +0000812 // FIXME: If the operand is a reference to a variable that's about to go out
Richard Smith2af65c42015-11-24 02:34:39 +0000813 // of scope, we should treat the operand as an xvalue for this overload
Richard Smith4ba66602015-11-22 07:05:16 +0000814 // resolution.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000815 VarDecl *Promise = FSI->CoroutinePromise;
Richard Smith4ba66602015-11-22 07:05:16 +0000816 ExprResult PC;
Eric Fiselier98131312016-10-06 21:23:38 +0000817 if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000818 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
Richard Smith4ba66602015-11-22 07:05:16 +0000819 } else {
820 E = MakeFullDiscardedValueExpr(E).get();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000821 PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
Richard Smith4ba66602015-11-22 07:05:16 +0000822 }
823 if (PC.isInvalid())
824 return StmtError();
825
826 Expr *PCE = ActOnFinishFullExpr(PC.get()).get();
827
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000828 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
Richard Smithcfd53b42015-10-22 06:13:50 +0000829 return Res;
830}
831
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000832/// Look up the std::nothrow object.
833static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
834 NamespaceDecl *Std = S.getStdNamespace();
835 assert(Std && "Should already be diagnosed");
836
837 LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
838 Sema::LookupOrdinaryName);
839 if (!S.LookupQualifiedName(Result, Std)) {
840 // FIXME: <experimental/coroutine> should have been included already.
841 // If we require it to include <new> then this diagnostic is no longer
842 // needed.
843 S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
844 return nullptr;
845 }
846
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000847 auto *VD = Result.getAsSingle<VarDecl>();
848 if (!VD) {
849 Result.suppressDiagnostics();
850 // We found something weird. Complain about the first thing we found.
851 NamedDecl *Found = *Result.begin();
852 S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
853 return nullptr;
854 }
855
856 ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
857 if (DR.isInvalid())
858 return nullptr;
859
860 return DR.get();
861}
862
Gor Nishanov8df64e92016-10-27 16:28:31 +0000863// Find an appropriate delete for the promise.
864static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc,
865 QualType PromiseType) {
866 FunctionDecl *OperatorDelete = nullptr;
867
868 DeclarationName DeleteName =
869 S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
870
871 auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
872 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
873
874 if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
875 return nullptr;
876
877 if (!OperatorDelete) {
878 // Look for a global declaration.
879 const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
880 const bool Overaligned = false;
881 OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
882 Overaligned, DeleteName);
883 }
884 S.MarkFunctionReferenced(Loc, OperatorDelete);
885 return OperatorDelete;
886}
887
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000888
889void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
890 FunctionScopeInfo *Fn = getCurFunction();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000891 assert(Fn && Fn->isCoroutine() && "not a coroutine");
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000892 if (!Body) {
893 assert(FD->isInvalidDecl() &&
894 "a null body is only allowed for invalid declarations");
895 return;
896 }
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000897 // We have a function that uses coroutine keywords, but we failed to build
898 // the promise type.
899 if (!Fn->CoroutinePromise)
900 return FD->setInvalidDecl();
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000901
902 if (isa<CoroutineBodyStmt>(Body)) {
Gor Nishanov29ff6382017-05-24 14:34:19 +0000903 // Nothing todo. the body is already a transformed coroutine body statement.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000904 return;
905 }
906
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000907 // Coroutines [stmt.return]p1:
908 // A return statement shall not appear in a coroutine.
909 if (Fn->FirstReturnLoc.isValid()) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000910 assert(Fn->FirstCoroutineStmtLoc.isValid() &&
911 "first coroutine location not set");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000912 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000913 Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
914 << Fn->getFirstCoroutineStmtKeyword();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000915 }
Eric Fiselierbee782b2017-04-03 19:21:00 +0000916 CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
917 if (Builder.isInvalid() || !Builder.buildStatements())
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000918 return FD->setInvalidDecl();
919
920 // Build body for the coroutine wrapper statement.
921 Body = CoroutineBodyStmt::Create(Context, Builder);
922}
923
Eric Fiselierbee782b2017-04-03 19:21:00 +0000924CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
925 sema::FunctionScopeInfo &Fn,
926 Stmt *Body)
927 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
928 IsPromiseDependentType(
929 !Fn.CoroutinePromise ||
930 Fn.CoroutinePromise->getType()->isDependentType()) {
931 this->Body = Body;
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000932
933 for (auto KV : Fn.CoroutineParameterMoves)
934 this->ParamMovesVector.push_back(KV.second);
935 this->ParamMoves = this->ParamMovesVector;
936
Eric Fiselierbee782b2017-04-03 19:21:00 +0000937 if (!IsPromiseDependentType) {
938 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
939 assert(PromiseRecordDecl && "Type should have already been checked");
940 }
941 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
942}
943
944bool CoroutineStmtBuilder::buildStatements() {
945 assert(this->IsValid && "coroutine already invalid");
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000946 this->IsValid = makeReturnObject();
Eric Fiselierbee782b2017-04-03 19:21:00 +0000947 if (this->IsValid && !IsPromiseDependentType)
948 buildDependentStatements();
949 return this->IsValid;
950}
951
952bool CoroutineStmtBuilder::buildDependentStatements() {
953 assert(this->IsValid && "coroutine already invalid");
954 assert(!this->IsPromiseDependentType &&
955 "coroutine cannot have a dependent promise type");
956 this->IsValid = makeOnException() && makeOnFallthrough() &&
Gor Nishanov6a470682017-05-22 20:22:23 +0000957 makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
958 makeNewAndDeleteExpr();
Eric Fiselierbee782b2017-04-03 19:21:00 +0000959 return this->IsValid;
960}
961
962bool CoroutineStmtBuilder::makePromiseStmt() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000963 // Form a declaration statement for the promise declaration, so that AST
964 // visitors can more easily find it.
965 StmtResult PromiseStmt =
966 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
967 if (PromiseStmt.isInvalid())
968 return false;
969
970 this->Promise = PromiseStmt.get();
971 return true;
972}
973
Eric Fiselierbee782b2017-04-03 19:21:00 +0000974bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000975 if (Fn.hasInvalidCoroutineSuspends())
976 return false;
977 this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
978 this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
979 return true;
980}
981
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000982static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
983 CXXRecordDecl *PromiseRecordDecl,
984 FunctionScopeInfo &Fn) {
985 auto Loc = E->getExprLoc();
986 if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
987 auto *Decl = DeclRef->getDecl();
988 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
989 if (Method->isStatic())
990 return true;
991 else
992 Loc = Decl->getLocation();
993 }
994 }
995
996 S.Diag(
997 Loc,
998 diag::err_coroutine_promise_get_return_object_on_allocation_failure)
999 << PromiseRecordDecl;
1000 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1001 << Fn.getFirstCoroutineStmtKeyword();
1002 return false;
1003}
1004
Eric Fiselierbee782b2017-04-03 19:21:00 +00001005bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
1006 assert(!IsPromiseDependentType &&
1007 "cannot make statement while the promise type is dependent");
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001008
1009 // [dcl.fct.def.coroutine]/8
1010 // The unqualified-id get_return_object_on_allocation_failure is looked up in
1011 // the scope of class P by class member access lookup (3.4.5). ...
1012 // If an allocation function returns nullptr, ... the coroutine return value
1013 // is obtained by a call to ... get_return_object_on_allocation_failure().
1014
1015 DeclarationName DN =
1016 S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
1017 LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
Eric Fiselierbee782b2017-04-03 19:21:00 +00001018 if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
1019 return true;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001020
1021 CXXScopeSpec SS;
1022 ExprResult DeclNameExpr =
1023 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
Eric Fiselierbee782b2017-04-03 19:21:00 +00001024 if (DeclNameExpr.isInvalid())
1025 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001026
1027 if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
1028 return false;
1029
1030 ExprResult ReturnObjectOnAllocationFailure =
1031 S.ActOnCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
Eric Fiselierbee782b2017-04-03 19:21:00 +00001032 if (ReturnObjectOnAllocationFailure.isInvalid())
1033 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001034
Gor Nishanovc4a19082017-03-28 02:51:45 +00001035 StmtResult ReturnStmt =
1036 S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
Gor Nishanov6a470682017-05-22 20:22:23 +00001037 if (ReturnStmt.isInvalid()) {
Eric Fiselierfc50f622017-05-25 14:59:39 +00001038 S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
1039 << DN;
Gor Nishanov6a470682017-05-22 20:22:23 +00001040 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1041 << Fn.getFirstCoroutineStmtKeyword();
Eric Fiselierbee782b2017-04-03 19:21:00 +00001042 return false;
Gor Nishanov6a470682017-05-22 20:22:23 +00001043 }
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001044
1045 this->ReturnStmtOnAllocFailure = ReturnStmt.get();
1046 return true;
1047}
1048
Eric Fiselierbee782b2017-04-03 19:21:00 +00001049bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001050 // Form and check allocation and deallocation calls.
Eric Fiselierbee782b2017-04-03 19:21:00 +00001051 assert(!IsPromiseDependentType &&
1052 "cannot make statement while the promise type is dependent");
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001053 QualType PromiseType = Fn.CoroutinePromise->getType();
Gor Nishanov8df64e92016-10-27 16:28:31 +00001054
1055 if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
1056 return false;
1057
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001058 const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
1059
Brian Gesiak98606222018-02-15 20:37:22 +00001060 // [dcl.fct.def.coroutine]/7
1061 // Lookup allocation functions using a parameter list composed of the
1062 // requested size of the coroutine state being allocated, followed by
1063 // the coroutine function's arguments. If a matching allocation function
1064 // exists, use it. Otherwise, use an allocation function that just takes
1065 // the requested size.
Gor Nishanov8df64e92016-10-27 16:28:31 +00001066
1067 FunctionDecl *OperatorNew = nullptr;
1068 FunctionDecl *OperatorDelete = nullptr;
1069 FunctionDecl *UnusedResult = nullptr;
1070 bool PassAlignment = false;
Eric Fiselierf747f532017-04-18 05:08:08 +00001071 SmallVector<Expr *, 1> PlacementArgs;
Gor Nishanov8df64e92016-10-27 16:28:31 +00001072
Brian Gesiak98606222018-02-15 20:37:22 +00001073 // [dcl.fct.def.coroutine]/7
1074 // "The allocation function’s name is looked up in the scope of P.
1075 // [...] If the lookup finds an allocation function in the scope of P,
1076 // overload resolution is performed on a function call created by assembling
1077 // an argument list. The first argument is the amount of space requested,
1078 // and has type std::size_t. The lvalues p1 ... pn are the succeeding
1079 // arguments."
1080 //
1081 // ...where "p1 ... pn" are defined earlier as:
1082 //
1083 // [dcl.fct.def.coroutine]/3
1084 // "For a coroutine f that is a non-static member function, let P1 denote the
1085 // type of the implicit object parameter (13.3.1) and P2 ... Pn be the types
1086 // of the function parameters; otherwise let P1 ... Pn be the types of the
1087 // function parameters. Let p1 ... pn be lvalues denoting those objects."
1088 if (auto *MD = dyn_cast<CXXMethodDecl>(&FD)) {
1089 if (MD->isInstance() && !isLambdaCallOperator(MD)) {
1090 ExprResult ThisExpr = S.ActOnCXXThis(Loc);
1091 if (ThisExpr.isInvalid())
1092 return false;
1093 ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
1094 if (ThisExpr.isInvalid())
1095 return false;
1096 PlacementArgs.push_back(ThisExpr.get());
1097 }
1098 }
1099 for (auto *PD : FD.parameters()) {
1100 if (PD->getType()->isDependentType())
1101 continue;
1102
1103 // Build a reference to the parameter.
1104 auto PDLoc = PD->getLocation();
1105 ExprResult PDRefExpr =
1106 S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),
1107 ExprValueKind::VK_LValue, PDLoc);
1108 if (PDRefExpr.isInvalid())
1109 return false;
1110
1111 PlacementArgs.push_back(PDRefExpr.get());
1112 }
Gor Nishanov8df64e92016-10-27 16:28:31 +00001113 S.FindAllocationFunctions(Loc, SourceRange(),
1114 /*UseGlobal*/ false, PromiseType,
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001115 /*isArray*/ false, PassAlignment, PlacementArgs,
Brian Gesiak98606222018-02-15 20:37:22 +00001116 OperatorNew, UnusedResult, /*Diagnose*/ false);
1117
1118 // [dcl.fct.def.coroutine]/7
1119 // "If no matching function is found, overload resolution is performed again
1120 // on a function call created by passing just the amount of space required as
1121 // an argument of type std::size_t."
1122 if (!OperatorNew && !PlacementArgs.empty()) {
1123 PlacementArgs.clear();
1124 S.FindAllocationFunctions(Loc, SourceRange(),
1125 /*UseGlobal*/ false, PromiseType,
1126 /*isArray*/ false, PassAlignment,
1127 PlacementArgs, OperatorNew, UnusedResult);
1128 }
Gor Nishanov8df64e92016-10-27 16:28:31 +00001129
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001130 bool IsGlobalOverload =
1131 OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
1132 // If we didn't find a class-local new declaration and non-throwing new
1133 // was is required then we need to lookup the non-throwing global operator
1134 // instead.
1135 if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
1136 auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
1137 if (!StdNoThrow)
1138 return false;
Eric Fiselierf747f532017-04-18 05:08:08 +00001139 PlacementArgs = {StdNoThrow};
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001140 OperatorNew = nullptr;
1141 S.FindAllocationFunctions(Loc, SourceRange(),
1142 /*UseGlobal*/ true, PromiseType,
1143 /*isArray*/ false, PassAlignment, PlacementArgs,
1144 OperatorNew, UnusedResult);
1145 }
Gor Nishanov8df64e92016-10-27 16:28:31 +00001146
Brian Gesiak98606222018-02-15 20:37:22 +00001147 if (!OperatorNew)
1148 return false;
Eric Fiselierc5128752017-04-18 05:30:39 +00001149
1150 if (RequiresNoThrowAlloc) {
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001151 const auto *FT = OperatorNew->getType()->getAs<FunctionProtoType>();
1152 if (!FT->isNothrow(S.Context, /*ResultIfDependent*/ false)) {
1153 S.Diag(OperatorNew->getLocation(),
1154 diag::err_coroutine_promise_new_requires_nothrow)
1155 << OperatorNew;
1156 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
1157 << OperatorNew;
1158 return false;
1159 }
1160 }
1161
1162 if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr)
Gor Nishanov8df64e92016-10-27 16:28:31 +00001163 return false;
1164
1165 Expr *FramePtr =
1166 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
1167
1168 Expr *FrameSize =
1169 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {});
1170
1171 // Make new call.
1172
1173 ExprResult NewRef =
1174 S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
1175 if (NewRef.isInvalid())
1176 return false;
1177
Eric Fiselierf747f532017-04-18 05:08:08 +00001178 SmallVector<Expr *, 2> NewArgs(1, FrameSize);
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001179 for (auto Arg : PlacementArgs)
1180 NewArgs.push_back(Arg);
1181
Gor Nishanov8df64e92016-10-27 16:28:31 +00001182 ExprResult NewExpr =
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001183 S.ActOnCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
1184 NewExpr = S.ActOnFinishFullExpr(NewExpr.get());
Gor Nishanov8df64e92016-10-27 16:28:31 +00001185 if (NewExpr.isInvalid())
1186 return false;
1187
Gor Nishanov8df64e92016-10-27 16:28:31 +00001188 // Make delete call.
1189
1190 QualType OpDeleteQualType = OperatorDelete->getType();
1191
1192 ExprResult DeleteRef =
1193 S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
1194 if (DeleteRef.isInvalid())
1195 return false;
1196
1197 Expr *CoroFree =
1198 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr});
1199
1200 SmallVector<Expr *, 2> DeleteArgs{CoroFree};
1201
1202 // Check if we need to pass the size.
1203 const auto *OpDeleteType =
1204 OpDeleteQualType.getTypePtr()->getAs<FunctionProtoType>();
1205 if (OpDeleteType->getNumParams() > 1)
1206 DeleteArgs.push_back(FrameSize);
1207
1208 ExprResult DeleteExpr =
1209 S.ActOnCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001210 DeleteExpr = S.ActOnFinishFullExpr(DeleteExpr.get());
Gor Nishanov8df64e92016-10-27 16:28:31 +00001211 if (DeleteExpr.isInvalid())
1212 return false;
1213
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001214 this->Allocate = NewExpr.get();
1215 this->Deallocate = DeleteExpr.get();
Gor Nishanov8df64e92016-10-27 16:28:31 +00001216
1217 return true;
1218}
1219
Eric Fiselierbee782b2017-04-03 19:21:00 +00001220bool CoroutineStmtBuilder::makeOnFallthrough() {
1221 assert(!IsPromiseDependentType &&
1222 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001223
1224 // [dcl.fct.def.coroutine]/4
1225 // The unqualified-ids 'return_void' and 'return_value' are looked up in
1226 // the scope of class P. If both are found, the program is ill-formed.
Eric Fiselierfc50f622017-05-25 14:59:39 +00001227 bool HasRVoid, HasRValue;
1228 LookupResult LRVoid =
1229 lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
1230 LookupResult LRValue =
1231 lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001232
Eric Fiselier709d1b32016-10-27 07:30:31 +00001233 StmtResult Fallthrough;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001234 if (HasRVoid && HasRValue) {
1235 // FIXME Improve this diagnostic
Eric Fiselierfc50f622017-05-25 14:59:39 +00001236 S.Diag(FD.getLocation(),
1237 diag::err_coroutine_promise_incompatible_return_functions)
1238 << PromiseRecordDecl;
1239 S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
1240 diag::note_member_first_declared_here)
1241 << LRVoid.getLookupName();
1242 S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
1243 diag::note_member_first_declared_here)
1244 << LRValue.getLookupName();
1245 return false;
1246 } else if (!HasRVoid && !HasRValue) {
1247 // FIXME: The PDTS currently specifies this case as UB, not ill-formed.
1248 // However we still diagnose this as an error since until the PDTS is fixed.
1249 S.Diag(FD.getLocation(),
1250 diag::err_coroutine_promise_requires_return_function)
1251 << PromiseRecordDecl;
1252 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001253 << PromiseRecordDecl;
1254 return false;
1255 } else if (HasRVoid) {
1256 // If the unqualified-id return_void is found, flowing off the end of a
1257 // coroutine is equivalent to a co_return with no operand. Otherwise,
1258 // flowing off the end of a coroutine results in undefined behavior.
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001259 Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
1260 /*IsImplicit*/false);
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001261 Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
1262 if (Fallthrough.isInvalid())
1263 return false;
Eric Fiselier709d1b32016-10-27 07:30:31 +00001264 }
Richard Smith2af65c42015-11-24 02:34:39 +00001265
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001266 this->OnFallthrough = Fallthrough.get();
1267 return true;
1268}
1269
Eric Fiselierbee782b2017-04-03 19:21:00 +00001270bool CoroutineStmtBuilder::makeOnException() {
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001271 // Try to form 'p.unhandled_exception();'
Eric Fiselierbee782b2017-04-03 19:21:00 +00001272 assert(!IsPromiseDependentType &&
1273 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001274
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001275 const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1276
1277 if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
1278 auto DiagID =
1279 RequireUnhandledException
1280 ? diag::err_coroutine_promise_unhandled_exception_required
1281 : diag::
1282 warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1283 S.Diag(Loc, DiagID) << PromiseRecordDecl;
Gor Nishanov29ff6382017-05-24 14:34:19 +00001284 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1285 << PromiseRecordDecl;
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001286 return !RequireUnhandledException;
1287 }
1288
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001289 // If exceptions are disabled, don't try to build OnException.
1290 if (!S.getLangOpts().CXXExceptions)
1291 return true;
1292
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001293 ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
1294 "unhandled_exception", None);
1295 UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc);
1296 if (UnhandledException.isInvalid())
1297 return false;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001298
Gor Nishanov5b050e42017-05-22 22:33:17 +00001299 // Since the body of the coroutine will be wrapped in try-catch, it will
1300 // be incompatible with SEH __try if present in a function.
1301 if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1302 S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1303 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1304 << Fn.getFirstCoroutineStmtKeyword();
1305 return false;
1306 }
1307
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001308 this->OnException = UnhandledException.get();
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001309 return true;
1310}
1311
Eric Fiselierbee782b2017-04-03 19:21:00 +00001312bool CoroutineStmtBuilder::makeReturnObject() {
Richard Smith2af65c42015-11-24 02:34:39 +00001313 // Build implicit 'p.get_return_object()' expression and form initialization
1314 // of return type from it.
1315 ExprResult ReturnObject =
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001316 buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
Richard Smith2af65c42015-11-24 02:34:39 +00001317 if (ReturnObject.isInvalid())
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001318 return false;
Richard Smith2af65c42015-11-24 02:34:39 +00001319
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001320 this->ReturnValue = ReturnObject.get();
1321 return true;
1322}
1323
Gor Nishanov6a470682017-05-22 20:22:23 +00001324static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
1325 if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
1326 auto *MethodDecl = MbrRef->getMethodDecl();
Eric Fiselierfc50f622017-05-25 14:59:39 +00001327 S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
1328 << MethodDecl;
Gor Nishanov6a470682017-05-22 20:22:23 +00001329 }
1330 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1331 << Fn.getFirstCoroutineStmtKeyword();
1332}
1333
1334bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1335 assert(!IsPromiseDependentType &&
1336 "cannot make statement while the promise type is dependent");
1337 assert(this->ReturnValue && "ReturnValue must be already formed");
1338
1339 QualType const GroType = this->ReturnValue->getType();
1340 assert(!GroType->isDependentType() &&
1341 "get_return_object type must no longer be dependent");
1342
1343 QualType const FnRetType = FD.getReturnType();
1344 assert(!FnRetType->isDependentType() &&
1345 "get_return_object type must no longer be dependent");
1346
1347 if (FnRetType->isVoidType()) {
1348 ExprResult Res = S.ActOnFinishFullExpr(this->ReturnValue, Loc);
1349 if (Res.isInvalid())
1350 return false;
1351
1352 this->ResultDecl = Res.get();
1353 return true;
1354 }
1355
1356 if (GroType->isVoidType()) {
1357 // Trigger a nice error message.
1358 InitializedEntity Entity =
1359 InitializedEntity::InitializeResult(Loc, FnRetType, false);
1360 S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue);
1361 noteMemberDeclaredHere(S, ReturnValue, Fn);
1362 return false;
1363 }
1364
1365 auto *GroDecl = VarDecl::Create(
1366 S.Context, &FD, FD.getLocation(), FD.getLocation(),
1367 &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
1368 S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
1369
1370 S.CheckVariableDeclarationType(GroDecl);
1371 if (GroDecl->isInvalidDecl())
1372 return false;
1373
1374 InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
1375 ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType,
1376 this->ReturnValue);
1377 if (Res.isInvalid())
1378 return false;
1379
1380 Res = S.ActOnFinishFullExpr(Res.get());
1381 if (Res.isInvalid())
1382 return false;
1383
Gor Nishanov6a470682017-05-22 20:22:23 +00001384 S.AddInitializerToDecl(GroDecl, Res.get(),
1385 /*DirectInit=*/false);
1386
1387 S.FinalizeDeclaration(GroDecl);
1388
1389 // Form a declaration statement for the return declaration, so that AST
1390 // visitors can more easily find it.
1391 StmtResult GroDeclStmt =
1392 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
1393 if (GroDeclStmt.isInvalid())
1394 return false;
1395
1396 this->ResultDecl = GroDeclStmt.get();
1397
1398 ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
1399 if (declRef.isInvalid())
1400 return false;
1401
1402 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
1403 if (ReturnStmt.isInvalid()) {
1404 noteMemberDeclaredHere(S, ReturnValue, Fn);
1405 return false;
1406 }
Eric Fiselier8ed97272018-02-01 23:47:54 +00001407 if (cast<clang::ReturnStmt>(ReturnStmt.get())->getNRVOCandidate() == GroDecl)
1408 GroDecl->setNRVOVariable(true);
Gor Nishanov6a470682017-05-22 20:22:23 +00001409
1410 this->ReturnStmt = ReturnStmt.get();
1411 return true;
1412}
1413
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001414// Create a static_cast\<T&&>(expr).
1415static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
1416 if (T.isNull())
1417 T = E->getType();
1418 QualType TargetType = S.BuildReferenceType(
1419 T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());
1420 SourceLocation ExprLoc = E->getLocStart();
1421 TypeSourceInfo *TargetLoc =
1422 S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
1423
1424 return S
1425 .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1426 SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
1427 .get();
1428}
1429
1430/// \brief Build a variable declaration for move parameter.
1431static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
Eric Fiselierde7943b2017-06-03 00:22:18 +00001432 IdentifierInfo *II) {
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001433 TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);
Brian Gesiak61f4ac92018-01-24 22:15:42 +00001434 VarDecl *Decl = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type,
1435 TInfo, SC_None);
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001436 Decl->setImplicit();
1437 return Decl;
1438}
1439
Brian Gesiak61f4ac92018-01-24 22:15:42 +00001440// Build statements that move coroutine function parameters to the coroutine
1441// frame, and store them on the function scope info.
1442bool Sema::buildCoroutineParameterMoves(SourceLocation Loc) {
1443 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
1444 auto *FD = cast<FunctionDecl>(CurContext);
1445
1446 auto *ScopeInfo = getCurFunction();
1447 assert(ScopeInfo->CoroutineParameterMoves.empty() &&
1448 "Should not build parameter moves twice");
1449
1450 for (auto *PD : FD->parameters()) {
1451 if (PD->getType()->isDependentType())
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001452 continue;
1453
Brian Gesiak98606222018-02-15 20:37:22 +00001454 ExprResult PDRefExpr =
1455 BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
1456 ExprValueKind::VK_LValue, Loc); // FIXME: scope?
1457 if (PDRefExpr.isInvalid())
1458 return false;
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001459
Brian Gesiak98606222018-02-15 20:37:22 +00001460 Expr *CExpr = nullptr;
1461 if (PD->getType()->getAsCXXRecordDecl() ||
1462 PD->getType()->isRValueReferenceType())
1463 CExpr = castForMoving(*this, PDRefExpr.get());
1464 else
1465 CExpr = PDRefExpr.get();
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001466
Brian Gesiak98606222018-02-15 20:37:22 +00001467 auto D = buildVarDecl(*this, Loc, PD->getType(), PD->getIdentifier());
1468 AddInitializerToDecl(D, CExpr, /*DirectInit=*/true);
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001469
Brian Gesiak98606222018-02-15 20:37:22 +00001470 // Convert decl to a statement.
1471 StmtResult Stmt = ActOnDeclStmt(ConvertDeclToDeclGroup(D), Loc, Loc);
1472 if (Stmt.isInvalid())
1473 return false;
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001474
Brian Gesiak98606222018-02-15 20:37:22 +00001475 ScopeInfo->CoroutineParameterMoves.insert(std::make_pair(PD, Stmt.get()));
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001476 }
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001477 return true;
Richard Smithcfd53b42015-10-22 06:13:50 +00001478}
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001479
1480StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1481 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
1482 if (!Res)
1483 return StmtError();
1484 return Res;
1485}