blob: 210f30e2a4ee32aaba0ff1d424241acb0643e5fc [file] [log] [blame]
Richard Smithcfd53b42015-10-22 06:13:50 +00001//===--- SemaCoroutines.cpp - Semantic Analysis for Coroutines ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ Coroutines.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/SemaInternal.h"
Richard Smith9f690bd2015-10-27 06:02:45 +000015#include "clang/AST/Decl.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/StmtCXX.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/Sema/Overload.h"
Richard Smithcfd53b42015-10-22 06:13:50 +000020using namespace clang;
21using namespace sema;
22
Richard Smith9f690bd2015-10-27 06:02:45 +000023/// Look up the std::coroutine_traits<...>::promise_type for the given
24/// function type.
25static QualType lookupPromiseType(Sema &S, const FunctionProtoType *FnType,
26 SourceLocation Loc) {
27 // FIXME: Cache std::coroutine_traits once we've found it.
28 NamespaceDecl *Std = S.getStdNamespace();
29 if (!Std) {
30 S.Diag(Loc, diag::err_implied_std_coroutine_traits_not_found);
31 return QualType();
32 }
33
34 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_traits"),
35 Loc, Sema::LookupOrdinaryName);
36 if (!S.LookupQualifiedName(Result, Std)) {
37 S.Diag(Loc, diag::err_implied_std_coroutine_traits_not_found);
38 return QualType();
39 }
40
41 ClassTemplateDecl *CoroTraits = Result.getAsSingle<ClassTemplateDecl>();
42 if (!CoroTraits) {
43 Result.suppressDiagnostics();
44 // We found something weird. Complain about the first thing we found.
45 NamedDecl *Found = *Result.begin();
46 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
47 return QualType();
48 }
49
50 // Form template argument list for coroutine_traits<R, P1, P2, ...>.
51 TemplateArgumentListInfo Args(Loc, Loc);
52 Args.addArgument(TemplateArgumentLoc(
53 TemplateArgument(FnType->getReturnType()),
54 S.Context.getTrivialTypeSourceInfo(FnType->getReturnType(), Loc)));
55 for (QualType T : FnType->getParamTypes())
56 Args.addArgument(TemplateArgumentLoc(
57 TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, Loc)));
58
59 // Build the template-id.
60 QualType CoroTrait =
61 S.CheckTemplateIdType(TemplateName(CoroTraits), Loc, Args);
62 if (CoroTrait.isNull())
63 return QualType();
64 if (S.RequireCompleteType(Loc, CoroTrait,
65 diag::err_coroutine_traits_missing_specialization))
66 return QualType();
67
68 CXXRecordDecl *RD = CoroTrait->getAsCXXRecordDecl();
69 assert(RD && "specialization of class template is not a class?");
70
71 // Look up the ::promise_type member.
72 LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), Loc,
73 Sema::LookupOrdinaryName);
74 S.LookupQualifiedName(R, RD);
75 auto *Promise = R.getAsSingle<TypeDecl>();
76 if (!Promise) {
77 S.Diag(Loc, diag::err_implied_std_coroutine_traits_promise_type_not_found)
78 << RD;
79 return QualType();
80 }
81
82 // The promise type is required to be a class type.
83 QualType PromiseType = S.Context.getTypeDeclType(Promise);
84 if (!PromiseType->getAsCXXRecordDecl()) {
Richard Smith9b2f53e2015-11-19 02:36:35 +000085 // Use the fully-qualified name of the type.
86 auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, Std);
87 NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
88 CoroTrait.getTypePtr());
89 PromiseType = S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
90
Richard Smith9f690bd2015-10-27 06:02:45 +000091 S.Diag(Loc, diag::err_implied_std_coroutine_traits_promise_type_not_class)
92 << PromiseType;
93 return QualType();
94 }
95
96 return PromiseType;
97}
98
99/// Check that this is a context in which a coroutine suspension can appear.
Richard Smithcfd53b42015-10-22 06:13:50 +0000100static FunctionScopeInfo *
101checkCoroutineContext(Sema &S, SourceLocation Loc, StringRef Keyword) {
102 // 'co_await' and 'co_yield' are permitted in unevaluated operands.
Richard Smith9f690bd2015-10-27 06:02:45 +0000103 // FIXME: Not in 'noexcept'.
Richard Smithcfd53b42015-10-22 06:13:50 +0000104 if (S.isUnevaluatedContext())
105 return nullptr;
106
107 // Any other usage must be within a function.
108 auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
109 if (!FD) {
110 S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
111 ? diag::err_coroutine_objc_method
112 : diag::err_coroutine_outside_function) << Keyword;
113 } else if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) {
114 // Coroutines TS [special]/6:
115 // A special member function shall not be a coroutine.
116 //
117 // FIXME: We assume that this really means that a coroutine cannot
118 // be a constructor or destructor.
119 S.Diag(Loc, diag::err_coroutine_ctor_dtor)
120 << isa<CXXDestructorDecl>(FD) << Keyword;
121 } else if (FD->isConstexpr()) {
122 S.Diag(Loc, diag::err_coroutine_constexpr) << Keyword;
123 } else if (FD->isVariadic()) {
124 S.Diag(Loc, diag::err_coroutine_varargs) << Keyword;
125 } else {
126 auto *ScopeInfo = S.getCurFunction();
127 assert(ScopeInfo && "missing function scope for function");
Richard Smith9f690bd2015-10-27 06:02:45 +0000128
129 // If we don't have a promise variable, build one now.
130 if (!ScopeInfo->CoroutinePromise && !FD->getType()->isDependentType()) {
131 QualType T =
132 lookupPromiseType(S, FD->getType()->castAs<FunctionProtoType>(), Loc);
133 if (T.isNull())
134 return nullptr;
135
136 // Create and default-initialize the promise.
137 ScopeInfo->CoroutinePromise =
138 VarDecl::Create(S.Context, FD, FD->getLocation(), FD->getLocation(),
139 &S.PP.getIdentifierTable().get("__promise"), T,
140 S.Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
141 S.CheckVariableDeclarationType(ScopeInfo->CoroutinePromise);
142 if (!ScopeInfo->CoroutinePromise->isInvalidDecl())
143 S.ActOnUninitializedDecl(ScopeInfo->CoroutinePromise, false);
144 }
145
Richard Smithcfd53b42015-10-22 06:13:50 +0000146 return ScopeInfo;
147 }
148
149 return nullptr;
150}
151
Richard Smith9f690bd2015-10-27 06:02:45 +0000152/// Build a call to 'operator co_await' if there is a suitable operator for
153/// the given expression.
154static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
155 SourceLocation Loc, Expr *E) {
156 UnresolvedSet<16> Functions;
157 SemaRef.LookupOverloadedOperatorName(OO_Coawait, S, E->getType(), QualType(),
158 Functions);
159 return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
160}
Richard Smithcfd53b42015-10-22 06:13:50 +0000161
Richard Smith9f690bd2015-10-27 06:02:45 +0000162struct ReadySuspendResumeResult {
163 bool IsInvalid;
164 Expr *Results[3];
165};
166
167/// Build calls to await_ready, await_suspend, and await_resume for a co_await
168/// expression.
169static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, SourceLocation Loc,
170 Expr *E) {
171 // Assume invalid until we see otherwise.
172 ReadySuspendResumeResult Calls = {true, {}};
173
174 const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
175 for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
176 DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Funcs[I]), Loc);
177
178 Expr *Operand = new (S.Context) OpaqueValueExpr(
179 Loc, E->getType(), E->getValueKind(), E->getObjectKind(), E);
180
181 // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
182 CXXScopeSpec SS;
183 ExprResult Result = S.BuildMemberReferenceExpr(
184 Operand, Operand->getType(), Loc, /*IsPtr=*/false, SS,
185 SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
186 /*Scope=*/nullptr);
187 if (Result.isInvalid())
188 return Calls;
189
190 // FIXME: Pass coroutine handle to await_suspend.
191 Result = S.ActOnCallExpr(nullptr, Result.get(), Loc, None, Loc, nullptr);
192 if (Result.isInvalid())
193 return Calls;
194 Calls.Results[I] = Result.get();
195 }
196
197 Calls.IsInvalid = false;
198 return Calls;
199}
200
201ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
202 ExprResult Awaitable = buildOperatorCoawaitCall(*this, S, Loc, E);
203 if (Awaitable.isInvalid())
204 return ExprError();
205 return BuildCoawaitExpr(Loc, Awaitable.get());
206}
207ExprResult Sema::BuildCoawaitExpr(SourceLocation Loc, Expr *E) {
208 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await");
209
210 if (E->getType()->isDependentType()) {
211 Expr *Res = new (Context) CoawaitExpr(Loc, Context.DependentTy, E);
212 if (Coroutine)
213 Coroutine->CoroutineStmts.push_back(Res);
214 return Res;
215 }
216
217 if (E->getType()->isPlaceholderType()) {
218 ExprResult R = CheckPlaceholderExpr(E);
219 if (R.isInvalid()) return ExprError();
220 E = R.get();
221 }
222
223 // FIXME: If E is a prvalue, create a temporary.
224 // FIXME: If E is an xvalue, convert to lvalue.
225
226 // Build the await_ready, await_suspend, await_resume calls.
227 ReadySuspendResumeResult RSS = buildCoawaitCalls(*this, Loc, E);
228 if (RSS.IsInvalid)
229 return ExprError();
230
231 Expr *Res = new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
232 RSS.Results[2]);
233 if (Coroutine)
234 Coroutine->CoroutineStmts.push_back(Res);
Richard Smithcfd53b42015-10-22 06:13:50 +0000235 return Res;
236}
237
Richard Smith9f690bd2015-10-27 06:02:45 +0000238ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
239 // FIXME: Build yield_value call.
240 ExprResult Awaitable = buildOperatorCoawaitCall(*this, S, Loc, E);
241 if (Awaitable.isInvalid())
242 return ExprError();
243 return BuildCoyieldExpr(Loc, Awaitable.get());
244}
245ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
246 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
Richard Smithcfd53b42015-10-22 06:13:50 +0000247
Richard Smith9f690bd2015-10-27 06:02:45 +0000248 // FIXME: Build await_* calls.
249 Expr *Res = new (Context) CoyieldExpr(Loc, Context.VoidTy, E);
250 if (Coroutine)
251 Coroutine->CoroutineStmts.push_back(Res);
Richard Smithcfd53b42015-10-22 06:13:50 +0000252 return Res;
253}
254
255StmtResult Sema::ActOnCoreturnStmt(SourceLocation Loc, Expr *E) {
Richard Smith9f690bd2015-10-27 06:02:45 +0000256 return BuildCoreturnStmt(Loc, E);
257}
258StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E) {
259 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_return");
Richard Smithcfd53b42015-10-22 06:13:50 +0000260
Richard Smith9f690bd2015-10-27 06:02:45 +0000261 // FIXME: Build return_* calls.
262 Stmt *Res = new (Context) CoreturnStmt(Loc, E);
263 if (Coroutine)
264 Coroutine->CoroutineStmts.push_back(Res);
Richard Smithcfd53b42015-10-22 06:13:50 +0000265 return Res;
266}
267
268void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *Body) {
269 FunctionScopeInfo *Fn = getCurFunction();
270 assert(Fn && !Fn->CoroutineStmts.empty() && "not a coroutine");
271
272 // Coroutines [stmt.return]p1:
273 // A return statement shall not appear in a coroutine.
Richard Smith9f690bd2015-10-27 06:02:45 +0000274 if (Fn->FirstReturnLoc.isValid()) {
275 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
Richard Smithcfd53b42015-10-22 06:13:50 +0000276 auto *First = Fn->CoroutineStmts[0];
277 Diag(First->getLocStart(), diag::note_declared_coroutine_here)
Richard Smith9f690bd2015-10-27 06:02:45 +0000278 << (isa<CoawaitExpr>(First) ? 0 :
279 isa<CoyieldExpr>(First) ? 1 : 2);
Richard Smithcfd53b42015-10-22 06:13:50 +0000280 }
281
282 bool AnyCoawaits = false;
283 bool AnyCoyields = false;
284 for (auto *CoroutineStmt : Fn->CoroutineStmts) {
Richard Smith9f690bd2015-10-27 06:02:45 +0000285 AnyCoawaits |= isa<CoawaitExpr>(CoroutineStmt);
286 AnyCoyields |= isa<CoyieldExpr>(CoroutineStmt);
Richard Smithcfd53b42015-10-22 06:13:50 +0000287 }
288
289 if (!AnyCoawaits && !AnyCoyields)
290 Diag(Fn->CoroutineStmts.front()->getLocStart(),
Richard Smith9f690bd2015-10-27 06:02:45 +0000291 diag::ext_coroutine_without_co_await_co_yield);
Richard Smithcfd53b42015-10-22 06:13:50 +0000292
Richard Smith9f690bd2015-10-27 06:02:45 +0000293 // FIXME: Perform analysis of initial and final suspend,
294 // and set_exception call.
Richard Smithcfd53b42015-10-22 06:13:50 +0000295}