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