clang  8.0.0svn
SemaCoroutine.cpp
Go to the documentation of this file.
1 //===--- 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 // This file contains references to sections of the Coroutines TS, which
13 // can be found at http://wg21.link/coroutines.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "CoroutineStmtBuilder.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/StmtCXX.h"
22 #include "clang/Lex/Preprocessor.h"
24 #include "clang/Sema/Overload.h"
25 #include "clang/Sema/ScopeInfo.h"
27 
28 using namespace clang;
29 using namespace sema;
30 
31 static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
32  SourceLocation Loc, bool &Res) {
34  LookupResult LR(S, DN, Loc, Sema::LookupMemberName);
35  // Suppress diagnostics when a private member is selected. The same warnings
36  // will be produced again when building the call.
38  Res = S.LookupQualifiedName(LR, RD);
39  return LR;
40 }
41 
42 static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
43  SourceLocation Loc) {
44  bool Res;
45  lookupMember(S, Name, RD, Loc, Res);
46  return Res;
47 }
48 
49 /// Look up the std::coroutine_traits<...>::promise_type for the given
50 /// function type.
52  SourceLocation KwLoc) {
53  const FunctionProtoType *FnType = FD->getType()->castAs<FunctionProtoType>();
54  const SourceLocation FuncLoc = FD->getLocation();
55  // FIXME: Cache std::coroutine_traits once we've found it.
57  if (!StdExp) {
58  S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
59  << "std::experimental::coroutine_traits";
60  return QualType();
61  }
62 
63  ClassTemplateDecl *CoroTraits = S.lookupCoroutineTraits(KwLoc, FuncLoc);
64  if (!CoroTraits) {
65  return QualType();
66  }
67 
68  // Form template argument list for coroutine_traits<R, P1, P2, ...> according
69  // to [dcl.fct.def.coroutine]3
70  TemplateArgumentListInfo Args(KwLoc, KwLoc);
71  auto AddArg = [&](QualType T) {
74  };
75  AddArg(FnType->getReturnType());
76  // If the function is a non-static member function, add the type
77  // of the implicit object parameter before the formal parameters.
78  if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
79  if (MD->isInstance()) {
80  // [over.match.funcs]4
81  // For non-static member functions, the type of the implicit object
82  // parameter is
83  // -- "lvalue reference to cv X" for functions declared without a
84  // ref-qualifier or with the & ref-qualifier
85  // -- "rvalue reference to cv X" for functions declared with the &&
86  // ref-qualifier
87  QualType T =
88  MD->getThisType(S.Context)->getAs<PointerType>()->getPointeeType();
89  T = FnType->getRefQualifier() == RQ_RValue
91  : S.Context.getLValueReferenceType(T, /*SpelledAsLValue*/ true);
92  AddArg(T);
93  }
94  }
95  for (QualType T : FnType->getParamTypes())
96  AddArg(T);
97 
98  // Build the template-id.
99  QualType CoroTrait =
100  S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
101  if (CoroTrait.isNull())
102  return QualType();
103  if (S.RequireCompleteType(KwLoc, CoroTrait,
104  diag::err_coroutine_type_missing_specialization))
105  return QualType();
106 
107  auto *RD = CoroTrait->getAsCXXRecordDecl();
108  assert(RD && "specialization of class template is not a class?");
109 
110  // Look up the ::promise_type member.
111  LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
113  S.LookupQualifiedName(R, RD);
114  auto *Promise = R.getAsSingle<TypeDecl>();
115  if (!Promise) {
116  S.Diag(FuncLoc,
117  diag::err_implied_std_coroutine_traits_promise_type_not_found)
118  << RD;
119  return QualType();
120  }
121  // The promise type is required to be a class type.
122  QualType PromiseType = S.Context.getTypeDeclType(Promise);
123 
124  auto buildElaboratedType = [&]() {
125  auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, StdExp);
126  NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
127  CoroTrait.getTypePtr());
128  return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
129  };
130 
131  if (!PromiseType->getAsCXXRecordDecl()) {
132  S.Diag(FuncLoc,
133  diag::err_implied_std_coroutine_traits_promise_type_not_class)
134  << buildElaboratedType();
135  return QualType();
136  }
137  if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
138  diag::err_coroutine_promise_type_incomplete))
139  return QualType();
140 
141  return PromiseType;
142 }
143 
144 /// Look up the std::experimental::coroutine_handle<PromiseType>.
146  SourceLocation Loc) {
147  if (PromiseType.isNull())
148  return QualType();
149 
151  assert(StdExp && "Should already be diagnosed");
152 
153  LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
155  if (!S.LookupQualifiedName(Result, StdExp)) {
156  S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
157  << "std::experimental::coroutine_handle";
158  return QualType();
159  }
160 
161  ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
162  if (!CoroHandle) {
163  Result.suppressDiagnostics();
164  // We found something weird. Complain about the first thing we found.
165  NamedDecl *Found = *Result.begin();
166  S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
167  return QualType();
168  }
169 
170  // Form template argument list for coroutine_handle<Promise>.
171  TemplateArgumentListInfo Args(Loc, Loc);
173  TemplateArgument(PromiseType),
174  S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
175 
176  // Build the template-id.
177  QualType CoroHandleType =
178  S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
179  if (CoroHandleType.isNull())
180  return QualType();
181  if (S.RequireCompleteType(Loc, CoroHandleType,
182  diag::err_coroutine_type_missing_specialization))
183  return QualType();
184 
185  return CoroHandleType;
186 }
187 
189  StringRef Keyword) {
190  // 'co_await' and 'co_yield' are not permitted in unevaluated operands,
191  // such as subexpressions of \c sizeof.
192  //
193  // [expr.await]p2, emphasis added: "An await-expression shall appear only in
194  // a *potentially evaluated* expression within the compound-statement of a
195  // function-body outside of a handler [...] A context within a function where
196  // an await-expression can appear is called a suspension context of the
197  // function." And per [expr.yield]p1: "A yield-expression shall appear only
198  // within a suspension context of a function."
199  if (S.isUnevaluatedContext()) {
200  S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
201  return false;
202  }
203 
204  // Per [expr.await]p2, any other usage must be within a function.
205  // FIXME: This also covers [expr.await]p2: "An await-expression shall not
206  // appear in a default argument." But the diagnostic QoI here could be
207  // improved to inform the user that default arguments specifically are not
208  // allowed.
209  auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
210  if (!FD) {
211  S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
212  ? diag::err_coroutine_objc_method
213  : diag::err_coroutine_outside_function) << Keyword;
214  return false;
215  }
216 
217  // An enumeration for mapping the diagnostic type to the correct diagnostic
218  // selection index.
219  enum InvalidFuncDiag {
220  DiagCtor = 0,
221  DiagDtor,
222  DiagCopyAssign,
223  DiagMoveAssign,
224  DiagMain,
225  DiagConstexpr,
226  DiagAutoRet,
227  DiagVarargs,
228  };
229  bool Diagnosed = false;
230  auto DiagInvalid = [&](InvalidFuncDiag ID) {
231  S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
232  Diagnosed = true;
233  return false;
234  };
235 
236  // Diagnose when a constructor, destructor, copy/move assignment operator,
237  // or the function 'main' are declared as a coroutine.
238  auto *MD = dyn_cast<CXXMethodDecl>(FD);
239  // [class.ctor]p6: "A constructor shall not be a coroutine."
240  if (MD && isa<CXXConstructorDecl>(MD))
241  return DiagInvalid(DiagCtor);
242  // [class.dtor]p17: "A destructor shall not be a coroutine."
243  else if (MD && isa<CXXDestructorDecl>(MD))
244  return DiagInvalid(DiagDtor);
245  // N4499 [special]p6: "A special member function shall not be a coroutine."
246  // Per C++ [special]p1, special member functions are the "default constructor,
247  // copy constructor and copy assignment operator, move constructor and move
248  // assignment operator, and destructor."
249  else if (MD && MD->isCopyAssignmentOperator())
250  return DiagInvalid(DiagCopyAssign);
251  else if (MD && MD->isMoveAssignmentOperator())
252  return DiagInvalid(DiagMoveAssign);
253  // [basic.start.main]p3: "The function main shall not be a coroutine."
254  else if (FD->isMain())
255  return DiagInvalid(DiagMain);
256 
257  // Emit a diagnostics for each of the following conditions which is not met.
258  // [expr.const]p2: "An expression e is a core constant expression unless the
259  // evaluation of e [...] would evaluate one of the following expressions:
260  // [...] an await-expression [...] a yield-expression."
261  if (FD->isConstexpr())
262  DiagInvalid(DiagConstexpr);
263  // [dcl.spec.auto]p15: "A function declared with a return type that uses a
264  // placeholder type shall not be a coroutine."
265  if (FD->getReturnType()->isUndeducedType())
266  DiagInvalid(DiagAutoRet);
267  // [dcl.fct.def.coroutine]p1: "The parameter-declaration-clause of the
268  // coroutine shall not terminate with an ellipsis that is not part of a
269  // parameter-declaration."
270  if (FD->isVariadic())
271  DiagInvalid(DiagVarargs);
272 
273  return !Diagnosed;
274 }
275 
277  SourceLocation Loc) {
278  DeclarationName OpName =
279  SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
280  LookupResult Operators(SemaRef, OpName, SourceLocation(),
282  SemaRef.LookupName(Operators, S);
283 
284  assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
285  const auto &Functions = Operators.asUnresolvedSet();
286  bool IsOverloaded =
287  Functions.size() > 1 ||
288  (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
289  Expr *CoawaitOp = UnresolvedLookupExpr::Create(
290  SemaRef.Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
291  DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
292  Functions.begin(), Functions.end());
293  assert(CoawaitOp);
294  return CoawaitOp;
295 }
296 
297 /// Build a call to 'operator co_await' if there is a suitable operator for
298 /// the given expression.
300  Expr *E,
301  UnresolvedLookupExpr *Lookup) {
302  UnresolvedSet<16> Functions;
303  Functions.append(Lookup->decls_begin(), Lookup->decls_end());
304  return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
305 }
306 
308  SourceLocation Loc, Expr *E) {
309  ExprResult R = buildOperatorCoawaitLookupExpr(SemaRef, S, Loc);
310  if (R.isInvalid())
311  return ExprError();
312  return buildOperatorCoawaitCall(SemaRef, Loc, E,
313  cast<UnresolvedLookupExpr>(R.get()));
314 }
315 
317  MultiExprArg CallArgs) {
318  StringRef Name = S.Context.BuiltinInfo.getName(Id);
320  S.LookupName(R, S.TUScope, /*AllowBuiltinCreation=*/true);
321 
322  auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
323  assert(BuiltInDecl && "failed to find builtin declaration");
324 
325  ExprResult DeclRef =
326  S.BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
327  assert(DeclRef.isUsable() && "Builtin reference cannot fail");
328 
329  ExprResult Call =
330  S.ActOnCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
331 
332  assert(!Call.isInvalid() && "Call to builtin cannot fail!");
333  return Call.get();
334 }
335 
337  SourceLocation Loc) {
338  QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
339  if (CoroHandleType.isNull())
340  return ExprError();
341 
342  DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
343  LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
345  if (!S.LookupQualifiedName(Found, LookupCtx)) {
346  S.Diag(Loc, diag::err_coroutine_handle_missing_member)
347  << "from_address";
348  return ExprError();
349  }
350 
351  Expr *FramePtr =
352  buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
353 
354  CXXScopeSpec SS;
355  ExprResult FromAddr =
356  S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
357  if (FromAddr.isInvalid())
358  return ExprError();
359 
360  return S.ActOnCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
361 }
362 
364  enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume };
365  Expr *Results[3];
367  bool IsInvalid;
368 };
369 
371  StringRef Name, MultiExprArg Args) {
372  DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
373 
374  // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
375  CXXScopeSpec SS;
377  Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
378  SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
379  /*Scope=*/nullptr);
380  if (Result.isInvalid())
381  return ExprError();
382 
383  // We meant exactly what we asked for. No need for typo correction.
384  if (auto *TE = dyn_cast<TypoExpr>(Result.get())) {
385  S.clearDelayedTypo(TE);
386  S.Diag(Loc, diag::err_no_member)
387  << NameInfo.getName() << Base->getType()->getAsCXXRecordDecl()
388  << Base->getSourceRange();
389  return ExprError();
390  }
391 
392  return S.ActOnCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
393 }
394 
395 // See if return type is coroutine-handle and if so, invoke builtin coro-resume
396 // on its address. This is to enable experimental support for coroutine-handle
397 // returning await_suspend that results in a guaranteed tail call to the target
398 // coroutine.
399 static Expr *maybeTailCall(Sema &S, QualType RetType, Expr *E,
400  SourceLocation Loc) {
401  if (RetType->isReferenceType())
402  return nullptr;
403  Type const *T = RetType.getTypePtr();
404  if (!T->isClassType() && !T->isStructureType())
405  return nullptr;
406 
407  // FIXME: Add convertability check to coroutine_handle<>. Possibly via
408  // EvaluateBinaryTypeTrait(BTT_IsConvertible, ...) which is at the moment
409  // a private function in SemaExprCXX.cpp
410 
411  ExprResult AddressExpr = buildMemberCall(S, E, Loc, "address", None);
412  if (AddressExpr.isInvalid())
413  return nullptr;
414 
415  Expr *JustAddress = AddressExpr.get();
416  // FIXME: Check that the type of AddressExpr is void*
417  return buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_resume,
418  JustAddress);
419 }
420 
421 /// Build calls to await_ready, await_suspend, and await_resume for a co_await
422 /// expression.
424  SourceLocation Loc, Expr *E) {
425  OpaqueValueExpr *Operand = new (S.Context)
426  OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
427 
428  // Assume invalid until we see otherwise.
429  ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true};
430 
431  ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc);
432  if (CoroHandleRes.isInvalid())
433  return Calls;
434  Expr *CoroHandle = CoroHandleRes.get();
435 
436  const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
437  MultiExprArg Args[] = {None, CoroHandle, None};
438  for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
439  ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]);
440  if (Result.isInvalid())
441  return Calls;
442  Calls.Results[I] = Result.get();
443  }
444 
445  // Assume the calls are valid; all further checking should make them invalid.
446  Calls.IsInvalid = false;
447 
449  CallExpr *AwaitReady = cast<CallExpr>(Calls.Results[ACT::ACT_Ready]);
450  if (!AwaitReady->getType()->isDependentType()) {
451  // [expr.await]p3 [...]
452  // — await-ready is the expression e.await_ready(), contextually converted
453  // to bool.
454  ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady);
455  if (Conv.isInvalid()) {
456  S.Diag(AwaitReady->getDirectCallee()->getBeginLoc(),
457  diag::note_await_ready_no_bool_conversion);
458  S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
459  << AwaitReady->getDirectCallee() << E->getSourceRange();
460  Calls.IsInvalid = true;
461  }
462  Calls.Results[ACT::ACT_Ready] = Conv.get();
463  }
464  CallExpr *AwaitSuspend = cast<CallExpr>(Calls.Results[ACT::ACT_Suspend]);
465  if (!AwaitSuspend->getType()->isDependentType()) {
466  // [expr.await]p3 [...]
467  // - await-suspend is the expression e.await_suspend(h), which shall be
468  // a prvalue of type void or bool.
469  QualType RetType = AwaitSuspend->getCallReturnType(S.Context);
470 
471  // Experimental support for coroutine_handle returning await_suspend.
472  if (Expr *TailCallSuspend = maybeTailCall(S, RetType, AwaitSuspend, Loc))
473  Calls.Results[ACT::ACT_Suspend] = TailCallSuspend;
474  else {
475  // non-class prvalues always have cv-unqualified types
476  if (RetType->isReferenceType() ||
477  (!RetType->isBooleanType() && !RetType->isVoidType())) {
478  S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
479  diag::err_await_suspend_invalid_return_type)
480  << RetType;
481  S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
482  << AwaitSuspend->getDirectCallee();
483  Calls.IsInvalid = true;
484  }
485  }
486  }
487 
488  return Calls;
489 }
490 
492  SourceLocation Loc, StringRef Name,
493  MultiExprArg Args) {
494 
495  // Form a reference to the promise.
496  ExprResult PromiseRef = S.BuildDeclRefExpr(
497  Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
498  if (PromiseRef.isInvalid())
499  return ExprError();
500 
501  return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
502 }
503 
505  assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
506  auto *FD = cast<FunctionDecl>(CurContext);
507  bool IsThisDependentType = [&] {
508  if (auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD))
509  return MD->isInstance() && MD->getThisType(Context)->isDependentType();
510  else
511  return false;
512  }();
513 
514  QualType T = FD->getType()->isDependentType() || IsThisDependentType
515  ? Context.DependentTy
516  : lookupPromiseType(*this, FD, Loc);
517  if (T.isNull())
518  return nullptr;
519 
520  auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
521  &PP.getIdentifierTable().get("__promise"), T,
522  Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
523  CheckVariableDeclarationType(VD);
524  if (VD->isInvalidDecl())
525  return nullptr;
526 
527  auto *ScopeInfo = getCurFunction();
528  // Build a list of arguments, based on the coroutine functions arguments,
529  // that will be passed to the promise type's constructor.
530  llvm::SmallVector<Expr *, 4> CtorArgExprs;
531 
532  // Add implicit object parameter.
533  if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
534  if (MD->isInstance() && !isLambdaCallOperator(MD)) {
535  ExprResult ThisExpr = ActOnCXXThis(Loc);
536  if (ThisExpr.isInvalid())
537  return nullptr;
538  ThisExpr = CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
539  if (ThisExpr.isInvalid())
540  return nullptr;
541  CtorArgExprs.push_back(ThisExpr.get());
542  }
543  }
544 
545  auto &Moves = ScopeInfo->CoroutineParameterMoves;
546  for (auto *PD : FD->parameters()) {
547  if (PD->getType()->isDependentType())
548  continue;
549 
550  auto RefExpr = ExprEmpty();
551  auto Move = Moves.find(PD);
552  assert(Move != Moves.end() &&
553  "Coroutine function parameter not inserted into move map");
554  // If a reference to the function parameter exists in the coroutine
555  // frame, use that reference.
556  auto *MoveDecl =
557  cast<VarDecl>(cast<DeclStmt>(Move->second)->getSingleDecl());
558  RefExpr =
559  BuildDeclRefExpr(MoveDecl, MoveDecl->getType().getNonReferenceType(),
560  ExprValueKind::VK_LValue, FD->getLocation());
561  if (RefExpr.isInvalid())
562  return nullptr;
563  CtorArgExprs.push_back(RefExpr.get());
564  }
565 
566  // Create an initialization sequence for the promise type using the
567  // constructor arguments, wrapped in a parenthesized list expression.
568  Expr *PLE = new (Context) ParenListExpr(Context, FD->getLocation(),
569  CtorArgExprs, FD->getLocation());
572  VD->getLocation(), /*DirectInit=*/true, PLE);
573  InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs,
574  /*TopLevelOfInitList=*/false,
575  /*TreatUnavailableAsInvalid=*/false);
576 
577  // Attempt to initialize the promise type with the arguments.
578  // If that fails, fall back to the promise type's default constructor.
579  if (InitSeq) {
580  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, CtorArgExprs);
581  if (Result.isInvalid()) {
582  VD->setInvalidDecl();
583  } else if (Result.get()) {
584  VD->setInit(MaybeCreateExprWithCleanups(Result.get()));
585  VD->setInitStyle(VarDecl::CallInit);
586  CheckCompleteVariableDeclaration(VD);
587  }
588  } else
589  ActOnUninitializedDecl(VD);
590 
591  FD->addDecl(VD);
592  return VD;
593 }
594 
595 /// Check that this is a context in which a coroutine suspension can appear.
597  StringRef Keyword,
598  bool IsImplicit = false) {
599  if (!isValidCoroutineContext(S, Loc, Keyword))
600  return nullptr;
601 
602  assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
603 
604  auto *ScopeInfo = S.getCurFunction();
605  assert(ScopeInfo && "missing function scope for function");
606 
607  if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
608  ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
609 
610  if (ScopeInfo->CoroutinePromise)
611  return ScopeInfo;
612 
613  if (!S.buildCoroutineParameterMoves(Loc))
614  return nullptr;
615 
616  ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
617  if (!ScopeInfo->CoroutinePromise)
618  return nullptr;
619 
620  return ScopeInfo;
621 }
622 
624  StringRef Keyword) {
625  if (!checkCoroutineContext(*this, KWLoc, Keyword))
626  return false;
627  auto *ScopeInfo = getCurFunction();
628  assert(ScopeInfo->CoroutinePromise);
629 
630  // If we have existing coroutine statements then we have already built
631  // the initial and final suspend points.
632  if (!ScopeInfo->NeedsCoroutineSuspends)
633  return true;
634 
635  ScopeInfo->setNeedsCoroutineSuspends(false);
636 
637  auto *Fn = cast<FunctionDecl>(CurContext);
638  SourceLocation Loc = Fn->getLocation();
639  // Build the initial suspend point
640  auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
641  ExprResult Suspend =
642  buildPromiseCall(*this, ScopeInfo->CoroutinePromise, Loc, Name, None);
643  if (Suspend.isInvalid())
644  return StmtError();
645  Suspend = buildOperatorCoawaitCall(*this, SC, Loc, Suspend.get());
646  if (Suspend.isInvalid())
647  return StmtError();
648  Suspend = BuildResolvedCoawaitExpr(Loc, Suspend.get(),
649  /*IsImplicit*/ true);
650  Suspend = ActOnFinishFullExpr(Suspend.get());
651  if (Suspend.isInvalid()) {
652  Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
653  << ((Name == "initial_suspend") ? 0 : 1);
654  Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
655  return StmtError();
656  }
657  return cast<Stmt>(Suspend.get());
658  };
659 
660  StmtResult InitSuspend = buildSuspends("initial_suspend");
661  if (InitSuspend.isInvalid())
662  return true;
663 
664  StmtResult FinalSuspend = buildSuspends("final_suspend");
665  if (FinalSuspend.isInvalid())
666  return true;
667 
668  ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
669 
670  return true;
671 }
672 
674  if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) {
675  CorrectDelayedTyposInExpr(E);
676  return ExprError();
677  }
678 
679  if (E->getType()->isPlaceholderType()) {
680  ExprResult R = CheckPlaceholderExpr(E);
681  if (R.isInvalid()) return ExprError();
682  E = R.get();
683  }
684  ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
685  if (Lookup.isInvalid())
686  return ExprError();
687  return BuildUnresolvedCoawaitExpr(Loc, E,
688  cast<UnresolvedLookupExpr>(Lookup.get()));
689 }
690 
692  UnresolvedLookupExpr *Lookup) {
693  auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
694  if (!FSI)
695  return ExprError();
696 
697  if (E->getType()->isPlaceholderType()) {
698  ExprResult R = CheckPlaceholderExpr(E);
699  if (R.isInvalid())
700  return ExprError();
701  E = R.get();
702  }
703 
704  auto *Promise = FSI->CoroutinePromise;
705  if (Promise->getType()->isDependentType()) {
706  Expr *Res =
707  new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
708  return Res;
709  }
710 
711  auto *RD = Promise->getType()->getAsCXXRecordDecl();
712  if (lookupMember(*this, "await_transform", RD, Loc)) {
713  ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
714  if (R.isInvalid()) {
715  Diag(Loc,
716  diag::note_coroutine_promise_implicit_await_transform_required_here)
717  << E->getSourceRange();
718  return ExprError();
719  }
720  E = R.get();
721  }
722  ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
723  if (Awaitable.isInvalid())
724  return ExprError();
725 
726  return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
727 }
728 
730  bool IsImplicit) {
731  auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
732  if (!Coroutine)
733  return ExprError();
734 
735  if (E->getType()->isPlaceholderType()) {
736  ExprResult R = CheckPlaceholderExpr(E);
737  if (R.isInvalid()) return ExprError();
738  E = R.get();
739  }
740 
741  if (E->getType()->isDependentType()) {
742  Expr *Res = new (Context)
743  CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
744  return Res;
745  }
746 
747  // If the expression is a temporary, materialize it as an lvalue so that we
748  // can use it multiple times.
749  if (E->getValueKind() == VK_RValue)
750  E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
751 
752  // The location of the `co_await` token cannot be used when constructing
753  // the member call expressions since it's before the location of `Expr`, which
754  // is used as the start of the member call expression.
755  SourceLocation CallLoc = E->getExprLoc();
756 
757  // Build the await_ready, await_suspend, await_resume calls.
759  buildCoawaitCalls(*this, Coroutine->CoroutinePromise, CallLoc, E);
760  if (RSS.IsInvalid)
761  return ExprError();
762 
763  Expr *Res =
764  new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
765  RSS.Results[2], RSS.OpaqueValue, IsImplicit);
766 
767  return Res;
768 }
769 
771  if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) {
772  CorrectDelayedTyposInExpr(E);
773  return ExprError();
774  }
775 
776  // Build yield_value call.
777  ExprResult Awaitable = buildPromiseCall(
778  *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
779  if (Awaitable.isInvalid())
780  return ExprError();
781 
782  // Build 'operator co_await' call.
783  Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
784  if (Awaitable.isInvalid())
785  return ExprError();
786 
787  return BuildCoyieldExpr(Loc, Awaitable.get());
788 }
790  auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
791  if (!Coroutine)
792  return ExprError();
793 
794  if (E->getType()->isPlaceholderType()) {
795  ExprResult R = CheckPlaceholderExpr(E);
796  if (R.isInvalid()) return ExprError();
797  E = R.get();
798  }
799 
800  if (E->getType()->isDependentType()) {
801  Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
802  return Res;
803  }
804 
805  // If the expression is a temporary, materialize it as an lvalue so that we
806  // can use it multiple times.
807  if (E->getValueKind() == VK_RValue)
808  E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
809 
810  // Build the await_ready, await_suspend, await_resume calls.
812  buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E);
813  if (RSS.IsInvalid)
814  return ExprError();
815 
816  Expr *Res =
817  new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
818  RSS.Results[2], RSS.OpaqueValue);
819 
820  return Res;
821 }
822 
824  if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) {
825  CorrectDelayedTyposInExpr(E);
826  return StmtError();
827  }
828  return BuildCoreturnStmt(Loc, E);
829 }
830 
832  bool IsImplicit) {
833  auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
834  if (!FSI)
835  return StmtError();
836 
837  if (E && E->getType()->isPlaceholderType() &&
838  !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
839  ExprResult R = CheckPlaceholderExpr(E);
840  if (R.isInvalid()) return StmtError();
841  E = R.get();
842  }
843 
844  // FIXME: If the operand is a reference to a variable that's about to go out
845  // of scope, we should treat the operand as an xvalue for this overload
846  // resolution.
847  VarDecl *Promise = FSI->CoroutinePromise;
848  ExprResult PC;
849  if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
850  PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
851  } else {
852  E = MakeFullDiscardedValueExpr(E).get();
853  PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
854  }
855  if (PC.isInvalid())
856  return StmtError();
857 
858  Expr *PCE = ActOnFinishFullExpr(PC.get()).get();
859 
860  Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
861  return Res;
862 }
863 
864 /// Look up the std::nothrow object.
867  assert(Std && "Should already be diagnosed");
868 
869  LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
871  if (!S.LookupQualifiedName(Result, Std)) {
872  // FIXME: <experimental/coroutine> should have been included already.
873  // If we require it to include <new> then this diagnostic is no longer
874  // needed.
875  S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
876  return nullptr;
877  }
878 
879  auto *VD = Result.getAsSingle<VarDecl>();
880  if (!VD) {
881  Result.suppressDiagnostics();
882  // We found something weird. Complain about the first thing we found.
883  NamedDecl *Found = *Result.begin();
884  S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
885  return nullptr;
886  }
887 
888  ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
889  if (DR.isInvalid())
890  return nullptr;
891 
892  return DR.get();
893 }
894 
895 // Find an appropriate delete for the promise.
897  QualType PromiseType) {
898  FunctionDecl *OperatorDelete = nullptr;
899 
900  DeclarationName DeleteName =
902 
903  auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
904  assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
905 
906  if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
907  return nullptr;
908 
909  if (!OperatorDelete) {
910  // Look for a global declaration.
911  const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
912  const bool Overaligned = false;
913  OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
914  Overaligned, DeleteName);
915  }
916  S.MarkFunctionReferenced(Loc, OperatorDelete);
917  return OperatorDelete;
918 }
919 
920 
922  FunctionScopeInfo *Fn = getCurFunction();
923  assert(Fn && Fn->isCoroutine() && "not a coroutine");
924  if (!Body) {
925  assert(FD->isInvalidDecl() &&
926  "a null body is only allowed for invalid declarations");
927  return;
928  }
929  // We have a function that uses coroutine keywords, but we failed to build
930  // the promise type.
931  if (!Fn->CoroutinePromise)
932  return FD->setInvalidDecl();
933 
934  if (isa<CoroutineBodyStmt>(Body)) {
935  // Nothing todo. the body is already a transformed coroutine body statement.
936  return;
937  }
938 
939  // Coroutines [stmt.return]p1:
940  // A return statement shall not appear in a coroutine.
941  if (Fn->FirstReturnLoc.isValid()) {
942  assert(Fn->FirstCoroutineStmtLoc.isValid() &&
943  "first coroutine location not set");
944  Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
945  Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
947  }
948  CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
949  if (Builder.isInvalid() || !Builder.buildStatements())
950  return FD->setInvalidDecl();
951 
952  // Build body for the coroutine wrapper statement.
953  Body = CoroutineBodyStmt::Create(Context, Builder);
954 }
955 
958  Stmt *Body)
959  : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
960  IsPromiseDependentType(
961  !Fn.CoroutinePromise ||
962  Fn.CoroutinePromise->getType()->isDependentType()) {
963  this->Body = Body;
964 
965  for (auto KV : Fn.CoroutineParameterMoves)
966  this->ParamMovesVector.push_back(KV.second);
967  this->ParamMoves = this->ParamMovesVector;
968 
969  if (!IsPromiseDependentType) {
970  PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
971  assert(PromiseRecordDecl && "Type should have already been checked");
972  }
973  this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
974 }
975 
977  assert(this->IsValid && "coroutine already invalid");
978  this->IsValid = makeReturnObject();
979  if (this->IsValid && !IsPromiseDependentType)
981  return this->IsValid;
982 }
983 
985  assert(this->IsValid && "coroutine already invalid");
986  assert(!this->IsPromiseDependentType &&
987  "coroutine cannot have a dependent promise type");
988  this->IsValid = makeOnException() && makeOnFallthrough() &&
989  makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
990  makeNewAndDeleteExpr();
991  return this->IsValid;
992 }
993 
994 bool CoroutineStmtBuilder::makePromiseStmt() {
995  // Form a declaration statement for the promise declaration, so that AST
996  // visitors can more easily find it.
997  StmtResult PromiseStmt =
999  if (PromiseStmt.isInvalid())
1000  return false;
1001 
1002  this->Promise = PromiseStmt.get();
1003  return true;
1004 }
1005 
1006 bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
1007  if (Fn.hasInvalidCoroutineSuspends())
1008  return false;
1009  this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
1010  this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
1011  return true;
1012 }
1013 
1015  CXXRecordDecl *PromiseRecordDecl,
1016  FunctionScopeInfo &Fn) {
1017  auto Loc = E->getExprLoc();
1018  if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
1019  auto *Decl = DeclRef->getDecl();
1020  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
1021  if (Method->isStatic())
1022  return true;
1023  else
1024  Loc = Decl->getLocation();
1025  }
1026  }
1027 
1028  S.Diag(
1029  Loc,
1030  diag::err_coroutine_promise_get_return_object_on_allocation_failure)
1031  << PromiseRecordDecl;
1032  S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1034  return false;
1035 }
1036 
1037 bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
1038  assert(!IsPromiseDependentType &&
1039  "cannot make statement while the promise type is dependent");
1040 
1041  // [dcl.fct.def.coroutine]/8
1042  // The unqualified-id get_return_object_on_allocation_failure is looked up in
1043  // the scope of class P by class member access lookup (3.4.5). ...
1044  // If an allocation function returns nullptr, ... the coroutine return value
1045  // is obtained by a call to ... get_return_object_on_allocation_failure().
1046 
1047  DeclarationName DN =
1048  S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
1049  LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
1050  if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
1051  return true;
1052 
1053  CXXScopeSpec SS;
1054  ExprResult DeclNameExpr =
1055  S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
1056  if (DeclNameExpr.isInvalid())
1057  return false;
1058 
1059  if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
1060  return false;
1061 
1062  ExprResult ReturnObjectOnAllocationFailure =
1063  S.ActOnCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
1064  if (ReturnObjectOnAllocationFailure.isInvalid())
1065  return false;
1066 
1068  S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
1069  if (ReturnStmt.isInvalid()) {
1070  S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
1071  << DN;
1072  S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1074  return false;
1075  }
1076 
1077  this->ReturnStmtOnAllocFailure = ReturnStmt.get();
1078  return true;
1079 }
1080 
1081 bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
1082  // Form and check allocation and deallocation calls.
1083  assert(!IsPromiseDependentType &&
1084  "cannot make statement while the promise type is dependent");
1085  QualType PromiseType = Fn.CoroutinePromise->getType();
1086 
1087  if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
1088  return false;
1089 
1090  const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
1091 
1092  // [dcl.fct.def.coroutine]/7
1093  // Lookup allocation functions using a parameter list composed of the
1094  // requested size of the coroutine state being allocated, followed by
1095  // the coroutine function's arguments. If a matching allocation function
1096  // exists, use it. Otherwise, use an allocation function that just takes
1097  // the requested size.
1098 
1099  FunctionDecl *OperatorNew = nullptr;
1100  FunctionDecl *OperatorDelete = nullptr;
1101  FunctionDecl *UnusedResult = nullptr;
1102  bool PassAlignment = false;
1103  SmallVector<Expr *, 1> PlacementArgs;
1104 
1105  // [dcl.fct.def.coroutine]/7
1106  // "The allocation function’s name is looked up in the scope of P.
1107  // [...] If the lookup finds an allocation function in the scope of P,
1108  // overload resolution is performed on a function call created by assembling
1109  // an argument list. The first argument is the amount of space requested,
1110  // and has type std::size_t. The lvalues p1 ... pn are the succeeding
1111  // arguments."
1112  //
1113  // ...where "p1 ... pn" are defined earlier as:
1114  //
1115  // [dcl.fct.def.coroutine]/3
1116  // "For a coroutine f that is a non-static member function, let P1 denote the
1117  // type of the implicit object parameter (13.3.1) and P2 ... Pn be the types
1118  // of the function parameters; otherwise let P1 ... Pn be the types of the
1119  // function parameters. Let p1 ... pn be lvalues denoting those objects."
1120  if (auto *MD = dyn_cast<CXXMethodDecl>(&FD)) {
1121  if (MD->isInstance() && !isLambdaCallOperator(MD)) {
1122  ExprResult ThisExpr = S.ActOnCXXThis(Loc);
1123  if (ThisExpr.isInvalid())
1124  return false;
1125  ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
1126  if (ThisExpr.isInvalid())
1127  return false;
1128  PlacementArgs.push_back(ThisExpr.get());
1129  }
1130  }
1131  for (auto *PD : FD.parameters()) {
1132  if (PD->getType()->isDependentType())
1133  continue;
1134 
1135  // Build a reference to the parameter.
1136  auto PDLoc = PD->getLocation();
1137  ExprResult PDRefExpr =
1138  S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),
1139  ExprValueKind::VK_LValue, PDLoc);
1140  if (PDRefExpr.isInvalid())
1141  return false;
1142 
1143  PlacementArgs.push_back(PDRefExpr.get());
1144  }
1145  S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class,
1146  /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1147  /*isArray*/ false, PassAlignment, PlacementArgs,
1148  OperatorNew, UnusedResult, /*Diagnose*/ false);
1149 
1150  // [dcl.fct.def.coroutine]/7
1151  // "If no matching function is found, overload resolution is performed again
1152  // on a function call created by passing just the amount of space required as
1153  // an argument of type std::size_t."
1154  if (!OperatorNew && !PlacementArgs.empty()) {
1155  PlacementArgs.clear();
1156  S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class,
1157  /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1158  /*isArray*/ false, PassAlignment, PlacementArgs,
1159  OperatorNew, UnusedResult, /*Diagnose*/ false);
1160  }
1161 
1162  // [dcl.fct.def.coroutine]/7
1163  // "The allocation function’s name is looked up in the scope of P. If this
1164  // lookup fails, the allocation function’s name is looked up in the global
1165  // scope."
1166  if (!OperatorNew) {
1167  S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Global,
1168  /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1169  /*isArray*/ false, PassAlignment, PlacementArgs,
1170  OperatorNew, UnusedResult);
1171  }
1172 
1173  bool IsGlobalOverload =
1174  OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
1175  // If we didn't find a class-local new declaration and non-throwing new
1176  // was is required then we need to lookup the non-throwing global operator
1177  // instead.
1178  if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
1179  auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
1180  if (!StdNoThrow)
1181  return false;
1182  PlacementArgs = {StdNoThrow};
1183  OperatorNew = nullptr;
1184  S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Both,
1185  /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1186  /*isArray*/ false, PassAlignment, PlacementArgs,
1187  OperatorNew, UnusedResult);
1188  }
1189 
1190  if (!OperatorNew)
1191  return false;
1192 
1193  if (RequiresNoThrowAlloc) {
1194  const auto *FT = OperatorNew->getType()->getAs<FunctionProtoType>();
1195  if (!FT->isNothrow(/*ResultIfDependent*/ false)) {
1196  S.Diag(OperatorNew->getLocation(),
1197  diag::err_coroutine_promise_new_requires_nothrow)
1198  << OperatorNew;
1199  S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
1200  << OperatorNew;
1201  return false;
1202  }
1203  }
1204 
1205  if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr)
1206  return false;
1207 
1208  Expr *FramePtr =
1209  buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
1210 
1211  Expr *FrameSize =
1212  buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {});
1213 
1214  // Make new call.
1215 
1216  ExprResult NewRef =
1217  S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
1218  if (NewRef.isInvalid())
1219  return false;
1220 
1221  SmallVector<Expr *, 2> NewArgs(1, FrameSize);
1222  for (auto Arg : PlacementArgs)
1223  NewArgs.push_back(Arg);
1224 
1225  ExprResult NewExpr =
1226  S.ActOnCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
1227  NewExpr = S.ActOnFinishFullExpr(NewExpr.get());
1228  if (NewExpr.isInvalid())
1229  return false;
1230 
1231  // Make delete call.
1232 
1233  QualType OpDeleteQualType = OperatorDelete->getType();
1234 
1235  ExprResult DeleteRef =
1236  S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
1237  if (DeleteRef.isInvalid())
1238  return false;
1239 
1240  Expr *CoroFree =
1241  buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr});
1242 
1243  SmallVector<Expr *, 2> DeleteArgs{CoroFree};
1244 
1245  // Check if we need to pass the size.
1246  const auto *OpDeleteType =
1247  OpDeleteQualType.getTypePtr()->getAs<FunctionProtoType>();
1248  if (OpDeleteType->getNumParams() > 1)
1249  DeleteArgs.push_back(FrameSize);
1250 
1251  ExprResult DeleteExpr =
1252  S.ActOnCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
1253  DeleteExpr = S.ActOnFinishFullExpr(DeleteExpr.get());
1254  if (DeleteExpr.isInvalid())
1255  return false;
1256 
1257  this->Allocate = NewExpr.get();
1258  this->Deallocate = DeleteExpr.get();
1259 
1260  return true;
1261 }
1262 
1263 bool CoroutineStmtBuilder::makeOnFallthrough() {
1264  assert(!IsPromiseDependentType &&
1265  "cannot make statement while the promise type is dependent");
1266 
1267  // [dcl.fct.def.coroutine]/4
1268  // The unqualified-ids 'return_void' and 'return_value' are looked up in
1269  // the scope of class P. If both are found, the program is ill-formed.
1270  bool HasRVoid, HasRValue;
1271  LookupResult LRVoid =
1272  lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
1273  LookupResult LRValue =
1274  lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
1275 
1276  StmtResult Fallthrough;
1277  if (HasRVoid && HasRValue) {
1278  // FIXME Improve this diagnostic
1279  S.Diag(FD.getLocation(),
1280  diag::err_coroutine_promise_incompatible_return_functions)
1281  << PromiseRecordDecl;
1282  S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
1283  diag::note_member_first_declared_here)
1284  << LRVoid.getLookupName();
1285  S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
1286  diag::note_member_first_declared_here)
1287  << LRValue.getLookupName();
1288  return false;
1289  } else if (!HasRVoid && !HasRValue) {
1290  // FIXME: The PDTS currently specifies this case as UB, not ill-formed.
1291  // However we still diagnose this as an error since until the PDTS is fixed.
1292  S.Diag(FD.getLocation(),
1293  diag::err_coroutine_promise_requires_return_function)
1294  << PromiseRecordDecl;
1295  S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1296  << PromiseRecordDecl;
1297  return false;
1298  } else if (HasRVoid) {
1299  // If the unqualified-id return_void is found, flowing off the end of a
1300  // coroutine is equivalent to a co_return with no operand. Otherwise,
1301  // flowing off the end of a coroutine results in undefined behavior.
1302  Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
1303  /*IsImplicit*/false);
1304  Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
1305  if (Fallthrough.isInvalid())
1306  return false;
1307  }
1308 
1309  this->OnFallthrough = Fallthrough.get();
1310  return true;
1311 }
1312 
1313 bool CoroutineStmtBuilder::makeOnException() {
1314  // Try to form 'p.unhandled_exception();'
1315  assert(!IsPromiseDependentType &&
1316  "cannot make statement while the promise type is dependent");
1317 
1318  const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1319 
1320  if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
1321  auto DiagID =
1322  RequireUnhandledException
1323  ? diag::err_coroutine_promise_unhandled_exception_required
1324  : diag::
1325  warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1326  S.Diag(Loc, DiagID) << PromiseRecordDecl;
1327  S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1328  << PromiseRecordDecl;
1329  return !RequireUnhandledException;
1330  }
1331 
1332  // If exceptions are disabled, don't try to build OnException.
1333  if (!S.getLangOpts().CXXExceptions)
1334  return true;
1335 
1336  ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
1337  "unhandled_exception", None);
1338  UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc);
1339  if (UnhandledException.isInvalid())
1340  return false;
1341 
1342  // Since the body of the coroutine will be wrapped in try-catch, it will
1343  // be incompatible with SEH __try if present in a function.
1344  if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1345  S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1346  S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1348  return false;
1349  }
1350 
1351  this->OnException = UnhandledException.get();
1352  return true;
1353 }
1354 
1355 bool CoroutineStmtBuilder::makeReturnObject() {
1356  // Build implicit 'p.get_return_object()' expression and form initialization
1357  // of return type from it.
1358  ExprResult ReturnObject =
1359  buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
1360  if (ReturnObject.isInvalid())
1361  return false;
1362 
1363  this->ReturnValue = ReturnObject.get();
1364  return true;
1365 }
1366 
1368  if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
1369  auto *MethodDecl = MbrRef->getMethodDecl();
1370  S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
1371  << MethodDecl;
1372  }
1373  S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1375 }
1376 
1377 bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1378  assert(!IsPromiseDependentType &&
1379  "cannot make statement while the promise type is dependent");
1380  assert(this->ReturnValue && "ReturnValue must be already formed");
1381 
1382  QualType const GroType = this->ReturnValue->getType();
1383  assert(!GroType->isDependentType() &&
1384  "get_return_object type must no longer be dependent");
1385 
1386  QualType const FnRetType = FD.getReturnType();
1387  assert(!FnRetType->isDependentType() &&
1388  "get_return_object type must no longer be dependent");
1389 
1390  if (FnRetType->isVoidType()) {
1391  ExprResult Res = S.ActOnFinishFullExpr(this->ReturnValue, Loc);
1392  if (Res.isInvalid())
1393  return false;
1394 
1395  this->ResultDecl = Res.get();
1396  return true;
1397  }
1398 
1399  if (GroType->isVoidType()) {
1400  // Trigger a nice error message.
1401  InitializedEntity Entity =
1402  InitializedEntity::InitializeResult(Loc, FnRetType, false);
1403  S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue);
1405  return false;
1406  }
1407 
1408  auto *GroDecl = VarDecl::Create(
1409  S.Context, &FD, FD.getLocation(), FD.getLocation(),
1410  &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
1411  S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
1412 
1413  S.CheckVariableDeclarationType(GroDecl);
1414  if (GroDecl->isInvalidDecl())
1415  return false;
1416 
1418  ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType,
1419  this->ReturnValue);
1420  if (Res.isInvalid())
1421  return false;
1422 
1423  Res = S.ActOnFinishFullExpr(Res.get());
1424  if (Res.isInvalid())
1425  return false;
1426 
1427  S.AddInitializerToDecl(GroDecl, Res.get(),
1428  /*DirectInit=*/false);
1429 
1430  S.FinalizeDeclaration(GroDecl);
1431 
1432  // Form a declaration statement for the return declaration, so that AST
1433  // visitors can more easily find it.
1434  StmtResult GroDeclStmt =
1435  S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
1436  if (GroDeclStmt.isInvalid())
1437  return false;
1438 
1439  this->ResultDecl = GroDeclStmt.get();
1440 
1441  ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
1442  if (declRef.isInvalid())
1443  return false;
1444 
1445  StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
1446  if (ReturnStmt.isInvalid()) {
1448  return false;
1449  }
1450  if (cast<clang::ReturnStmt>(ReturnStmt.get())->getNRVOCandidate() == GroDecl)
1451  GroDecl->setNRVOVariable(true);
1452 
1453  this->ReturnStmt = ReturnStmt.get();
1454  return true;
1455 }
1456 
1457 // Create a static_cast<T&&>(expr).
1458 static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
1459  if (T.isNull())
1460  T = E->getType();
1461  QualType TargetType = S.BuildReferenceType(
1462  T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());
1463  SourceLocation ExprLoc = E->getBeginLoc();
1464  TypeSourceInfo *TargetLoc =
1465  S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
1466 
1467  return S
1468  .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1469  SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
1470  .get();
1471 }
1472 
1473 /// Build a variable declaration for move parameter.
1475  IdentifierInfo *II) {
1476  TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);
1477  VarDecl *Decl = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type,
1478  TInfo, SC_None);
1479  Decl->setImplicit();
1480  return Decl;
1481 }
1482 
1483 // Build statements that move coroutine function parameters to the coroutine
1484 // frame, and store them on the function scope info.
1486  assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
1487  auto *FD = cast<FunctionDecl>(CurContext);
1488 
1489  auto *ScopeInfo = getCurFunction();
1490  assert(ScopeInfo->CoroutineParameterMoves.empty() &&
1491  "Should not build parameter moves twice");
1492 
1493  for (auto *PD : FD->parameters()) {
1494  if (PD->getType()->isDependentType())
1495  continue;
1496 
1497  ExprResult PDRefExpr =
1498  BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
1499  ExprValueKind::VK_LValue, Loc); // FIXME: scope?
1500  if (PDRefExpr.isInvalid())
1501  return false;
1502 
1503  Expr *CExpr = nullptr;
1504  if (PD->getType()->getAsCXXRecordDecl() ||
1505  PD->getType()->isRValueReferenceType())
1506  CExpr = castForMoving(*this, PDRefExpr.get());
1507  else
1508  CExpr = PDRefExpr.get();
1509 
1510  auto D = buildVarDecl(*this, Loc, PD->getType(), PD->getIdentifier());
1511  AddInitializerToDecl(D, CExpr, /*DirectInit=*/true);
1512 
1513  // Convert decl to a statement.
1514  StmtResult Stmt = ActOnDeclStmt(ConvertDeclToDeclGroup(D), Loc, Loc);
1515  if (Stmt.isInvalid())
1516  return false;
1517 
1518  ScopeInfo->CoroutineParameterMoves.insert(std::make_pair(PD, Stmt.get()));
1519  }
1520  return true;
1521 }
1522 
1524  CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
1525  if (!Res)
1526  return StmtError();
1527  return Res;
1528 }
1529 
1531  SourceLocation FuncLoc) {
1532  if (!StdCoroutineTraitsCache) {
1533  if (auto StdExp = lookupStdExperimentalNamespace()) {
1534  LookupResult Result(*this,
1535  &PP.getIdentifierTable().get("coroutine_traits"),
1536  FuncLoc, LookupOrdinaryName);
1537  if (!LookupQualifiedName(Result, StdExp)) {
1538  Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
1539  << "std::experimental::coroutine_traits";
1540  return nullptr;
1541  }
1542  if (!(StdCoroutineTraitsCache =
1543  Result.getAsSingle<ClassTemplateDecl>())) {
1544  Result.suppressDiagnostics();
1545  NamedDecl *Found = *Result.begin();
1546  Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
1547  return nullptr;
1548  }
1549  }
1550  }
1551  return StdCoroutineTraitsCache;
1552 }
NamespaceDecl * lookupStdExperimentalNamespace()
static Expr * buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc)
Look up the std::nothrow object.
static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc, StringRef Name, MultiExprArg Args)
void setImplicit(bool I=true)
Definition: DeclBase.h:561
Represents a function declaration or definition.
Definition: Decl.h:1722
Represents a &#39;co_await&#39; expression while the type of the promise is dependent.
Definition: ExprCXX.h:4716
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl *&Operator, bool Diagnose=true)
NamespaceDecl * getStdNamespace() const
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this function type.
Definition: Type.h:3893
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2497
A (possibly-)qualified type.
Definition: Type.h:641
static Expr * maybeTailCall(Sema &S, QualType RetType, Expr *E, SourceLocation Loc)
static VarDecl * buildVarDecl(Sema &S, SourceLocation Loc, QualType Type, IdentifierInfo *II)
Build a variable declaration for move parameter.
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc...
Definition: Sema.h:3016
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false)
Perform unqualified name lookup starting from a given scope.
static Expr * castForMoving(Sema &S, Expr *E, QualType T=QualType())
static UnresolvedLookupExpr * Create(const ASTContext &C, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool ADL, bool Overloaded, UnresolvedSetIterator Begin, UnresolvedSetIterator End)
Definition: ExprCXX.h:3034
Represents a &#39;co_return&#39; statement in the C++ Coroutines TS.
Definition: StmtCXX.h:472
Stmt - This represents one statement.
Definition: Stmt.h:66
bool isSpecificPlaceholderType(unsigned K) const
Test for a specific placeholder type.
Definition: Type.h:6426
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type...
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1281
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:2989
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:806
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:6161
The base class of the type hierarchy.
Definition: Type.h:1414
OpaqueValueExpr * OpaqueValue
StringRef getFirstCoroutineStmtKeyword() const
Definition: ScopeInfo.h:441
Represent a C++ namespace.
Definition: Decl.h:514
A container of type source information.
Definition: Decl.h:86
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2, C99 6.9p3)
Definition: SemaExpr.cpp:14290
std::pair< Stmt *, Stmt * > CoroutineSuspends
The initial and final coroutine suspend points.
Definition: ScopeInfo.h:199
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:96
This file provides some common utility functions for processing Lambda related AST Constructs...
Represents a variable declaration or definition.
Definition: Decl.h:820
ActionResult< Stmt * > StmtResult
Definition: Ownership.h:268
bool isStructureType() const
Definition: Type.cpp:435
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:241
QualType getReturnType() const
Definition: Decl.h:2276
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6625
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E, bool IsImplicit=false)
bool isAmbiguous() const
Definition: Lookup.h:290
bool isInvalidDecl() const
Definition: DeclBase.h:555
static InitializedEntity InitializeResult(SourceLocation ReturnLoc, QualType Type, bool NRVO)
Create the initialization entity for the result of a function.
static bool diagReturnOnAllocFailure(Sema &S, Expr *E, CXXRecordDecl *PromiseRecordDecl, FunctionScopeInfo &Fn)
Defines the clang::Expr interface and subclasses for C++ expressions.
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:5300
llvm::SmallMapVector< ParmVarDecl *, Stmt *, 4 > CoroutineParameterMoves
A mapping between the coroutine function parameters that were moved to the coroutine frame...
Definition: ScopeInfo.h:196
bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope, QualType AllocType, bool IsArray, bool &PassAlignment, MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete, bool Diagnose=true)
Finds the overloads of operator new and delete that are appropriate for the allocation.
One of these records is kept for each identifier that is lexed.
static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise, SourceLocation Loc, Expr *E)
Build calls to await_ready, await_suspend, and await_resume for a co_await expression.
A C++ nested-name-specifier augmented with source location information.
ExprResult ExprEmpty()
Definition: Ownership.h:289
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:3779
bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc, StringRef Keyword)
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:280
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:54
static FunctionDecl * findDeleteForPromise(Sema &S, SourceLocation Loc, QualType PromiseType)
bool isReferenceType() const
Definition: Type.h:6224
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:746
IdentifierTable & Idents
Definition: ASTContext.h:564
SourceLocation FirstSEHTryLoc
First SEH &#39;__try&#39; statement in the current function.
Definition: ScopeInfo.h:173
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:110
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2236
bool isCompleteType(SourceLocation Loc, QualType T)
Definition: Sema.h:1616
Represents the results of name lookup.
Definition: Lookup.h:47
PtrTy get() const
Definition: Ownership.h:174
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, SourceLocation Loc, Expr *E, UnresolvedLookupExpr *Lookup)
Build a call to &#39;operator co_await&#39; if there is a suitable operator for the given expression...
A convenient class for passing around template argument information.
Definition: TemplateBase.h:552
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:405
StmtResult StmtError()
Definition: Ownership.h:284
Represents a declaration of a type.
Definition: Decl.h:2849
static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise, SourceLocation Loc, StringRef Name, MultiExprArg Args)
static QualType lookupPromiseType(Sema &S, const FunctionDecl *FD, SourceLocation KwLoc)
Look up the std::coroutine_traits<...>::promise_type for the given function type. ...
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:40
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:5988
ExprResult ActOnCXXThis(SourceLocation loc)
void append(iterator I, iterator E)
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:63
void CheckVariableDeclarationType(VarDecl *NewVD)
Definition: SemaDecl.cpp:7298
Preprocessor & PP
Definition: Sema.h:318
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:1898
const LangOptions & getLangOpts() const
Definition: Sema.h:1204
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:28
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5...
Definition: Sema.h:7507
ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs=nullptr)
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:3024
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:2738
QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:277
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc)
Definition: SemaStmt.cpp:73
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1627
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3536
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp)
Definition: SemaStmt.cpp:3460
StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E)
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:567
const char * getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:86
bool buildCoroutineParameterMoves(SourceLocation Loc)
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location, which defaults to the empty location.
Scope * getCurScope() const
Retrieve the parser&#39;s current scope.
Definition: Sema.h:10623
Expr - This represents one expression.
Definition: Expr.h:106
int Id
Definition: ASTDiff.cpp:191
ClassTemplateDecl * lookupCoroutineTraits(SourceLocation KwLoc, SourceLocation FuncLoc)
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6688
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs)
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
Defines the clang::Preprocessor interface.
DeclContext * getDeclContext()
Definition: DeclBase.h:434
ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens)
Definition: SemaCast.cpp:255
static bool IsOverloaded(const UnresolvedSetImpl &Functions)
Represents a C++ template name within the type system.
Definition: TemplateName.h:178
decls_iterator decls_begin() const
Definition: ExprCXX.h:2893
bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:7494
static bool isValidCoroutineContext(Sema &S, SourceLocation Loc, StringRef Keyword)
QualType getType() const
Definition: Expr.h:128
bool buildStatements()
Build the coroutine body statements, including the "promise dependent" statements when the promise ty...
static FunctionScopeInfo * checkCoroutineContext(Sema &S, SourceLocation Loc, StringRef Keyword, bool IsImplicit=false)
Check that this is a context in which a coroutine suspension can appear.
ReturnStmt - This represents a return, optionally of an expression: return; return 4;...
Definition: Stmt.h:1588
static Expr * buildBuiltinCall(Sema &S, SourceLocation Loc, Builtin::ID Id, MultiExprArg CallArgs)
bool isInvalid() const
Definition: Ownership.h:170
bool isUsable() const
Definition: Ownership.h:171
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1400
The result type of a method or function.
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:706
VarDecl * CoroutinePromise
The promise object for this coroutine, if any.
Definition: ScopeInfo.h:192
ExprResult ActOnFinishFullExpr(Expr *Expr)
Definition: Sema.h:5317
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:412
static CoroutineBodyStmt * Create(const ASTContext &C, CtorArgs const &Args)
Definition: StmtCXX.cpp:86
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class...
Definition: Expr.h:875
Kind
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:157
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
Encodes a location in the source.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
QualType getReturnType() const
Definition: Type.h:3469
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
Definition: SemaDecl.cpp:11919
FunctionDecl * FindUsualDeallocationFunction(SourceLocation StartLoc, bool CanProvideSize, bool Overaligned, DeclarationName Name)
IdentifierTable & getIdentifierTable()
Definition: Preprocessor.h:832
static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType, SourceLocation Loc)
Look up the std::experimental::coroutine_handle<PromiseType>.
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2051
Only look for allocation functions in the scope of the allocated class.
Definition: Sema.h:5197
ArrayRef< Stmt * > ParamMoves
Definition: StmtCXX.h:374
Describes the kind of initialization being performed, along with location information for tokens rela...
SourceLocation FirstCoroutineStmtLoc
First coroutine statement in the current function.
Definition: ScopeInfo.h:164
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
Definition: SemaType.cpp:1925
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1373
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:592
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:216
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition: Type.h:6413
Represents a template argument.
Definition: TemplateBase.h:51
Dataflow Directional Tag Classes.
bool isValid() const
Return true if this is a valid SourceLocation object.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1272
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return 0.
Definition: Expr.cpp:1251
void clearDelayedTypo(TypoExpr *TE)
Clears the state of the given TypoExpr.
CoroutineStmtBuilder(Sema &S, FunctionDecl &FD, sema::FunctionScopeInfo &Fn, Stmt *Body)
Construct a CoroutineStmtBuilder and initialize the promise statement and initial/final suspends from...
Represents a &#39;co_yield&#39; expression.
Definition: ExprCXX.h:4771
DeclarationName - The name of a declaration.
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:506
bool isBooleanType() const
Definition: Type.h:6552
A set of unresolved declarations.
ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, UnresolvedLookupExpr *Lookup)
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition: Expr.cpp:1342
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:10902
static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType, SourceLocation Loc)
SourceLocation FirstReturnLoc
First &#39;return&#39; statement in the current function.
Definition: ScopeInfo.h:167
Decl * getCalleeDecl()
Definition: Expr.cpp:1255
StmtResult ActOnFinishFullStmt(Stmt *Stmt)
const UnresolvedSetImpl & asUnresolvedSet() const
Definition: Lookup.h:320
Represents the body of a coroutine.
Definition: StmtCXX.h:331
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:450
ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E)
Look for allocation functions in both the global scope and in the scope of the allocated class...
Definition: Sema.h:5200
CanQualType DependentTy
Definition: ASTContext.h:1052
Represents a &#39;co_await&#39; expression.
Definition: ExprCXX.h:4680
static ExprResult buildOperatorCoawaitLookupExpr(Sema &SemaRef, Scope *S, SourceLocation Loc)
ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E)
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr)
Definition: SemaExpr.cpp:12590
ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E)
bool isClassType() const
Definition: Type.cpp:429
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
Call-style initialization (C++98)
Definition: Decl.h:828
ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const VarDecl *NRVOCandidate, QualType ResultType, Expr *Value, bool AllowNRVO=true)
Perform the initialization of a potentially-movable value, which is the result of return value...
Definition: SemaStmt.cpp:3019
ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:1641
Describes the sequence of initializations required to initialize a given object or reference with a s...
Only look for allocation functions in the global scope.
Definition: Sema.h:5194
Represents a C++ struct/union/class.
Definition: DeclCXX.h:308
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type...
bool isVoidType() const
Definition: Type.h:6439
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:1331
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:566
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:331
Declaration of a class template.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:268
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2406
ExprResult ExprError()
Definition: Ownership.h:283
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2046
bool hasInvalidCoroutineSuspends() const
Definition: ScopeInfo.h:459
void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body)
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:572
ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, bool IsImplicit=false)
bool buildDependentStatements()
Build the coroutine body statements that require a non-dependent promise type in order to construct...
QualType getType() const
Definition: Decl.h:651
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:114
A trivial tuple used to represent a source range.
ASTContext & Context
Definition: Sema.h:319
This represents a decl that may have a name.
Definition: Decl.h:248
No keyword precedes the qualified type name.
Definition: Type.h:4987
Describes an entity that is being initialized.
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition: Sema.h:3028
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:513
decls_iterator decls_end() const
Definition: ExprCXX.h:2894
static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD, SourceLocation Loc, bool &Res)
SourceLocation getLocation() const
Definition: DeclBase.h:425
LangStandard::Kind Std
VarDecl * buildCoroutinePromise(SourceLocation Loc)
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
getCXXOperatorName - Get the name of the overloadable C++ operator corresponding to Op...
static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn)