blob: f5594bd64d9a7a54c89520e938270f8eda20064d [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);
Eric Fiselier37b8a372017-05-31 19:36:59 +0000440 FD->addDecl(VD);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000441 assert(!VD->isInvalidDecl());
442 return VD;
443}
444
445/// Check that this is a context in which a coroutine suspension can appear.
446static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000447 StringRef Keyword,
448 bool IsImplicit = false) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000449 if (!isValidCoroutineContext(S, Loc, Keyword))
450 return nullptr;
451
452 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000453
454 auto *ScopeInfo = S.getCurFunction();
455 assert(ScopeInfo && "missing function scope for function");
456
Eric Fiseliercac0a592017-03-11 02:35:37 +0000457 if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
458 ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
459
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000460 if (ScopeInfo->CoroutinePromise)
461 return ScopeInfo;
462
463 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
464 if (!ScopeInfo->CoroutinePromise)
465 return nullptr;
466
467 return ScopeInfo;
468}
469
470static bool actOnCoroutineBodyStart(Sema &S, Scope *SC, SourceLocation KWLoc,
471 StringRef Keyword) {
472 if (!checkCoroutineContext(S, KWLoc, Keyword))
473 return false;
474 auto *ScopeInfo = S.getCurFunction();
475 assert(ScopeInfo->CoroutinePromise);
476
477 // If we have existing coroutine statements then we have already built
478 // the initial and final suspend points.
479 if (!ScopeInfo->NeedsCoroutineSuspends)
480 return true;
481
482 ScopeInfo->setNeedsCoroutineSuspends(false);
483
484 auto *Fn = cast<FunctionDecl>(S.CurContext);
485 SourceLocation Loc = Fn->getLocation();
486 // Build the initial suspend point
487 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
488 ExprResult Suspend =
489 buildPromiseCall(S, ScopeInfo->CoroutinePromise, Loc, Name, None);
490 if (Suspend.isInvalid())
491 return StmtError();
492 Suspend = buildOperatorCoawaitCall(S, SC, Loc, Suspend.get());
493 if (Suspend.isInvalid())
494 return StmtError();
495 Suspend = S.BuildResolvedCoawaitExpr(Loc, Suspend.get(),
496 /*IsImplicit*/ true);
497 Suspend = S.ActOnFinishFullExpr(Suspend.get());
498 if (Suspend.isInvalid()) {
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000499 S.Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000500 << ((Name == "initial_suspend") ? 0 : 1);
501 S.Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
502 return StmtError();
503 }
504 return cast<Stmt>(Suspend.get());
505 };
506
507 StmtResult InitSuspend = buildSuspends("initial_suspend");
508 if (InitSuspend.isInvalid())
509 return true;
510
511 StmtResult FinalSuspend = buildSuspends("final_suspend");
512 if (FinalSuspend.isInvalid())
513 return true;
514
515 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
516
517 return true;
518}
519
Richard Smith9f690bd2015-10-27 06:02:45 +0000520ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000521 if (!actOnCoroutineBodyStart(*this, S, Loc, "co_await")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000522 CorrectDelayedTyposInExpr(E);
523 return ExprError();
524 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000525
Richard Smith10610f72015-11-20 22:57:24 +0000526 if (E->getType()->isPlaceholderType()) {
527 ExprResult R = CheckPlaceholderExpr(E);
528 if (R.isInvalid()) return ExprError();
529 E = R.get();
530 }
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000531 ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
532 if (Lookup.isInvalid())
533 return ExprError();
534 return BuildUnresolvedCoawaitExpr(Loc, E,
535 cast<UnresolvedLookupExpr>(Lookup.get()));
536}
Richard Smith10610f72015-11-20 22:57:24 +0000537
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000538ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E,
Eric Fiseliercac0a592017-03-11 02:35:37 +0000539 UnresolvedLookupExpr *Lookup) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000540 auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
541 if (!FSI)
542 return ExprError();
543
544 if (E->getType()->isPlaceholderType()) {
545 ExprResult R = CheckPlaceholderExpr(E);
546 if (R.isInvalid())
547 return ExprError();
548 E = R.get();
549 }
550
551 auto *Promise = FSI->CoroutinePromise;
552 if (Promise->getType()->isDependentType()) {
553 Expr *Res =
554 new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000555 return Res;
556 }
557
558 auto *RD = Promise->getType()->getAsCXXRecordDecl();
559 if (lookupMember(*this, "await_transform", RD, Loc)) {
560 ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
561 if (R.isInvalid()) {
562 Diag(Loc,
563 diag::note_coroutine_promise_implicit_await_transform_required_here)
564 << E->getSourceRange();
565 return ExprError();
566 }
567 E = R.get();
568 }
569 ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
Richard Smith9f690bd2015-10-27 06:02:45 +0000570 if (Awaitable.isInvalid())
571 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000572
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000573 return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
Richard Smith9f690bd2015-10-27 06:02:45 +0000574}
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000575
576ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E,
577 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000578 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
Richard Smith744b2242015-11-20 02:54:01 +0000579 if (!Coroutine)
580 return ExprError();
Richard Smith9f690bd2015-10-27 06:02:45 +0000581
Richard Smith9f690bd2015-10-27 06:02:45 +0000582 if (E->getType()->isPlaceholderType()) {
583 ExprResult R = CheckPlaceholderExpr(E);
584 if (R.isInvalid()) return ExprError();
585 E = R.get();
586 }
587
Richard Smith10610f72015-11-20 22:57:24 +0000588 if (E->getType()->isDependentType()) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000589 Expr *Res = new (Context)
590 CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
Richard Smith10610f72015-11-20 22:57:24 +0000591 return Res;
592 }
593
Richard Smith1f38edd2015-11-22 03:13:02 +0000594 // If the expression is a temporary, materialize it as an lvalue so that we
595 // can use it multiple times.
596 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000597 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smith9f690bd2015-10-27 06:02:45 +0000598
599 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000600 ReadySuspendResumeResult RSS =
601 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000602 if (RSS.IsInvalid)
603 return ExprError();
604
Gor Nishanovce43bd22017-03-11 01:30:17 +0000605 Expr *Res =
606 new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
607 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000608
Richard Smithcfd53b42015-10-22 06:13:50 +0000609 return Res;
610}
611
Richard Smith9f690bd2015-10-27 06:02:45 +0000612ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000613 if (!actOnCoroutineBodyStart(*this, S, Loc, "co_yield")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000614 CorrectDelayedTyposInExpr(E);
Richard Smith23da82c2015-11-20 22:40:06 +0000615 return ExprError();
Eric Fiseliera5465282016-09-29 21:47:39 +0000616 }
Richard Smith23da82c2015-11-20 22:40:06 +0000617
618 // Build yield_value call.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000619 ExprResult Awaitable = buildPromiseCall(
620 *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
Richard Smith9f690bd2015-10-27 06:02:45 +0000621 if (Awaitable.isInvalid())
622 return ExprError();
Richard Smith23da82c2015-11-20 22:40:06 +0000623
624 // Build 'operator co_await' call.
625 Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
626 if (Awaitable.isInvalid())
627 return ExprError();
628
Richard Smith9f690bd2015-10-27 06:02:45 +0000629 return BuildCoyieldExpr(Loc, Awaitable.get());
630}
631ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
632 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
Richard Smith744b2242015-11-20 02:54:01 +0000633 if (!Coroutine)
634 return ExprError();
Richard Smithcfd53b42015-10-22 06:13:50 +0000635
Richard Smith10610f72015-11-20 22:57:24 +0000636 if (E->getType()->isPlaceholderType()) {
637 ExprResult R = CheckPlaceholderExpr(E);
638 if (R.isInvalid()) return ExprError();
639 E = R.get();
640 }
641
Richard Smithd7bed4d2015-11-22 02:57:17 +0000642 if (E->getType()->isDependentType()) {
643 Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000644 return Res;
645 }
646
Richard Smith1f38edd2015-11-22 03:13:02 +0000647 // If the expression is a temporary, materialize it as an lvalue so that we
648 // can use it multiple times.
649 if (E->getValueKind() == VK_RValue)
Tim Shen4a05bb82016-06-21 20:29:17 +0000650 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000651
652 // Build the await_ready, await_suspend, await_resume calls.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000653 ReadySuspendResumeResult RSS =
654 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
Richard Smithd7bed4d2015-11-22 02:57:17 +0000655 if (RSS.IsInvalid)
656 return ExprError();
657
658 Expr *Res = new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
Gor Nishanovce43bd22017-03-11 01:30:17 +0000659 RSS.Results[2], RSS.OpaqueValue);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000660
Richard Smithcfd53b42015-10-22 06:13:50 +0000661 return Res;
662}
663
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000664StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
665 if (!actOnCoroutineBodyStart(*this, S, Loc, "co_return")) {
Eric Fiseliera5465282016-09-29 21:47:39 +0000666 CorrectDelayedTyposInExpr(E);
667 return StmtError();
668 }
Richard Smith9f690bd2015-10-27 06:02:45 +0000669 return BuildCoreturnStmt(Loc, E);
670}
Gor Nishanov3e048bb2016-10-04 00:31:16 +0000671
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000672StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
673 bool IsImplicit) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000674 auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000675 if (!FSI)
Richard Smith71d403e2015-11-22 07:33:28 +0000676 return StmtError();
677
678 if (E && E->getType()->isPlaceholderType() &&
679 !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
Richard Smith10610f72015-11-20 22:57:24 +0000680 ExprResult R = CheckPlaceholderExpr(E);
681 if (R.isInvalid()) return StmtError();
682 E = R.get();
683 }
684
Richard Smith4ba66602015-11-22 07:05:16 +0000685 // FIXME: If the operand is a reference to a variable that's about to go out
Richard Smith2af65c42015-11-24 02:34:39 +0000686 // of scope, we should treat the operand as an xvalue for this overload
Richard Smith4ba66602015-11-22 07:05:16 +0000687 // resolution.
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000688 VarDecl *Promise = FSI->CoroutinePromise;
Richard Smith4ba66602015-11-22 07:05:16 +0000689 ExprResult PC;
Eric Fiselier98131312016-10-06 21:23:38 +0000690 if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000691 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
Richard Smith4ba66602015-11-22 07:05:16 +0000692 } else {
693 E = MakeFullDiscardedValueExpr(E).get();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000694 PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
Richard Smith4ba66602015-11-22 07:05:16 +0000695 }
696 if (PC.isInvalid())
697 return StmtError();
698
699 Expr *PCE = ActOnFinishFullExpr(PC.get()).get();
700
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000701 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
Richard Smithcfd53b42015-10-22 06:13:50 +0000702 return Res;
703}
704
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000705/// Look up the std::nothrow object.
706static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
707 NamespaceDecl *Std = S.getStdNamespace();
708 assert(Std && "Should already be diagnosed");
709
710 LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
711 Sema::LookupOrdinaryName);
712 if (!S.LookupQualifiedName(Result, Std)) {
713 // FIXME: <experimental/coroutine> should have been included already.
714 // If we require it to include <new> then this diagnostic is no longer
715 // needed.
716 S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
717 return nullptr;
718 }
719
720 // FIXME: Mark the variable as ODR used. This currently does not work
721 // likely due to the scope at in which this function is called.
722 auto *VD = Result.getAsSingle<VarDecl>();
723 if (!VD) {
724 Result.suppressDiagnostics();
725 // We found something weird. Complain about the first thing we found.
726 NamedDecl *Found = *Result.begin();
727 S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
728 return nullptr;
729 }
730
731 ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
732 if (DR.isInvalid())
733 return nullptr;
734
735 return DR.get();
736}
737
Gor Nishanov8df64e92016-10-27 16:28:31 +0000738// Find an appropriate delete for the promise.
739static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc,
740 QualType PromiseType) {
741 FunctionDecl *OperatorDelete = nullptr;
742
743 DeclarationName DeleteName =
744 S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
745
746 auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
747 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
748
749 if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
750 return nullptr;
751
752 if (!OperatorDelete) {
753 // Look for a global declaration.
754 const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
755 const bool Overaligned = false;
756 OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
757 Overaligned, DeleteName);
758 }
759 S.MarkFunctionReferenced(Loc, OperatorDelete);
760 return OperatorDelete;
761}
762
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000763
764void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
765 FunctionScopeInfo *Fn = getCurFunction();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000766 assert(Fn && Fn->isCoroutine() && "not a coroutine");
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000767 if (!Body) {
768 assert(FD->isInvalidDecl() &&
769 "a null body is only allowed for invalid declarations");
770 return;
771 }
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000772 // We have a function that uses coroutine keywords, but we failed to build
773 // the promise type.
774 if (!Fn->CoroutinePromise)
775 return FD->setInvalidDecl();
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000776
777 if (isa<CoroutineBodyStmt>(Body)) {
Gor Nishanov29ff6382017-05-24 14:34:19 +0000778 // Nothing todo. the body is already a transformed coroutine body statement.
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000779 return;
780 }
781
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000782 // Coroutines [stmt.return]p1:
783 // A return statement shall not appear in a coroutine.
784 if (Fn->FirstReturnLoc.isValid()) {
Eric Fiseliercac0a592017-03-11 02:35:37 +0000785 assert(Fn->FirstCoroutineStmtLoc.isValid() &&
786 "first coroutine location not set");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000787 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
Eric Fiseliercac0a592017-03-11 02:35:37 +0000788 Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
789 << Fn->getFirstCoroutineStmtKeyword();
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000790 }
Eric Fiselierbee782b2017-04-03 19:21:00 +0000791 CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
792 if (Builder.isInvalid() || !Builder.buildStatements())
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000793 return FD->setInvalidDecl();
794
795 // Build body for the coroutine wrapper statement.
796 Body = CoroutineBodyStmt::Create(Context, Builder);
797}
798
Eric Fiselierbee782b2017-04-03 19:21:00 +0000799CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
800 sema::FunctionScopeInfo &Fn,
801 Stmt *Body)
802 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
803 IsPromiseDependentType(
804 !Fn.CoroutinePromise ||
805 Fn.CoroutinePromise->getType()->isDependentType()) {
806 this->Body = Body;
807 if (!IsPromiseDependentType) {
808 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
809 assert(PromiseRecordDecl && "Type should have already been checked");
810 }
811 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
812}
813
814bool CoroutineStmtBuilder::buildStatements() {
815 assert(this->IsValid && "coroutine already invalid");
816 this->IsValid = makeReturnObject() && makeParamMoves();
817 if (this->IsValid && !IsPromiseDependentType)
818 buildDependentStatements();
819 return this->IsValid;
820}
821
822bool CoroutineStmtBuilder::buildDependentStatements() {
823 assert(this->IsValid && "coroutine already invalid");
824 assert(!this->IsPromiseDependentType &&
825 "coroutine cannot have a dependent promise type");
826 this->IsValid = makeOnException() && makeOnFallthrough() &&
Gor Nishanov6a470682017-05-22 20:22:23 +0000827 makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
828 makeNewAndDeleteExpr();
Eric Fiselierbee782b2017-04-03 19:21:00 +0000829 return this->IsValid;
830}
831
832bool CoroutineStmtBuilder::makePromiseStmt() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000833 // Form a declaration statement for the promise declaration, so that AST
834 // visitors can more easily find it.
835 StmtResult PromiseStmt =
836 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
837 if (PromiseStmt.isInvalid())
838 return false;
839
840 this->Promise = PromiseStmt.get();
841 return true;
842}
843
Eric Fiselierbee782b2017-04-03 19:21:00 +0000844bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000845 if (Fn.hasInvalidCoroutineSuspends())
846 return false;
847 this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
848 this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
849 return true;
850}
851
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000852static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
853 CXXRecordDecl *PromiseRecordDecl,
854 FunctionScopeInfo &Fn) {
855 auto Loc = E->getExprLoc();
856 if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
857 auto *Decl = DeclRef->getDecl();
858 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
859 if (Method->isStatic())
860 return true;
861 else
862 Loc = Decl->getLocation();
863 }
864 }
865
866 S.Diag(
867 Loc,
868 diag::err_coroutine_promise_get_return_object_on_allocation_failure)
869 << PromiseRecordDecl;
870 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
871 << Fn.getFirstCoroutineStmtKeyword();
872 return false;
873}
874
Eric Fiselierbee782b2017-04-03 19:21:00 +0000875bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
876 assert(!IsPromiseDependentType &&
877 "cannot make statement while the promise type is dependent");
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000878
879 // [dcl.fct.def.coroutine]/8
880 // The unqualified-id get_return_object_on_allocation_failure is looked up in
881 // the scope of class P by class member access lookup (3.4.5). ...
882 // If an allocation function returns nullptr, ... the coroutine return value
883 // is obtained by a call to ... get_return_object_on_allocation_failure().
884
885 DeclarationName DN =
886 S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
887 LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
Eric Fiselierbee782b2017-04-03 19:21:00 +0000888 if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
889 return true;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000890
891 CXXScopeSpec SS;
892 ExprResult DeclNameExpr =
893 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
Eric Fiselierbee782b2017-04-03 19:21:00 +0000894 if (DeclNameExpr.isInvalid())
895 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000896
897 if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
898 return false;
899
900 ExprResult ReturnObjectOnAllocationFailure =
901 S.ActOnCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
Eric Fiselierbee782b2017-04-03 19:21:00 +0000902 if (ReturnObjectOnAllocationFailure.isInvalid())
903 return false;
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000904
Gor Nishanovc4a19082017-03-28 02:51:45 +0000905 StmtResult ReturnStmt =
906 S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
Gor Nishanov6a470682017-05-22 20:22:23 +0000907 if (ReturnStmt.isInvalid()) {
Eric Fiselierfc50f622017-05-25 14:59:39 +0000908 S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
909 << DN;
Gor Nishanov6a470682017-05-22 20:22:23 +0000910 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
911 << Fn.getFirstCoroutineStmtKeyword();
Eric Fiselierbee782b2017-04-03 19:21:00 +0000912 return false;
Gor Nishanov6a470682017-05-22 20:22:23 +0000913 }
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000914
915 this->ReturnStmtOnAllocFailure = ReturnStmt.get();
916 return true;
917}
918
Eric Fiselierbee782b2017-04-03 19:21:00 +0000919bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000920 // Form and check allocation and deallocation calls.
Eric Fiselierbee782b2017-04-03 19:21:00 +0000921 assert(!IsPromiseDependentType &&
922 "cannot make statement while the promise type is dependent");
Eric Fiselier20f25cb2017-03-06 23:38:15 +0000923 QualType PromiseType = Fn.CoroutinePromise->getType();
Gor Nishanov8df64e92016-10-27 16:28:31 +0000924
925 if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
926 return false;
927
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000928 const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
929
Gor Nishanov8df64e92016-10-27 16:28:31 +0000930 // FIXME: Add support for stateful allocators.
931
932 FunctionDecl *OperatorNew = nullptr;
933 FunctionDecl *OperatorDelete = nullptr;
934 FunctionDecl *UnusedResult = nullptr;
935 bool PassAlignment = false;
Eric Fiselierf747f532017-04-18 05:08:08 +0000936 SmallVector<Expr *, 1> PlacementArgs;
Gor Nishanov8df64e92016-10-27 16:28:31 +0000937
938 S.FindAllocationFunctions(Loc, SourceRange(),
939 /*UseGlobal*/ false, PromiseType,
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000940 /*isArray*/ false, PassAlignment, PlacementArgs,
941 OperatorNew, UnusedResult);
Gor Nishanov8df64e92016-10-27 16:28:31 +0000942
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000943 bool IsGlobalOverload =
944 OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
945 // If we didn't find a class-local new declaration and non-throwing new
946 // was is required then we need to lookup the non-throwing global operator
947 // instead.
948 if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
949 auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
950 if (!StdNoThrow)
951 return false;
Eric Fiselierf747f532017-04-18 05:08:08 +0000952 PlacementArgs = {StdNoThrow};
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000953 OperatorNew = nullptr;
954 S.FindAllocationFunctions(Loc, SourceRange(),
955 /*UseGlobal*/ true, PromiseType,
956 /*isArray*/ false, PassAlignment, PlacementArgs,
957 OperatorNew, UnusedResult);
958 }
Gor Nishanov8df64e92016-10-27 16:28:31 +0000959
Eric Fiselierc5128752017-04-18 05:30:39 +0000960 assert(OperatorNew && "expected definition of operator new to be found");
961
962 if (RequiresNoThrowAlloc) {
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000963 const auto *FT = OperatorNew->getType()->getAs<FunctionProtoType>();
964 if (!FT->isNothrow(S.Context, /*ResultIfDependent*/ false)) {
965 S.Diag(OperatorNew->getLocation(),
966 diag::err_coroutine_promise_new_requires_nothrow)
967 << OperatorNew;
968 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
969 << OperatorNew;
970 return false;
971 }
972 }
973
974 if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr)
Gor Nishanov8df64e92016-10-27 16:28:31 +0000975 return false;
976
977 Expr *FramePtr =
978 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
979
980 Expr *FrameSize =
981 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {});
982
983 // Make new call.
984
985 ExprResult NewRef =
986 S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
987 if (NewRef.isInvalid())
988 return false;
989
Eric Fiselierf747f532017-04-18 05:08:08 +0000990 SmallVector<Expr *, 2> NewArgs(1, FrameSize);
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000991 for (auto Arg : PlacementArgs)
992 NewArgs.push_back(Arg);
993
Gor Nishanov8df64e92016-10-27 16:28:31 +0000994 ExprResult NewExpr =
Eric Fiselierf692e7d2017-04-18 03:12:48 +0000995 S.ActOnCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
996 NewExpr = S.ActOnFinishFullExpr(NewExpr.get());
Gor Nishanov8df64e92016-10-27 16:28:31 +0000997 if (NewExpr.isInvalid())
998 return false;
999
Gor Nishanov8df64e92016-10-27 16:28:31 +00001000 // Make delete call.
1001
1002 QualType OpDeleteQualType = OperatorDelete->getType();
1003
1004 ExprResult DeleteRef =
1005 S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
1006 if (DeleteRef.isInvalid())
1007 return false;
1008
1009 Expr *CoroFree =
1010 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr});
1011
1012 SmallVector<Expr *, 2> DeleteArgs{CoroFree};
1013
1014 // Check if we need to pass the size.
1015 const auto *OpDeleteType =
1016 OpDeleteQualType.getTypePtr()->getAs<FunctionProtoType>();
1017 if (OpDeleteType->getNumParams() > 1)
1018 DeleteArgs.push_back(FrameSize);
1019
1020 ExprResult DeleteExpr =
1021 S.ActOnCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
Eric Fiselierf692e7d2017-04-18 03:12:48 +00001022 DeleteExpr = S.ActOnFinishFullExpr(DeleteExpr.get());
Gor Nishanov8df64e92016-10-27 16:28:31 +00001023 if (DeleteExpr.isInvalid())
1024 return false;
1025
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001026 this->Allocate = NewExpr.get();
1027 this->Deallocate = DeleteExpr.get();
Gor Nishanov8df64e92016-10-27 16:28:31 +00001028
1029 return true;
1030}
1031
Eric Fiselierbee782b2017-04-03 19:21:00 +00001032bool CoroutineStmtBuilder::makeOnFallthrough() {
1033 assert(!IsPromiseDependentType &&
1034 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001035
1036 // [dcl.fct.def.coroutine]/4
1037 // The unqualified-ids 'return_void' and 'return_value' are looked up in
1038 // the scope of class P. If both are found, the program is ill-formed.
Eric Fiselierfc50f622017-05-25 14:59:39 +00001039 bool HasRVoid, HasRValue;
1040 LookupResult LRVoid =
1041 lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
1042 LookupResult LRValue =
1043 lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001044
Eric Fiselier709d1b32016-10-27 07:30:31 +00001045 StmtResult Fallthrough;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001046 if (HasRVoid && HasRValue) {
1047 // FIXME Improve this diagnostic
Eric Fiselierfc50f622017-05-25 14:59:39 +00001048 S.Diag(FD.getLocation(),
1049 diag::err_coroutine_promise_incompatible_return_functions)
1050 << PromiseRecordDecl;
1051 S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
1052 diag::note_member_first_declared_here)
1053 << LRVoid.getLookupName();
1054 S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
1055 diag::note_member_first_declared_here)
1056 << LRValue.getLookupName();
1057 return false;
1058 } else if (!HasRVoid && !HasRValue) {
1059 // FIXME: The PDTS currently specifies this case as UB, not ill-formed.
1060 // However we still diagnose this as an error since until the PDTS is fixed.
1061 S.Diag(FD.getLocation(),
1062 diag::err_coroutine_promise_requires_return_function)
1063 << PromiseRecordDecl;
1064 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001065 << PromiseRecordDecl;
1066 return false;
1067 } else if (HasRVoid) {
1068 // If the unqualified-id return_void is found, flowing off the end of a
1069 // coroutine is equivalent to a co_return with no operand. Otherwise,
1070 // flowing off the end of a coroutine results in undefined behavior.
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001071 Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
1072 /*IsImplicit*/false);
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001073 Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
1074 if (Fallthrough.isInvalid())
1075 return false;
Eric Fiselier709d1b32016-10-27 07:30:31 +00001076 }
Richard Smith2af65c42015-11-24 02:34:39 +00001077
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001078 this->OnFallthrough = Fallthrough.get();
1079 return true;
1080}
1081
Eric Fiselierbee782b2017-04-03 19:21:00 +00001082bool CoroutineStmtBuilder::makeOnException() {
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001083 // Try to form 'p.unhandled_exception();'
Eric Fiselierbee782b2017-04-03 19:21:00 +00001084 assert(!IsPromiseDependentType &&
1085 "cannot make statement while the promise type is dependent");
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001086
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001087 const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1088
1089 if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
1090 auto DiagID =
1091 RequireUnhandledException
1092 ? diag::err_coroutine_promise_unhandled_exception_required
1093 : diag::
1094 warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1095 S.Diag(Loc, DiagID) << PromiseRecordDecl;
Gor Nishanov29ff6382017-05-24 14:34:19 +00001096 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1097 << PromiseRecordDecl;
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001098 return !RequireUnhandledException;
1099 }
1100
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001101 // If exceptions are disabled, don't try to build OnException.
1102 if (!S.getLangOpts().CXXExceptions)
1103 return true;
1104
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001105 ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
1106 "unhandled_exception", None);
1107 UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc);
1108 if (UnhandledException.isInvalid())
1109 return false;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001110
Gor Nishanov5b050e42017-05-22 22:33:17 +00001111 // Since the body of the coroutine will be wrapped in try-catch, it will
1112 // be incompatible with SEH __try if present in a function.
1113 if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1114 S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1115 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1116 << Fn.getFirstCoroutineStmtKeyword();
1117 return false;
1118 }
1119
Eric Fiseliera9fdb342017-03-23 00:33:33 +00001120 this->OnException = UnhandledException.get();
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001121 return true;
1122}
1123
Eric Fiselierbee782b2017-04-03 19:21:00 +00001124bool CoroutineStmtBuilder::makeReturnObject() {
Richard Smith2af65c42015-11-24 02:34:39 +00001125 // Build implicit 'p.get_return_object()' expression and form initialization
1126 // of return type from it.
1127 ExprResult ReturnObject =
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001128 buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
Richard Smith2af65c42015-11-24 02:34:39 +00001129 if (ReturnObject.isInvalid())
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001130 return false;
Richard Smith2af65c42015-11-24 02:34:39 +00001131
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001132 this->ReturnValue = ReturnObject.get();
1133 return true;
1134}
1135
Gor Nishanov6a470682017-05-22 20:22:23 +00001136static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
1137 if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
1138 auto *MethodDecl = MbrRef->getMethodDecl();
Eric Fiselierfc50f622017-05-25 14:59:39 +00001139 S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
1140 << MethodDecl;
Gor Nishanov6a470682017-05-22 20:22:23 +00001141 }
1142 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1143 << Fn.getFirstCoroutineStmtKeyword();
1144}
1145
1146bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1147 assert(!IsPromiseDependentType &&
1148 "cannot make statement while the promise type is dependent");
1149 assert(this->ReturnValue && "ReturnValue must be already formed");
1150
1151 QualType const GroType = this->ReturnValue->getType();
1152 assert(!GroType->isDependentType() &&
1153 "get_return_object type must no longer be dependent");
1154
1155 QualType const FnRetType = FD.getReturnType();
1156 assert(!FnRetType->isDependentType() &&
1157 "get_return_object type must no longer be dependent");
1158
1159 if (FnRetType->isVoidType()) {
1160 ExprResult Res = S.ActOnFinishFullExpr(this->ReturnValue, Loc);
1161 if (Res.isInvalid())
1162 return false;
1163
1164 this->ResultDecl = Res.get();
1165 return true;
1166 }
1167
1168 if (GroType->isVoidType()) {
1169 // Trigger a nice error message.
1170 InitializedEntity Entity =
1171 InitializedEntity::InitializeResult(Loc, FnRetType, false);
1172 S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue);
1173 noteMemberDeclaredHere(S, ReturnValue, Fn);
1174 return false;
1175 }
1176
1177 auto *GroDecl = VarDecl::Create(
1178 S.Context, &FD, FD.getLocation(), FD.getLocation(),
1179 &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
1180 S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
1181
1182 S.CheckVariableDeclarationType(GroDecl);
1183 if (GroDecl->isInvalidDecl())
1184 return false;
1185
1186 InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
1187 ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType,
1188 this->ReturnValue);
1189 if (Res.isInvalid())
1190 return false;
1191
1192 Res = S.ActOnFinishFullExpr(Res.get());
1193 if (Res.isInvalid())
1194 return false;
1195
1196 if (GroType == FnRetType) {
1197 GroDecl->setNRVOVariable(true);
1198 }
1199
1200 S.AddInitializerToDecl(GroDecl, Res.get(),
1201 /*DirectInit=*/false);
1202
1203 S.FinalizeDeclaration(GroDecl);
1204
1205 // Form a declaration statement for the return declaration, so that AST
1206 // visitors can more easily find it.
1207 StmtResult GroDeclStmt =
1208 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
1209 if (GroDeclStmt.isInvalid())
1210 return false;
1211
1212 this->ResultDecl = GroDeclStmt.get();
1213
1214 ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
1215 if (declRef.isInvalid())
1216 return false;
1217
1218 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
1219 if (ReturnStmt.isInvalid()) {
1220 noteMemberDeclaredHere(S, ReturnValue, Fn);
1221 return false;
1222 }
1223
1224 this->ReturnStmt = ReturnStmt.get();
1225 return true;
1226}
1227
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001228// Create a static_cast\<T&&>(expr).
1229static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
1230 if (T.isNull())
1231 T = E->getType();
1232 QualType TargetType = S.BuildReferenceType(
1233 T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());
1234 SourceLocation ExprLoc = E->getLocStart();
1235 TypeSourceInfo *TargetLoc =
1236 S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
1237
1238 return S
1239 .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1240 SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
1241 .get();
1242}
1243
1244/// \brief Build a variable declaration for move parameter.
1245static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
1246 StringRef Name) {
1247 DeclContext *DC = S.CurContext;
1248 IdentifierInfo *II = &S.PP.getIdentifierTable().get(Name);
1249 TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);
1250 VarDecl *Decl =
1251 VarDecl::Create(S.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1252 Decl->setImplicit();
1253 return Decl;
1254}
1255
Eric Fiselierbee782b2017-04-03 19:21:00 +00001256bool CoroutineStmtBuilder::makeParamMoves() {
Gor Nishanov33d5fd22017-05-24 20:09:14 +00001257 for (auto *paramDecl : FD.parameters()) {
1258 auto Ty = paramDecl->getType();
1259 if (Ty->isDependentType())
1260 continue;
1261
1262 // No need to copy scalars, llvm will take care of them.
1263 if (Ty->getAsCXXRecordDecl()) {
1264 if (!paramDecl->getIdentifier())
1265 continue;
1266
1267 ExprResult ParamRef =
1268 S.BuildDeclRefExpr(paramDecl, paramDecl->getType(),
1269 ExprValueKind::VK_LValue, Loc); // FIXME: scope?
1270 if (ParamRef.isInvalid())
1271 return false;
1272
1273 Expr *RCast = castForMoving(S, ParamRef.get());
1274
1275 auto D = buildVarDecl(S, Loc, Ty, paramDecl->getIdentifier()->getName());
1276
1277 S.AddInitializerToDecl(D, RCast, /*DirectInit=*/true);
1278
1279 // Convert decl to a statement.
1280 StmtResult Stmt = S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(D), Loc, Loc);
1281 if (Stmt.isInvalid())
1282 return false;
1283
1284 ParamMovesVector.push_back(Stmt.get());
1285 }
1286 }
1287
1288 // Convert to ArrayRef in CtorArgs structure that builder inherits from.
1289 ParamMoves = ParamMovesVector;
Gor Nishanovbbe1c072017-02-13 05:05:02 +00001290 return true;
Richard Smithcfd53b42015-10-22 06:13:50 +00001291}
Eric Fiselier20f25cb2017-03-06 23:38:15 +00001292
1293StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1294 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
1295 if (!Res)
1296 return StmtError();
1297 return Res;
1298}