blob: e4cb4cf059fa2d55698e3f3cb5a9f972deea8f7e [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
365 return S.ActOnCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
366}
367
Gor Nishanov0f333002017-08-25 04:46:54 +0000368// See if return type is coroutine-handle and if so, invoke builtin coro-resume
369// on its address. This is to enable experimental support for coroutine-handle
370// returning await_suspend that results in a guranteed tail call to the target
371// coroutine.
372static Expr *maybeTailCall(Sema &S, QualType RetType, Expr *E,
373 SourceLocation Loc) {
374 if (RetType->isReferenceType())
375 return nullptr;
376 Type const *T = RetType.getTypePtr();
377 if (!T->isClassType() && !T->isStructureType())
378 return nullptr;
379
380 // FIXME: Add convertability check to coroutine_handle<>. Possibly via
381 // EvaluateBinaryTypeTrait(BTT_IsConvertible, ...) which is at the moment
382 // a private function in SemaExprCXX.cpp
383
384 ExprResult AddressExpr = buildMemberCall(S, E, Loc, "address", None);
385 if (AddressExpr.isInvalid())
386 return nullptr;
387
388 Expr *JustAddress = AddressExpr.get();
389 // FIXME: Check that the type of AddressExpr is void*
390 return buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_resume,
391 JustAddress);
392}
393
Richard Smith9f690bd2015-10-27 06:02:45 +0000394/// Build calls to await_ready, await_suspend, and await_resume for a co_await
395/// expression.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000396static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
397 SourceLocation Loc, Expr *E) {
Gor Nishanovce43bd22017-03-11 01:30:17 +0000398 OpaqueValueExpr *Operand = new (S.Context)
399 OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
400
Richard Smith9f690bd2015-10-27 06:02:45 +0000401 // Assume invalid until we see otherwise.
Gor Nishanovce43bd22017-03-11 01:30:17 +0000402 ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true};
Richard Smith9f690bd2015-10-27 06:02:45 +0000403
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000404 ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc);
405 if (CoroHandleRes.isInvalid())
406 return Calls;
407 Expr *CoroHandle = CoroHandleRes.get();
408
Richard Smith9f690bd2015-10-27 06:02:45 +0000409 const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000410 MultiExprArg Args[] = {None, CoroHandle, None};
Richard Smith9f690bd2015-10-27 06:02:45 +0000411 for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000412 ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]);
Richard Smith9f690bd2015-10-27 06:02:45 +0000413 if (Result.isInvalid())
414 return Calls;
415 Calls.Results[I] = Result.get();
416 }
417
Eric Fiselierd978e532017-05-28 18:21:12 +0000418 // Assume the calls are valid; all further checking should make them invalid.
Richard Smith9f690bd2015-10-27 06:02:45 +0000419 Calls.IsInvalid = false;
Eric Fiselierd978e532017-05-28 18:21:12 +0000420
421 using ACT = ReadySuspendResumeResult::AwaitCallType;
422 CallExpr *AwaitReady = cast<CallExpr>(Calls.Results[ACT::ACT_Ready]);
423 if (!AwaitReady->getType()->isDependentType()) {
424 // [expr.await]p3 [...]
425 // — await-ready is the expression e.await_ready(), contextually converted
426 // to bool.
427 ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady);
428 if (Conv.isInvalid()) {
429 S.Diag(AwaitReady->getDirectCallee()->getLocStart(),
430 diag::note_await_ready_no_bool_conversion);
431 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
432 << AwaitReady->getDirectCallee() << E->getSourceRange();
433 Calls.IsInvalid = true;
434 }
435 Calls.Results[ACT::ACT_Ready] = Conv.get();
436 }
437 CallExpr *AwaitSuspend = cast<CallExpr>(Calls.Results[ACT::ACT_Suspend]);
438 if (!AwaitSuspend->getType()->isDependentType()) {
439 // [expr.await]p3 [...]
440 // - await-suspend is the expression e.await_suspend(h), which shall be
441 // a prvalue of type void or bool.
Eric Fiselier84ee7ff2017-05-31 23:41:11 +0000442 QualType RetType = AwaitSuspend->getCallReturnType(S.Context);
Gor Nishanovdb419a62017-09-05 19:31:52 +0000443
Gor Nishanov0f333002017-08-25 04:46:54 +0000444 // Experimental support for coroutine_handle returning await_suspend.
445 if (Expr *TailCallSuspend = maybeTailCall(S, RetType, AwaitSuspend, Loc))
446 Calls.Results[ACT::ACT_Suspend] = TailCallSuspend;
447 else {
448 // non-class prvalues always have cv-unqualified types
Gor Nishanov0f333002017-08-25 04:46:54 +0000449 if (RetType->isReferenceType() ||
Gor Nishanovdb419a62017-09-05 19:31:52 +0000450 (!RetType->isBooleanType() && !RetType->isVoidType())) {
Gor Nishanov0f333002017-08-25 04:46:54 +0000451 S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
452 diag::err_await_suspend_invalid_return_type)
453 << RetType;
454 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
455 << AwaitSuspend->getDirectCallee();
456 Calls.IsInvalid = true;
457 }
Eric Fiselierd978e532017-05-28 18:21:12 +0000458 }
459 }
460
Richard Smith9f690bd2015-10-27 06:02:45 +0000461 return Calls;
462}
463
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000464static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
465 SourceLocation Loc, StringRef Name,
466 MultiExprArg Args) {
467
468 // Form a reference to the promise.
469 ExprResult PromiseRef = S.BuildDeclRefExpr(
470 Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
471 if (PromiseRef.isInvalid())
472 return ExprError();
473
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000474 return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
475}
476
477VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
478 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
479 auto *FD = cast<FunctionDecl>(CurContext);
Eric Fiselier166c6e62017-07-10 01:27:22 +0000480 bool IsThisDependentType = [&] {
481 if (auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD))
482 return MD->isInstance() && MD->getThisType(Context)->isDependentType();
483 else
484 return false;
485 }();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000486
Eric Fiselier166c6e62017-07-10 01:27:22 +0000487 QualType T = FD->getType()->isDependentType() || IsThisDependentType
488 ? Context.DependentTy
489 : lookupPromiseType(*this, FD, Loc);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000490 if (T.isNull())
491 return nullptr;
492
493 auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
494 &PP.getIdentifierTable().get("__promise"), T,
495 Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
496 CheckVariableDeclarationType(VD);
497 if (VD->isInvalidDecl())
498 return nullptr;
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000499
500 auto *ScopeInfo = getCurFunction();
501 // Build a list of arguments, based on the coroutine functions arguments,
502 // that will be passed to the promise type's constructor.
503 llvm::SmallVector<Expr *, 4> CtorArgExprs;
504 auto &Moves = ScopeInfo->CoroutineParameterMoves;
505 for (auto *PD : FD->parameters()) {
506 if (PD->getType()->isDependentType())
507 continue;
508
509 auto RefExpr = ExprEmpty();
510 auto Move = Moves.find(PD);
Brian Gesiak98606222018-02-15 20:37:22 +0000511 assert(Move != Moves.end() &&
512 "Coroutine function parameter not inserted into move map");
513 // If a reference to the function parameter exists in the coroutine
514 // frame, use that reference.
515 auto *MoveDecl =
516 cast<VarDecl>(cast<DeclStmt>(Move->second)->getSingleDecl());
517 RefExpr =
518 BuildDeclRefExpr(MoveDecl, MoveDecl->getType().getNonReferenceType(),
519 ExprValueKind::VK_LValue, FD->getLocation());
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000520 if (RefExpr.isInvalid())
521 return nullptr;
522 CtorArgExprs.push_back(RefExpr.get());
523 }
524
525 // Create an initialization sequence for the promise type using the
526 // constructor arguments, wrapped in a parenthesized list expression.
527 Expr *PLE = new (Context) ParenListExpr(Context, FD->getLocation(),
528 CtorArgExprs, FD->getLocation());
529 InitializedEntity Entity = InitializedEntity::InitializeVariable(VD);
530 InitializationKind Kind = InitializationKind::CreateForInit(
531 VD->getLocation(), /*DirectInit=*/true, PLE);
532 InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs,
533 /*TopLevelOfInitList=*/false,
534 /*TreatUnavailableAsInvalid=*/false);
535
536 // Attempt to initialize the promise type with the arguments.
537 // If that fails, fall back to the promise type's default constructor.
538 if (InitSeq) {
539 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, CtorArgExprs);
540 if (Result.isInvalid()) {
541 VD->setInvalidDecl();
542 } else if (Result.get()) {
543 VD->setInit(MaybeCreateExprWithCleanups(Result.get()));
544 VD->setInitStyle(VarDecl::CallInit);
545 CheckCompleteVariableDeclaration(VD);
546 }
547 } else
548 ActOnUninitializedDecl(VD);
549
Eric Fiselier37b8a372017-05-31 19:36:59 +0000550 FD->addDecl(VD);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000551 return VD;
552}
553
554/// Check that this is a context in which a coroutine suspension can appear.
555static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000556 StringRef Keyword,
557 bool IsImplicit = false) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000558 if (!isValidCoroutineContext(S, Loc, Keyword))
559 return nullptr;
560
561 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000562
563 auto *ScopeInfo = S.getCurFunction();
564 assert(ScopeInfo && "missing function scope for function");
565
Eric Fiseliercac0a592017-03-11 02:35:37 +0000566 if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
567 ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
568
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000569 if (ScopeInfo->CoroutinePromise)
570 return ScopeInfo;
571
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000572 if (!S.buildCoroutineParameterMoves(Loc))
573 return nullptr;
574
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000575 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
576 if (!ScopeInfo->CoroutinePromise)
577 return nullptr;
578
579 return ScopeInfo;
580}
581
Eric Fiselierb936a392017-06-14 03:24:55 +0000582bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc,
583 StringRef Keyword) {
584 if (!checkCoroutineContext(*this, KWLoc, Keyword))
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000585 return false;
Eric Fiselierb936a392017-06-14 03:24:55 +0000586 auto *ScopeInfo = getCurFunction();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000587 assert(ScopeInfo->CoroutinePromise);
588
589 // If we have existing coroutine statements then we have already built
590 // the initial and final suspend points.
591 if (!ScopeInfo->NeedsCoroutineSuspends)
592 return true;
593
594 ScopeInfo->setNeedsCoroutineSuspends(false);
595
Eric Fiselierb936a392017-06-14 03:24:55 +0000596 auto *Fn = cast<FunctionDecl>(CurContext);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000597 SourceLocation Loc = Fn->getLocation();
598 // Build the initial suspend point
599 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
600 ExprResult Suspend =
Eric Fiselierb936a392017-06-14 03:24:55 +0000601 buildPromiseCall(*this, ScopeInfo->CoroutinePromise, Loc, Name, None);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000602 if (Suspend.isInvalid())
603 return StmtError();
Eric Fiselierb936a392017-06-14 03:24:55 +0000604 Suspend = buildOperatorCoawaitCall(*this, SC, Loc, Suspend.get());
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000605 if (Suspend.isInvalid())
606 return StmtError();
Eric Fiselierb936a392017-06-14 03:24:55 +0000607 Suspend = BuildResolvedCoawaitExpr(Loc, Suspend.get(),
608 /*IsImplicit*/ true);
609 Suspend = ActOnFinishFullExpr(Suspend.get());
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000610 if (Suspend.isInvalid()) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000611 Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000612 << ((Name == "initial_suspend") ? 0 : 1);
Eric Fiselierb936a392017-06-14 03:24:55 +0000613 Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000614 return StmtError();
615 }
616 return cast<Stmt>(Suspend.get());
617 };
618
619 StmtResult InitSuspend = buildSuspends("initial_suspend");
620 if (InitSuspend.isInvalid())
621 return true;
622
623 StmtResult FinalSuspend = buildSuspends("final_suspend");
624 if (FinalSuspend.isInvalid())
625 return true;
626
627 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
628
629 return true;
630}
631
Richard Smith9f690bd2015-10-27 06:02:45 +0000632ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000633 if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000634 CorrectDelayedTyposInExpr(E);
635 return ExprError();
636 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000637
Richard Smith10610f72015-11-20 22:57:24 +0000638 if (E->getType()->isPlaceholderType()) {
639 ExprResult R = CheckPlaceholderExpr(E);
640 if (R.isInvalid()) return ExprError();
641 E = R.get();
642 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000643 ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
644 if (Lookup.isInvalid())
645 return ExprError();
646 return BuildUnresolvedCoawaitExpr(Loc, E,
647 cast<UnresolvedLookupExpr>(Lookup.get()));
648}
Richard Smith10610f72015-11-20 22:57:24 +0000649
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000650ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000651 UnresolvedLookupExpr *Lookup) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000652 auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
653 if (!FSI)
654 return ExprError();
655
656 if (E->getType()->isPlaceholderType()) {
657 ExprResult R = CheckPlaceholderExpr(E);
658 if (R.isInvalid())
659 return ExprError();
660 E = R.get();
661 }
662
663 auto *Promise = FSI->CoroutinePromise;
664 if (Promise->getType()->isDependentType()) {
665 Expr *Res =
666 new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000667 return Res;
668 }
669
670 auto *RD = Promise->getType()->getAsCXXRecordDecl();
671 if (lookupMember(*this, "await_transform", RD, Loc)) {
672 ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
673 if (R.isInvalid()) {
674 Diag(Loc,
675 diag::note_coroutine_promise_implicit_await_transform_required_here)
676 << E->getSourceRange();
677 return ExprError();
678 }
679 E = R.get();
680 }
681 ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
Richard Smith9f690bd2015-10-27 06:02:45 +0000682 if (Awaitable.isInvalid())
683 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000684
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000685 return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
Richard Smith9f690bd2015-10-27 06:02:45 +0000686}
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000687
688ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E,
689 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000690 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
Richard Smith744b2242015-11-20 02:54:01 +0000691 if (!Coroutine)
692 return ExprError();
Richard Smith9f690bd2015-10-27 06:02:45 +0000693
Richard Smith9f690bd2015-10-27 06:02:45 +0000694 if (E->getType()->isPlaceholderType()) {
695 ExprResult R = CheckPlaceholderExpr(E);
696 if (R.isInvalid()) return ExprError();
697 E = R.get();
698 }
699
Richard Smith10610f72015-11-20 22:57:24 +0000700 if (E->getType()->isDependentType()) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000701 Expr *Res = new (Context)
702 CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
Richard Smith10610f72015-11-20 22:57:24 +0000703 return Res;
704 }
705
Richard Smith1f38edd2015-11-22 03:13:02 +0000706 // If the expression is a temporary, materialize it as an lvalue so that we
707 // can use it multiple times.
708 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000709 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smith9f690bd2015-10-27 06:02:45 +0000710
711 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000712 ReadySuspendResumeResult RSS =
713 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000714 if (RSS.IsInvalid)
715 return ExprError();
716
Gor Nishanovce43bd22017-03-11 01:30:17 +0000717 Expr *Res =
718 new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
719 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000720
Richard Smithcfd53b42015-10-22 06:13:50 +0000721 return Res;
722}
723
Richard Smith9f690bd2015-10-27 06:02:45 +0000724ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000725 if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000726 CorrectDelayedTyposInExpr(E);
Richard Smith23da82c2015-11-20 22:40:06 +0000727 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000728 }
Richard Smith23da82c2015-11-20 22:40:06 +0000729
730 // Build yield_value call.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000731 ExprResult Awaitable = buildPromiseCall(
732 *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000733 if (Awaitable.isInvalid())
734 return ExprError();
Richard Smith23da82c2015-11-20 22:40:06 +0000735
736 // Build 'operator co_await' call.
737 Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
738 if (Awaitable.isInvalid())
739 return ExprError();
740
Richard Smith9f690bd2015-10-27 06:02:45 +0000741 return BuildCoyieldExpr(Loc, Awaitable.get());
742}
743ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
744 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
Richard Smith744b2242015-11-20 02:54:01 +0000745 if (!Coroutine)
746 return ExprError();
Richard Smithcfd53b42015-10-22 06:13:50 +0000747
Richard Smith10610f72015-11-20 22:57:24 +0000748 if (E->getType()->isPlaceholderType()) {
749 ExprResult R = CheckPlaceholderExpr(E);
750 if (R.isInvalid()) return ExprError();
751 E = R.get();
752 }
753
Richard Smithd7bed4d2015-11-22 02:57:17 +0000754 if (E->getType()->isDependentType()) {
755 Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000756 return Res;
757 }
758
Richard Smith1f38edd2015-11-22 03:13:02 +0000759 // If the expression is a temporary, materialize it as an lvalue so that we
760 // can use it multiple times.
761 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000762 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000763
764 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000765 ReadySuspendResumeResult RSS =
766 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000767 if (RSS.IsInvalid)
768 return ExprError();
769
Eric Fiselierb936a392017-06-14 03:24:55 +0000770 Expr *Res =
771 new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
772 RSS.Results[2], RSS.OpaqueValue);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000773
Richard Smithcfd53b42015-10-22 06:13:50 +0000774 return Res;
775}
776
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000777StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselierb936a392017-06-14 03:24:55 +0000778 if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000779 CorrectDelayedTyposInExpr(E);
780 return StmtError();
781 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000782 return BuildCoreturnStmt(Loc, E);
783}
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000784
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000785StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
786 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000787 auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000788 if (!FSI)
Richard Smith71d403e2015-11-22 07:33:28 +0000789 return StmtError();
790
791 if (E && E->getType()->isPlaceholderType() &&
792 !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
Richard Smith10610f72015-11-20 22:57:24 +0000793 ExprResult R = CheckPlaceholderExpr(E);
794 if (R.isInvalid()) return StmtError();
795 E = R.get();
796 }
797
Richard Smith4ba66602015-11-22 07:05:16 +0000798 // FIXME: If the operand is a reference to a variable that's about to go out
Richard Smith2af65c42015-11-24 02:34:39 +0000799 // of scope, we should treat the operand as an xvalue for this overload
Richard Smith4ba66602015-11-22 07:05:16 +0000800 // resolution.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000801 VarDecl *Promise = FSI->CoroutinePromise;
Richard Smith4ba66602015-11-22 07:05:16 +0000802 ExprResult PC;
Eric Fiselier98131312016-10-06 21:23:38 +0000803 if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000804 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
Richard Smith4ba66602015-11-22 07:05:16 +0000805 } else {
806 E = MakeFullDiscardedValueExpr(E).get();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000807 PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
Richard Smith4ba66602015-11-22 07:05:16 +0000808 }
809 if (PC.isInvalid())
810 return StmtError();
811
812 Expr *PCE = ActOnFinishFullExpr(PC.get()).get();
813
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000814 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
Richard Smithcfd53b42015-10-22 06:13:50 +0000815 return Res;
816}
817
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000818/// Look up the std::nothrow object.
819static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
820 NamespaceDecl *Std = S.getStdNamespace();
821 assert(Std && "Should already be diagnosed");
822
823 LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
824 Sema::LookupOrdinaryName);
825 if (!S.LookupQualifiedName(Result, Std)) {
826 // FIXME: <experimental/coroutine> should have been included already.
827 // If we require it to include <new> then this diagnostic is no longer
828 // needed.
829 S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
830 return nullptr;
831 }
832
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000833 auto *VD = Result.getAsSingle<VarDecl>();
834 if (!VD) {
835 Result.suppressDiagnostics();
836 // We found something weird. Complain about the first thing we found.
837 NamedDecl *Found = *Result.begin();
838 S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
839 return nullptr;
840 }
841
842 ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
843 if (DR.isInvalid())
844 return nullptr;
845
846 return DR.get();
847}
848
Gor Nishanov8df64e92016-10-27 16:28:31 +0000849// Find an appropriate delete for the promise.
850static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc,
851 QualType PromiseType) {
852 FunctionDecl *OperatorDelete = nullptr;
853
854 DeclarationName DeleteName =
855 S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
856
857 auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
858 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
859
860 if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
861 return nullptr;
862
863 if (!OperatorDelete) {
864 // Look for a global declaration.
865 const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
866 const bool Overaligned = false;
867 OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
868 Overaligned, DeleteName);
869 }
870 S.MarkFunctionReferenced(Loc, OperatorDelete);
871 return OperatorDelete;
872}
873
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000874
875void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
876 FunctionScopeInfo *Fn = getCurFunction();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000877 assert(Fn && Fn->isCoroutine() && "not a coroutine");
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000878 if (!Body) {
879 assert(FD->isInvalidDecl() &&
880 "a null body is only allowed for invalid declarations");
881 return;
882 }
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000883 // We have a function that uses coroutine keywords, but we failed to build
884 // the promise type.
885 if (!Fn->CoroutinePromise)
886 return FD->setInvalidDecl();
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000887
888 if (isa<CoroutineBodyStmt>(Body)) {
Gor Nishanov29ff6382017-05-24 14:34:19 +0000889 // Nothing todo. the body is already a transformed coroutine body statement.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000890 return;
891 }
892
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000893 // Coroutines [stmt.return]p1:
894 // A return statement shall not appear in a coroutine.
895 if (Fn->FirstReturnLoc.isValid()) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000896 assert(Fn->FirstCoroutineStmtLoc.isValid() &&
897 "first coroutine location not set");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000898 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000899 Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
900 << Fn->getFirstCoroutineStmtKeyword();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000901 }
Eric Fiselierbee782b2017-04-03 19:21:00 +0000902 CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
903 if (Builder.isInvalid() || !Builder.buildStatements())
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000904 return FD->setInvalidDecl();
905
906 // Build body for the coroutine wrapper statement.
907 Body = CoroutineBodyStmt::Create(Context, Builder);
908}
909
Eric Fiselierbee782b2017-04-03 19:21:00 +0000910CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
911 sema::FunctionScopeInfo &Fn,
912 Stmt *Body)
913 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
914 IsPromiseDependentType(
915 !Fn.CoroutinePromise ||
916 Fn.CoroutinePromise->getType()->isDependentType()) {
917 this->Body = Body;
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000918
919 for (auto KV : Fn.CoroutineParameterMoves)
920 this->ParamMovesVector.push_back(KV.second);
921 this->ParamMoves = this->ParamMovesVector;
922
Eric Fiselierbee782b2017-04-03 19:21:00 +0000923 if (!IsPromiseDependentType) {
924 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
925 assert(PromiseRecordDecl && "Type should have already been checked");
926 }
927 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
928}
929
930bool CoroutineStmtBuilder::buildStatements() {
931 assert(this->IsValid && "coroutine already invalid");
Brian Gesiak61f4ac92018-01-24 22:15:42 +0000932 this->IsValid = makeReturnObject();
Eric Fiselierbee782b2017-04-03 19:21:00 +0000933 if (this->IsValid && !IsPromiseDependentType)
934 buildDependentStatements();
935 return this->IsValid;
936}
937
938bool CoroutineStmtBuilder::buildDependentStatements() {
939 assert(this->IsValid && "coroutine already invalid");
940 assert(!this->IsPromiseDependentType &&
941 "coroutine cannot have a dependent promise type");
942 this->IsValid = makeOnException() && makeOnFallthrough() &&
Gor Nishanov6a470682017-05-22 20:22:23 +0000943 makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
944 makeNewAndDeleteExpr();
Eric Fiselierbee782b2017-04-03 19:21:00 +0000945 return this->IsValid;
946}
947
948bool CoroutineStmtBuilder::makePromiseStmt() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000949 // Form a declaration statement for the promise declaration, so that AST
950 // visitors can more easily find it.
951 StmtResult PromiseStmt =
952 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
953 if (PromiseStmt.isInvalid())
954 return false;
955
956 this->Promise = PromiseStmt.get();
957 return true;
958}
959
Eric Fiselierbee782b2017-04-03 19:21:00 +0000960bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000961 if (Fn.hasInvalidCoroutineSuspends())
962 return false;
963 this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
964 this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
965 return true;
966}
967
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000968static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
969 CXXRecordDecl *PromiseRecordDecl,
970 FunctionScopeInfo &Fn) {
971 auto Loc = E->getExprLoc();
972 if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
973 auto *Decl = DeclRef->getDecl();
974 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
975 if (Method->isStatic())
976 return true;
977 else
978 Loc = Decl->getLocation();
979 }
980 }
981
982 S.Diag(
983 Loc,
984 diag::err_coroutine_promise_get_return_object_on_allocation_failure)
985 << PromiseRecordDecl;
986 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
987 << Fn.getFirstCoroutineStmtKeyword();
988 return false;
989}
990
Eric Fiselierbee782b2017-04-03 19:21:00 +0000991bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
992 assert(!IsPromiseDependentType &&
993 "cannot make statement while the promise type is dependent");
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000994
995 // [dcl.fct.def.coroutine]/8
996 // The unqualified-id get_return_object_on_allocation_failure is looked up in
997 // the scope of class P by class member access lookup (3.4.5). ...
998 // If an allocation function returns nullptr, ... the coroutine return value
999 // is obtained by a call to ... get_return_object_on_allocation_failure().
1000
1001 DeclarationName DN =
1002 S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
1003 LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
Eric Fiselierbee782b2017-04-03 19:21:00 +00001004 if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
1005 return true;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001006
1007 CXXScopeSpec SS;
1008 ExprResult DeclNameExpr =
1009 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
Eric Fiselierbee782b2017-04-03 19:21:00 +00001010 if (DeclNameExpr.isInvalid())
1011 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001012
1013 if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
1014 return false;
1015
1016 ExprResult ReturnObjectOnAllocationFailure =
1017 S.ActOnCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
Eric Fiselierbee782b2017-04-03 19:21:00 +00001018 if (ReturnObjectOnAllocationFailure.isInvalid())
1019 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001020
Gor Nishanovc4a19082017-03-28 02:51:45 +00001021 StmtResult ReturnStmt =
1022 S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
Gor Nishanov6a470682017-05-22 20:22:23 +00001023 if (ReturnStmt.isInvalid()) {
Eric Fiselierfc50f622017-05-25 14:59:39 +00001024 S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
1025 << DN;
Gor Nishanov6a470682017-05-22 20:22:23 +00001026 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1027 << Fn.getFirstCoroutineStmtKeyword();
Eric Fiselierbee782b2017-04-03 19:21:00 +00001028 return false;
Gor Nishanov6a470682017-05-22 20:22:23 +00001029 }
Gor Nishanov3aa9eb32017-03-27 23:36:59 +00001030
1031 this->ReturnStmtOnAllocFailure = ReturnStmt.get();
1032 return true;
1033}
1034
Eric Fiselierbee782b2017-04-03 19:21:00 +00001035bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001036 // Form and check allocation and deallocation calls.
Eric Fiselierbee782b2017-04-03 19:21:00 +00001037 assert(!IsPromiseDependentType &&
1038 "cannot make statement while the promise type is dependent");
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001039 QualType PromiseType = Fn.CoroutinePromise->getType();
Gor Nishanov8df64e92016-10-27 16:28:31 +00001040
1041 if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
1042 return false;
1043
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001044 const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
1045
Brian Gesiak98606222018-02-15 20:37:22 +00001046 // [dcl.fct.def.coroutine]/7
1047 // Lookup allocation functions using a parameter list composed of the
1048 // requested size of the coroutine state being allocated, followed by
1049 // the coroutine function's arguments. If a matching allocation function
1050 // exists, use it. Otherwise, use an allocation function that just takes
1051 // the requested size.
Gor Nishanov8df64e92016-10-27 16:28:31 +00001052
1053 FunctionDecl *OperatorNew = nullptr;
1054 FunctionDecl *OperatorDelete = nullptr;
1055 FunctionDecl *UnusedResult = nullptr;
1056 bool PassAlignment = false;
Eric Fiselierf747f532017-04-18 05:08:08 +00001057 SmallVector<Expr *, 1> PlacementArgs;
Gor Nishanov8df64e92016-10-27 16:28:31 +00001058
Brian Gesiak98606222018-02-15 20:37:22 +00001059 // [dcl.fct.def.coroutine]/7
1060 // "The allocation function’s name is looked up in the scope of P.
1061 // [...] If the lookup finds an allocation function in the scope of P,
1062 // overload resolution is performed on a function call created by assembling
1063 // an argument list. The first argument is the amount of space requested,
1064 // and has type std::size_t. The lvalues p1 ... pn are the succeeding
1065 // arguments."
1066 //
1067 // ...where "p1 ... pn" are defined earlier as:
1068 //
1069 // [dcl.fct.def.coroutine]/3
1070 // "For a coroutine f that is a non-static member function, let P1 denote the
1071 // type of the implicit object parameter (13.3.1) and P2 ... Pn be the types
1072 // of the function parameters; otherwise let P1 ... Pn be the types of the
1073 // function parameters. Let p1 ... pn be lvalues denoting those objects."
1074 if (auto *MD = dyn_cast<CXXMethodDecl>(&FD)) {
1075 if (MD->isInstance() && !isLambdaCallOperator(MD)) {
1076 ExprResult ThisExpr = S.ActOnCXXThis(Loc);
1077 if (ThisExpr.isInvalid())
1078 return false;
1079 ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
1080 if (ThisExpr.isInvalid())
1081 return false;
1082 PlacementArgs.push_back(ThisExpr.get());
1083 }
1084 }
1085 for (auto *PD : FD.parameters()) {
1086 if (PD->getType()->isDependentType())
1087 continue;
1088
1089 // Build a reference to the parameter.
1090 auto PDLoc = PD->getLocation();
1091 ExprResult PDRefExpr =
1092 S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),
1093 ExprValueKind::VK_LValue, PDLoc);
1094 if (PDRefExpr.isInvalid())
1095 return false;
1096
1097 PlacementArgs.push_back(PDRefExpr.get());
1098 }
Gor Nishanov8df64e92016-10-27 16:28:31 +00001099 S.FindAllocationFunctions(Loc, SourceRange(),
1100 /*UseGlobal*/ false, PromiseType,
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001101 /*isArray*/ false, PassAlignment, PlacementArgs,
Brian Gesiak98606222018-02-15 20:37:22 +00001102 OperatorNew, UnusedResult, /*Diagnose*/ false);
1103
1104 // [dcl.fct.def.coroutine]/7
1105 // "If no matching function is found, overload resolution is performed again
1106 // on a function call created by passing just the amount of space required as
1107 // an argument of type std::size_t."
1108 if (!OperatorNew && !PlacementArgs.empty()) {
1109 PlacementArgs.clear();
1110 S.FindAllocationFunctions(Loc, SourceRange(),
1111 /*UseGlobal*/ false, PromiseType,
1112 /*isArray*/ false, PassAlignment,
1113 PlacementArgs, OperatorNew, UnusedResult);
1114 }
Gor Nishanov8df64e92016-10-27 16:28:31 +00001115
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001116 bool IsGlobalOverload =
1117 OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
1118 // If we didn't find a class-local new declaration and non-throwing new
1119 // was is required then we need to lookup the non-throwing global operator
1120 // instead.
1121 if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
1122 auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
1123 if (!StdNoThrow)
1124 return false;
Eric Fiselierf747f532017-04-18 05:08:08 +00001125 PlacementArgs = {StdNoThrow};
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001126 OperatorNew = nullptr;
1127 S.FindAllocationFunctions(Loc, SourceRange(),
1128 /*UseGlobal*/ true, PromiseType,
1129 /*isArray*/ false, PassAlignment, PlacementArgs,
1130 OperatorNew, UnusedResult);
1131 }
Gor Nishanov8df64e92016-10-27 16:28:31 +00001132
Brian Gesiak98606222018-02-15 20:37:22 +00001133 if (!OperatorNew)
1134 return false;
Eric Fiselierc5128752017-04-18 05:30:39 +00001135
1136 if (RequiresNoThrowAlloc) {
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001137 const auto *FT = OperatorNew->getType()->getAs<FunctionProtoType>();
1138 if (!FT->isNothrow(S.Context, /*ResultIfDependent*/ false)) {
1139 S.Diag(OperatorNew->getLocation(),
1140 diag::err_coroutine_promise_new_requires_nothrow)
1141 << OperatorNew;
1142 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
1143 << OperatorNew;
1144 return false;
1145 }
1146 }
1147
1148 if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr)
Gor Nishanov8df64e92016-10-27 16:28:31 +00001149 return false;
1150
1151 Expr *FramePtr =
1152 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
1153
1154 Expr *FrameSize =
1155 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {});
1156
1157 // Make new call.
1158
1159 ExprResult NewRef =
1160 S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
1161 if (NewRef.isInvalid())
1162 return false;
1163
Eric Fiselierf747f532017-04-18 05:08:08 +00001164 SmallVector<Expr *, 2> NewArgs(1, FrameSize);
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001165 for (auto Arg : PlacementArgs)
1166 NewArgs.push_back(Arg);
1167
Gor Nishanov8df64e92016-10-27 16:28:31 +00001168 ExprResult NewExpr =
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001169 S.ActOnCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
1170 NewExpr = S.ActOnFinishFullExpr(NewExpr.get());
Gor Nishanov8df64e92016-10-27 16:28:31 +00001171 if (NewExpr.isInvalid())
1172 return false;
1173
Gor Nishanov8df64e92016-10-27 16:28:31 +00001174 // Make delete call.
1175
1176 QualType OpDeleteQualType = OperatorDelete->getType();
1177
1178 ExprResult DeleteRef =
1179 S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
1180 if (DeleteRef.isInvalid())
1181 return false;
1182
1183 Expr *CoroFree =
1184 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr});
1185
1186 SmallVector<Expr *, 2> DeleteArgs{CoroFree};
1187
1188 // Check if we need to pass the size.
1189 const auto *OpDeleteType =
1190 OpDeleteQualType.getTypePtr()->getAs<FunctionProtoType>();
1191 if (OpDeleteType->getNumParams() > 1)
1192 DeleteArgs.push_back(FrameSize);
1193
1194 ExprResult DeleteExpr =
1195 S.ActOnCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001196 DeleteExpr = S.ActOnFinishFullExpr(DeleteExpr.get());
Gor Nishanov8df64e92016-10-27 16:28:31 +00001197 if (DeleteExpr.isInvalid())
1198 return false;
1199
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001200 this->Allocate = NewExpr.get();
1201 this->Deallocate = DeleteExpr.get();
Gor Nishanov8df64e92016-10-27 16:28:31 +00001202
1203 return true;
1204}
1205
Eric Fiselierbee782b2017-04-03 19:21:00 +00001206bool CoroutineStmtBuilder::makeOnFallthrough() {
1207 assert(!IsPromiseDependentType &&
1208 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001209
1210 // [dcl.fct.def.coroutine]/4
1211 // The unqualified-ids 'return_void' and 'return_value' are looked up in
1212 // the scope of class P. If both are found, the program is ill-formed.
Eric Fiselierfc50f622017-05-25 14:59:39 +00001213 bool HasRVoid, HasRValue;
1214 LookupResult LRVoid =
1215 lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
1216 LookupResult LRValue =
1217 lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001218
Eric Fiselier709d1b32016-10-27 07:30:31 +00001219 StmtResult Fallthrough;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001220 if (HasRVoid && HasRValue) {
1221 // FIXME Improve this diagnostic
Eric Fiselierfc50f622017-05-25 14:59:39 +00001222 S.Diag(FD.getLocation(),
1223 diag::err_coroutine_promise_incompatible_return_functions)
1224 << PromiseRecordDecl;
1225 S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
1226 diag::note_member_first_declared_here)
1227 << LRVoid.getLookupName();
1228 S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
1229 diag::note_member_first_declared_here)
1230 << LRValue.getLookupName();
1231 return false;
1232 } else if (!HasRVoid && !HasRValue) {
1233 // FIXME: The PDTS currently specifies this case as UB, not ill-formed.
1234 // However we still diagnose this as an error since until the PDTS is fixed.
1235 S.Diag(FD.getLocation(),
1236 diag::err_coroutine_promise_requires_return_function)
1237 << PromiseRecordDecl;
1238 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001239 << PromiseRecordDecl;
1240 return false;
1241 } else if (HasRVoid) {
1242 // If the unqualified-id return_void is found, flowing off the end of a
1243 // coroutine is equivalent to a co_return with no operand. Otherwise,
1244 // flowing off the end of a coroutine results in undefined behavior.
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001245 Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
1246 /*IsImplicit*/false);
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001247 Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
1248 if (Fallthrough.isInvalid())
1249 return false;
Eric Fiselier709d1b32016-10-27 07:30:31 +00001250 }
Richard Smith2af65c42015-11-24 02:34:39 +00001251
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001252 this->OnFallthrough = Fallthrough.get();
1253 return true;
1254}
1255
Eric Fiselierbee782b2017-04-03 19:21:00 +00001256bool CoroutineStmtBuilder::makeOnException() {
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001257 // Try to form 'p.unhandled_exception();'
Eric Fiselierbee782b2017-04-03 19:21:00 +00001258 assert(!IsPromiseDependentType &&
1259 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001260
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001261 const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1262
1263 if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
1264 auto DiagID =
1265 RequireUnhandledException
1266 ? diag::err_coroutine_promise_unhandled_exception_required
1267 : diag::
1268 warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1269 S.Diag(Loc, DiagID) << PromiseRecordDecl;
Gor Nishanov29ff6382017-05-24 14:34:19 +00001270 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1271 << PromiseRecordDecl;
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001272 return !RequireUnhandledException;
1273 }
1274
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001275 // If exceptions are disabled, don't try to build OnException.
1276 if (!S.getLangOpts().CXXExceptions)
1277 return true;
1278
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001279 ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
1280 "unhandled_exception", None);
1281 UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc);
1282 if (UnhandledException.isInvalid())
1283 return false;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001284
Gor Nishanov5b050e42017-05-22 22:33:17 +00001285 // Since the body of the coroutine will be wrapped in try-catch, it will
1286 // be incompatible with SEH __try if present in a function.
1287 if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1288 S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1289 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1290 << Fn.getFirstCoroutineStmtKeyword();
1291 return false;
1292 }
1293
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001294 this->OnException = UnhandledException.get();
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001295 return true;
1296}
1297
Eric Fiselierbee782b2017-04-03 19:21:00 +00001298bool CoroutineStmtBuilder::makeReturnObject() {
Richard Smith2af65c42015-11-24 02:34:39 +00001299 // Build implicit 'p.get_return_object()' expression and form initialization
1300 // of return type from it.
1301 ExprResult ReturnObject =
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001302 buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
Richard Smith2af65c42015-11-24 02:34:39 +00001303 if (ReturnObject.isInvalid())
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001304 return false;
Richard Smith2af65c42015-11-24 02:34:39 +00001305
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001306 this->ReturnValue = ReturnObject.get();
1307 return true;
1308}
1309
Gor Nishanov6a470682017-05-22 20:22:23 +00001310static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
1311 if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
1312 auto *MethodDecl = MbrRef->getMethodDecl();
Eric Fiselierfc50f622017-05-25 14:59:39 +00001313 S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
1314 << MethodDecl;
Gor Nishanov6a470682017-05-22 20:22:23 +00001315 }
1316 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1317 << Fn.getFirstCoroutineStmtKeyword();
1318}
1319
1320bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1321 assert(!IsPromiseDependentType &&
1322 "cannot make statement while the promise type is dependent");
1323 assert(this->ReturnValue && "ReturnValue must be already formed");
1324
1325 QualType const GroType = this->ReturnValue->getType();
1326 assert(!GroType->isDependentType() &&
1327 "get_return_object type must no longer be dependent");
1328
1329 QualType const FnRetType = FD.getReturnType();
1330 assert(!FnRetType->isDependentType() &&
1331 "get_return_object type must no longer be dependent");
1332
1333 if (FnRetType->isVoidType()) {
1334 ExprResult Res = S.ActOnFinishFullExpr(this->ReturnValue, Loc);
1335 if (Res.isInvalid())
1336 return false;
1337
1338 this->ResultDecl = Res.get();
1339 return true;
1340 }
1341
1342 if (GroType->isVoidType()) {
1343 // Trigger a nice error message.
1344 InitializedEntity Entity =
1345 InitializedEntity::InitializeResult(Loc, FnRetType, false);
1346 S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue);
1347 noteMemberDeclaredHere(S, ReturnValue, Fn);
1348 return false;
1349 }
1350
1351 auto *GroDecl = VarDecl::Create(
1352 S.Context, &FD, FD.getLocation(), FD.getLocation(),
1353 &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
1354 S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
1355
1356 S.CheckVariableDeclarationType(GroDecl);
1357 if (GroDecl->isInvalidDecl())
1358 return false;
1359
1360 InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
1361 ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType,
1362 this->ReturnValue);
1363 if (Res.isInvalid())
1364 return false;
1365
1366 Res = S.ActOnFinishFullExpr(Res.get());
1367 if (Res.isInvalid())
1368 return false;
1369
Gor Nishanov6a470682017-05-22 20:22:23 +00001370 S.AddInitializerToDecl(GroDecl, Res.get(),
1371 /*DirectInit=*/false);
1372
1373 S.FinalizeDeclaration(GroDecl);
1374
1375 // Form a declaration statement for the return declaration, so that AST
1376 // visitors can more easily find it.
1377 StmtResult GroDeclStmt =
1378 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
1379 if (GroDeclStmt.isInvalid())
1380 return false;
1381
1382 this->ResultDecl = GroDeclStmt.get();
1383
1384 ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
1385 if (declRef.isInvalid())
1386 return false;
1387
1388 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
1389 if (ReturnStmt.isInvalid()) {
1390 noteMemberDeclaredHere(S, ReturnValue, Fn);
1391 return false;
1392 }
Eric Fiselier8ed97272018-02-01 23:47:54 +00001393 if (cast<clang::ReturnStmt>(ReturnStmt.get())->getNRVOCandidate() == GroDecl)
1394 GroDecl->setNRVOVariable(true);
Gor Nishanov6a470682017-05-22 20:22:23 +00001395
1396 this->ReturnStmt = ReturnStmt.get();
1397 return true;
1398}
1399
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001400// Create a static_cast\<T&&>(expr).
1401static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
1402 if (T.isNull())
1403 T = E->getType();
1404 QualType TargetType = S.BuildReferenceType(
1405 T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());
1406 SourceLocation ExprLoc = E->getLocStart();
1407 TypeSourceInfo *TargetLoc =
1408 S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
1409
1410 return S
1411 .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1412 SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
1413 .get();
1414}
1415
1416/// \brief Build a variable declaration for move parameter.
1417static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
Eric Fiselierde7943b2017-06-03 00:22:18 +00001418 IdentifierInfo *II) {
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001419 TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);
Brian Gesiak61f4ac92018-01-24 22:15:42 +00001420 VarDecl *Decl = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type,
1421 TInfo, SC_None);
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001422 Decl->setImplicit();
1423 return Decl;
1424}
1425
Brian Gesiak61f4ac92018-01-24 22:15:42 +00001426// Build statements that move coroutine function parameters to the coroutine
1427// frame, and store them on the function scope info.
1428bool Sema::buildCoroutineParameterMoves(SourceLocation Loc) {
1429 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
1430 auto *FD = cast<FunctionDecl>(CurContext);
1431
1432 auto *ScopeInfo = getCurFunction();
1433 assert(ScopeInfo->CoroutineParameterMoves.empty() &&
1434 "Should not build parameter moves twice");
1435
1436 for (auto *PD : FD->parameters()) {
1437 if (PD->getType()->isDependentType())
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001438 continue;
1439
Brian Gesiak98606222018-02-15 20:37:22 +00001440 ExprResult PDRefExpr =
1441 BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
1442 ExprValueKind::VK_LValue, Loc); // FIXME: scope?
1443 if (PDRefExpr.isInvalid())
1444 return false;
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001445
Brian Gesiak98606222018-02-15 20:37:22 +00001446 Expr *CExpr = nullptr;
1447 if (PD->getType()->getAsCXXRecordDecl() ||
1448 PD->getType()->isRValueReferenceType())
1449 CExpr = castForMoving(*this, PDRefExpr.get());
1450 else
1451 CExpr = PDRefExpr.get();
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001452
Brian Gesiak98606222018-02-15 20:37:22 +00001453 auto D = buildVarDecl(*this, Loc, PD->getType(), PD->getIdentifier());
1454 AddInitializerToDecl(D, CExpr, /*DirectInit=*/true);
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001455
Brian Gesiak98606222018-02-15 20:37:22 +00001456 // Convert decl to a statement.
1457 StmtResult Stmt = ActOnDeclStmt(ConvertDeclToDeclGroup(D), Loc, Loc);
1458 if (Stmt.isInvalid())
1459 return false;
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001460
Brian Gesiak98606222018-02-15 20:37:22 +00001461 ScopeInfo->CoroutineParameterMoves.insert(std::make_pair(PD, Stmt.get()));
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001462 }
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001463 return true;
Richard Smithcfd53b42015-10-22 06:13:50 +00001464}
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001465
1466StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1467 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
1468 if (!Res)
1469 return StmtError();
1470 return Res;
1471}