blob: ae6c35f22065f3e21a7d6f59e916ce219bdfeb4e [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 Fiselierfc50f622017-05-25 14:59:39 +000026static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
27 SourceLocation Loc, bool &Res) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +000028 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();
Eric Fiselierfc50f622017-05-25 14:59:39 +000033 Res = S.LookupQualifiedName(LR, RD);
34 return LR;
35}
36
37static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
38 SourceLocation Loc) {
39 bool Res;
40 lookupMember(S, Name, RD, Loc, Res);
41 return Res;
Eric Fiselier20f25cb2017-03-06 23:38:15 +000042}
43
Richard Smith9f690bd2015-10-27 06:02:45 +000044/// Look up the std::coroutine_traits<...>::promise_type for the given
45/// function type.
46static QualType lookupPromiseType(Sema &S, const FunctionProtoType *FnType,
Eric Fiselier89bf0e72017-03-06 22:52:28 +000047 SourceLocation KwLoc,
48 SourceLocation FuncLoc) {
Richard Smith9f690bd2015-10-27 06:02:45 +000049 // FIXME: Cache std::coroutine_traits once we've found it.
Gor Nishanov3e048bb2016-10-04 00:31:16 +000050 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
51 if (!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 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_traits"),
Eric Fiselier89bf0e72017-03-06 22:52:28 +000058 FuncLoc, Sema::LookupOrdinaryName);
Gor Nishanov3e048bb2016-10-04 00:31:16 +000059 if (!S.LookupQualifiedName(Result, StdExp)) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000060 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
61 << "std::experimental::coroutine_traits";
Richard Smith9f690bd2015-10-27 06:02:45 +000062 return QualType();
63 }
64
65 ClassTemplateDecl *CoroTraits = Result.getAsSingle<ClassTemplateDecl>();
66 if (!CoroTraits) {
67 Result.suppressDiagnostics();
68 // We found something weird. Complain about the first thing we found.
69 NamedDecl *Found = *Result.begin();
70 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
71 return QualType();
72 }
73
74 // Form template argument list for coroutine_traits<R, P1, P2, ...>.
Eric Fiselier89bf0e72017-03-06 22:52:28 +000075 TemplateArgumentListInfo Args(KwLoc, KwLoc);
Richard Smith9f690bd2015-10-27 06:02:45 +000076 Args.addArgument(TemplateArgumentLoc(
77 TemplateArgument(FnType->getReturnType()),
Eric Fiselier89bf0e72017-03-06 22:52:28 +000078 S.Context.getTrivialTypeSourceInfo(FnType->getReturnType(), KwLoc)));
Richard Smith71d403e2015-11-22 07:33:28 +000079 // FIXME: If the function is a non-static member function, add the type
80 // of the implicit object parameter before the formal parameters.
Richard Smith9f690bd2015-10-27 06:02:45 +000081 for (QualType T : FnType->getParamTypes())
82 Args.addArgument(TemplateArgumentLoc(
Eric Fiselier89bf0e72017-03-06 22:52:28 +000083 TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));
Richard Smith9f690bd2015-10-27 06:02:45 +000084
85 // Build the template-id.
86 QualType CoroTrait =
Eric Fiselier89bf0e72017-03-06 22:52:28 +000087 S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
Richard Smith9f690bd2015-10-27 06:02:45 +000088 if (CoroTrait.isNull())
89 return QualType();
Eric Fiselier89bf0e72017-03-06 22:52:28 +000090 if (S.RequireCompleteType(KwLoc, CoroTrait,
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +000091 diag::err_coroutine_type_missing_specialization))
Richard Smith9f690bd2015-10-27 06:02:45 +000092 return QualType();
93
Eric Fiselier89bf0e72017-03-06 22:52:28 +000094 auto *RD = CoroTrait->getAsCXXRecordDecl();
Richard Smith9f690bd2015-10-27 06:02:45 +000095 assert(RD && "specialization of class template is not a class?");
96
97 // Look up the ::promise_type member.
Eric Fiselier89bf0e72017-03-06 22:52:28 +000098 LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
Richard Smith9f690bd2015-10-27 06:02:45 +000099 Sema::LookupOrdinaryName);
100 S.LookupQualifiedName(R, RD);
101 auto *Promise = R.getAsSingle<TypeDecl>();
102 if (!Promise) {
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000103 S.Diag(FuncLoc,
104 diag::err_implied_std_coroutine_traits_promise_type_not_found)
Gor Nishanov8df64e92016-10-27 16:28:31 +0000105 << RD;
Richard Smith9f690bd2015-10-27 06:02:45 +0000106 return QualType();
107 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000108 // The promise type is required to be a class type.
109 QualType PromiseType = S.Context.getTypeDeclType(Promise);
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000110
111 auto buildElaboratedType = [&]() {
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000112 auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, StdExp);
Richard Smith9b2f53e2015-11-19 02:36:35 +0000113 NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
114 CoroTrait.getTypePtr());
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000115 return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
116 };
Richard Smith9b2f53e2015-11-19 02:36:35 +0000117
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000118 if (!PromiseType->getAsCXXRecordDecl()) {
119 S.Diag(FuncLoc,
120 diag::err_implied_std_coroutine_traits_promise_type_not_class)
121 << buildElaboratedType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000122 return QualType();
123 }
Eric Fiselier89bf0e72017-03-06 22:52:28 +0000124 if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
125 diag::err_coroutine_promise_type_incomplete))
126 return QualType();
Richard Smith9f690bd2015-10-27 06:02:45 +0000127
128 return PromiseType;
129}
130
Gor Nishanov29ff6382017-05-24 14:34:19 +0000131/// Look up the std::experimental::coroutine_handle<PromiseType>.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000132static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
133 SourceLocation Loc) {
134 if (PromiseType.isNull())
135 return QualType();
136
137 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
138 assert(StdExp && "Should already be diagnosed");
139
140 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
141 Loc, Sema::LookupOrdinaryName);
142 if (!S.LookupQualifiedName(Result, StdExp)) {
143 S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
144 << "std::experimental::coroutine_handle";
145 return QualType();
146 }
147
148 ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
149 if (!CoroHandle) {
150 Result.suppressDiagnostics();
151 // We found something weird. Complain about the first thing we found.
152 NamedDecl *Found = *Result.begin();
153 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
154 return QualType();
155 }
156
157 // Form template argument list for coroutine_handle<Promise>.
158 TemplateArgumentListInfo Args(Loc, Loc);
159 Args.addArgument(TemplateArgumentLoc(
160 TemplateArgument(PromiseType),
161 S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
162
163 // Build the template-id.
164 QualType CoroHandleType =
165 S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
166 if (CoroHandleType.isNull())
167 return QualType();
168 if (S.RequireCompleteType(Loc, CoroHandleType,
169 diag::err_coroutine_type_missing_specialization))
170 return QualType();
171
172 return CoroHandleType;
173}
174
Eric Fiselierc8efda72016-10-27 18:43:28 +0000175static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
176 StringRef Keyword) {
Richard Smith744b2242015-11-20 02:54:01 +0000177 // 'co_await' and 'co_yield' are not permitted in unevaluated operands.
178 if (S.isUnevaluatedContext()) {
179 S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
Eric Fiselierc8efda72016-10-27 18:43:28 +0000180 return false;
Richard Smith744b2242015-11-20 02:54:01 +0000181 }
Richard Smithcfd53b42015-10-22 06:13:50 +0000182
183 // Any other usage must be within a function.
184 auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
185 if (!FD) {
186 S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
187 ? diag::err_coroutine_objc_method
188 : diag::err_coroutine_outside_function) << Keyword;
Eric Fiselierc8efda72016-10-27 18:43:28 +0000189 return false;
Richard Smithcfd53b42015-10-22 06:13:50 +0000190 }
191
Eric Fiselierc8efda72016-10-27 18:43:28 +0000192 // An enumeration for mapping the diagnostic type to the correct diagnostic
193 // selection index.
194 enum InvalidFuncDiag {
195 DiagCtor = 0,
196 DiagDtor,
197 DiagCopyAssign,
198 DiagMoveAssign,
199 DiagMain,
200 DiagConstexpr,
201 DiagAutoRet,
202 DiagVarargs,
203 };
204 bool Diagnosed = false;
205 auto DiagInvalid = [&](InvalidFuncDiag ID) {
206 S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
207 Diagnosed = true;
208 return false;
209 };
210
211 // Diagnose when a constructor, destructor, copy/move assignment operator,
212 // or the function 'main' are declared as a coroutine.
213 auto *MD = dyn_cast<CXXMethodDecl>(FD);
214 if (MD && isa<CXXConstructorDecl>(MD))
215 return DiagInvalid(DiagCtor);
216 else if (MD && isa<CXXDestructorDecl>(MD))
217 return DiagInvalid(DiagDtor);
218 else if (MD && MD->isCopyAssignmentOperator())
219 return DiagInvalid(DiagCopyAssign);
220 else if (MD && MD->isMoveAssignmentOperator())
221 return DiagInvalid(DiagMoveAssign);
222 else if (FD->isMain())
223 return DiagInvalid(DiagMain);
224
225 // Emit a diagnostics for each of the following conditions which is not met.
226 if (FD->isConstexpr())
227 DiagInvalid(DiagConstexpr);
228 if (FD->getReturnType()->isUndeducedType())
229 DiagInvalid(DiagAutoRet);
230 if (FD->isVariadic())
231 DiagInvalid(DiagVarargs);
232
233 return !Diagnosed;
234}
235
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000236static ExprResult buildOperatorCoawaitLookupExpr(Sema &SemaRef, Scope *S,
237 SourceLocation Loc) {
238 DeclarationName OpName =
239 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
240 LookupResult Operators(SemaRef, OpName, SourceLocation(),
241 Sema::LookupOperatorName);
242 SemaRef.LookupName(Operators, S);
Eric Fiselierc8efda72016-10-27 18:43:28 +0000243
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000244 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
245 const auto &Functions = Operators.asUnresolvedSet();
246 bool IsOverloaded =
247 Functions.size() > 1 ||
248 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
249 Expr *CoawaitOp = UnresolvedLookupExpr::Create(
250 SemaRef.Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
251 DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
252 Functions.begin(), Functions.end());
253 assert(CoawaitOp);
254 return CoawaitOp;
255}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000256
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000257/// Build a call to 'operator co_await' if there is a suitable operator for
258/// the given expression.
259static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, SourceLocation Loc,
260 Expr *E,
261 UnresolvedLookupExpr *Lookup) {
262 UnresolvedSet<16> Functions;
263 Functions.append(Lookup->decls_begin(), Lookup->decls_end());
264 return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
265}
Eric Fiselierc8efda72016-10-27 18:43:28 +0000266
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000267static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
268 SourceLocation Loc, Expr *E) {
269 ExprResult R = buildOperatorCoawaitLookupExpr(SemaRef, S, Loc);
270 if (R.isInvalid())
271 return ExprError();
272 return buildOperatorCoawaitCall(SemaRef, Loc, E,
273 cast<UnresolvedLookupExpr>(R.get()));
Richard Smithcfd53b42015-10-22 06:13:50 +0000274}
275
Gor Nishanov8df64e92016-10-27 16:28:31 +0000276static Expr *buildBuiltinCall(Sema &S, SourceLocation Loc, Builtin::ID Id,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000277 MultiExprArg CallArgs) {
Gor Nishanov8df64e92016-10-27 16:28:31 +0000278 StringRef Name = S.Context.BuiltinInfo.getName(Id);
279 LookupResult R(S, &S.Context.Idents.get(Name), Loc, Sema::LookupOrdinaryName);
280 S.LookupName(R, S.TUScope, /*AllowBuiltinCreation=*/true);
281
282 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
283 assert(BuiltInDecl && "failed to find builtin declaration");
284
285 ExprResult DeclRef =
286 S.BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
287 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
288
289 ExprResult Call =
290 S.ActOnCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
291
292 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
293 return Call.get();
294}
295
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000296static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
297 SourceLocation Loc) {
298 QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
299 if (CoroHandleType.isNull())
300 return ExprError();
301
302 DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
303 LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
304 Sema::LookupOrdinaryName);
305 if (!S.LookupQualifiedName(Found, LookupCtx)) {
306 S.Diag(Loc, diag::err_coroutine_handle_missing_member)
307 << "from_address";
308 return ExprError();
309 }
310
311 Expr *FramePtr =
312 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
313
314 CXXScopeSpec SS;
315 ExprResult FromAddr =
316 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
317 if (FromAddr.isInvalid())
318 return ExprError();
319
320 return S.ActOnCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
321}
Richard Smithcfd53b42015-10-22 06:13:50 +0000322
Richard Smith9f690bd2015-10-27 06:02:45 +0000323struct ReadySuspendResumeResult {
Eric Fiselierd978e532017-05-28 18:21:12 +0000324 enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume };
Richard Smith9f690bd2015-10-27 06:02:45 +0000325 Expr *Results[3];
Gor Nishanovce43bd22017-03-11 01:30:17 +0000326 OpaqueValueExpr *OpaqueValue;
327 bool IsInvalid;
Richard Smith9f690bd2015-10-27 06:02:45 +0000328};
329
Richard Smith23da82c2015-11-20 22:40:06 +0000330static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000331 StringRef Name, MultiExprArg Args) {
Richard Smith23da82c2015-11-20 22:40:06 +0000332 DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
333
334 // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
335 CXXScopeSpec SS;
336 ExprResult Result = S.BuildMemberReferenceExpr(
337 Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
338 SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
339 /*Scope=*/nullptr);
340 if (Result.isInvalid())
341 return ExprError();
342
343 return S.ActOnCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
344}
345
Richard Smith9f690bd2015-10-27 06:02:45 +0000346/// Build calls to await_ready, await_suspend, and await_resume for a co_await
347/// expression.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000348static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
349 SourceLocation Loc, Expr *E) {
Gor Nishanovce43bd22017-03-11 01:30:17 +0000350 OpaqueValueExpr *Operand = new (S.Context)
351 OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
352
Richard Smith9f690bd2015-10-27 06:02:45 +0000353 // Assume invalid until we see otherwise.
Gor Nishanovce43bd22017-03-11 01:30:17 +0000354 ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true};
Richard Smith9f690bd2015-10-27 06:02:45 +0000355
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000356 ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc);
357 if (CoroHandleRes.isInvalid())
358 return Calls;
359 Expr *CoroHandle = CoroHandleRes.get();
360
Richard Smith9f690bd2015-10-27 06:02:45 +0000361 const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000362 MultiExprArg Args[] = {None, CoroHandle, None};
Richard Smith9f690bd2015-10-27 06:02:45 +0000363 for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000364 ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]);
Richard Smith9f690bd2015-10-27 06:02:45 +0000365 if (Result.isInvalid())
366 return Calls;
367 Calls.Results[I] = Result.get();
368 }
369
Eric Fiselierd978e532017-05-28 18:21:12 +0000370 // Assume the calls are valid; all further checking should make them invalid.
Richard Smith9f690bd2015-10-27 06:02:45 +0000371 Calls.IsInvalid = false;
Eric Fiselierd978e532017-05-28 18:21:12 +0000372
373 using ACT = ReadySuspendResumeResult::AwaitCallType;
374 CallExpr *AwaitReady = cast<CallExpr>(Calls.Results[ACT::ACT_Ready]);
375 if (!AwaitReady->getType()->isDependentType()) {
376 // [expr.await]p3 [...]
377 // — await-ready is the expression e.await_ready(), contextually converted
378 // to bool.
379 ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady);
380 if (Conv.isInvalid()) {
381 S.Diag(AwaitReady->getDirectCallee()->getLocStart(),
382 diag::note_await_ready_no_bool_conversion);
383 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
384 << AwaitReady->getDirectCallee() << E->getSourceRange();
385 Calls.IsInvalid = true;
386 }
387 Calls.Results[ACT::ACT_Ready] = Conv.get();
388 }
389 CallExpr *AwaitSuspend = cast<CallExpr>(Calls.Results[ACT::ACT_Suspend]);
390 if (!AwaitSuspend->getType()->isDependentType()) {
391 // [expr.await]p3 [...]
392 // - await-suspend is the expression e.await_suspend(h), which shall be
393 // a prvalue of type void or bool.
394 QualType RetType = AwaitSuspend->getType();
395 if (RetType != S.Context.BoolTy && RetType != S.Context.VoidTy) {
396 S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
397 diag::err_await_suspend_invalid_return_type)
398 << RetType;
399 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
400 << AwaitSuspend->getDirectCallee();
401 Calls.IsInvalid = true;
402 }
403 }
404
Richard Smith9f690bd2015-10-27 06:02:45 +0000405 return Calls;
406}
407
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000408static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
409 SourceLocation Loc, StringRef Name,
410 MultiExprArg Args) {
411
412 // Form a reference to the promise.
413 ExprResult PromiseRef = S.BuildDeclRefExpr(
414 Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
415 if (PromiseRef.isInvalid())
416 return ExprError();
417
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000418 return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
419}
420
421VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
422 assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
423 auto *FD = cast<FunctionDecl>(CurContext);
424
425 QualType T =
426 FD->getType()->isDependentType()
427 ? Context.DependentTy
428 : lookupPromiseType(*this, FD->getType()->castAs<FunctionProtoType>(),
429 Loc, FD->getLocation());
430 if (T.isNull())
431 return nullptr;
432
433 auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
434 &PP.getIdentifierTable().get("__promise"), T,
435 Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
436 CheckVariableDeclarationType(VD);
437 if (VD->isInvalidDecl())
438 return nullptr;
439 ActOnUninitializedDecl(VD);
440 assert(!VD->isInvalidDecl());
441 return VD;
442}
443
444/// Check that this is a context in which a coroutine suspension can appear.
445static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000446 StringRef Keyword,
447 bool IsImplicit = false) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000448 if (!isValidCoroutineContext(S, Loc, Keyword))
449 return nullptr;
450
451 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000452
453 auto *ScopeInfo = S.getCurFunction();
454 assert(ScopeInfo && "missing function scope for function");
455
Eric Fiseliercac0a592017-03-11 02:35:37 +0000456 if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
457 ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
458
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000459 if (ScopeInfo->CoroutinePromise)
460 return ScopeInfo;
461
462 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
463 if (!ScopeInfo->CoroutinePromise)
464 return nullptr;
465
466 return ScopeInfo;
467}
468
469static bool actOnCoroutineBodyStart(Sema &S, Scope *SC, SourceLocation KWLoc,
470 StringRef Keyword) {
471 if (!checkCoroutineContext(S, KWLoc, Keyword))
472 return false;
473 auto *ScopeInfo = S.getCurFunction();
474 assert(ScopeInfo->CoroutinePromise);
475
476 // If we have existing coroutine statements then we have already built
477 // the initial and final suspend points.
478 if (!ScopeInfo->NeedsCoroutineSuspends)
479 return true;
480
481 ScopeInfo->setNeedsCoroutineSuspends(false);
482
483 auto *Fn = cast<FunctionDecl>(S.CurContext);
484 SourceLocation Loc = Fn->getLocation();
485 // Build the initial suspend point
486 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
487 ExprResult Suspend =
488 buildPromiseCall(S, ScopeInfo->CoroutinePromise, Loc, Name, None);
489 if (Suspend.isInvalid())
490 return StmtError();
491 Suspend = buildOperatorCoawaitCall(S, SC, Loc, Suspend.get());
492 if (Suspend.isInvalid())
493 return StmtError();
494 Suspend = S.BuildResolvedCoawaitExpr(Loc, Suspend.get(),
495 /*IsImplicit*/ true);
496 Suspend = S.ActOnFinishFullExpr(Suspend.get());
497 if (Suspend.isInvalid()) {
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000498 S.Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000499 << ((Name == "initial_suspend") ? 0 : 1);
500 S.Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
501 return StmtError();
502 }
503 return cast<Stmt>(Suspend.get());
504 };
505
506 StmtResult InitSuspend = buildSuspends("initial_suspend");
507 if (InitSuspend.isInvalid())
508 return true;
509
510 StmtResult FinalSuspend = buildSuspends("final_suspend");
511 if (FinalSuspend.isInvalid())
512 return true;
513
514 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
515
516 return true;
517}
518
Richard Smith9f690bd2015-10-27 06:02:45 +0000519ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000520 if (!actOnCoroutineBodyStart(*this, S, Loc, "co_await")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000521 CorrectDelayedTyposInExpr(E);
522 return ExprError();
523 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000524
Richard Smith10610f72015-11-20 22:57:24 +0000525 if (E->getType()->isPlaceholderType()) {
526 ExprResult R = CheckPlaceholderExpr(E);
527 if (R.isInvalid()) return ExprError();
528 E = R.get();
529 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000530 ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
531 if (Lookup.isInvalid())
532 return ExprError();
533 return BuildUnresolvedCoawaitExpr(Loc, E,
534 cast<UnresolvedLookupExpr>(Lookup.get()));
535}
Richard Smith10610f72015-11-20 22:57:24 +0000536
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000537ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000538 UnresolvedLookupExpr *Lookup) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000539 auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
540 if (!FSI)
541 return ExprError();
542
543 if (E->getType()->isPlaceholderType()) {
544 ExprResult R = CheckPlaceholderExpr(E);
545 if (R.isInvalid())
546 return ExprError();
547 E = R.get();
548 }
549
550 auto *Promise = FSI->CoroutinePromise;
551 if (Promise->getType()->isDependentType()) {
552 Expr *Res =
553 new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000554 return Res;
555 }
556
557 auto *RD = Promise->getType()->getAsCXXRecordDecl();
558 if (lookupMember(*this, "await_transform", RD, Loc)) {
559 ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
560 if (R.isInvalid()) {
561 Diag(Loc,
562 diag::note_coroutine_promise_implicit_await_transform_required_here)
563 << E->getSourceRange();
564 return ExprError();
565 }
566 E = R.get();
567 }
568 ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
Richard Smith9f690bd2015-10-27 06:02:45 +0000569 if (Awaitable.isInvalid())
570 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000571
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000572 return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
Richard Smith9f690bd2015-10-27 06:02:45 +0000573}
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000574
575ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E,
576 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000577 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
Richard Smith744b2242015-11-20 02:54:01 +0000578 if (!Coroutine)
579 return ExprError();
Richard Smith9f690bd2015-10-27 06:02:45 +0000580
Richard Smith9f690bd2015-10-27 06:02:45 +0000581 if (E->getType()->isPlaceholderType()) {
582 ExprResult R = CheckPlaceholderExpr(E);
583 if (R.isInvalid()) return ExprError();
584 E = R.get();
585 }
586
Richard Smith10610f72015-11-20 22:57:24 +0000587 if (E->getType()->isDependentType()) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000588 Expr *Res = new (Context)
589 CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
Richard Smith10610f72015-11-20 22:57:24 +0000590 return Res;
591 }
592
Richard Smith1f38edd2015-11-22 03:13:02 +0000593 // If the expression is a temporary, materialize it as an lvalue so that we
594 // can use it multiple times.
595 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000596 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smith9f690bd2015-10-27 06:02:45 +0000597
598 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000599 ReadySuspendResumeResult RSS =
600 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000601 if (RSS.IsInvalid)
602 return ExprError();
603
Gor Nishanovce43bd22017-03-11 01:30:17 +0000604 Expr *Res =
605 new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
606 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000607
Richard Smithcfd53b42015-10-22 06:13:50 +0000608 return Res;
609}
610
Richard Smith9f690bd2015-10-27 06:02:45 +0000611ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000612 if (!actOnCoroutineBodyStart(*this, S, Loc, "co_yield")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000613 CorrectDelayedTyposInExpr(E);
Richard Smith23da82c2015-11-20 22:40:06 +0000614 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000615 }
Richard Smith23da82c2015-11-20 22:40:06 +0000616
617 // Build yield_value call.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000618 ExprResult Awaitable = buildPromiseCall(
619 *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000620 if (Awaitable.isInvalid())
621 return ExprError();
Richard Smith23da82c2015-11-20 22:40:06 +0000622
623 // Build 'operator co_await' call.
624 Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
625 if (Awaitable.isInvalid())
626 return ExprError();
627
Richard Smith9f690bd2015-10-27 06:02:45 +0000628 return BuildCoyieldExpr(Loc, Awaitable.get());
629}
630ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
631 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
Richard Smith744b2242015-11-20 02:54:01 +0000632 if (!Coroutine)
633 return ExprError();
Richard Smithcfd53b42015-10-22 06:13:50 +0000634
Richard Smith10610f72015-11-20 22:57:24 +0000635 if (E->getType()->isPlaceholderType()) {
636 ExprResult R = CheckPlaceholderExpr(E);
637 if (R.isInvalid()) return ExprError();
638 E = R.get();
639 }
640
Richard Smithd7bed4d2015-11-22 02:57:17 +0000641 if (E->getType()->isDependentType()) {
642 Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000643 return Res;
644 }
645
Richard Smith1f38edd2015-11-22 03:13:02 +0000646 // If the expression is a temporary, materialize it as an lvalue so that we
647 // can use it multiple times.
648 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000649 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000650
651 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000652 ReadySuspendResumeResult RSS =
653 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000654 if (RSS.IsInvalid)
655 return ExprError();
656
657 Expr *Res = new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
Gor Nishanovce43bd22017-03-11 01:30:17 +0000658 RSS.Results[2], RSS.OpaqueValue);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000659
Richard Smithcfd53b42015-10-22 06:13:50 +0000660 return Res;
661}
662
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000663StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
664 if (!actOnCoroutineBodyStart(*this, S, Loc, "co_return")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000665 CorrectDelayedTyposInExpr(E);
666 return StmtError();
667 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000668 return BuildCoreturnStmt(Loc, E);
669}
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000670
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000671StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
672 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000673 auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000674 if (!FSI)
Richard Smith71d403e2015-11-22 07:33:28 +0000675 return StmtError();
676
677 if (E && E->getType()->isPlaceholderType() &&
678 !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
Richard Smith10610f72015-11-20 22:57:24 +0000679 ExprResult R = CheckPlaceholderExpr(E);
680 if (R.isInvalid()) return StmtError();
681 E = R.get();
682 }
683
Richard Smith4ba66602015-11-22 07:05:16 +0000684 // FIXME: If the operand is a reference to a variable that's about to go out
Richard Smith2af65c42015-11-24 02:34:39 +0000685 // of scope, we should treat the operand as an xvalue for this overload
Richard Smith4ba66602015-11-22 07:05:16 +0000686 // resolution.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000687 VarDecl *Promise = FSI->CoroutinePromise;
Richard Smith4ba66602015-11-22 07:05:16 +0000688 ExprResult PC;
Eric Fiselier98131312016-10-06 21:23:38 +0000689 if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000690 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
Richard Smith4ba66602015-11-22 07:05:16 +0000691 } else {
692 E = MakeFullDiscardedValueExpr(E).get();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000693 PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
Richard Smith4ba66602015-11-22 07:05:16 +0000694 }
695 if (PC.isInvalid())
696 return StmtError();
697
698 Expr *PCE = ActOnFinishFullExpr(PC.get()).get();
699
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000700 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
Richard Smithcfd53b42015-10-22 06:13:50 +0000701 return Res;
702}
703
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000704/// Look up the std::nothrow object.
705static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
706 NamespaceDecl *Std = S.getStdNamespace();
707 assert(Std && "Should already be diagnosed");
708
709 LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
710 Sema::LookupOrdinaryName);
711 if (!S.LookupQualifiedName(Result, Std)) {
712 // FIXME: <experimental/coroutine> should have been included already.
713 // If we require it to include <new> then this diagnostic is no longer
714 // needed.
715 S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
716 return nullptr;
717 }
718
719 // FIXME: Mark the variable as ODR used. This currently does not work
720 // likely due to the scope at in which this function is called.
721 auto *VD = Result.getAsSingle<VarDecl>();
722 if (!VD) {
723 Result.suppressDiagnostics();
724 // We found something weird. Complain about the first thing we found.
725 NamedDecl *Found = *Result.begin();
726 S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
727 return nullptr;
728 }
729
730 ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
731 if (DR.isInvalid())
732 return nullptr;
733
734 return DR.get();
735}
736
Gor Nishanov8df64e92016-10-27 16:28:31 +0000737// Find an appropriate delete for the promise.
738static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc,
739 QualType PromiseType) {
740 FunctionDecl *OperatorDelete = nullptr;
741
742 DeclarationName DeleteName =
743 S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
744
745 auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
746 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
747
748 if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
749 return nullptr;
750
751 if (!OperatorDelete) {
752 // Look for a global declaration.
753 const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
754 const bool Overaligned = false;
755 OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
756 Overaligned, DeleteName);
757 }
758 S.MarkFunctionReferenced(Loc, OperatorDelete);
759 return OperatorDelete;
760}
761
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000762
763void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
764 FunctionScopeInfo *Fn = getCurFunction();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000765 assert(Fn && Fn->isCoroutine() && "not a coroutine");
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000766 if (!Body) {
767 assert(FD->isInvalidDecl() &&
768 "a null body is only allowed for invalid declarations");
769 return;
770 }
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000771 // We have a function that uses coroutine keywords, but we failed to build
772 // the promise type.
773 if (!Fn->CoroutinePromise)
774 return FD->setInvalidDecl();
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000775
776 if (isa<CoroutineBodyStmt>(Body)) {
Gor Nishanov29ff6382017-05-24 14:34:19 +0000777 // Nothing todo. the body is already a transformed coroutine body statement.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000778 return;
779 }
780
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000781 // Coroutines [stmt.return]p1:
782 // A return statement shall not appear in a coroutine.
783 if (Fn->FirstReturnLoc.isValid()) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000784 assert(Fn->FirstCoroutineStmtLoc.isValid() &&
785 "first coroutine location not set");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000786 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000787 Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
788 << Fn->getFirstCoroutineStmtKeyword();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000789 }
Eric Fiselierbee782b2017-04-03 19:21:00 +0000790 CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
791 if (Builder.isInvalid() || !Builder.buildStatements())
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000792 return FD->setInvalidDecl();
793
794 // Build body for the coroutine wrapper statement.
795 Body = CoroutineBodyStmt::Create(Context, Builder);
796}
797
Eric Fiselierbee782b2017-04-03 19:21:00 +0000798CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
799 sema::FunctionScopeInfo &Fn,
800 Stmt *Body)
801 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
802 IsPromiseDependentType(
803 !Fn.CoroutinePromise ||
804 Fn.CoroutinePromise->getType()->isDependentType()) {
805 this->Body = Body;
806 if (!IsPromiseDependentType) {
807 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
808 assert(PromiseRecordDecl && "Type should have already been checked");
809 }
810 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
811}
812
813bool CoroutineStmtBuilder::buildStatements() {
814 assert(this->IsValid && "coroutine already invalid");
815 this->IsValid = makeReturnObject() && makeParamMoves();
816 if (this->IsValid && !IsPromiseDependentType)
817 buildDependentStatements();
818 return this->IsValid;
819}
820
821bool CoroutineStmtBuilder::buildDependentStatements() {
822 assert(this->IsValid && "coroutine already invalid");
823 assert(!this->IsPromiseDependentType &&
824 "coroutine cannot have a dependent promise type");
825 this->IsValid = makeOnException() && makeOnFallthrough() &&
Gor Nishanov6a470682017-05-22 20:22:23 +0000826 makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
827 makeNewAndDeleteExpr();
Eric Fiselierbee782b2017-04-03 19:21:00 +0000828 return this->IsValid;
829}
830
831bool CoroutineStmtBuilder::makePromiseStmt() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000832 // Form a declaration statement for the promise declaration, so that AST
833 // visitors can more easily find it.
834 StmtResult PromiseStmt =
835 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
836 if (PromiseStmt.isInvalid())
837 return false;
838
839 this->Promise = PromiseStmt.get();
840 return true;
841}
842
Eric Fiselierbee782b2017-04-03 19:21:00 +0000843bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000844 if (Fn.hasInvalidCoroutineSuspends())
845 return false;
846 this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
847 this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
848 return true;
849}
850
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000851static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
852 CXXRecordDecl *PromiseRecordDecl,
853 FunctionScopeInfo &Fn) {
854 auto Loc = E->getExprLoc();
855 if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
856 auto *Decl = DeclRef->getDecl();
857 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
858 if (Method->isStatic())
859 return true;
860 else
861 Loc = Decl->getLocation();
862 }
863 }
864
865 S.Diag(
866 Loc,
867 diag::err_coroutine_promise_get_return_object_on_allocation_failure)
868 << PromiseRecordDecl;
869 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
870 << Fn.getFirstCoroutineStmtKeyword();
871 return false;
872}
873
Eric Fiselierbee782b2017-04-03 19:21:00 +0000874bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
875 assert(!IsPromiseDependentType &&
876 "cannot make statement while the promise type is dependent");
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000877
878 // [dcl.fct.def.coroutine]/8
879 // The unqualified-id get_return_object_on_allocation_failure is looked up in
880 // the scope of class P by class member access lookup (3.4.5). ...
881 // If an allocation function returns nullptr, ... the coroutine return value
882 // is obtained by a call to ... get_return_object_on_allocation_failure().
883
884 DeclarationName DN =
885 S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
886 LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
Eric Fiselierbee782b2017-04-03 19:21:00 +0000887 if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
888 return true;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000889
890 CXXScopeSpec SS;
891 ExprResult DeclNameExpr =
892 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
Eric Fiselierbee782b2017-04-03 19:21:00 +0000893 if (DeclNameExpr.isInvalid())
894 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000895
896 if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
897 return false;
898
899 ExprResult ReturnObjectOnAllocationFailure =
900 S.ActOnCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
Eric Fiselierbee782b2017-04-03 19:21:00 +0000901 if (ReturnObjectOnAllocationFailure.isInvalid())
902 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000903
Gor Nishanovc4a19082017-03-28 02:51:45 +0000904 StmtResult ReturnStmt =
905 S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
Gor Nishanov6a470682017-05-22 20:22:23 +0000906 if (ReturnStmt.isInvalid()) {
Eric Fiselierfc50f622017-05-25 14:59:39 +0000907 S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
908 << DN;
Gor Nishanov6a470682017-05-22 20:22:23 +0000909 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
910 << Fn.getFirstCoroutineStmtKeyword();
Eric Fiselierbee782b2017-04-03 19:21:00 +0000911 return false;
Gor Nishanov6a470682017-05-22 20:22:23 +0000912 }
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000913
914 this->ReturnStmtOnAllocFailure = ReturnStmt.get();
915 return true;
916}
917
Eric Fiselierbee782b2017-04-03 19:21:00 +0000918bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000919 // Form and check allocation and deallocation calls.
Eric Fiselierbee782b2017-04-03 19:21:00 +0000920 assert(!IsPromiseDependentType &&
921 "cannot make statement while the promise type is dependent");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000922 QualType PromiseType = Fn.CoroutinePromise->getType();
Gor Nishanov8df64e92016-10-27 16:28:31 +0000923
924 if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
925 return false;
926
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000927 const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
928
Gor Nishanov8df64e92016-10-27 16:28:31 +0000929 // FIXME: Add support for stateful allocators.
930
931 FunctionDecl *OperatorNew = nullptr;
932 FunctionDecl *OperatorDelete = nullptr;
933 FunctionDecl *UnusedResult = nullptr;
934 bool PassAlignment = false;
Eric Fiselierf747f532017-04-18 05:08:08 +0000935 SmallVector<Expr *, 1> PlacementArgs;
Gor Nishanov8df64e92016-10-27 16:28:31 +0000936
937 S.FindAllocationFunctions(Loc, SourceRange(),
938 /*UseGlobal*/ false, PromiseType,
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000939 /*isArray*/ false, PassAlignment, PlacementArgs,
940 OperatorNew, UnusedResult);
Gor Nishanov8df64e92016-10-27 16:28:31 +0000941
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000942 bool IsGlobalOverload =
943 OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
944 // If we didn't find a class-local new declaration and non-throwing new
945 // was is required then we need to lookup the non-throwing global operator
946 // instead.
947 if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
948 auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
949 if (!StdNoThrow)
950 return false;
Eric Fiselierf747f532017-04-18 05:08:08 +0000951 PlacementArgs = {StdNoThrow};
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000952 OperatorNew = nullptr;
953 S.FindAllocationFunctions(Loc, SourceRange(),
954 /*UseGlobal*/ true, PromiseType,
955 /*isArray*/ false, PassAlignment, PlacementArgs,
956 OperatorNew, UnusedResult);
957 }
Gor Nishanov8df64e92016-10-27 16:28:31 +0000958
Eric Fiselierc5128752017-04-18 05:30:39 +0000959 assert(OperatorNew && "expected definition of operator new to be found");
960
961 if (RequiresNoThrowAlloc) {
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000962 const auto *FT = OperatorNew->getType()->getAs<FunctionProtoType>();
963 if (!FT->isNothrow(S.Context, /*ResultIfDependent*/ false)) {
964 S.Diag(OperatorNew->getLocation(),
965 diag::err_coroutine_promise_new_requires_nothrow)
966 << OperatorNew;
967 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
968 << OperatorNew;
969 return false;
970 }
971 }
972
973 if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr)
Gor Nishanov8df64e92016-10-27 16:28:31 +0000974 return false;
975
976 Expr *FramePtr =
977 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
978
979 Expr *FrameSize =
980 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {});
981
982 // Make new call.
983
984 ExprResult NewRef =
985 S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
986 if (NewRef.isInvalid())
987 return false;
988
Eric Fiselierf747f532017-04-18 05:08:08 +0000989 SmallVector<Expr *, 2> NewArgs(1, FrameSize);
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000990 for (auto Arg : PlacementArgs)
991 NewArgs.push_back(Arg);
992
Gor Nishanov8df64e92016-10-27 16:28:31 +0000993 ExprResult NewExpr =
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000994 S.ActOnCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
995 NewExpr = S.ActOnFinishFullExpr(NewExpr.get());
Gor Nishanov8df64e92016-10-27 16:28:31 +0000996 if (NewExpr.isInvalid())
997 return false;
998
Gor Nishanov8df64e92016-10-27 16:28:31 +0000999 // Make delete call.
1000
1001 QualType OpDeleteQualType = OperatorDelete->getType();
1002
1003 ExprResult DeleteRef =
1004 S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
1005 if (DeleteRef.isInvalid())
1006 return false;
1007
1008 Expr *CoroFree =
1009 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr});
1010
1011 SmallVector<Expr *, 2> DeleteArgs{CoroFree};
1012
1013 // Check if we need to pass the size.
1014 const auto *OpDeleteType =
1015 OpDeleteQualType.getTypePtr()->getAs<FunctionProtoType>();
1016 if (OpDeleteType->getNumParams() > 1)
1017 DeleteArgs.push_back(FrameSize);
1018
1019 ExprResult DeleteExpr =
1020 S.ActOnCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001021 DeleteExpr = S.ActOnFinishFullExpr(DeleteExpr.get());
Gor Nishanov8df64e92016-10-27 16:28:31 +00001022 if (DeleteExpr.isInvalid())
1023 return false;
1024
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001025 this->Allocate = NewExpr.get();
1026 this->Deallocate = DeleteExpr.get();
Gor Nishanov8df64e92016-10-27 16:28:31 +00001027
1028 return true;
1029}
1030
Eric Fiselierbee782b2017-04-03 19:21:00 +00001031bool CoroutineStmtBuilder::makeOnFallthrough() {
1032 assert(!IsPromiseDependentType &&
1033 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001034
1035 // [dcl.fct.def.coroutine]/4
1036 // The unqualified-ids 'return_void' and 'return_value' are looked up in
1037 // the scope of class P. If both are found, the program is ill-formed.
Eric Fiselierfc50f622017-05-25 14:59:39 +00001038 bool HasRVoid, HasRValue;
1039 LookupResult LRVoid =
1040 lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
1041 LookupResult LRValue =
1042 lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001043
Eric Fiselier709d1b32016-10-27 07:30:31 +00001044 StmtResult Fallthrough;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001045 if (HasRVoid && HasRValue) {
1046 // FIXME Improve this diagnostic
Eric Fiselierfc50f622017-05-25 14:59:39 +00001047 S.Diag(FD.getLocation(),
1048 diag::err_coroutine_promise_incompatible_return_functions)
1049 << PromiseRecordDecl;
1050 S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
1051 diag::note_member_first_declared_here)
1052 << LRVoid.getLookupName();
1053 S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
1054 diag::note_member_first_declared_here)
1055 << LRValue.getLookupName();
1056 return false;
1057 } else if (!HasRVoid && !HasRValue) {
1058 // FIXME: The PDTS currently specifies this case as UB, not ill-formed.
1059 // However we still diagnose this as an error since until the PDTS is fixed.
1060 S.Diag(FD.getLocation(),
1061 diag::err_coroutine_promise_requires_return_function)
1062 << PromiseRecordDecl;
1063 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001064 << PromiseRecordDecl;
1065 return false;
1066 } else if (HasRVoid) {
1067 // If the unqualified-id return_void is found, flowing off the end of a
1068 // coroutine is equivalent to a co_return with no operand. Otherwise,
1069 // flowing off the end of a coroutine results in undefined behavior.
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001070 Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
1071 /*IsImplicit*/false);
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001072 Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
1073 if (Fallthrough.isInvalid())
1074 return false;
Eric Fiselier709d1b32016-10-27 07:30:31 +00001075 }
Richard Smith2af65c42015-11-24 02:34:39 +00001076
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001077 this->OnFallthrough = Fallthrough.get();
1078 return true;
1079}
1080
Eric Fiselierbee782b2017-04-03 19:21:00 +00001081bool CoroutineStmtBuilder::makeOnException() {
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001082 // Try to form 'p.unhandled_exception();'
Eric Fiselierbee782b2017-04-03 19:21:00 +00001083 assert(!IsPromiseDependentType &&
1084 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001085
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001086 const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1087
1088 if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
1089 auto DiagID =
1090 RequireUnhandledException
1091 ? diag::err_coroutine_promise_unhandled_exception_required
1092 : diag::
1093 warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1094 S.Diag(Loc, DiagID) << PromiseRecordDecl;
Gor Nishanov29ff6382017-05-24 14:34:19 +00001095 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1096 << PromiseRecordDecl;
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001097 return !RequireUnhandledException;
1098 }
1099
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001100 // If exceptions are disabled, don't try to build OnException.
1101 if (!S.getLangOpts().CXXExceptions)
1102 return true;
1103
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001104 ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
1105 "unhandled_exception", None);
1106 UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc);
1107 if (UnhandledException.isInvalid())
1108 return false;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001109
Gor Nishanov5b050e42017-05-22 22:33:17 +00001110 // Since the body of the coroutine will be wrapped in try-catch, it will
1111 // be incompatible with SEH __try if present in a function.
1112 if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1113 S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1114 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1115 << Fn.getFirstCoroutineStmtKeyword();
1116 return false;
1117 }
1118
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001119 this->OnException = UnhandledException.get();
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001120 return true;
1121}
1122
Eric Fiselierbee782b2017-04-03 19:21:00 +00001123bool CoroutineStmtBuilder::makeReturnObject() {
Richard Smith2af65c42015-11-24 02:34:39 +00001124 // Build implicit 'p.get_return_object()' expression and form initialization
1125 // of return type from it.
1126 ExprResult ReturnObject =
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001127 buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
Richard Smith2af65c42015-11-24 02:34:39 +00001128 if (ReturnObject.isInvalid())
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001129 return false;
Richard Smith2af65c42015-11-24 02:34:39 +00001130
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001131 this->ReturnValue = ReturnObject.get();
1132 return true;
1133}
1134
Gor Nishanov6a470682017-05-22 20:22:23 +00001135static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
1136 if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
1137 auto *MethodDecl = MbrRef->getMethodDecl();
Eric Fiselierfc50f622017-05-25 14:59:39 +00001138 S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
1139 << MethodDecl;
Gor Nishanov6a470682017-05-22 20:22:23 +00001140 }
1141 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1142 << Fn.getFirstCoroutineStmtKeyword();
1143}
1144
1145bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1146 assert(!IsPromiseDependentType &&
1147 "cannot make statement while the promise type is dependent");
1148 assert(this->ReturnValue && "ReturnValue must be already formed");
1149
1150 QualType const GroType = this->ReturnValue->getType();
1151 assert(!GroType->isDependentType() &&
1152 "get_return_object type must no longer be dependent");
1153
1154 QualType const FnRetType = FD.getReturnType();
1155 assert(!FnRetType->isDependentType() &&
1156 "get_return_object type must no longer be dependent");
1157
1158 if (FnRetType->isVoidType()) {
1159 ExprResult Res = S.ActOnFinishFullExpr(this->ReturnValue, Loc);
1160 if (Res.isInvalid())
1161 return false;
1162
1163 this->ResultDecl = Res.get();
1164 return true;
1165 }
1166
1167 if (GroType->isVoidType()) {
1168 // Trigger a nice error message.
1169 InitializedEntity Entity =
1170 InitializedEntity::InitializeResult(Loc, FnRetType, false);
1171 S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue);
1172 noteMemberDeclaredHere(S, ReturnValue, Fn);
1173 return false;
1174 }
1175
1176 auto *GroDecl = VarDecl::Create(
1177 S.Context, &FD, FD.getLocation(), FD.getLocation(),
1178 &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
1179 S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
1180
1181 S.CheckVariableDeclarationType(GroDecl);
1182 if (GroDecl->isInvalidDecl())
1183 return false;
1184
1185 InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
1186 ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType,
1187 this->ReturnValue);
1188 if (Res.isInvalid())
1189 return false;
1190
1191 Res = S.ActOnFinishFullExpr(Res.get());
1192 if (Res.isInvalid())
1193 return false;
1194
1195 if (GroType == FnRetType) {
1196 GroDecl->setNRVOVariable(true);
1197 }
1198
1199 S.AddInitializerToDecl(GroDecl, Res.get(),
1200 /*DirectInit=*/false);
1201
1202 S.FinalizeDeclaration(GroDecl);
1203
1204 // Form a declaration statement for the return declaration, so that AST
1205 // visitors can more easily find it.
1206 StmtResult GroDeclStmt =
1207 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
1208 if (GroDeclStmt.isInvalid())
1209 return false;
1210
1211 this->ResultDecl = GroDeclStmt.get();
1212
1213 ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
1214 if (declRef.isInvalid())
1215 return false;
1216
1217 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
1218 if (ReturnStmt.isInvalid()) {
1219 noteMemberDeclaredHere(S, ReturnValue, Fn);
1220 return false;
1221 }
1222
1223 this->ReturnStmt = ReturnStmt.get();
1224 return true;
1225}
1226
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001227// Create a static_cast\<T&&>(expr).
1228static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
1229 if (T.isNull())
1230 T = E->getType();
1231 QualType TargetType = S.BuildReferenceType(
1232 T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());
1233 SourceLocation ExprLoc = E->getLocStart();
1234 TypeSourceInfo *TargetLoc =
1235 S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
1236
1237 return S
1238 .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1239 SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
1240 .get();
1241}
1242
1243/// \brief Build a variable declaration for move parameter.
1244static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
1245 StringRef Name) {
1246 DeclContext *DC = S.CurContext;
1247 IdentifierInfo *II = &S.PP.getIdentifierTable().get(Name);
1248 TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);
1249 VarDecl *Decl =
1250 VarDecl::Create(S.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1251 Decl->setImplicit();
1252 return Decl;
1253}
1254
Eric Fiselierbee782b2017-04-03 19:21:00 +00001255bool CoroutineStmtBuilder::makeParamMoves() {
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001256 for (auto *paramDecl : FD.parameters()) {
1257 auto Ty = paramDecl->getType();
1258 if (Ty->isDependentType())
1259 continue;
1260
1261 // No need to copy scalars, llvm will take care of them.
1262 if (Ty->getAsCXXRecordDecl()) {
1263 if (!paramDecl->getIdentifier())
1264 continue;
1265
1266 ExprResult ParamRef =
1267 S.BuildDeclRefExpr(paramDecl, paramDecl->getType(),
1268 ExprValueKind::VK_LValue, Loc); // FIXME: scope?
1269 if (ParamRef.isInvalid())
1270 return false;
1271
1272 Expr *RCast = castForMoving(S, ParamRef.get());
1273
1274 auto D = buildVarDecl(S, Loc, Ty, paramDecl->getIdentifier()->getName());
1275
1276 S.AddInitializerToDecl(D, RCast, /*DirectInit=*/true);
1277
1278 // Convert decl to a statement.
1279 StmtResult Stmt = S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(D), Loc, Loc);
1280 if (Stmt.isInvalid())
1281 return false;
1282
1283 ParamMovesVector.push_back(Stmt.get());
1284 }
1285 }
1286
1287 // Convert to ArrayRef in CtorArgs structure that builder inherits from.
1288 ParamMoves = ParamMovesVector;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001289 return true;
Richard Smithcfd53b42015-10-22 06:13:50 +00001290}
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001291
1292StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1293 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
1294 if (!Res)
1295 return StmtError();
1296 return Res;
1297}