blob: b02196500d9bf86046c178ff4d5e5de3ebf16647 [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"
Richard Smith9f690bd2015-10-27 06:02:45 +000015#include "clang/AST/Decl.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/StmtCXX.h"
18#include "clang/Lex/Preprocessor.h"
Richard Smith2af65c42015-11-24 02:34:39 +000019#include "clang/Sema/Initialization.h"
Richard Smith9f690bd2015-10-27 06:02:45 +000020#include "clang/Sema/Overload.h"
Eric Fiselierbee782b2017-04-03 19:21:00 +000021#include "clang/Sema/SemaInternal.h"
22
Richard Smithcfd53b42015-10-22 06:13:50 +000023using namespace clang;
24using namespace sema;
25
Eric Fiselier20f25cb2017-03-06 23:38:15 +000026static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
27 SourceLocation Loc) {
28 DeclarationName DN = S.PP.getIdentifierInfo(Name);
29 LookupResult LR(S, DN, Loc, Sema::LookupMemberName);
30 // Suppress diagnostics when a private member is selected. The same warnings
31 // will be produced again when building the call.
32 LR.suppressDiagnostics();
33 return S.LookupQualifiedName(LR, RD);
34}
35
Richard Smith9f690bd2015-10-27 06:02:45 +000036/// Look up the std::coroutine_traits<...>::promise_type for the given
37/// function type.
38static QualType lookupPromiseType(Sema &S, const FunctionProtoType *FnType,
Eric Fiselier89bf0e72017-03-06 22:52:28 +000039 SourceLocation KwLoc,
40 SourceLocation FuncLoc) {
Richard Smith9f690bd2015-10-27 06:02:45 +000041 // FIXME: Cache std::coroutine_traits once we've found it.
Gor Nishanov3e048bb2016-10-04 00:31:16 +000042 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
43 if (!StdExp) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000044 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
45 << "std::experimental::coroutine_traits";
Richard Smith9f690bd2015-10-27 06:02:45 +000046 return QualType();
47 }
48
49 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_traits"),
Eric Fiselier89bf0e72017-03-06 22:52:28 +000050 FuncLoc, Sema::LookupOrdinaryName);
Gor Nishanov3e048bb2016-10-04 00:31:16 +000051 if (!S.LookupQualifiedName(Result, StdExp)) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000052 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
53 << "std::experimental::coroutine_traits";
Richard Smith9f690bd2015-10-27 06:02:45 +000054 return QualType();
55 }
56
57 ClassTemplateDecl *CoroTraits = Result.getAsSingle<ClassTemplateDecl>();
58 if (!CoroTraits) {
59 Result.suppressDiagnostics();
60 // We found something weird. Complain about the first thing we found.
61 NamedDecl *Found = *Result.begin();
62 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
63 return QualType();
64 }
65
66 // Form template argument list for coroutine_traits<R, P1, P2, ...>.
Eric Fiselier89bf0e72017-03-06 22:52:28 +000067 TemplateArgumentListInfo Args(KwLoc, KwLoc);
Richard Smith9f690bd2015-10-27 06:02:45 +000068 Args.addArgument(TemplateArgumentLoc(
69 TemplateArgument(FnType->getReturnType()),
Eric Fiselier89bf0e72017-03-06 22:52:28 +000070 S.Context.getTrivialTypeSourceInfo(FnType->getReturnType(), KwLoc)));
Richard Smith71d403e2015-11-22 07:33:28 +000071 // FIXME: If the function is a non-static member function, add the type
72 // of the implicit object parameter before the formal parameters.
Richard Smith9f690bd2015-10-27 06:02:45 +000073 for (QualType T : FnType->getParamTypes())
74 Args.addArgument(TemplateArgumentLoc(
Eric Fiselier89bf0e72017-03-06 22:52:28 +000075 TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));
Richard Smith9f690bd2015-10-27 06:02:45 +000076
77 // Build the template-id.
78 QualType CoroTrait =
Eric Fiselier89bf0e72017-03-06 22:52:28 +000079 S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
Richard Smith9f690bd2015-10-27 06:02:45 +000080 if (CoroTrait.isNull())
81 return QualType();
Eric Fiselier89bf0e72017-03-06 22:52:28 +000082 if (S.RequireCompleteType(KwLoc, CoroTrait,
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000083 diag::err_coroutine_type_missing_specialization))
Richard Smith9f690bd2015-10-27 06:02:45 +000084 return QualType();
85
Eric Fiselier89bf0e72017-03-06 22:52:28 +000086 auto *RD = CoroTrait->getAsCXXRecordDecl();
Richard Smith9f690bd2015-10-27 06:02:45 +000087 assert(RD && "specialization of class template is not a class?");
88
89 // Look up the ::promise_type member.
Eric Fiselier89bf0e72017-03-06 22:52:28 +000090 LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
Richard Smith9f690bd2015-10-27 06:02:45 +000091 Sema::LookupOrdinaryName);
92 S.LookupQualifiedName(R, RD);
93 auto *Promise = R.getAsSingle<TypeDecl>();
94 if (!Promise) {
Eric Fiselier89bf0e72017-03-06 22:52:28 +000095 S.Diag(FuncLoc,
96 diag::err_implied_std_coroutine_traits_promise_type_not_found)
Gor Nishanov8df64e92016-10-27 16:28:31 +000097 << RD;
Richard Smith9f690bd2015-10-27 06:02:45 +000098 return QualType();
99 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000100 // The promise type is required to be a class type.
101 QualType PromiseType = S.Context.getTypeDeclType(Promise);
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000102
103 auto buildElaboratedType = [&]() {
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000104 auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, StdExp);
Richard Smith9b2f53e2015-11-19 02:36:35 +0000105 NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
106 CoroTrait.getTypePtr());
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000107 return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
108 };
Richard Smith9b2f53e2015-11-19 02:36:35 +0000109
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000110 if (!PromiseType->getAsCXXRecordDecl()) {
111 S.Diag(FuncLoc,
112 diag::err_implied_std_coroutine_traits_promise_type_not_class)
113 << buildElaboratedType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000114 return QualType();
115 }
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000116 if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
117 diag::err_coroutine_promise_type_incomplete))
118 return QualType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000119
120 return PromiseType;
121}
122
Gor Nishanov29ff6382017-05-24 14:34:19 +0000123/// Look up the std::experimental::coroutine_handle<PromiseType>.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000124static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
125 SourceLocation Loc) {
126 if (PromiseType.isNull())
127 return QualType();
128
129 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
130 assert(StdExp && "Should already be diagnosed");
131
132 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
133 Loc, Sema::LookupOrdinaryName);
134 if (!S.LookupQualifiedName(Result, StdExp)) {
135 S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
136 << "std::experimental::coroutine_handle";
137 return QualType();
138 }
139
140 ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
141 if (!CoroHandle) {
142 Result.suppressDiagnostics();
143 // We found something weird. Complain about the first thing we found.
144 NamedDecl *Found = *Result.begin();
145 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
146 return QualType();
147 }
148
149 // Form template argument list for coroutine_handle<Promise>.
150 TemplateArgumentListInfo Args(Loc, Loc);
151 Args.addArgument(TemplateArgumentLoc(
152 TemplateArgument(PromiseType),
153 S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
154
155 // Build the template-id.
156 QualType CoroHandleType =
157 S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
158 if (CoroHandleType.isNull())
159 return QualType();
160 if (S.RequireCompleteType(Loc, CoroHandleType,
161 diag::err_coroutine_type_missing_specialization))
162 return QualType();
163
164 return CoroHandleType;
165}
166
Eric Fiselierc8efda72016-10-27 18:43:28 +0000167static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
168 StringRef Keyword) {
Richard Smith744b2242015-11-20 02:54:01 +0000169 // 'co_await' and 'co_yield' are not permitted in unevaluated operands.
170 if (S.isUnevaluatedContext()) {
171 S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
Eric Fiselierc8efda72016-10-27 18:43:28 +0000172 return false;
Richard Smith744b2242015-11-20 02:54:01 +0000173 }
Richard Smithcfd53b42015-10-22 06:13:50 +0000174
175 // Any other usage must be within a function.
176 auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
177 if (!FD) {
178 S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
179 ? diag::err_coroutine_objc_method
180 : diag::err_coroutine_outside_function) << Keyword;
Eric Fiselierc8efda72016-10-27 18:43:28 +0000181 return false;
Richard Smithcfd53b42015-10-22 06:13:50 +0000182 }
183
Eric Fiselierc8efda72016-10-27 18:43:28 +0000184 // An enumeration for mapping the diagnostic type to the correct diagnostic
185 // selection index.
186 enum InvalidFuncDiag {
187 DiagCtor = 0,
188 DiagDtor,
189 DiagCopyAssign,
190 DiagMoveAssign,
191 DiagMain,
192 DiagConstexpr,
193 DiagAutoRet,
194 DiagVarargs,
195 };
196 bool Diagnosed = false;
197 auto DiagInvalid = [&](InvalidFuncDiag ID) {
198 S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
199 Diagnosed = true;
200 return false;
201 };
202
203 // Diagnose when a constructor, destructor, copy/move assignment operator,
204 // or the function 'main' are declared as a coroutine.
205 auto *MD = dyn_cast<CXXMethodDecl>(FD);
206 if (MD && isa<CXXConstructorDecl>(MD))
207 return DiagInvalid(DiagCtor);
208 else if (MD && isa<CXXDestructorDecl>(MD))
209 return DiagInvalid(DiagDtor);
210 else if (MD && MD->isCopyAssignmentOperator())
211 return DiagInvalid(DiagCopyAssign);
212 else if (MD && MD->isMoveAssignmentOperator())
213 return DiagInvalid(DiagMoveAssign);
214 else if (FD->isMain())
215 return DiagInvalid(DiagMain);
216
217 // Emit a diagnostics for each of the following conditions which is not met.
218 if (FD->isConstexpr())
219 DiagInvalid(DiagConstexpr);
220 if (FD->getReturnType()->isUndeducedType())
221 DiagInvalid(DiagAutoRet);
222 if (FD->isVariadic())
223 DiagInvalid(DiagVarargs);
224
225 return !Diagnosed;
226}
227
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000228static ExprResult buildOperatorCoawaitLookupExpr(Sema &SemaRef, Scope *S,
229 SourceLocation Loc) {
230 DeclarationName OpName =
231 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
232 LookupResult Operators(SemaRef, OpName, SourceLocation(),
233 Sema::LookupOperatorName);
234 SemaRef.LookupName(Operators, S);
Eric Fiselierc8efda72016-10-27 18:43:28 +0000235
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000236 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
237 const auto &Functions = Operators.asUnresolvedSet();
238 bool IsOverloaded =
239 Functions.size() > 1 ||
240 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
241 Expr *CoawaitOp = UnresolvedLookupExpr::Create(
242 SemaRef.Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
243 DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
244 Functions.begin(), Functions.end());
245 assert(CoawaitOp);
246 return CoawaitOp;
247}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000248
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000249/// Build a call to 'operator co_await' if there is a suitable operator for
250/// the given expression.
251static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, SourceLocation Loc,
252 Expr *E,
253 UnresolvedLookupExpr *Lookup) {
254 UnresolvedSet<16> Functions;
255 Functions.append(Lookup->decls_begin(), Lookup->decls_end());
256 return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
257}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000258
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000259static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
260 SourceLocation Loc, Expr *E) {
261 ExprResult R = buildOperatorCoawaitLookupExpr(SemaRef, S, Loc);
262 if (R.isInvalid())
263 return ExprError();
264 return buildOperatorCoawaitCall(SemaRef, Loc, E,
265 cast<UnresolvedLookupExpr>(R.get()));
Richard Smithcfd53b42015-10-22 06:13:50 +0000266}
267
Gor Nishanov8df64e92016-10-27 16:28:31 +0000268static Expr *buildBuiltinCall(Sema &S, SourceLocation Loc, Builtin::ID Id,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000269 MultiExprArg CallArgs) {
Gor Nishanov8df64e92016-10-27 16:28:31 +0000270 StringRef Name = S.Context.BuiltinInfo.getName(Id);
271 LookupResult R(S, &S.Context.Idents.get(Name), Loc, Sema::LookupOrdinaryName);
272 S.LookupName(R, S.TUScope, /*AllowBuiltinCreation=*/true);
273
274 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
275 assert(BuiltInDecl && "failed to find builtin declaration");
276
277 ExprResult DeclRef =
278 S.BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
279 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
280
281 ExprResult Call =
282 S.ActOnCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
283
284 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
285 return Call.get();
286}
287
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000288static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
289 SourceLocation Loc) {
290 QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
291 if (CoroHandleType.isNull())
292 return ExprError();
293
294 DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
295 LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
296 Sema::LookupOrdinaryName);
297 if (!S.LookupQualifiedName(Found, LookupCtx)) {
298 S.Diag(Loc, diag::err_coroutine_handle_missing_member)
299 << "from_address";
300 return ExprError();
301 }
302
303 Expr *FramePtr =
304 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
305
306 CXXScopeSpec SS;
307 ExprResult FromAddr =
308 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
309 if (FromAddr.isInvalid())
310 return ExprError();
311
312 return S.ActOnCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
313}
Richard Smithcfd53b42015-10-22 06:13:50 +0000314
Richard Smith9f690bd2015-10-27 06:02:45 +0000315struct ReadySuspendResumeResult {
Richard Smith9f690bd2015-10-27 06:02:45 +0000316 Expr *Results[3];
Gor Nishanovce43bd22017-03-11 01:30:17 +0000317 OpaqueValueExpr *OpaqueValue;
318 bool IsInvalid;
Richard Smith9f690bd2015-10-27 06:02:45 +0000319};
320
Richard Smith23da82c2015-11-20 22:40:06 +0000321static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000322 StringRef Name, MultiExprArg Args) {
Richard Smith23da82c2015-11-20 22:40:06 +0000323 DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
324
325 // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
326 CXXScopeSpec SS;
327 ExprResult Result = S.BuildMemberReferenceExpr(
328 Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
329 SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
330 /*Scope=*/nullptr);
331 if (Result.isInvalid())
332 return ExprError();
333
334 return S.ActOnCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
335}
336
Richard Smith9f690bd2015-10-27 06:02:45 +0000337/// Build calls to await_ready, await_suspend, and await_resume for a co_await
338/// expression.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000339static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
340 SourceLocation Loc, Expr *E) {
Gor Nishanovce43bd22017-03-11 01:30:17 +0000341 OpaqueValueExpr *Operand = new (S.Context)
342 OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
343
Richard Smith9f690bd2015-10-27 06:02:45 +0000344 // Assume invalid until we see otherwise.
Gor Nishanovce43bd22017-03-11 01:30:17 +0000345 ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true};
Richard Smith9f690bd2015-10-27 06:02:45 +0000346
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000347 ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc);
348 if (CoroHandleRes.isInvalid())
349 return Calls;
350 Expr *CoroHandle = CoroHandleRes.get();
351
Richard Smith9f690bd2015-10-27 06:02:45 +0000352 const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000353 MultiExprArg Args[] = {None, CoroHandle, None};
Richard Smith9f690bd2015-10-27 06:02:45 +0000354 for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000355 ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]);
Richard Smith9f690bd2015-10-27 06:02:45 +0000356 if (Result.isInvalid())
357 return Calls;
358 Calls.Results[I] = Result.get();
359 }
360
361 Calls.IsInvalid = false;
362 return Calls;
363}
364
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000365static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
366 SourceLocation Loc, StringRef Name,
367 MultiExprArg Args) {
368
369 // Form a reference to the promise.
370 ExprResult PromiseRef = S.BuildDeclRefExpr(
371 Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
372 if (PromiseRef.isInvalid())
373 return ExprError();
374
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000375 return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
376}
377
378VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
379 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
380 auto *FD = cast<FunctionDecl>(CurContext);
381
382 QualType T =
383 FD->getType()->isDependentType()
384 ? Context.DependentTy
385 : lookupPromiseType(*this, FD->getType()->castAs<FunctionProtoType>(),
386 Loc, FD->getLocation());
387 if (T.isNull())
388 return nullptr;
389
390 auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
391 &PP.getIdentifierTable().get("__promise"), T,
392 Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
393 CheckVariableDeclarationType(VD);
394 if (VD->isInvalidDecl())
395 return nullptr;
396 ActOnUninitializedDecl(VD);
397 assert(!VD->isInvalidDecl());
398 return VD;
399}
400
401/// Check that this is a context in which a coroutine suspension can appear.
402static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000403 StringRef Keyword,
404 bool IsImplicit = false) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000405 if (!isValidCoroutineContext(S, Loc, Keyword))
406 return nullptr;
407
408 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000409
410 auto *ScopeInfo = S.getCurFunction();
411 assert(ScopeInfo && "missing function scope for function");
412
Eric Fiseliercac0a592017-03-11 02:35:37 +0000413 if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
414 ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
415
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000416 if (ScopeInfo->CoroutinePromise)
417 return ScopeInfo;
418
419 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
420 if (!ScopeInfo->CoroutinePromise)
421 return nullptr;
422
423 return ScopeInfo;
424}
425
426static bool actOnCoroutineBodyStart(Sema &S, Scope *SC, SourceLocation KWLoc,
427 StringRef Keyword) {
428 if (!checkCoroutineContext(S, KWLoc, Keyword))
429 return false;
430 auto *ScopeInfo = S.getCurFunction();
431 assert(ScopeInfo->CoroutinePromise);
432
433 // If we have existing coroutine statements then we have already built
434 // the initial and final suspend points.
435 if (!ScopeInfo->NeedsCoroutineSuspends)
436 return true;
437
438 ScopeInfo->setNeedsCoroutineSuspends(false);
439
440 auto *Fn = cast<FunctionDecl>(S.CurContext);
441 SourceLocation Loc = Fn->getLocation();
442 // Build the initial suspend point
443 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
444 ExprResult Suspend =
445 buildPromiseCall(S, ScopeInfo->CoroutinePromise, Loc, Name, None);
446 if (Suspend.isInvalid())
447 return StmtError();
448 Suspend = buildOperatorCoawaitCall(S, SC, Loc, Suspend.get());
449 if (Suspend.isInvalid())
450 return StmtError();
451 Suspend = S.BuildResolvedCoawaitExpr(Loc, Suspend.get(),
452 /*IsImplicit*/ true);
453 Suspend = S.ActOnFinishFullExpr(Suspend.get());
454 if (Suspend.isInvalid()) {
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000455 S.Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000456 << ((Name == "initial_suspend") ? 0 : 1);
457 S.Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
458 return StmtError();
459 }
460 return cast<Stmt>(Suspend.get());
461 };
462
463 StmtResult InitSuspend = buildSuspends("initial_suspend");
464 if (InitSuspend.isInvalid())
465 return true;
466
467 StmtResult FinalSuspend = buildSuspends("final_suspend");
468 if (FinalSuspend.isInvalid())
469 return true;
470
471 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
472
473 return true;
474}
475
Richard Smith9f690bd2015-10-27 06:02:45 +0000476ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000477 if (!actOnCoroutineBodyStart(*this, S, Loc, "co_await")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000478 CorrectDelayedTyposInExpr(E);
479 return ExprError();
480 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000481
Richard Smith10610f72015-11-20 22:57:24 +0000482 if (E->getType()->isPlaceholderType()) {
483 ExprResult R = CheckPlaceholderExpr(E);
484 if (R.isInvalid()) return ExprError();
485 E = R.get();
486 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000487 ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
488 if (Lookup.isInvalid())
489 return ExprError();
490 return BuildUnresolvedCoawaitExpr(Loc, E,
491 cast<UnresolvedLookupExpr>(Lookup.get()));
492}
Richard Smith10610f72015-11-20 22:57:24 +0000493
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000494ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000495 UnresolvedLookupExpr *Lookup) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000496 auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
497 if (!FSI)
498 return ExprError();
499
500 if (E->getType()->isPlaceholderType()) {
501 ExprResult R = CheckPlaceholderExpr(E);
502 if (R.isInvalid())
503 return ExprError();
504 E = R.get();
505 }
506
507 auto *Promise = FSI->CoroutinePromise;
508 if (Promise->getType()->isDependentType()) {
509 Expr *Res =
510 new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000511 return Res;
512 }
513
514 auto *RD = Promise->getType()->getAsCXXRecordDecl();
515 if (lookupMember(*this, "await_transform", RD, Loc)) {
516 ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
517 if (R.isInvalid()) {
518 Diag(Loc,
519 diag::note_coroutine_promise_implicit_await_transform_required_here)
520 << E->getSourceRange();
521 return ExprError();
522 }
523 E = R.get();
524 }
525 ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
Richard Smith9f690bd2015-10-27 06:02:45 +0000526 if (Awaitable.isInvalid())
527 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000528
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000529 return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
Richard Smith9f690bd2015-10-27 06:02:45 +0000530}
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000531
532ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E,
533 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000534 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
Richard Smith744b2242015-11-20 02:54:01 +0000535 if (!Coroutine)
536 return ExprError();
Richard Smith9f690bd2015-10-27 06:02:45 +0000537
Richard Smith9f690bd2015-10-27 06:02:45 +0000538 if (E->getType()->isPlaceholderType()) {
539 ExprResult R = CheckPlaceholderExpr(E);
540 if (R.isInvalid()) return ExprError();
541 E = R.get();
542 }
543
Richard Smith10610f72015-11-20 22:57:24 +0000544 if (E->getType()->isDependentType()) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000545 Expr *Res = new (Context)
546 CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
Richard Smith10610f72015-11-20 22:57:24 +0000547 return Res;
548 }
549
Richard Smith1f38edd2015-11-22 03:13:02 +0000550 // If the expression is a temporary, materialize it as an lvalue so that we
551 // can use it multiple times.
552 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000553 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smith9f690bd2015-10-27 06:02:45 +0000554
555 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000556 ReadySuspendResumeResult RSS =
557 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000558 if (RSS.IsInvalid)
559 return ExprError();
560
Gor Nishanovce43bd22017-03-11 01:30:17 +0000561 Expr *Res =
562 new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
563 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000564
Richard Smithcfd53b42015-10-22 06:13:50 +0000565 return Res;
566}
567
Richard Smith9f690bd2015-10-27 06:02:45 +0000568ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000569 if (!actOnCoroutineBodyStart(*this, S, Loc, "co_yield")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000570 CorrectDelayedTyposInExpr(E);
Richard Smith23da82c2015-11-20 22:40:06 +0000571 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000572 }
Richard Smith23da82c2015-11-20 22:40:06 +0000573
574 // Build yield_value call.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000575 ExprResult Awaitable = buildPromiseCall(
576 *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000577 if (Awaitable.isInvalid())
578 return ExprError();
Richard Smith23da82c2015-11-20 22:40:06 +0000579
580 // Build 'operator co_await' call.
581 Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
582 if (Awaitable.isInvalid())
583 return ExprError();
584
Richard Smith9f690bd2015-10-27 06:02:45 +0000585 return BuildCoyieldExpr(Loc, Awaitable.get());
586}
587ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
588 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
Richard Smith744b2242015-11-20 02:54:01 +0000589 if (!Coroutine)
590 return ExprError();
Richard Smithcfd53b42015-10-22 06:13:50 +0000591
Richard Smith10610f72015-11-20 22:57:24 +0000592 if (E->getType()->isPlaceholderType()) {
593 ExprResult R = CheckPlaceholderExpr(E);
594 if (R.isInvalid()) return ExprError();
595 E = R.get();
596 }
597
Richard Smithd7bed4d2015-11-22 02:57:17 +0000598 if (E->getType()->isDependentType()) {
599 Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000600 return Res;
601 }
602
Richard Smith1f38edd2015-11-22 03:13:02 +0000603 // If the expression is a temporary, materialize it as an lvalue so that we
604 // can use it multiple times.
605 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000606 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000607
608 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000609 ReadySuspendResumeResult RSS =
610 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000611 if (RSS.IsInvalid)
612 return ExprError();
613
614 Expr *Res = new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
Gor Nishanovce43bd22017-03-11 01:30:17 +0000615 RSS.Results[2], RSS.OpaqueValue);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000616
Richard Smithcfd53b42015-10-22 06:13:50 +0000617 return Res;
618}
619
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000620StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
621 if (!actOnCoroutineBodyStart(*this, S, Loc, "co_return")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000622 CorrectDelayedTyposInExpr(E);
623 return StmtError();
624 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000625 return BuildCoreturnStmt(Loc, E);
626}
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000627
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000628StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
629 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000630 auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000631 if (!FSI)
Richard Smith71d403e2015-11-22 07:33:28 +0000632 return StmtError();
633
634 if (E && E->getType()->isPlaceholderType() &&
635 !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
Richard Smith10610f72015-11-20 22:57:24 +0000636 ExprResult R = CheckPlaceholderExpr(E);
637 if (R.isInvalid()) return StmtError();
638 E = R.get();
639 }
640
Richard Smith4ba66602015-11-22 07:05:16 +0000641 // FIXME: If the operand is a reference to a variable that's about to go out
Richard Smith2af65c42015-11-24 02:34:39 +0000642 // of scope, we should treat the operand as an xvalue for this overload
Richard Smith4ba66602015-11-22 07:05:16 +0000643 // resolution.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000644 VarDecl *Promise = FSI->CoroutinePromise;
Richard Smith4ba66602015-11-22 07:05:16 +0000645 ExprResult PC;
Eric Fiselier98131312016-10-06 21:23:38 +0000646 if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000647 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
Richard Smith4ba66602015-11-22 07:05:16 +0000648 } else {
649 E = MakeFullDiscardedValueExpr(E).get();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000650 PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
Richard Smith4ba66602015-11-22 07:05:16 +0000651 }
652 if (PC.isInvalid())
653 return StmtError();
654
655 Expr *PCE = ActOnFinishFullExpr(PC.get()).get();
656
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000657 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
Richard Smithcfd53b42015-10-22 06:13:50 +0000658 return Res;
659}
660
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000661/// Look up the std::nothrow object.
662static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
663 NamespaceDecl *Std = S.getStdNamespace();
664 assert(Std && "Should already be diagnosed");
665
666 LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
667 Sema::LookupOrdinaryName);
668 if (!S.LookupQualifiedName(Result, Std)) {
669 // FIXME: <experimental/coroutine> should have been included already.
670 // If we require it to include <new> then this diagnostic is no longer
671 // needed.
672 S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
673 return nullptr;
674 }
675
676 // FIXME: Mark the variable as ODR used. This currently does not work
677 // likely due to the scope at in which this function is called.
678 auto *VD = Result.getAsSingle<VarDecl>();
679 if (!VD) {
680 Result.suppressDiagnostics();
681 // We found something weird. Complain about the first thing we found.
682 NamedDecl *Found = *Result.begin();
683 S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
684 return nullptr;
685 }
686
687 ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
688 if (DR.isInvalid())
689 return nullptr;
690
691 return DR.get();
692}
693
Gor Nishanov8df64e92016-10-27 16:28:31 +0000694// Find an appropriate delete for the promise.
695static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc,
696 QualType PromiseType) {
697 FunctionDecl *OperatorDelete = nullptr;
698
699 DeclarationName DeleteName =
700 S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
701
702 auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
703 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
704
705 if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
706 return nullptr;
707
708 if (!OperatorDelete) {
709 // Look for a global declaration.
710 const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
711 const bool Overaligned = false;
712 OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
713 Overaligned, DeleteName);
714 }
715 S.MarkFunctionReferenced(Loc, OperatorDelete);
716 return OperatorDelete;
717}
718
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000719
720void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
721 FunctionScopeInfo *Fn = getCurFunction();
722 assert(Fn && Fn->CoroutinePromise && "not a coroutine");
723
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000724 if (!Body) {
725 assert(FD->isInvalidDecl() &&
726 "a null body is only allowed for invalid declarations");
727 return;
728 }
729
730 if (isa<CoroutineBodyStmt>(Body)) {
Gor Nishanov29ff6382017-05-24 14:34:19 +0000731 // Nothing todo. the body is already a transformed coroutine body statement.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000732 return;
733 }
734
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000735 // Coroutines [stmt.return]p1:
736 // A return statement shall not appear in a coroutine.
737 if (Fn->FirstReturnLoc.isValid()) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000738 assert(Fn->FirstCoroutineStmtLoc.isValid() &&
739 "first coroutine location not set");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000740 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000741 Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
742 << Fn->getFirstCoroutineStmtKeyword();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000743 }
Eric Fiselierbee782b2017-04-03 19:21:00 +0000744 CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
745 if (Builder.isInvalid() || !Builder.buildStatements())
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000746 return FD->setInvalidDecl();
747
748 // Build body for the coroutine wrapper statement.
749 Body = CoroutineBodyStmt::Create(Context, Builder);
750}
751
Eric Fiselierbee782b2017-04-03 19:21:00 +0000752CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
753 sema::FunctionScopeInfo &Fn,
754 Stmt *Body)
755 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
756 IsPromiseDependentType(
757 !Fn.CoroutinePromise ||
758 Fn.CoroutinePromise->getType()->isDependentType()) {
759 this->Body = Body;
760 if (!IsPromiseDependentType) {
761 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
762 assert(PromiseRecordDecl && "Type should have already been checked");
763 }
764 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
765}
766
767bool CoroutineStmtBuilder::buildStatements() {
768 assert(this->IsValid && "coroutine already invalid");
769 this->IsValid = makeReturnObject() && makeParamMoves();
770 if (this->IsValid && !IsPromiseDependentType)
771 buildDependentStatements();
772 return this->IsValid;
773}
774
775bool CoroutineStmtBuilder::buildDependentStatements() {
776 assert(this->IsValid && "coroutine already invalid");
777 assert(!this->IsPromiseDependentType &&
778 "coroutine cannot have a dependent promise type");
779 this->IsValid = makeOnException() && makeOnFallthrough() &&
Gor Nishanov6a470682017-05-22 20:22:23 +0000780 makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
781 makeNewAndDeleteExpr();
Eric Fiselierbee782b2017-04-03 19:21:00 +0000782 return this->IsValid;
783}
784
785bool CoroutineStmtBuilder::makePromiseStmt() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000786 // Form a declaration statement for the promise declaration, so that AST
787 // visitors can more easily find it.
788 StmtResult PromiseStmt =
789 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
790 if (PromiseStmt.isInvalid())
791 return false;
792
793 this->Promise = PromiseStmt.get();
794 return true;
795}
796
Eric Fiselierbee782b2017-04-03 19:21:00 +0000797bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000798 if (Fn.hasInvalidCoroutineSuspends())
799 return false;
800 this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
801 this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
802 return true;
803}
804
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000805static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
806 CXXRecordDecl *PromiseRecordDecl,
807 FunctionScopeInfo &Fn) {
808 auto Loc = E->getExprLoc();
809 if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
810 auto *Decl = DeclRef->getDecl();
811 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
812 if (Method->isStatic())
813 return true;
814 else
815 Loc = Decl->getLocation();
816 }
817 }
818
819 S.Diag(
820 Loc,
821 diag::err_coroutine_promise_get_return_object_on_allocation_failure)
822 << PromiseRecordDecl;
823 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
824 << Fn.getFirstCoroutineStmtKeyword();
825 return false;
826}
827
Eric Fiselierbee782b2017-04-03 19:21:00 +0000828bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
829 assert(!IsPromiseDependentType &&
830 "cannot make statement while the promise type is dependent");
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000831
832 // [dcl.fct.def.coroutine]/8
833 // The unqualified-id get_return_object_on_allocation_failure is looked up in
834 // the scope of class P by class member access lookup (3.4.5). ...
835 // If an allocation function returns nullptr, ... the coroutine return value
836 // is obtained by a call to ... get_return_object_on_allocation_failure().
837
838 DeclarationName DN =
839 S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
840 LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
Eric Fiselierbee782b2017-04-03 19:21:00 +0000841 if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
842 return true;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000843
844 CXXScopeSpec SS;
845 ExprResult DeclNameExpr =
846 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
Eric Fiselierbee782b2017-04-03 19:21:00 +0000847 if (DeclNameExpr.isInvalid())
848 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000849
850 if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
851 return false;
852
853 ExprResult ReturnObjectOnAllocationFailure =
854 S.ActOnCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
Eric Fiselierbee782b2017-04-03 19:21:00 +0000855 if (ReturnObjectOnAllocationFailure.isInvalid())
856 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000857
Gor Nishanovc4a19082017-03-28 02:51:45 +0000858 StmtResult ReturnStmt =
859 S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
Gor Nishanov6a470682017-05-22 20:22:23 +0000860 if (ReturnStmt.isInvalid()) {
861 S.Diag(Found.getFoundDecl()->getLocation(),
862 diag::note_promise_member_declared_here)
863 << DN.getAsString();
864 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
865 << Fn.getFirstCoroutineStmtKeyword();
Eric Fiselierbee782b2017-04-03 19:21:00 +0000866 return false;
Gor Nishanov6a470682017-05-22 20:22:23 +0000867 }
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000868
869 this->ReturnStmtOnAllocFailure = ReturnStmt.get();
870 return true;
871}
872
Eric Fiselierbee782b2017-04-03 19:21:00 +0000873bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000874 // Form and check allocation and deallocation calls.
Eric Fiselierbee782b2017-04-03 19:21:00 +0000875 assert(!IsPromiseDependentType &&
876 "cannot make statement while the promise type is dependent");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000877 QualType PromiseType = Fn.CoroutinePromise->getType();
Gor Nishanov8df64e92016-10-27 16:28:31 +0000878
879 if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
880 return false;
881
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000882 const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
883
Gor Nishanov8df64e92016-10-27 16:28:31 +0000884 // FIXME: Add support for stateful allocators.
885
886 FunctionDecl *OperatorNew = nullptr;
887 FunctionDecl *OperatorDelete = nullptr;
888 FunctionDecl *UnusedResult = nullptr;
889 bool PassAlignment = false;
Eric Fiselierf747f532017-04-18 05:08:08 +0000890 SmallVector<Expr *, 1> PlacementArgs;
Gor Nishanov8df64e92016-10-27 16:28:31 +0000891
892 S.FindAllocationFunctions(Loc, SourceRange(),
893 /*UseGlobal*/ false, PromiseType,
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000894 /*isArray*/ false, PassAlignment, PlacementArgs,
895 OperatorNew, UnusedResult);
Gor Nishanov8df64e92016-10-27 16:28:31 +0000896
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000897 bool IsGlobalOverload =
898 OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
899 // If we didn't find a class-local new declaration and non-throwing new
900 // was is required then we need to lookup the non-throwing global operator
901 // instead.
902 if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
903 auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
904 if (!StdNoThrow)
905 return false;
Eric Fiselierf747f532017-04-18 05:08:08 +0000906 PlacementArgs = {StdNoThrow};
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000907 OperatorNew = nullptr;
908 S.FindAllocationFunctions(Loc, SourceRange(),
909 /*UseGlobal*/ true, PromiseType,
910 /*isArray*/ false, PassAlignment, PlacementArgs,
911 OperatorNew, UnusedResult);
912 }
Gor Nishanov8df64e92016-10-27 16:28:31 +0000913
Eric Fiselierc5128752017-04-18 05:30:39 +0000914 assert(OperatorNew && "expected definition of operator new to be found");
915
916 if (RequiresNoThrowAlloc) {
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000917 const auto *FT = OperatorNew->getType()->getAs<FunctionProtoType>();
918 if (!FT->isNothrow(S.Context, /*ResultIfDependent*/ false)) {
919 S.Diag(OperatorNew->getLocation(),
920 diag::err_coroutine_promise_new_requires_nothrow)
921 << OperatorNew;
922 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
923 << OperatorNew;
924 return false;
925 }
926 }
927
928 if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr)
Gor Nishanov8df64e92016-10-27 16:28:31 +0000929 return false;
930
931 Expr *FramePtr =
932 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
933
934 Expr *FrameSize =
935 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {});
936
937 // Make new call.
938
939 ExprResult NewRef =
940 S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
941 if (NewRef.isInvalid())
942 return false;
943
Eric Fiselierf747f532017-04-18 05:08:08 +0000944 SmallVector<Expr *, 2> NewArgs(1, FrameSize);
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000945 for (auto Arg : PlacementArgs)
946 NewArgs.push_back(Arg);
947
Gor Nishanov8df64e92016-10-27 16:28:31 +0000948 ExprResult NewExpr =
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000949 S.ActOnCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
950 NewExpr = S.ActOnFinishFullExpr(NewExpr.get());
Gor Nishanov8df64e92016-10-27 16:28:31 +0000951 if (NewExpr.isInvalid())
952 return false;
953
Gor Nishanov8df64e92016-10-27 16:28:31 +0000954 // Make delete call.
955
956 QualType OpDeleteQualType = OperatorDelete->getType();
957
958 ExprResult DeleteRef =
959 S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
960 if (DeleteRef.isInvalid())
961 return false;
962
963 Expr *CoroFree =
964 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr});
965
966 SmallVector<Expr *, 2> DeleteArgs{CoroFree};
967
968 // Check if we need to pass the size.
969 const auto *OpDeleteType =
970 OpDeleteQualType.getTypePtr()->getAs<FunctionProtoType>();
971 if (OpDeleteType->getNumParams() > 1)
972 DeleteArgs.push_back(FrameSize);
973
974 ExprResult DeleteExpr =
975 S.ActOnCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000976 DeleteExpr = S.ActOnFinishFullExpr(DeleteExpr.get());
Gor Nishanov8df64e92016-10-27 16:28:31 +0000977 if (DeleteExpr.isInvalid())
978 return false;
979
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000980 this->Allocate = NewExpr.get();
981 this->Deallocate = DeleteExpr.get();
Gor Nishanov8df64e92016-10-27 16:28:31 +0000982
983 return true;
984}
985
Eric Fiselierbee782b2017-04-03 19:21:00 +0000986bool CoroutineStmtBuilder::makeOnFallthrough() {
987 assert(!IsPromiseDependentType &&
988 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000989
990 // [dcl.fct.def.coroutine]/4
991 // The unqualified-ids 'return_void' and 'return_value' are looked up in
992 // the scope of class P. If both are found, the program is ill-formed.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000993 const bool HasRVoid = lookupMember(S, "return_void", PromiseRecordDecl, Loc);
994 const bool HasRValue = lookupMember(S, "return_value", PromiseRecordDecl, Loc);
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000995
Eric Fiselier709d1b32016-10-27 07:30:31 +0000996 StmtResult Fallthrough;
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000997 if (HasRVoid && HasRValue) {
998 // FIXME Improve this diagnostic
999 S.Diag(FD.getLocation(), diag::err_coroutine_promise_return_ill_formed)
1000 << PromiseRecordDecl;
1001 return false;
1002 } else if (HasRVoid) {
1003 // If the unqualified-id return_void is found, flowing off the end of a
1004 // coroutine is equivalent to a co_return with no operand. Otherwise,
1005 // flowing off the end of a coroutine results in undefined behavior.
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001006 Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
1007 /*IsImplicit*/false);
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001008 Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
1009 if (Fallthrough.isInvalid())
1010 return false;
Eric Fiselier709d1b32016-10-27 07:30:31 +00001011 }
Richard Smith2af65c42015-11-24 02:34:39 +00001012
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001013 this->OnFallthrough = Fallthrough.get();
1014 return true;
1015}
1016
Eric Fiselierbee782b2017-04-03 19:21:00 +00001017bool CoroutineStmtBuilder::makeOnException() {
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001018 // Try to form 'p.unhandled_exception();'
Eric Fiselierbee782b2017-04-03 19:21:00 +00001019 assert(!IsPromiseDependentType &&
1020 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001021
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001022 const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1023
1024 if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
1025 auto DiagID =
1026 RequireUnhandledException
1027 ? diag::err_coroutine_promise_unhandled_exception_required
1028 : diag::
1029 warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1030 S.Diag(Loc, DiagID) << PromiseRecordDecl;
Gor Nishanov29ff6382017-05-24 14:34:19 +00001031 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1032 << PromiseRecordDecl;
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001033 return !RequireUnhandledException;
1034 }
1035
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001036 // If exceptions are disabled, don't try to build OnException.
1037 if (!S.getLangOpts().CXXExceptions)
1038 return true;
1039
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001040 ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
1041 "unhandled_exception", None);
1042 UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc);
1043 if (UnhandledException.isInvalid())
1044 return false;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001045
Gor Nishanov5b050e42017-05-22 22:33:17 +00001046 // Since the body of the coroutine will be wrapped in try-catch, it will
1047 // be incompatible with SEH __try if present in a function.
1048 if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1049 S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1050 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1051 << Fn.getFirstCoroutineStmtKeyword();
1052 return false;
1053 }
1054
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001055 this->OnException = UnhandledException.get();
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001056 return true;
1057}
1058
Eric Fiselierbee782b2017-04-03 19:21:00 +00001059bool CoroutineStmtBuilder::makeReturnObject() {
Richard Smith2af65c42015-11-24 02:34:39 +00001060 // Build implicit 'p.get_return_object()' expression and form initialization
1061 // of return type from it.
1062 ExprResult ReturnObject =
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001063 buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
Richard Smith2af65c42015-11-24 02:34:39 +00001064 if (ReturnObject.isInvalid())
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001065 return false;
Richard Smith2af65c42015-11-24 02:34:39 +00001066
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001067 this->ReturnValue = ReturnObject.get();
1068 return true;
1069}
1070
Gor Nishanov6a470682017-05-22 20:22:23 +00001071static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
1072 if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
1073 auto *MethodDecl = MbrRef->getMethodDecl();
1074 S.Diag(MethodDecl->getLocation(), diag::note_promise_member_declared_here)
1075 << MethodDecl->getName();
1076 }
1077 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1078 << Fn.getFirstCoroutineStmtKeyword();
1079}
1080
1081bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1082 assert(!IsPromiseDependentType &&
1083 "cannot make statement while the promise type is dependent");
1084 assert(this->ReturnValue && "ReturnValue must be already formed");
1085
1086 QualType const GroType = this->ReturnValue->getType();
1087 assert(!GroType->isDependentType() &&
1088 "get_return_object type must no longer be dependent");
1089
1090 QualType const FnRetType = FD.getReturnType();
1091 assert(!FnRetType->isDependentType() &&
1092 "get_return_object type must no longer be dependent");
1093
1094 if (FnRetType->isVoidType()) {
1095 ExprResult Res = S.ActOnFinishFullExpr(this->ReturnValue, Loc);
1096 if (Res.isInvalid())
1097 return false;
1098
1099 this->ResultDecl = Res.get();
1100 return true;
1101 }
1102
1103 if (GroType->isVoidType()) {
1104 // Trigger a nice error message.
1105 InitializedEntity Entity =
1106 InitializedEntity::InitializeResult(Loc, FnRetType, false);
1107 S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue);
1108 noteMemberDeclaredHere(S, ReturnValue, Fn);
1109 return false;
1110 }
1111
1112 auto *GroDecl = VarDecl::Create(
1113 S.Context, &FD, FD.getLocation(), FD.getLocation(),
1114 &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
1115 S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
1116
1117 S.CheckVariableDeclarationType(GroDecl);
1118 if (GroDecl->isInvalidDecl())
1119 return false;
1120
1121 InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
1122 ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType,
1123 this->ReturnValue);
1124 if (Res.isInvalid())
1125 return false;
1126
1127 Res = S.ActOnFinishFullExpr(Res.get());
1128 if (Res.isInvalid())
1129 return false;
1130
1131 if (GroType == FnRetType) {
1132 GroDecl->setNRVOVariable(true);
1133 }
1134
1135 S.AddInitializerToDecl(GroDecl, Res.get(),
1136 /*DirectInit=*/false);
1137
1138 S.FinalizeDeclaration(GroDecl);
1139
1140 // Form a declaration statement for the return declaration, so that AST
1141 // visitors can more easily find it.
1142 StmtResult GroDeclStmt =
1143 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
1144 if (GroDeclStmt.isInvalid())
1145 return false;
1146
1147 this->ResultDecl = GroDeclStmt.get();
1148
1149 ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
1150 if (declRef.isInvalid())
1151 return false;
1152
1153 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
1154 if (ReturnStmt.isInvalid()) {
1155 noteMemberDeclaredHere(S, ReturnValue, Fn);
1156 return false;
1157 }
1158
1159 this->ReturnStmt = ReturnStmt.get();
1160 return true;
1161}
1162
Eric Fiselierbee782b2017-04-03 19:21:00 +00001163bool CoroutineStmtBuilder::makeParamMoves() {
Richard Smith2af65c42015-11-24 02:34:39 +00001164 // FIXME: Perform move-initialization of parameters into frame-local copies.
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001165 return true;
Richard Smithcfd53b42015-10-22 06:13:50 +00001166}
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001167
1168StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1169 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
1170 if (!Res)
1171 return StmtError();
1172 return Res;
1173}