blob: 7bbb2f46e56cc4f51f124ef2667c07bae8bec459 [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
14#include "clang/Sema/SemaInternal.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"
Richard Smithcfd53b42015-10-22 06:13:50 +000021using namespace clang;
22using namespace sema;
23
Eric Fiselier20f25cb2017-03-06 23:38:15 +000024static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
25 SourceLocation Loc) {
26 DeclarationName DN = S.PP.getIdentifierInfo(Name);
27 LookupResult LR(S, DN, Loc, Sema::LookupMemberName);
28 // Suppress diagnostics when a private member is selected. The same warnings
29 // will be produced again when building the call.
30 LR.suppressDiagnostics();
31 return S.LookupQualifiedName(LR, RD);
32}
33
Richard Smith9f690bd2015-10-27 06:02:45 +000034/// Look up the std::coroutine_traits<...>::promise_type for the given
35/// function type.
36static QualType lookupPromiseType(Sema &S, const FunctionProtoType *FnType,
Eric Fiselier89bf0e72017-03-06 22:52:28 +000037 SourceLocation KwLoc,
38 SourceLocation FuncLoc) {
Richard Smith9f690bd2015-10-27 06:02:45 +000039 // FIXME: Cache std::coroutine_traits once we've found it.
Gor Nishanov3e048bb2016-10-04 00:31:16 +000040 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
41 if (!StdExp) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000042 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
43 << "std::experimental::coroutine_traits";
Richard Smith9f690bd2015-10-27 06:02:45 +000044 return QualType();
45 }
46
47 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_traits"),
Eric Fiselier89bf0e72017-03-06 22:52:28 +000048 FuncLoc, Sema::LookupOrdinaryName);
Gor Nishanov3e048bb2016-10-04 00:31:16 +000049 if (!S.LookupQualifiedName(Result, StdExp)) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000050 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
51 << "std::experimental::coroutine_traits";
Richard Smith9f690bd2015-10-27 06:02:45 +000052 return QualType();
53 }
54
55 ClassTemplateDecl *CoroTraits = Result.getAsSingle<ClassTemplateDecl>();
56 if (!CoroTraits) {
57 Result.suppressDiagnostics();
58 // We found something weird. Complain about the first thing we found.
59 NamedDecl *Found = *Result.begin();
60 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
61 return QualType();
62 }
63
64 // Form template argument list for coroutine_traits<R, P1, P2, ...>.
Eric Fiselier89bf0e72017-03-06 22:52:28 +000065 TemplateArgumentListInfo Args(KwLoc, KwLoc);
Richard Smith9f690bd2015-10-27 06:02:45 +000066 Args.addArgument(TemplateArgumentLoc(
67 TemplateArgument(FnType->getReturnType()),
Eric Fiselier89bf0e72017-03-06 22:52:28 +000068 S.Context.getTrivialTypeSourceInfo(FnType->getReturnType(), KwLoc)));
Richard Smith71d403e2015-11-22 07:33:28 +000069 // FIXME: If the function is a non-static member function, add the type
70 // of the implicit object parameter before the formal parameters.
Richard Smith9f690bd2015-10-27 06:02:45 +000071 for (QualType T : FnType->getParamTypes())
72 Args.addArgument(TemplateArgumentLoc(
Eric Fiselier89bf0e72017-03-06 22:52:28 +000073 TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));
Richard Smith9f690bd2015-10-27 06:02:45 +000074
75 // Build the template-id.
76 QualType CoroTrait =
Eric Fiselier89bf0e72017-03-06 22:52:28 +000077 S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
Richard Smith9f690bd2015-10-27 06:02:45 +000078 if (CoroTrait.isNull())
79 return QualType();
Eric Fiselier89bf0e72017-03-06 22:52:28 +000080 if (S.RequireCompleteType(KwLoc, CoroTrait,
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000081 diag::err_coroutine_type_missing_specialization))
Richard Smith9f690bd2015-10-27 06:02:45 +000082 return QualType();
83
Eric Fiselier89bf0e72017-03-06 22:52:28 +000084 auto *RD = CoroTrait->getAsCXXRecordDecl();
Richard Smith9f690bd2015-10-27 06:02:45 +000085 assert(RD && "specialization of class template is not a class?");
86
87 // Look up the ::promise_type member.
Eric Fiselier89bf0e72017-03-06 22:52:28 +000088 LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
Richard Smith9f690bd2015-10-27 06:02:45 +000089 Sema::LookupOrdinaryName);
90 S.LookupQualifiedName(R, RD);
91 auto *Promise = R.getAsSingle<TypeDecl>();
92 if (!Promise) {
Eric Fiselier89bf0e72017-03-06 22:52:28 +000093 S.Diag(FuncLoc,
94 diag::err_implied_std_coroutine_traits_promise_type_not_found)
Gor Nishanov8df64e92016-10-27 16:28:31 +000095 << RD;
Richard Smith9f690bd2015-10-27 06:02:45 +000096 return QualType();
97 }
Richard Smith9f690bd2015-10-27 06:02:45 +000098 // The promise type is required to be a class type.
99 QualType PromiseType = S.Context.getTypeDeclType(Promise);
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000100
101 auto buildElaboratedType = [&]() {
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000102 auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, StdExp);
Richard Smith9b2f53e2015-11-19 02:36:35 +0000103 NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
104 CoroTrait.getTypePtr());
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000105 return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
106 };
Richard Smith9b2f53e2015-11-19 02:36:35 +0000107
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000108 if (!PromiseType->getAsCXXRecordDecl()) {
109 S.Diag(FuncLoc,
110 diag::err_implied_std_coroutine_traits_promise_type_not_class)
111 << buildElaboratedType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000112 return QualType();
113 }
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000114 if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
115 diag::err_coroutine_promise_type_incomplete))
116 return QualType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000117
118 return PromiseType;
119}
120
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000121/// Look up the std::coroutine_traits<...>::promise_type for the given
122/// function type.
123static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
124 SourceLocation Loc) {
125 if (PromiseType.isNull())
126 return QualType();
127
128 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
129 assert(StdExp && "Should already be diagnosed");
130
131 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
132 Loc, Sema::LookupOrdinaryName);
133 if (!S.LookupQualifiedName(Result, StdExp)) {
134 S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
135 << "std::experimental::coroutine_handle";
136 return QualType();
137 }
138
139 ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
140 if (!CoroHandle) {
141 Result.suppressDiagnostics();
142 // We found something weird. Complain about the first thing we found.
143 NamedDecl *Found = *Result.begin();
144 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
145 return QualType();
146 }
147
148 // Form template argument list for coroutine_handle<Promise>.
149 TemplateArgumentListInfo Args(Loc, Loc);
150 Args.addArgument(TemplateArgumentLoc(
151 TemplateArgument(PromiseType),
152 S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
153
154 // Build the template-id.
155 QualType CoroHandleType =
156 S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
157 if (CoroHandleType.isNull())
158 return QualType();
159 if (S.RequireCompleteType(Loc, CoroHandleType,
160 diag::err_coroutine_type_missing_specialization))
161 return QualType();
162
163 return CoroHandleType;
164}
165
Eric Fiselierc8efda72016-10-27 18:43:28 +0000166static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
167 StringRef Keyword) {
Richard Smith744b2242015-11-20 02:54:01 +0000168 // 'co_await' and 'co_yield' are not permitted in unevaluated operands.
169 if (S.isUnevaluatedContext()) {
170 S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
Eric Fiselierc8efda72016-10-27 18:43:28 +0000171 return false;
Richard Smith744b2242015-11-20 02:54:01 +0000172 }
Richard Smithcfd53b42015-10-22 06:13:50 +0000173
174 // Any other usage must be within a function.
175 auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
176 if (!FD) {
177 S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
178 ? diag::err_coroutine_objc_method
179 : diag::err_coroutine_outside_function) << Keyword;
Eric Fiselierc8efda72016-10-27 18:43:28 +0000180 return false;
Richard Smithcfd53b42015-10-22 06:13:50 +0000181 }
182
Eric Fiselierc8efda72016-10-27 18:43:28 +0000183 // An enumeration for mapping the diagnostic type to the correct diagnostic
184 // selection index.
185 enum InvalidFuncDiag {
186 DiagCtor = 0,
187 DiagDtor,
188 DiagCopyAssign,
189 DiagMoveAssign,
190 DiagMain,
191 DiagConstexpr,
192 DiagAutoRet,
193 DiagVarargs,
194 };
195 bool Diagnosed = false;
196 auto DiagInvalid = [&](InvalidFuncDiag ID) {
197 S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
198 Diagnosed = true;
199 return false;
200 };
201
202 // Diagnose when a constructor, destructor, copy/move assignment operator,
203 // or the function 'main' are declared as a coroutine.
204 auto *MD = dyn_cast<CXXMethodDecl>(FD);
205 if (MD && isa<CXXConstructorDecl>(MD))
206 return DiagInvalid(DiagCtor);
207 else if (MD && isa<CXXDestructorDecl>(MD))
208 return DiagInvalid(DiagDtor);
209 else if (MD && MD->isCopyAssignmentOperator())
210 return DiagInvalid(DiagCopyAssign);
211 else if (MD && MD->isMoveAssignmentOperator())
212 return DiagInvalid(DiagMoveAssign);
213 else if (FD->isMain())
214 return DiagInvalid(DiagMain);
215
216 // Emit a diagnostics for each of the following conditions which is not met.
217 if (FD->isConstexpr())
218 DiagInvalid(DiagConstexpr);
219 if (FD->getReturnType()->isUndeducedType())
220 DiagInvalid(DiagAutoRet);
221 if (FD->isVariadic())
222 DiagInvalid(DiagVarargs);
223
224 return !Diagnosed;
225}
226
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000227static ExprResult buildOperatorCoawaitLookupExpr(Sema &SemaRef, Scope *S,
228 SourceLocation Loc) {
229 DeclarationName OpName =
230 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
231 LookupResult Operators(SemaRef, OpName, SourceLocation(),
232 Sema::LookupOperatorName);
233 SemaRef.LookupName(Operators, S);
Eric Fiselierc8efda72016-10-27 18:43:28 +0000234
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000235 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
236 const auto &Functions = Operators.asUnresolvedSet();
237 bool IsOverloaded =
238 Functions.size() > 1 ||
239 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
240 Expr *CoawaitOp = UnresolvedLookupExpr::Create(
241 SemaRef.Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
242 DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
243 Functions.begin(), Functions.end());
244 assert(CoawaitOp);
245 return CoawaitOp;
246}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000247
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000248/// Build a call to 'operator co_await' if there is a suitable operator for
249/// the given expression.
250static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, SourceLocation Loc,
251 Expr *E,
252 UnresolvedLookupExpr *Lookup) {
253 UnresolvedSet<16> Functions;
254 Functions.append(Lookup->decls_begin(), Lookup->decls_end());
255 return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
256}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000257
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000258static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
259 SourceLocation Loc, Expr *E) {
260 ExprResult R = buildOperatorCoawaitLookupExpr(SemaRef, S, Loc);
261 if (R.isInvalid())
262 return ExprError();
263 return buildOperatorCoawaitCall(SemaRef, Loc, E,
264 cast<UnresolvedLookupExpr>(R.get()));
Richard Smithcfd53b42015-10-22 06:13:50 +0000265}
266
Gor Nishanov8df64e92016-10-27 16:28:31 +0000267static Expr *buildBuiltinCall(Sema &S, SourceLocation Loc, Builtin::ID Id,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000268 MultiExprArg CallArgs) {
Gor Nishanov8df64e92016-10-27 16:28:31 +0000269 StringRef Name = S.Context.BuiltinInfo.getName(Id);
270 LookupResult R(S, &S.Context.Idents.get(Name), Loc, Sema::LookupOrdinaryName);
271 S.LookupName(R, S.TUScope, /*AllowBuiltinCreation=*/true);
272
273 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
274 assert(BuiltInDecl && "failed to find builtin declaration");
275
276 ExprResult DeclRef =
277 S.BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
278 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
279
280 ExprResult Call =
281 S.ActOnCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
282
283 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
284 return Call.get();
285}
286
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000287static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
288 SourceLocation Loc) {
289 QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
290 if (CoroHandleType.isNull())
291 return ExprError();
292
293 DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
294 LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
295 Sema::LookupOrdinaryName);
296 if (!S.LookupQualifiedName(Found, LookupCtx)) {
297 S.Diag(Loc, diag::err_coroutine_handle_missing_member)
298 << "from_address";
299 return ExprError();
300 }
301
302 Expr *FramePtr =
303 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
304
305 CXXScopeSpec SS;
306 ExprResult FromAddr =
307 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
308 if (FromAddr.isInvalid())
309 return ExprError();
310
311 return S.ActOnCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
312}
Richard Smithcfd53b42015-10-22 06:13:50 +0000313
Richard Smith9f690bd2015-10-27 06:02:45 +0000314struct ReadySuspendResumeResult {
Richard Smith9f690bd2015-10-27 06:02:45 +0000315 Expr *Results[3];
Gor Nishanovce43bd22017-03-11 01:30:17 +0000316 OpaqueValueExpr *OpaqueValue;
317 bool IsInvalid;
Richard Smith9f690bd2015-10-27 06:02:45 +0000318};
319
Richard Smith23da82c2015-11-20 22:40:06 +0000320static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000321 StringRef Name, MultiExprArg Args) {
Richard Smith23da82c2015-11-20 22:40:06 +0000322 DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
323
324 // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
325 CXXScopeSpec SS;
326 ExprResult Result = S.BuildMemberReferenceExpr(
327 Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
328 SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
329 /*Scope=*/nullptr);
330 if (Result.isInvalid())
331 return ExprError();
332
333 return S.ActOnCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
334}
335
Richard Smith9f690bd2015-10-27 06:02:45 +0000336/// Build calls to await_ready, await_suspend, and await_resume for a co_await
337/// expression.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000338static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
339 SourceLocation Loc, Expr *E) {
Gor Nishanovce43bd22017-03-11 01:30:17 +0000340 OpaqueValueExpr *Operand = new (S.Context)
341 OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
342
Richard Smith9f690bd2015-10-27 06:02:45 +0000343 // Assume invalid until we see otherwise.
Gor Nishanovce43bd22017-03-11 01:30:17 +0000344 ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true};
Richard Smith9f690bd2015-10-27 06:02:45 +0000345
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000346 ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc);
347 if (CoroHandleRes.isInvalid())
348 return Calls;
349 Expr *CoroHandle = CoroHandleRes.get();
350
Richard Smith9f690bd2015-10-27 06:02:45 +0000351 const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000352 MultiExprArg Args[] = {None, CoroHandle, None};
Richard Smith9f690bd2015-10-27 06:02:45 +0000353 for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000354 ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]);
Richard Smith9f690bd2015-10-27 06:02:45 +0000355 if (Result.isInvalid())
356 return Calls;
357 Calls.Results[I] = Result.get();
358 }
359
360 Calls.IsInvalid = false;
361 return Calls;
362}
363
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000364static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
365 SourceLocation Loc, StringRef Name,
366 MultiExprArg Args) {
367
368 // Form a reference to the promise.
369 ExprResult PromiseRef = S.BuildDeclRefExpr(
370 Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
371 if (PromiseRef.isInvalid())
372 return ExprError();
373
374 // Call 'yield_value', passing in E.
375 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,
403 StringRef Keyword) {
404 if (!isValidCoroutineContext(S, Loc, Keyword))
405 return nullptr;
406
407 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000408
409 auto *ScopeInfo = S.getCurFunction();
410 assert(ScopeInfo && "missing function scope for function");
411
412 if (ScopeInfo->CoroutinePromise)
413 return ScopeInfo;
414
415 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
416 if (!ScopeInfo->CoroutinePromise)
417 return nullptr;
418
419 return ScopeInfo;
420}
421
422static bool actOnCoroutineBodyStart(Sema &S, Scope *SC, SourceLocation KWLoc,
423 StringRef Keyword) {
424 if (!checkCoroutineContext(S, KWLoc, Keyword))
425 return false;
426 auto *ScopeInfo = S.getCurFunction();
427 assert(ScopeInfo->CoroutinePromise);
428
429 // If we have existing coroutine statements then we have already built
430 // the initial and final suspend points.
431 if (!ScopeInfo->NeedsCoroutineSuspends)
432 return true;
433
434 ScopeInfo->setNeedsCoroutineSuspends(false);
435
436 auto *Fn = cast<FunctionDecl>(S.CurContext);
437 SourceLocation Loc = Fn->getLocation();
438 // Build the initial suspend point
439 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
440 ExprResult Suspend =
441 buildPromiseCall(S, ScopeInfo->CoroutinePromise, Loc, Name, None);
442 if (Suspend.isInvalid())
443 return StmtError();
444 Suspend = buildOperatorCoawaitCall(S, SC, Loc, Suspend.get());
445 if (Suspend.isInvalid())
446 return StmtError();
447 Suspend = S.BuildResolvedCoawaitExpr(Loc, Suspend.get(),
448 /*IsImplicit*/ true);
449 Suspend = S.ActOnFinishFullExpr(Suspend.get());
450 if (Suspend.isInvalid()) {
451 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
452 << ((Name == "initial_suspend") ? 0 : 1);
453 S.Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
454 return StmtError();
455 }
456 return cast<Stmt>(Suspend.get());
457 };
458
459 StmtResult InitSuspend = buildSuspends("initial_suspend");
460 if (InitSuspend.isInvalid())
461 return true;
462
463 StmtResult FinalSuspend = buildSuspends("final_suspend");
464 if (FinalSuspend.isInvalid())
465 return true;
466
467 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
468
469 return true;
470}
471
Richard Smith9f690bd2015-10-27 06:02:45 +0000472ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000473 if (!actOnCoroutineBodyStart(*this, S, Loc, "co_await")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000474 CorrectDelayedTyposInExpr(E);
475 return ExprError();
476 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000477
Richard Smith10610f72015-11-20 22:57:24 +0000478 if (E->getType()->isPlaceholderType()) {
479 ExprResult R = CheckPlaceholderExpr(E);
480 if (R.isInvalid()) return ExprError();
481 E = R.get();
482 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000483 ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
484 if (Lookup.isInvalid())
485 return ExprError();
486 return BuildUnresolvedCoawaitExpr(Loc, E,
487 cast<UnresolvedLookupExpr>(Lookup.get()));
488}
Richard Smith10610f72015-11-20 22:57:24 +0000489
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000490ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E,
491 UnresolvedLookupExpr *Lookup) {
492 auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
493 if (!FSI)
494 return ExprError();
495
496 if (E->getType()->isPlaceholderType()) {
497 ExprResult R = CheckPlaceholderExpr(E);
498 if (R.isInvalid())
499 return ExprError();
500 E = R.get();
501 }
502
503 auto *Promise = FSI->CoroutinePromise;
504 if (Promise->getType()->isDependentType()) {
505 Expr *Res =
506 new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
507 FSI->CoroutineStmts.push_back(Res);
508 return Res;
509 }
510
511 auto *RD = Promise->getType()->getAsCXXRecordDecl();
512 if (lookupMember(*this, "await_transform", RD, Loc)) {
513 ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
514 if (R.isInvalid()) {
515 Diag(Loc,
516 diag::note_coroutine_promise_implicit_await_transform_required_here)
517 << E->getSourceRange();
518 return ExprError();
519 }
520 E = R.get();
521 }
522 ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
Richard Smith9f690bd2015-10-27 06:02:45 +0000523 if (Awaitable.isInvalid())
524 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000525
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000526 return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
Richard Smith9f690bd2015-10-27 06:02:45 +0000527}
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000528
529ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E,
530 bool IsImplicit) {
Richard Smith9f690bd2015-10-27 06:02:45 +0000531 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await");
Richard Smith744b2242015-11-20 02:54:01 +0000532 if (!Coroutine)
533 return ExprError();
Richard Smith9f690bd2015-10-27 06:02:45 +0000534
Richard Smith9f690bd2015-10-27 06:02:45 +0000535 if (E->getType()->isPlaceholderType()) {
536 ExprResult R = CheckPlaceholderExpr(E);
537 if (R.isInvalid()) return ExprError();
538 E = R.get();
539 }
540
Richard Smith10610f72015-11-20 22:57:24 +0000541 if (E->getType()->isDependentType()) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000542 Expr *Res = new (Context)
543 CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
544 if (!IsImplicit)
545 Coroutine->CoroutineStmts.push_back(Res);
Richard Smith10610f72015-11-20 22:57:24 +0000546 return Res;
547 }
548
Richard Smith1f38edd2015-11-22 03:13:02 +0000549 // If the expression is a temporary, materialize it as an lvalue so that we
550 // can use it multiple times.
551 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000552 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smith9f690bd2015-10-27 06:02:45 +0000553
554 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000555 ReadySuspendResumeResult RSS =
556 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000557 if (RSS.IsInvalid)
558 return ExprError();
559
Gor Nishanovce43bd22017-03-11 01:30:17 +0000560 Expr *Res =
561 new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
562 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000563 if (!IsImplicit)
564 Coroutine->CoroutineStmts.push_back(Res);
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);
600 Coroutine->CoroutineStmts.push_back(Res);
601 return Res;
602 }
603
Richard Smith1f38edd2015-11-22 03:13:02 +0000604 // If the expression is a temporary, materialize it as an lvalue so that we
605 // can use it multiple times.
606 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000607 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000608
609 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000610 ReadySuspendResumeResult RSS =
611 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000612 if (RSS.IsInvalid)
613 return ExprError();
614
615 Expr *Res = new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
Gor Nishanovce43bd22017-03-11 01:30:17 +0000616 RSS.Results[2], RSS.OpaqueValue);
Richard Smith744b2242015-11-20 02:54:01 +0000617 Coroutine->CoroutineStmts.push_back(Res);
Richard Smithcfd53b42015-10-22 06:13:50 +0000618 return Res;
619}
620
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000621StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
622 if (!actOnCoroutineBodyStart(*this, S, Loc, "co_return")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000623 CorrectDelayedTyposInExpr(E);
624 return StmtError();
625 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000626 return BuildCoreturnStmt(Loc, E);
627}
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000628
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000629StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
630 bool IsImplicit) {
631 auto *FSI = checkCoroutineContext(*this, Loc, "co_return");
632 if (!FSI)
Richard Smith71d403e2015-11-22 07:33:28 +0000633 return StmtError();
634
635 if (E && E->getType()->isPlaceholderType() &&
636 !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
Richard Smith10610f72015-11-20 22:57:24 +0000637 ExprResult R = CheckPlaceholderExpr(E);
638 if (R.isInvalid()) return StmtError();
639 E = R.get();
640 }
641
Richard Smith4ba66602015-11-22 07:05:16 +0000642 // FIXME: If the operand is a reference to a variable that's about to go out
Richard Smith2af65c42015-11-24 02:34:39 +0000643 // of scope, we should treat the operand as an xvalue for this overload
Richard Smith4ba66602015-11-22 07:05:16 +0000644 // resolution.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000645 VarDecl *Promise = FSI->CoroutinePromise;
Richard Smith4ba66602015-11-22 07:05:16 +0000646 ExprResult PC;
Eric Fiselier98131312016-10-06 21:23:38 +0000647 if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000648 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
Richard Smith4ba66602015-11-22 07:05:16 +0000649 } else {
650 E = MakeFullDiscardedValueExpr(E).get();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000651 PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
Richard Smith4ba66602015-11-22 07:05:16 +0000652 }
653 if (PC.isInvalid())
654 return StmtError();
655
656 Expr *PCE = ActOnFinishFullExpr(PC.get()).get();
657
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000658 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
659 if (!IsImplicit)
660 FSI->CoroutineStmts.push_back(Res);
Richard Smithcfd53b42015-10-22 06:13:50 +0000661 return Res;
662}
663
Eric Fiselier709d1b32016-10-27 07:30:31 +0000664static ExprResult buildStdCurrentExceptionCall(Sema &S, SourceLocation Loc) {
665 NamespaceDecl *Std = S.getStdNamespace();
666 if (!Std) {
667 S.Diag(Loc, diag::err_implied_std_current_exception_not_found);
668 return ExprError();
669 }
670 LookupResult Result(S, &S.PP.getIdentifierTable().get("current_exception"),
671 Loc, Sema::LookupOrdinaryName);
672 if (!S.LookupQualifiedName(Result, Std)) {
673 S.Diag(Loc, diag::err_implied_std_current_exception_not_found);
674 return ExprError();
675 }
676
677 // FIXME The STL is free to provide more than one overload.
678 FunctionDecl *FD = Result.getAsSingle<FunctionDecl>();
679 if (!FD) {
680 S.Diag(Loc, diag::err_malformed_std_current_exception);
681 return ExprError();
682 }
683 ExprResult Res = S.BuildDeclRefExpr(FD, FD->getType(), VK_LValue, Loc);
684 Res = S.ActOnCallExpr(/*Scope*/ nullptr, Res.get(), Loc, None, Loc);
685 if (Res.isInvalid()) {
686 S.Diag(Loc, diag::err_malformed_std_current_exception);
687 return ExprError();
688 }
689 return Res;
690}
691
Gor Nishanov8df64e92016-10-27 16:28:31 +0000692// Find an appropriate delete for the promise.
693static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc,
694 QualType PromiseType) {
695 FunctionDecl *OperatorDelete = nullptr;
696
697 DeclarationName DeleteName =
698 S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
699
700 auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
701 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
702
703 if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
704 return nullptr;
705
706 if (!OperatorDelete) {
707 // Look for a global declaration.
708 const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
709 const bool Overaligned = false;
710 OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
711 Overaligned, DeleteName);
712 }
713 S.MarkFunctionReferenced(Loc, OperatorDelete);
714 return OperatorDelete;
715}
716
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000717namespace {
718class SubStmtBuilder : public CoroutineBodyStmt::CtorArgs {
719 Sema &S;
720 FunctionDecl &FD;
721 FunctionScopeInfo &Fn;
722 bool IsValid;
723 SourceLocation Loc;
724 QualType RetType;
725 SmallVector<Stmt *, 4> ParamMovesVector;
726 const bool IsPromiseDependentType;
727 CXXRecordDecl *PromiseRecordDecl = nullptr;
728
729public:
730 SubStmtBuilder(Sema &S, FunctionDecl &FD, FunctionScopeInfo &Fn, Stmt *Body)
731 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
732 IsPromiseDependentType(
733 !Fn.CoroutinePromise ||
734 Fn.CoroutinePromise->getType()->isDependentType()) {
735 this->Body = Body;
736 if (!IsPromiseDependentType) {
737 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
738 assert(PromiseRecordDecl && "Type should have already been checked");
739 }
740 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend() &&
741 makeOnException() && makeOnFallthrough() &&
742 makeNewAndDeleteExpr() && makeReturnObject() &&
743 makeParamMoves();
744 }
745
746 bool isInvalid() const { return !this->IsValid; }
747
748 bool makePromiseStmt();
749 bool makeInitialAndFinalSuspend();
750 bool makeNewAndDeleteExpr();
751 bool makeOnFallthrough();
752 bool makeOnException();
753 bool makeReturnObject();
754 bool makeParamMoves();
755};
756}
757
758void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
759 FunctionScopeInfo *Fn = getCurFunction();
760 assert(Fn && Fn->CoroutinePromise && "not a coroutine");
761
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000762 if (!Body) {
763 assert(FD->isInvalidDecl() &&
764 "a null body is only allowed for invalid declarations");
765 return;
766 }
767
768 if (isa<CoroutineBodyStmt>(Body)) {
769 // FIXME(EricWF): Nothing todo. the body is already a transformed coroutine
770 // body statement.
771 return;
772 }
773
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000774 // Coroutines [stmt.return]p1:
775 // A return statement shall not appear in a coroutine.
776 if (Fn->FirstReturnLoc.isValid()) {
777 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000778 // FIXME: Every Coroutine statement may be invalid and therefore not added
779 // to CoroutineStmts. Find another way to provide location information.
780 if (!Fn->CoroutineStmts.empty()) {
781 auto *First = Fn->CoroutineStmts[0];
782 Diag(First->getLocStart(), diag::note_declared_coroutine_here)
783 << (isa<CoawaitExpr>(First) ? "co_await" :
784 isa<CoyieldExpr>(First) ? "co_yield" : "co_return");
785 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000786 }
787 SubStmtBuilder Builder(*this, *FD, *Fn, Body);
788 if (Builder.isInvalid())
789 return FD->setInvalidDecl();
790
791 // Build body for the coroutine wrapper statement.
792 Body = CoroutineBodyStmt::Create(Context, Builder);
793}
794
795bool SubStmtBuilder::makePromiseStmt() {
796 // Form a declaration statement for the promise declaration, so that AST
797 // visitors can more easily find it.
798 StmtResult PromiseStmt =
799 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
800 if (PromiseStmt.isInvalid())
801 return false;
802
803 this->Promise = PromiseStmt.get();
804 return true;
805}
806
807bool SubStmtBuilder::makeInitialAndFinalSuspend() {
808 if (Fn.hasInvalidCoroutineSuspends())
809 return false;
810 this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
811 this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
812 return true;
813}
814
815bool SubStmtBuilder::makeNewAndDeleteExpr() {
816 // Form and check allocation and deallocation calls.
817 QualType PromiseType = Fn.CoroutinePromise->getType();
Gor Nishanov8df64e92016-10-27 16:28:31 +0000818 if (PromiseType->isDependentType())
819 return true;
820
821 if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
822 return false;
823
824 // FIXME: Add support for get_return_object_on_allocation failure.
825 // FIXME: Add support for stateful allocators.
826
827 FunctionDecl *OperatorNew = nullptr;
828 FunctionDecl *OperatorDelete = nullptr;
829 FunctionDecl *UnusedResult = nullptr;
830 bool PassAlignment = false;
831
832 S.FindAllocationFunctions(Loc, SourceRange(),
833 /*UseGlobal*/ false, PromiseType,
834 /*isArray*/ false, PassAlignment,
835 /*PlacementArgs*/ None, OperatorNew, UnusedResult);
836
837 OperatorDelete = findDeleteForPromise(S, Loc, PromiseType);
838
839 if (!OperatorDelete || !OperatorNew)
840 return false;
841
842 Expr *FramePtr =
843 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
844
845 Expr *FrameSize =
846 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {});
847
848 // Make new call.
849
850 ExprResult NewRef =
851 S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
852 if (NewRef.isInvalid())
853 return false;
854
855 ExprResult NewExpr =
856 S.ActOnCallExpr(S.getCurScope(), NewRef.get(), Loc, FrameSize, Loc);
857 if (NewExpr.isInvalid())
858 return false;
859
Gor Nishanov8df64e92016-10-27 16:28:31 +0000860 // Make delete call.
861
862 QualType OpDeleteQualType = OperatorDelete->getType();
863
864 ExprResult DeleteRef =
865 S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
866 if (DeleteRef.isInvalid())
867 return false;
868
869 Expr *CoroFree =
870 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr});
871
872 SmallVector<Expr *, 2> DeleteArgs{CoroFree};
873
874 // Check if we need to pass the size.
875 const auto *OpDeleteType =
876 OpDeleteQualType.getTypePtr()->getAs<FunctionProtoType>();
877 if (OpDeleteType->getNumParams() > 1)
878 DeleteArgs.push_back(FrameSize);
879
880 ExprResult DeleteExpr =
881 S.ActOnCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
882 if (DeleteExpr.isInvalid())
883 return false;
884
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000885 this->Allocate = NewExpr.get();
886 this->Deallocate = DeleteExpr.get();
Gor Nishanov8df64e92016-10-27 16:28:31 +0000887
888 return true;
889}
890
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000891bool SubStmtBuilder::makeOnFallthrough() {
892 if (!PromiseRecordDecl)
893 return true;
894
895 // [dcl.fct.def.coroutine]/4
896 // The unqualified-ids 'return_void' and 'return_value' are looked up in
897 // the scope of class P. If both are found, the program is ill-formed.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000898 const bool HasRVoid = lookupMember(S, "return_void", PromiseRecordDecl, Loc);
899 const bool HasRValue = lookupMember(S, "return_value", PromiseRecordDecl, Loc);
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000900
Eric Fiselier709d1b32016-10-27 07:30:31 +0000901 StmtResult Fallthrough;
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000902 if (HasRVoid && HasRValue) {
903 // FIXME Improve this diagnostic
904 S.Diag(FD.getLocation(), diag::err_coroutine_promise_return_ill_formed)
905 << PromiseRecordDecl;
906 return false;
907 } else if (HasRVoid) {
908 // If the unqualified-id return_void is found, flowing off the end of a
909 // coroutine is equivalent to a co_return with no operand. Otherwise,
910 // flowing off the end of a coroutine results in undefined behavior.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000911 Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
912 /*IsImplicit*/false);
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000913 Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
914 if (Fallthrough.isInvalid())
915 return false;
Eric Fiselier709d1b32016-10-27 07:30:31 +0000916 }
Richard Smith2af65c42015-11-24 02:34:39 +0000917
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000918 this->OnFallthrough = Fallthrough.get();
919 return true;
920}
921
922bool SubStmtBuilder::makeOnException() {
923 // Try to form 'p.set_exception(std::current_exception());' to handle
924 // uncaught exceptions.
925 // TODO: Post WG21 Issaquah 2016 renamed set_exception to unhandled_exception
926 // TODO: and dropped exception_ptr parameter. Make it so.
927
928 if (!PromiseRecordDecl)
929 return true;
930
931 // If exceptions are disabled, don't try to build OnException.
932 if (!S.getLangOpts().CXXExceptions)
933 return true;
934
935 ExprResult SetException;
936
937 // [dcl.fct.def.coroutine]/3
938 // The unqualified-id set_exception is found in the scope of P by class
939 // member access lookup (3.4.5).
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000940 if (lookupMember(S, "set_exception", PromiseRecordDecl, Loc)) {
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000941 // Form the call 'p.set_exception(std::current_exception())'
942 SetException = buildStdCurrentExceptionCall(S, Loc);
943 if (SetException.isInvalid())
944 return false;
945 Expr *E = SetException.get();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000946 SetException = buildPromiseCall(S, Fn.CoroutinePromise, Loc, "set_exception", E);
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000947 SetException = S.ActOnFinishFullExpr(SetException.get(), Loc);
948 if (SetException.isInvalid())
949 return false;
950 }
951
952 this->OnException = SetException.get();
953 return true;
954}
955
956bool SubStmtBuilder::makeReturnObject() {
957
Richard Smith2af65c42015-11-24 02:34:39 +0000958 // Build implicit 'p.get_return_object()' expression and form initialization
959 // of return type from it.
960 ExprResult ReturnObject =
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000961 buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
Richard Smith2af65c42015-11-24 02:34:39 +0000962 if (ReturnObject.isInvalid())
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000963 return false;
964 QualType RetType = FD.getReturnType();
Richard Smith2af65c42015-11-24 02:34:39 +0000965 if (!RetType->isDependentType()) {
966 InitializedEntity Entity =
967 InitializedEntity::InitializeResult(Loc, RetType, false);
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000968 ReturnObject = S.PerformMoveOrCopyInitialization(Entity, nullptr, RetType,
Richard Smith2af65c42015-11-24 02:34:39 +0000969 ReturnObject.get());
970 if (ReturnObject.isInvalid())
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000971 return false;
Richard Smith2af65c42015-11-24 02:34:39 +0000972 }
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000973 ReturnObject = S.ActOnFinishFullExpr(ReturnObject.get(), Loc);
Richard Smith2af65c42015-11-24 02:34:39 +0000974 if (ReturnObject.isInvalid())
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000975 return false;
Richard Smith2af65c42015-11-24 02:34:39 +0000976
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000977 this->ReturnValue = ReturnObject.get();
978 return true;
979}
980
981bool SubStmtBuilder::makeParamMoves() {
Richard Smith2af65c42015-11-24 02:34:39 +0000982 // FIXME: Perform move-initialization of parameters into frame-local copies.
Gor Nishanovbbe1c072017-02-13 05:05:02 +0000983 return true;
Richard Smithcfd53b42015-10-22 06:13:50 +0000984}
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000985
986StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
987 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
988 if (!Res)
989 return StmtError();
990 return Res;
991}