clang 19.0.0git
SemaLambda.cpp
Go to the documentation of this file.
1//===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ lambda expressions.
10//
11//===----------------------------------------------------------------------===//
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTLambda.h"
15#include "clang/AST/ExprCXX.h"
17#include "clang/Sema/DeclSpec.h"
19#include "clang/Sema/Lookup.h"
20#include "clang/Sema/Scope.h"
22#include "clang/Sema/SemaCUDA.h"
25#include "clang/Sema/Template.h"
26#include "llvm/ADT/STLExtras.h"
27#include <optional>
28using namespace clang;
29using namespace sema;
30
31/// Examines the FunctionScopeInfo stack to determine the nearest
32/// enclosing lambda (to the current lambda) that is 'capture-ready' for
33/// the variable referenced in the current lambda (i.e. \p VarToCapture).
34/// If successful, returns the index into Sema's FunctionScopeInfo stack
35/// of the capture-ready lambda's LambdaScopeInfo.
36///
37/// Climbs down the stack of lambdas (deepest nested lambda - i.e. current
38/// lambda - is on top) to determine the index of the nearest enclosing/outer
39/// lambda that is ready to capture the \p VarToCapture being referenced in
40/// the current lambda.
41/// As we climb down the stack, we want the index of the first such lambda -
42/// that is the lambda with the highest index that is 'capture-ready'.
43///
44/// A lambda 'L' is capture-ready for 'V' (var or this) if:
45/// - its enclosing context is non-dependent
46/// - and if the chain of lambdas between L and the lambda in which
47/// V is potentially used (i.e. the lambda at the top of the scope info
48/// stack), can all capture or have already captured V.
49/// If \p VarToCapture is 'null' then we are trying to capture 'this'.
50///
51/// Note that a lambda that is deemed 'capture-ready' still needs to be checked
52/// for whether it is 'capture-capable' (see
53/// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly
54/// capture.
55///
56/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
57/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
58/// is at the top of the stack and has the highest index.
59/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
60///
61/// \returns An std::optional<unsigned> Index that if evaluates to 'true'
62/// contains the index (into Sema's FunctionScopeInfo stack) of the innermost
63/// lambda which is capture-ready. If the return value evaluates to 'false'
64/// then no lambda is capture-ready for \p VarToCapture.
65
66static inline std::optional<unsigned>
69 ValueDecl *VarToCapture) {
70 // Label failure to capture.
71 const std::optional<unsigned> NoLambdaIsCaptureReady;
72
73 // Ignore all inner captured regions.
74 unsigned CurScopeIndex = FunctionScopes.size() - 1;
75 while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>(
76 FunctionScopes[CurScopeIndex]))
77 --CurScopeIndex;
78 assert(
79 isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) &&
80 "The function on the top of sema's function-info stack must be a lambda");
81
82 // If VarToCapture is null, we are attempting to capture 'this'.
83 const bool IsCapturingThis = !VarToCapture;
84 const bool IsCapturingVariable = !IsCapturingThis;
85
86 // Start with the current lambda at the top of the stack (highest index).
87 DeclContext *EnclosingDC =
88 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
89
90 do {
92 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
93 // IF we have climbed down to an intervening enclosing lambda that contains
94 // the variable declaration - it obviously can/must not capture the
95 // variable.
96 // Since its enclosing DC is dependent, all the lambdas between it and the
97 // innermost nested lambda are dependent (otherwise we wouldn't have
98 // arrived here) - so we don't yet have a lambda that can capture the
99 // variable.
100 if (IsCapturingVariable &&
101 VarToCapture->getDeclContext()->Equals(EnclosingDC))
102 return NoLambdaIsCaptureReady;
103
104 // For an enclosing lambda to be capture ready for an entity, all
105 // intervening lambda's have to be able to capture that entity. If even
106 // one of the intervening lambda's is not capable of capturing the entity
107 // then no enclosing lambda can ever capture that entity.
108 // For e.g.
109 // const int x = 10;
110 // [=](auto a) { #1
111 // [](auto b) { #2 <-- an intervening lambda that can never capture 'x'
112 // [=](auto c) { #3
113 // f(x, c); <-- can not lead to x's speculative capture by #1 or #2
114 // }; }; };
115 // If they do not have a default implicit capture, check to see
116 // if the entity has already been explicitly captured.
117 // If even a single dependent enclosing lambda lacks the capability
118 // to ever capture this variable, there is no further enclosing
119 // non-dependent lambda that can capture this variable.
120 if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {
121 if (IsCapturingVariable && !LSI->isCaptured(VarToCapture))
122 return NoLambdaIsCaptureReady;
123 if (IsCapturingThis && !LSI->isCXXThisCaptured())
124 return NoLambdaIsCaptureReady;
125 }
126 EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);
127
128 assert(CurScopeIndex);
129 --CurScopeIndex;
130 } while (!EnclosingDC->isTranslationUnit() &&
131 EnclosingDC->isDependentContext() &&
132 isLambdaCallOperator(EnclosingDC));
133
134 assert(CurScopeIndex < (FunctionScopes.size() - 1));
135 // If the enclosingDC is not dependent, then the immediately nested lambda
136 // (one index above) is capture-ready.
137 if (!EnclosingDC->isDependentContext())
138 return CurScopeIndex + 1;
139 return NoLambdaIsCaptureReady;
140}
141
142/// Examines the FunctionScopeInfo stack to determine the nearest
143/// enclosing lambda (to the current lambda) that is 'capture-capable' for
144/// the variable referenced in the current lambda (i.e. \p VarToCapture).
145/// If successful, returns the index into Sema's FunctionScopeInfo stack
146/// of the capture-capable lambda's LambdaScopeInfo.
147///
148/// Given the current stack of lambdas being processed by Sema and
149/// the variable of interest, to identify the nearest enclosing lambda (to the
150/// current lambda at the top of the stack) that can truly capture
151/// a variable, it has to have the following two properties:
152/// a) 'capture-ready' - be the innermost lambda that is 'capture-ready':
153/// - climb down the stack (i.e. starting from the innermost and examining
154/// each outer lambda step by step) checking if each enclosing
155/// lambda can either implicitly or explicitly capture the variable.
156/// Record the first such lambda that is enclosed in a non-dependent
157/// context. If no such lambda currently exists return failure.
158/// b) 'capture-capable' - make sure the 'capture-ready' lambda can truly
159/// capture the variable by checking all its enclosing lambdas:
160/// - check if all outer lambdas enclosing the 'capture-ready' lambda
161/// identified above in 'a' can also capture the variable (this is done
162/// via tryCaptureVariable for variables and CheckCXXThisCapture for
163/// 'this' by passing in the index of the Lambda identified in step 'a')
164///
165/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
166/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
167/// is at the top of the stack.
168///
169/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
170///
171///
172/// \returns An std::optional<unsigned> Index that if evaluates to 'true'
173/// contains the index (into Sema's FunctionScopeInfo stack) of the innermost
174/// lambda which is capture-capable. If the return value evaluates to 'false'
175/// then no lambda is capture-capable for \p VarToCapture.
176
177std::optional<unsigned>
180 ValueDecl *VarToCapture, Sema &S) {
181
182 const std::optional<unsigned> NoLambdaIsCaptureCapable;
183
184 const std::optional<unsigned> OptionalStackIndex =
186 VarToCapture);
187 if (!OptionalStackIndex)
188 return NoLambdaIsCaptureCapable;
189
190 const unsigned IndexOfCaptureReadyLambda = *OptionalStackIndex;
191 assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||
192 S.getCurGenericLambda()) &&
193 "The capture ready lambda for a potential capture can only be the "
194 "current lambda if it is a generic lambda");
195
196 const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
197 cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);
198
199 // If VarToCapture is null, we are attempting to capture 'this'
200 const bool IsCapturingThis = !VarToCapture;
201 const bool IsCapturingVariable = !IsCapturingThis;
202
203 if (IsCapturingVariable) {
204 // Check if the capture-ready lambda can truly capture the variable, by
205 // checking whether all enclosing lambdas of the capture-ready lambda allow
206 // the capture - i.e. make sure it is capture-capable.
207 QualType CaptureType, DeclRefType;
208 const bool CanCaptureVariable =
209 !S.tryCaptureVariable(VarToCapture,
210 /*ExprVarIsUsedInLoc*/ SourceLocation(),
212 /*EllipsisLoc*/ SourceLocation(),
213 /*BuildAndDiagnose*/ false, CaptureType,
214 DeclRefType, &IndexOfCaptureReadyLambda);
215 if (!CanCaptureVariable)
216 return NoLambdaIsCaptureCapable;
217 } else {
218 // Check if the capture-ready lambda can truly capture 'this' by checking
219 // whether all enclosing lambdas of the capture-ready lambda can capture
220 // 'this'.
221 const bool CanCaptureThis =
223 CaptureReadyLambdaLSI->PotentialThisCaptureLocation,
224 /*Explicit*/ false, /*BuildAndDiagnose*/ false,
225 &IndexOfCaptureReadyLambda);
226 if (!CanCaptureThis)
227 return NoLambdaIsCaptureCapable;
228 }
229 return IndexOfCaptureReadyLambda;
230}
231
232static inline TemplateParameterList *
234 if (!LSI->GLTemplateParameterList && !LSI->TemplateParams.empty()) {
235 LSI->GLTemplateParameterList = TemplateParameterList::Create(
236 SemaRef.Context,
237 /*Template kw loc*/ SourceLocation(),
238 /*L angle loc*/ LSI->ExplicitTemplateParamsRange.getBegin(),
239 LSI->TemplateParams,
240 /*R angle loc*/LSI->ExplicitTemplateParamsRange.getEnd(),
241 LSI->RequiresClause.get());
242 }
243 return LSI->GLTemplateParameterList;
244}
245
248 unsigned LambdaDependencyKind,
249 LambdaCaptureDefault CaptureDefault) {
251 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
252 DC = DC->getParent();
253
254 bool IsGenericLambda =
256 // Start constructing the lambda class.
258 Context, DC, Info, IntroducerRange.getBegin(), LambdaDependencyKind,
259 IsGenericLambda, CaptureDefault);
260 DC->addDecl(Class);
261
262 return Class;
263}
264
265/// Determine whether the given context is or is enclosed in an inline
266/// function.
267static bool isInInlineFunction(const DeclContext *DC) {
268 while (!DC->isFileContext()) {
269 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
270 if (FD->isInlined())
271 return true;
272
273 DC = DC->getLexicalParent();
274 }
275
276 return false;
277}
278
279std::tuple<MangleNumberingContext *, Decl *>
281 // Compute the context for allocating mangling numbers in the current
282 // expression, if the ABI requires them.
283 Decl *ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
284
285 enum ContextKind {
286 Normal,
288 DataMember,
289 InlineVariable,
290 TemplatedVariable,
291 Concept
292 } Kind = Normal;
293
294 bool IsInNonspecializedTemplate =
296
297 // Default arguments of member function parameters that appear in a class
298 // definition, as well as the initializers of data members, receive special
299 // treatment. Identify them.
300 if (ManglingContextDecl) {
301 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
302 if (const DeclContext *LexicalDC
303 = Param->getDeclContext()->getLexicalParent())
304 if (LexicalDC->isRecord())
305 Kind = DefaultArgument;
306 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
307 if (Var->getMostRecentDecl()->isInline())
308 Kind = InlineVariable;
309 else if (Var->getDeclContext()->isRecord() && IsInNonspecializedTemplate)
310 Kind = TemplatedVariable;
311 else if (Var->getDescribedVarTemplate())
312 Kind = TemplatedVariable;
313 else if (auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
314 if (!VTS->isExplicitSpecialization())
315 Kind = TemplatedVariable;
316 }
317 } else if (isa<FieldDecl>(ManglingContextDecl)) {
318 Kind = DataMember;
319 } else if (isa<ImplicitConceptSpecializationDecl>(ManglingContextDecl)) {
320 Kind = Concept;
321 }
322 }
323
324 // Itanium ABI [5.1.7]:
325 // In the following contexts [...] the one-definition rule requires closure
326 // types in different translation units to "correspond":
327 switch (Kind) {
328 case Normal: {
329 // -- the bodies of inline or templated functions
330 if ((IsInNonspecializedTemplate &&
331 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
333 while (auto *CD = dyn_cast<CapturedDecl>(DC))
334 DC = CD->getParent();
335 return std::make_tuple(&Context.getManglingNumberContext(DC), nullptr);
336 }
337
338 return std::make_tuple(nullptr, nullptr);
339 }
340
341 case Concept:
342 // Concept definitions aren't code generated and thus aren't mangled,
343 // however the ManglingContextDecl is important for the purposes of
344 // re-forming the template argument list of the lambda for constraint
345 // evaluation.
346 case DataMember:
347 // -- default member initializers
348 case DefaultArgument:
349 // -- default arguments appearing in class definitions
350 case InlineVariable:
351 case TemplatedVariable:
352 // -- the initializers of inline or templated variables
353 return std::make_tuple(
355 ManglingContextDecl),
356 ManglingContextDecl);
357 }
358
359 llvm_unreachable("unexpected context");
360}
361
362static QualType
364 TemplateParameterList *TemplateParams,
365 TypeSourceInfo *MethodTypeInfo) {
366 assert(MethodTypeInfo && "expected a non null type");
367
368 QualType MethodType = MethodTypeInfo->getType();
369 // If a lambda appears in a dependent context or is a generic lambda (has
370 // template parameters) and has an 'auto' return type, deduce it to a
371 // dependent type.
372 if (Class->isDependentContext() || TemplateParams) {
373 const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
375 if (Result->isUndeducedType()) {
377 MethodType = S.Context.getFunctionType(Result, FPT->getParamTypes(),
378 FPT->getExtProtoInfo());
379 }
380 }
381 return MethodType;
382}
383
384// [C++2b] [expr.prim.lambda.closure] p4
385// Given a lambda with a lambda-capture, the type of the explicit object
386// parameter, if any, of the lambda's function call operator (possibly
387// instantiated from a function call operator template) shall be either:
388// - the closure type,
389// - class type derived from the closure type, or
390// - a reference to a possibly cv-qualified such type.
392 CXXMethodDecl *Method) {
394 return;
395 CXXRecordDecl *RD = Method->getParent();
396 if (Method->getType()->isDependentType())
397 return;
398 if (RD->isCapturelessLambda())
399 return;
400 QualType ExplicitObjectParameterType = Method->getParamDecl(0)
401 ->getType()
405 QualType LambdaType = getASTContext().getRecordType(RD);
406 if (LambdaType == ExplicitObjectParameterType)
407 return;
408 if (IsDerivedFrom(RD->getLocation(), ExplicitObjectParameterType, LambdaType))
409 return;
410 Diag(Method->getParamDecl(0)->getLocation(),
411 diag::err_invalid_explicit_object_type_in_lambda)
412 << ExplicitObjectParameterType;
413}
414
417 std::optional<CXXRecordDecl::LambdaNumbering> NumberingOverride) {
418 if (NumberingOverride) {
419 Class->setLambdaNumbering(*NumberingOverride);
420 return;
421 }
422
423 ContextRAII ManglingContext(*this, Class->getDeclContext());
424
425 auto getMangleNumberingContext =
426 [this](CXXRecordDecl *Class,
427 Decl *ManglingContextDecl) -> MangleNumberingContext * {
428 // Get mangle numbering context if there's any extra decl context.
429 if (ManglingContextDecl)
431 ASTContext::NeedExtraManglingDecl, ManglingContextDecl);
432 // Otherwise, from that lambda's decl context.
433 auto DC = Class->getDeclContext();
434 while (auto *CD = dyn_cast<CapturedDecl>(DC))
435 DC = CD->getParent();
437 };
438
441 std::tie(MCtx, Numbering.ContextDecl) =
442 getCurrentMangleNumberContext(Class->getDeclContext());
443 if (!MCtx && (getLangOpts().CUDA || getLangOpts().SYCLIsDevice ||
444 getLangOpts().SYCLIsHost)) {
445 // Force lambda numbering in CUDA/HIP as we need to name lambdas following
446 // ODR. Both device- and host-compilation need to have a consistent naming
447 // on kernel functions. As lambdas are potential part of these `__global__`
448 // function names, they needs numbering following ODR.
449 // Also force for SYCL, since we need this for the
450 // __builtin_sycl_unique_stable_name implementation, which depends on lambda
451 // mangling.
452 MCtx = getMangleNumberingContext(Class, Numbering.ContextDecl);
453 assert(MCtx && "Retrieving mangle numbering context failed!");
454 Numbering.HasKnownInternalLinkage = true;
455 }
456 if (MCtx) {
457 Numbering.IndexInContext = MCtx->getNextLambdaIndex();
458 Numbering.ManglingNumber = MCtx->getManglingNumber(Method);
459 Numbering.DeviceManglingNumber = MCtx->getDeviceManglingNumber(Method);
460 Class->setLambdaNumbering(Numbering);
461
462 if (auto *Source =
463 dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
464 Source->AssignedLambdaNumbering(Class);
465 }
466}
467
469 CXXMethodDecl *CallOperator,
470 bool ExplicitResultType) {
471 if (ExplicitResultType) {
472 LSI->HasImplicitReturnType = false;
473 LSI->ReturnType = CallOperator->getReturnType();
474 if (!LSI->ReturnType->isDependentType() && !LSI->ReturnType->isVoidType())
475 S.RequireCompleteType(CallOperator->getBeginLoc(), LSI->ReturnType,
476 diag::err_lambda_incomplete_result);
477 } else {
478 LSI->HasImplicitReturnType = true;
479 }
480}
481
483 SourceRange IntroducerRange,
484 LambdaCaptureDefault CaptureDefault,
485 SourceLocation CaptureDefaultLoc,
486 bool ExplicitParams, bool Mutable) {
487 LSI->CallOperator = CallOperator;
488 CXXRecordDecl *LambdaClass = CallOperator->getParent();
489 LSI->Lambda = LambdaClass;
490 if (CaptureDefault == LCD_ByCopy)
491 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
492 else if (CaptureDefault == LCD_ByRef)
493 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
494 LSI->CaptureDefaultLoc = CaptureDefaultLoc;
495 LSI->IntroducerRange = IntroducerRange;
496 LSI->ExplicitParams = ExplicitParams;
497 LSI->Mutable = Mutable;
498}
499
502}
503
505 LambdaIntroducer &Intro, SourceLocation LAngleLoc,
506 ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc,
507 ExprResult RequiresClause) {
509 assert(LSI && "Expected a lambda scope");
510 assert(LSI->NumExplicitTemplateParams == 0 &&
511 "Already acted on explicit template parameters");
512 assert(LSI->TemplateParams.empty() &&
513 "Explicit template parameters should come "
514 "before invented (auto) ones");
515 assert(!TParams.empty() &&
516 "No template parameters to act on");
517 LSI->TemplateParams.append(TParams.begin(), TParams.end());
518 LSI->NumExplicitTemplateParams = TParams.size();
519 LSI->ExplicitTemplateParamsRange = {LAngleLoc, RAngleLoc};
520 LSI->RequiresClause = RequiresClause;
521}
522
523/// If this expression is an enumerator-like expression of some type
524/// T, return the type T; otherwise, return null.
525///
526/// Pointer comparisons on the result here should always work because
527/// it's derived from either the parent of an EnumConstantDecl
528/// (i.e. the definition) or the declaration returned by
529/// EnumType::getDecl() (i.e. the definition).
531 // An expression is an enumerator-like expression of type T if,
532 // ignoring parens and parens-like expressions:
533 E = E->IgnoreParens();
534
535 // - it is an enumerator whose enum type is T or
536 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
537 if (EnumConstantDecl *D
538 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
539 return cast<EnumDecl>(D->getDeclContext());
540 }
541 return nullptr;
542 }
543
544 // - it is a comma expression whose RHS is an enumerator-like
545 // expression of type T or
546 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
547 if (BO->getOpcode() == BO_Comma)
548 return findEnumForBlockReturn(BO->getRHS());
549 return nullptr;
550 }
551
552 // - it is a statement-expression whose value expression is an
553 // enumerator-like expression of type T or
554 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
555 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
556 return findEnumForBlockReturn(last);
557 return nullptr;
558 }
559
560 // - it is a ternary conditional operator (not the GNU ?:
561 // extension) whose second and third operands are
562 // enumerator-like expressions of type T or
563 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
564 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
565 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
566 return ED;
567 return nullptr;
568 }
569
570 // (implicitly:)
571 // - it is an implicit integral conversion applied to an
572 // enumerator-like expression of type T or
573 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
574 // We can sometimes see integral conversions in valid
575 // enumerator-like expressions.
576 if (ICE->getCastKind() == CK_IntegralCast)
577 return findEnumForBlockReturn(ICE->getSubExpr());
578
579 // Otherwise, just rely on the type.
580 }
581
582 // - it is an expression of that formal enum type.
583 if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
584 return ET->getDecl();
585 }
586
587 // Otherwise, nope.
588 return nullptr;
589}
590
591/// Attempt to find a type T for which the returned expression of the
592/// given statement is an enumerator-like expression of that type.
594 if (Expr *retValue = ret->getRetValue())
595 return findEnumForBlockReturn(retValue);
596 return nullptr;
597}
598
599/// Attempt to find a common type T for which all of the returned
600/// expressions in a block are enumerator-like expressions of that
601/// type.
603 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
604
605 // Try to find one for the first return.
607 if (!ED) return nullptr;
608
609 // Check that the rest of the returns have the same enum.
610 for (++i; i != e; ++i) {
611 if (findEnumForBlockReturn(*i) != ED)
612 return nullptr;
613 }
614
615 // Never infer an anonymous enum type.
616 if (!ED->hasNameForLinkage()) return nullptr;
617
618 return ED;
619}
620
621/// Adjust the given return statements so that they formally return
622/// the given type. It should require, at most, an IntegralCast.
624 QualType returnType) {
626 i = returns.begin(), e = returns.end(); i != e; ++i) {
627 ReturnStmt *ret = *i;
628 Expr *retValue = ret->getRetValue();
629 if (S.Context.hasSameType(retValue->getType(), returnType))
630 continue;
631
632 // Right now we only support integral fixup casts.
633 assert(returnType->isIntegralOrUnscopedEnumerationType());
634 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
635
636 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
637
638 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
639 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast, E,
640 /*base path*/ nullptr, VK_PRValue,
642 if (cleanups) {
643 cleanups->setSubExpr(E);
644 } else {
645 ret->setRetValue(E);
646 }
647 }
648}
649
651 assert(CSI.HasImplicitReturnType);
652 // If it was ever a placeholder, it had to been deduced to DependentTy.
653 assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
654 assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) &&
655 "lambda expressions use auto deduction in C++14 onwards");
656
657 // C++ core issue 975:
658 // If a lambda-expression does not include a trailing-return-type,
659 // it is as if the trailing-return-type denotes the following type:
660 // - if there are no return statements in the compound-statement,
661 // or all return statements return either an expression of type
662 // void or no expression or braced-init-list, the type void;
663 // - otherwise, if all return statements return an expression
664 // and the types of the returned expressions after
665 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
666 // array-to-pointer conversion (4.2 [conv.array]), and
667 // function-to-pointer conversion (4.3 [conv.func]) are the
668 // same, that common type;
669 // - otherwise, the program is ill-formed.
670 //
671 // C++ core issue 1048 additionally removes top-level cv-qualifiers
672 // from the types of returned expressions to match the C++14 auto
673 // deduction rules.
674 //
675 // In addition, in blocks in non-C++ modes, if all of the return
676 // statements are enumerator-like expressions of some type T, where
677 // T has a name for linkage, then we infer the return type of the
678 // block to be that type.
679
680 // First case: no return statements, implicit void return type.
681 ASTContext &Ctx = getASTContext();
682 if (CSI.Returns.empty()) {
683 // It's possible there were simply no /valid/ return statements.
684 // In this case, the first one we found may have at least given us a type.
685 if (CSI.ReturnType.isNull())
686 CSI.ReturnType = Ctx.VoidTy;
687 return;
688 }
689
690 // Second case: at least one return statement has dependent type.
691 // Delay type checking until instantiation.
692 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
693 if (CSI.ReturnType->isDependentType())
694 return;
695
696 // Try to apply the enum-fuzz rule.
697 if (!getLangOpts().CPlusPlus) {
698 assert(isa<BlockScopeInfo>(CSI));
700 if (ED) {
703 return;
704 }
705 }
706
707 // Third case: only one return statement. Don't bother doing extra work!
708 if (CSI.Returns.size() == 1)
709 return;
710
711 // General case: many return statements.
712 // Check that they all have compatible return types.
713
714 // We require the return types to strictly match here.
715 // Note that we've already done the required promotions as part of
716 // processing the return statement.
717 for (const ReturnStmt *RS : CSI.Returns) {
718 const Expr *RetE = RS->getRetValue();
719
720 QualType ReturnType =
721 (RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType();
722 if (Context.getCanonicalFunctionResultType(ReturnType) ==
724 // Use the return type with the strictest possible nullability annotation.
725 auto RetTyNullability = ReturnType->getNullability();
726 auto BlockNullability = CSI.ReturnType->getNullability();
727 if (BlockNullability &&
728 (!RetTyNullability ||
729 hasWeakerNullability(*RetTyNullability, *BlockNullability)))
730 CSI.ReturnType = ReturnType;
731 continue;
732 }
733
734 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
735 // TODO: It's possible that the *first* return is the divergent one.
736 Diag(RS->getBeginLoc(),
737 diag::err_typecheck_missing_return_type_incompatible)
738 << ReturnType << CSI.ReturnType << isa<LambdaScopeInfo>(CSI);
739 // Continue iterating so that we keep emitting diagnostics.
740 }
741}
742
744 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
745 std::optional<unsigned> NumExpansions, IdentifierInfo *Id,
746 bool IsDirectInit, Expr *&Init) {
747 // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
748 // deduce against.
749 QualType DeductType = Context.getAutoDeductType();
750 TypeLocBuilder TLB;
751 AutoTypeLoc TL = TLB.push<AutoTypeLoc>(DeductType);
752 TL.setNameLoc(Loc);
753 if (ByRef) {
754 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
755 assert(!DeductType.isNull() && "can't build reference to auto");
756 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
757 }
758 if (EllipsisLoc.isValid()) {
759 if (Init->containsUnexpandedParameterPack()) {
760 Diag(EllipsisLoc, getLangOpts().CPlusPlus20
761 ? diag::warn_cxx17_compat_init_capture_pack
762 : diag::ext_init_capture_pack);
763 DeductType = Context.getPackExpansionType(DeductType, NumExpansions,
764 /*ExpectPackInType=*/false);
765 TLB.push<PackExpansionTypeLoc>(DeductType).setEllipsisLoc(EllipsisLoc);
766 } else {
767 // Just ignore the ellipsis for now and form a non-pack variable. We'll
768 // diagnose this later when we try to capture it.
769 }
770 }
771 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
772
773 // Deduce the type of the init capture.
775 /*VarDecl*/nullptr, DeclarationName(Id), DeductType, TSI,
776 SourceRange(Loc, Loc), IsDirectInit, Init);
777 if (DeducedType.isNull())
778 return QualType();
779
780 // Are we a non-list direct initialization?
781 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
782
783 // Perform initialization analysis and ensure any implicit conversions
784 // (such as lvalue-to-rvalue) are enforced.
785 InitializedEntity Entity =
787 InitializationKind Kind =
788 IsDirectInit
789 ? (CXXDirectInit ? InitializationKind::CreateDirect(
790 Loc, Init->getBeginLoc(), Init->getEndLoc())
792 : InitializationKind::CreateCopy(Loc, Init->getBeginLoc());
793
794 MultiExprArg Args = Init;
795 if (CXXDirectInit)
796 Args =
797 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
798 QualType DclT;
799 InitializationSequence InitSeq(*this, Entity, Kind, Args);
800 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
801
802 if (Result.isInvalid())
803 return QualType();
804
805 Init = Result.getAs<Expr>();
806 return DeducedType;
807}
808
810 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
811 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx) {
812 // FIXME: Retain the TypeSourceInfo from buildLambdaInitCaptureInitialization
813 // rather than reconstructing it here.
814 TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType, Loc);
815 if (auto PETL = TSI->getTypeLoc().getAs<PackExpansionTypeLoc>())
816 PETL.setEllipsisLoc(EllipsisLoc);
817
818 // Create a dummy variable representing the init-capture. This is not actually
819 // used as a variable, and only exists as a way to name and refer to the
820 // init-capture.
821 // FIXME: Pass in separate source locations for '&' and identifier.
822 VarDecl *NewVD = VarDecl::Create(Context, DeclCtx, Loc, Loc, Id,
823 InitCaptureType, TSI, SC_Auto);
824 NewVD->setInitCapture(true);
825 NewVD->setReferenced(true);
826 // FIXME: Pass in a VarDecl::InitializationStyle.
827 NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));
828 NewVD->markUsed(Context);
829 NewVD->setInit(Init);
830 if (NewVD->isParameterPack())
831 getCurLambda()->LocalPacks.push_back(NewVD);
832 return NewVD;
833}
834
835void Sema::addInitCapture(LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef) {
836 assert(Var->isInitCapture() && "init capture flag should be set");
837 LSI->addCapture(Var, /*isBlock=*/false, ByRef,
838 /*isNested=*/false, Var->getLocation(), SourceLocation(),
839 Var->getType(), /*Invalid=*/false);
840}
841
842// Unlike getCurLambda, getCurrentLambdaScopeUnsafe doesn't
843// check that the current lambda is in a consistent or fully constructed state.
845 assert(!S.FunctionScopes.empty());
846 return cast<LambdaScopeInfo>(S.FunctionScopes[S.FunctionScopes.size() - 1]);
847}
848
849static TypeSourceInfo *
851 // C++11 [expr.prim.lambda]p4:
852 // If a lambda-expression does not include a lambda-declarator, it is as
853 // if the lambda-declarator were ().
855 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
856 EPI.HasTrailingReturn = true;
857 EPI.TypeQuals.addConst();
859 if (AS != LangAS::Default)
861
862 // C++1y [expr.prim.lambda]:
863 // The lambda return type is 'auto', which is replaced by the
864 // trailing-return type if provided and/or deduced from 'return'
865 // statements
866 // We don't do this before C++1y, because we don't support deduced return
867 // types there.
868 QualType DefaultTypeForNoTrailingReturn = S.getLangOpts().CPlusPlus14
871 QualType MethodTy = S.Context.getFunctionType(DefaultTypeForNoTrailingReturn,
872 std::nullopt, EPI);
873 return S.Context.getTrivialTypeSourceInfo(MethodTy, Loc);
874}
875
877 Declarator &ParamInfo, Scope *CurScope,
878 SourceLocation Loc,
879 bool &ExplicitResultType) {
880
881 ExplicitResultType = false;
882
883 assert(
884 (ParamInfo.getDeclSpec().getStorageClassSpec() ==
887 "Unexpected storage specifier");
888 bool IsLambdaStatic =
890
891 TypeSourceInfo *MethodTyInfo;
892
893 if (ParamInfo.getNumTypeObjects() == 0) {
894 MethodTyInfo = getDummyLambdaType(S, Loc);
895 } else {
896 // Check explicit parameters
897 S.CheckExplicitObjectLambda(ParamInfo);
898
900
901 bool HasExplicitObjectParameter =
903
904 ExplicitResultType = FTI.hasTrailingReturnType();
905 if (!FTI.hasMutableQualifier() && !IsLambdaStatic &&
906 !HasExplicitObjectParameter)
908
909 if (ExplicitResultType && S.getLangOpts().HLSL) {
910 QualType RetTy = FTI.getTrailingReturnType().get();
911 if (!RetTy.isNull()) {
912 // HLSL does not support specifying an address space on a lambda return
913 // type.
914 LangAS AddressSpace = RetTy.getAddressSpace();
915 if (AddressSpace != LangAS::Default)
917 diag::err_return_value_with_address_space);
918 }
919 }
920
921 MethodTyInfo = S.GetTypeForDeclarator(ParamInfo);
922 assert(MethodTyInfo && "no type from lambda-declarator");
923
924 // Check for unexpanded parameter packs in the method type.
925 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
926 S.DiagnoseUnexpandedParameterPack(Intro.Range.getBegin(), MethodTyInfo,
928 }
929 return MethodTyInfo;
930}
931
934
935 // C++20 [expr.prim.lambda.closure]p3:
936 // The closure type for a lambda-expression has a public inline function
937 // call operator (for a non-generic lambda) or function call operator
938 // template (for a generic lambda) whose parameters and return type are
939 // described by the lambda-expression's parameter-declaration-clause
940 // and trailing-return-type respectively.
941 DeclarationName MethodName =
943 DeclarationNameLoc MethodNameLoc =
947 DeclarationNameInfo(MethodName, IntroducerRange.getBegin(),
948 MethodNameLoc),
949 QualType(), /*Tinfo=*/nullptr, SC_None,
950 getCurFPFeatures().isFPConstrained(),
952 /*TrailingRequiresClause=*/nullptr);
953 Method->setAccess(AS_public);
954 return Method;
955}
956
958 CXXMethodDecl *CallOperator, CXXRecordDecl *Class,
959 TemplateParameterList *TemplateParams) {
960 assert(TemplateParams && "no template parameters");
962 Context, Class, CallOperator->getLocation(), CallOperator->getDeclName(),
963 TemplateParams, CallOperator);
964 TemplateMethod->setAccess(AS_public);
965 CallOperator->setDescribedFunctionTemplate(TemplateMethod);
966}
967
969 CXXMethodDecl *Method, SourceLocation LambdaLoc,
970 SourceLocation CallOperatorLoc, Expr *TrailingRequiresClause,
971 TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind,
973 bool HasExplicitResultType) {
974
976
977 if (TrailingRequiresClause)
978 Method->setTrailingRequiresClause(TrailingRequiresClause);
979
980 TemplateParameterList *TemplateParams =
982
983 DeclContext *DC = Method->getLexicalDeclContext();
984 Method->setLexicalDeclContext(LSI->Lambda);
985 if (TemplateParams) {
986 FunctionTemplateDecl *TemplateMethod =
988 assert(TemplateMethod &&
989 "AddTemplateParametersToLambdaCallOperator should have been called");
990
991 LSI->Lambda->addDecl(TemplateMethod);
992 TemplateMethod->setLexicalDeclContext(DC);
993 } else {
994 LSI->Lambda->addDecl(Method);
995 }
996 LSI->Lambda->setLambdaIsGeneric(TemplateParams);
997 LSI->Lambda->setLambdaTypeInfo(MethodTyInfo);
998
999 Method->setLexicalDeclContext(DC);
1000 Method->setLocation(LambdaLoc);
1001 Method->setInnerLocStart(CallOperatorLoc);
1002 Method->setTypeSourceInfo(MethodTyInfo);
1003 Method->setType(buildTypeForLambdaCallOperator(*this, LSI->Lambda,
1004 TemplateParams, MethodTyInfo));
1005 Method->setConstexprKind(ConstexprKind);
1006 Method->setStorageClass(SC);
1007 if (!Params.empty()) {
1008 CheckParmsForFunctionDef(Params, /*CheckParameterNames=*/false);
1009 Method->setParams(Params);
1010 for (auto P : Method->parameters()) {
1011 assert(P && "null in a parameter list");
1012 P->setOwningFunction(Method);
1013 }
1014 }
1015
1016 buildLambdaScopeReturnType(*this, LSI, Method, HasExplicitResultType);
1017}
1018
1020 Scope *CurrentScope) {
1021
1023 assert(LSI && "LambdaScopeInfo should be on stack!");
1024
1025 if (Intro.Default == LCD_ByCopy)
1026 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
1027 else if (Intro.Default == LCD_ByRef)
1028 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
1029 LSI->CaptureDefaultLoc = Intro.DefaultLoc;
1030 LSI->IntroducerRange = Intro.Range;
1031 LSI->AfterParameterList = false;
1032
1033 assert(LSI->NumExplicitTemplateParams == 0);
1034
1035 // Determine if we're within a context where we know that the lambda will
1036 // be dependent, because there are template parameters in scope.
1037 CXXRecordDecl::LambdaDependencyKind LambdaDependencyKind =
1039 if (LSI->NumExplicitTemplateParams > 0) {
1040 Scope *TemplateParamScope = CurScope->getTemplateParamParent();
1041 assert(TemplateParamScope &&
1042 "Lambda with explicit template param list should establish a "
1043 "template param scope");
1044 assert(TemplateParamScope->getParent());
1045 if (TemplateParamScope->getParent()->getTemplateParamParent() != nullptr)
1046 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
1047 } else if (CurScope->getTemplateParamParent() != nullptr) {
1048 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
1049 }
1050
1052 Intro.Range, /*Info=*/nullptr, LambdaDependencyKind, Intro.Default);
1053 LSI->Lambda = Class;
1054
1056 LSI->CallOperator = Method;
1058
1059 PushDeclContext(CurScope, Method);
1060
1061 bool ContainsUnexpandedParameterPack = false;
1062
1063 // Distinct capture names, for diagnostics.
1064 llvm::DenseMap<IdentifierInfo *, ValueDecl *> CaptureNames;
1065
1066 // Handle explicit captures.
1067 SourceLocation PrevCaptureLoc =
1068 Intro.Default == LCD_None ? Intro.Range.getBegin() : Intro.DefaultLoc;
1069 for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;
1070 PrevCaptureLoc = C->Loc, ++C) {
1071 if (C->Kind == LCK_This || C->Kind == LCK_StarThis) {
1072 if (C->Kind == LCK_StarThis)
1073 Diag(C->Loc, !getLangOpts().CPlusPlus17
1074 ? diag::ext_star_this_lambda_capture_cxx17
1075 : diag::warn_cxx14_compat_star_this_lambda_capture);
1076
1077 // C++11 [expr.prim.lambda]p8:
1078 // An identifier or this shall not appear more than once in a
1079 // lambda-capture.
1080 if (LSI->isCXXThisCaptured()) {
1081 Diag(C->Loc, diag::err_capture_more_than_once)
1082 << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())
1084 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1085 continue;
1086 }
1087
1088 // C++20 [expr.prim.lambda]p8:
1089 // If a lambda-capture includes a capture-default that is =,
1090 // each simple-capture of that lambda-capture shall be of the form
1091 // "&identifier", "this", or "* this". [ Note: The form [&,this] is
1092 // redundant but accepted for compatibility with ISO C++14. --end note ]
1093 if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis)
1094 Diag(C->Loc, !getLangOpts().CPlusPlus20
1095 ? diag::ext_equals_this_lambda_capture_cxx20
1096 : diag::warn_cxx17_compat_equals_this_lambda_capture);
1097
1098 // C++11 [expr.prim.lambda]p12:
1099 // If this is captured by a local lambda expression, its nearest
1100 // enclosing function shall be a non-static member function.
1101 QualType ThisCaptureType = getCurrentThisType();
1102 if (ThisCaptureType.isNull()) {
1103 Diag(C->Loc, diag::err_this_capture) << true;
1104 continue;
1105 }
1106
1107 CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true,
1108 /*FunctionScopeIndexToStopAtPtr*/ nullptr,
1109 C->Kind == LCK_StarThis);
1110 if (!LSI->Captures.empty())
1111 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1112 continue;
1113 }
1114
1115 assert(C->Id && "missing identifier for capture");
1116
1117 if (C->Init.isInvalid())
1118 continue;
1119
1120 ValueDecl *Var = nullptr;
1121 if (C->Init.isUsable()) {
1123 ? diag::warn_cxx11_compat_init_capture
1124 : diag::ext_init_capture);
1125
1126 // If the initializer expression is usable, but the InitCaptureType
1127 // is not, then an error has occurred - so ignore the capture for now.
1128 // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
1129 // FIXME: we should create the init capture variable and mark it invalid
1130 // in this case.
1131 if (C->InitCaptureType.get().isNull())
1132 continue;
1133
1134 if (C->Init.get()->containsUnexpandedParameterPack() &&
1135 !C->InitCaptureType.get()->getAs<PackExpansionType>())
1137
1138 unsigned InitStyle;
1139 switch (C->InitKind) {
1141 llvm_unreachable("not an init-capture?");
1143 InitStyle = VarDecl::CInit;
1144 break;
1146 InitStyle = VarDecl::CallInit;
1147 break;
1149 InitStyle = VarDecl::ListInit;
1150 break;
1151 }
1152 Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
1153 C->EllipsisLoc, C->Id, InitStyle,
1154 C->Init.get(), Method);
1155 assert(Var && "createLambdaInitCaptureVarDecl returned a null VarDecl?");
1156 if (auto *V = dyn_cast<VarDecl>(Var))
1157 CheckShadow(CurrentScope, V);
1158 PushOnScopeChains(Var, CurrentScope, false);
1159 } else {
1160 assert(C->InitKind == LambdaCaptureInitKind::NoInit &&
1161 "init capture has valid but null init?");
1162
1163 // C++11 [expr.prim.lambda]p8:
1164 // If a lambda-capture includes a capture-default that is &, the
1165 // identifiers in the lambda-capture shall not be preceded by &.
1166 // If a lambda-capture includes a capture-default that is =, [...]
1167 // each identifier it contains shall be preceded by &.
1168 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
1169 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
1171 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1172 continue;
1173 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
1174 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
1176 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1177 continue;
1178 }
1179
1180 // C++11 [expr.prim.lambda]p10:
1181 // The identifiers in a capture-list are looked up using the usual
1182 // rules for unqualified name lookup (3.4.1)
1183 DeclarationNameInfo Name(C->Id, C->Loc);
1184 LookupResult R(*this, Name, LookupOrdinaryName);
1185 LookupName(R, CurScope);
1186 if (R.isAmbiguous())
1187 continue;
1188 if (R.empty()) {
1189 // FIXME: Disable corrections that would add qualification?
1190 CXXScopeSpec ScopeSpec;
1191 DeclFilterCCC<VarDecl> Validator{};
1192 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
1193 continue;
1194 }
1195
1196 if (auto *BD = R.getAsSingle<BindingDecl>())
1197 Var = BD;
1198 else
1199 Var = R.getAsSingle<VarDecl>();
1200 if (Var && DiagnoseUseOfDecl(Var, C->Loc))
1201 continue;
1202 }
1203
1204 // C++11 [expr.prim.lambda]p10:
1205 // [...] each such lookup shall find a variable with automatic storage
1206 // duration declared in the reaching scope of the local lambda expression.
1207 // Note that the 'reaching scope' check happens in tryCaptureVariable().
1208 if (!Var) {
1209 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
1210 continue;
1211 }
1212
1213 // C++11 [expr.prim.lambda]p8:
1214 // An identifier or this shall not appear more than once in a
1215 // lambda-capture.
1216 if (auto [It, Inserted] = CaptureNames.insert(std::pair{C->Id, Var});
1217 !Inserted) {
1218 if (C->InitKind == LambdaCaptureInitKind::NoInit &&
1219 !Var->isInitCapture()) {
1220 Diag(C->Loc, diag::err_capture_more_than_once)
1221 << C->Id << It->second->getBeginLoc()
1223 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1224 Var->setInvalidDecl();
1225 } else if (Var && Var->isPlaceholderVar(getLangOpts())) {
1227 } else {
1228 // Previous capture captured something different (one or both was
1229 // an init-capture): no fixit.
1230 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
1231 continue;
1232 }
1233 }
1234
1235 // Ignore invalid decls; they'll just confuse the code later.
1236 if (Var->isInvalidDecl())
1237 continue;
1238
1239 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
1240
1241 if (!Underlying->hasLocalStorage()) {
1242 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
1243 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
1244 continue;
1245 }
1246
1247 // C++11 [expr.prim.lambda]p23:
1248 // A capture followed by an ellipsis is a pack expansion (14.5.3).
1249 SourceLocation EllipsisLoc;
1250 if (C->EllipsisLoc.isValid()) {
1251 if (Var->isParameterPack()) {
1252 EllipsisLoc = C->EllipsisLoc;
1253 } else {
1254 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1255 << (C->Init.isUsable() ? C->Init.get()->getSourceRange()
1256 : SourceRange(C->Loc));
1257
1258 // Just ignore the ellipsis.
1259 }
1260 } else if (Var->isParameterPack()) {
1261 ContainsUnexpandedParameterPack = true;
1262 }
1263
1264 if (C->Init.isUsable()) {
1265 addInitCapture(LSI, cast<VarDecl>(Var), C->Kind == LCK_ByRef);
1266 PushOnScopeChains(Var, CurScope, false);
1267 } else {
1270 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
1271 }
1272 if (!LSI->Captures.empty())
1273 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1274 }
1276 LSI->ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
1278}
1279
1281 SourceLocation MutableLoc) {
1282
1284 LSI->Mutable = MutableLoc.isValid();
1285 ContextRAII Context(*this, LSI->CallOperator, /*NewThisContext*/ false);
1286
1287 // C++11 [expr.prim.lambda]p9:
1288 // A lambda-expression whose smallest enclosing scope is a block scope is a
1289 // local lambda expression; any other lambda expression shall not have a
1290 // capture-default or simple-capture in its lambda-introducer.
1291 //
1292 // For simple-captures, this is covered by the check below that any named
1293 // entity is a variable that can be captured.
1294 //
1295 // For DR1632, we also allow a capture-default in any context where we can
1296 // odr-use 'this' (in particular, in a default initializer for a non-static
1297 // data member).
1298 if (Intro.Default != LCD_None &&
1299 !LSI->Lambda->getParent()->isFunctionOrMethod() &&
1300 (getCurrentThisType().isNull() ||
1301 CheckCXXThisCapture(SourceLocation(), /*Explicit=*/true,
1302 /*BuildAndDiagnose=*/false)))
1303 Diag(Intro.DefaultLoc, diag::err_capture_default_non_local);
1304}
1305
1309 PushDeclContext(LambdaScope, LSI->CallOperator);
1310
1311 for (const DeclaratorChunk::ParamInfo &P : Params) {
1312 auto *Param = cast<ParmVarDecl>(P.Param);
1313 Param->setOwningFunction(LSI->CallOperator);
1314 if (Param->getIdentifier())
1315 PushOnScopeChains(Param, LambdaScope, false);
1316 }
1317
1318 // After the parameter list, we may parse a noexcept/requires/trailing return
1319 // type which need to know whether the call operator constiture a dependent
1320 // context, so we need to setup the FunctionTemplateDecl of generic lambdas
1321 // now.
1322 TemplateParameterList *TemplateParams =
1324 if (TemplateParams) {
1326 TemplateParams);
1327 LSI->Lambda->setLambdaIsGeneric(true);
1328 }
1329 LSI->AfterParameterList = true;
1330}
1331
1333 Declarator &ParamInfo,
1334 const DeclSpec &DS) {
1335
1338
1340 bool ExplicitResultType;
1341
1342 SourceLocation TypeLoc, CallOperatorLoc;
1343 if (ParamInfo.getNumTypeObjects() == 0) {
1344 CallOperatorLoc = TypeLoc = Intro.Range.getEnd();
1345 } else {
1346 unsigned Index;
1347 ParamInfo.isFunctionDeclarator(Index);
1348 const auto &Object = ParamInfo.getTypeObject(Index);
1349 TypeLoc =
1350 Object.Loc.isValid() ? Object.Loc : ParamInfo.getSourceRange().getEnd();
1351 CallOperatorLoc = ParamInfo.getSourceRange().getEnd();
1352 }
1353
1354 CXXRecordDecl *Class = LSI->Lambda;
1355 CXXMethodDecl *Method = LSI->CallOperator;
1356
1357 TypeSourceInfo *MethodTyInfo = getLambdaType(
1358 *this, Intro, ParamInfo, getCurScope(), TypeLoc, ExplicitResultType);
1359
1360 LSI->ExplicitParams = ParamInfo.getNumTypeObjects() != 0;
1361
1362 if (ParamInfo.isFunctionDeclarator() != 0 &&
1364 const auto &FTI = ParamInfo.getFunctionTypeInfo();
1365 Params.reserve(Params.size());
1366 for (unsigned I = 0; I < FTI.NumParams; ++I) {
1367 auto *Param = cast<ParmVarDecl>(FTI.Params[I].Param);
1368 Param->setScopeInfo(0, Params.size());
1369 Params.push_back(Param);
1370 }
1371 }
1372
1373 bool IsLambdaStatic =
1375
1377 Method, Intro.Range.getBegin(), CallOperatorLoc,
1378 ParamInfo.getTrailingRequiresClause(), MethodTyInfo,
1379 ParamInfo.getDeclSpec().getConstexprSpecifier(),
1380 IsLambdaStatic ? SC_Static : SC_None, Params, ExplicitResultType);
1381
1383
1384 // This represents the function body for the lambda function, check if we
1385 // have to apply optnone due to a pragma.
1386 AddRangeBasedOptnone(Method);
1387
1388 // code_seg attribute on lambda apply to the method.
1390 Method, /*IsDefinition=*/true))
1391 Method->addAttr(A);
1392
1393 // Attributes on the lambda apply to the method.
1394 ProcessDeclAttributes(CurScope, Method, ParamInfo);
1395
1396 // CUDA lambdas get implicit host and device attributes.
1397 if (getLangOpts().CUDA)
1398 CUDA().SetLambdaAttrs(Method);
1399
1400 // OpenMP lambdas might get assumumption attributes.
1401 if (LangOpts.OpenMP)
1403
1405
1406 for (auto &&C : LSI->Captures) {
1407 if (!C.isVariableCapture())
1408 continue;
1409 ValueDecl *Var = C.getVariable();
1410 if (Var && Var->isInitCapture()) {
1411 PushOnScopeChains(Var, CurScope, false);
1412 }
1413 }
1414
1415 auto CheckRedefinition = [&](ParmVarDecl *Param) {
1416 for (const auto &Capture : Intro.Captures) {
1417 if (Capture.Id == Param->getIdentifier()) {
1418 Diag(Param->getLocation(), diag::err_parameter_shadow_capture);
1419 Diag(Capture.Loc, diag::note_var_explicitly_captured_here)
1420 << Capture.Id << true;
1421 return false;
1422 }
1423 }
1424 return true;
1425 };
1426
1427 for (ParmVarDecl *P : Params) {
1428 if (!P->getIdentifier())
1429 continue;
1430 if (CheckRedefinition(P))
1431 CheckShadow(CurScope, P);
1432 PushOnScopeChains(P, CurScope);
1433 }
1434
1435 // C++23 [expr.prim.lambda.capture]p5:
1436 // If an identifier in a capture appears as the declarator-id of a parameter
1437 // of the lambda-declarator's parameter-declaration-clause or as the name of a
1438 // template parameter of the lambda-expression's template-parameter-list, the
1439 // program is ill-formed.
1440 TemplateParameterList *TemplateParams =
1442 if (TemplateParams) {
1443 for (const auto *TP : TemplateParams->asArray()) {
1444 if (!TP->getIdentifier())
1445 continue;
1446 for (const auto &Capture : Intro.Captures) {
1447 if (Capture.Id == TP->getIdentifier()) {
1448 Diag(Capture.Loc, diag::err_template_param_shadow) << Capture.Id;
1450 }
1451 }
1452 }
1453 }
1454
1455 // C++20: dcl.decl.general p4:
1456 // The optional requires-clause ([temp.pre]) in an init-declarator or
1457 // member-declarator shall be present only if the declarator declares a
1458 // templated function ([dcl.fct]).
1459 if (Expr *TRC = Method->getTrailingRequiresClause()) {
1460 // [temp.pre]/8:
1461 // An entity is templated if it is
1462 // - a template,
1463 // - an entity defined ([basic.def]) or created ([class.temporary]) in a
1464 // templated entity,
1465 // - a member of a templated entity,
1466 // - an enumerator for an enumeration that is a templated entity, or
1467 // - the closure type of a lambda-expression ([expr.prim.lambda.closure])
1468 // appearing in the declaration of a templated entity. [Note 6: A local
1469 // class, a local or block variable, or a friend function defined in a
1470 // templated entity is a templated entity. — end note]
1471 //
1472 // A templated function is a function template or a function that is
1473 // templated. A templated class is a class template or a class that is
1474 // templated. A templated variable is a variable template or a variable
1475 // that is templated.
1476
1477 // Note: we only have to check if this is defined in a template entity, OR
1478 // if we are a template, since the rest don't apply. The requires clause
1479 // applies to the call operator, which we already know is a member function,
1480 // AND defined.
1481 if (!Method->getDescribedFunctionTemplate() && !Method->isTemplated()) {
1482 Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
1483 }
1484 }
1485
1486 // Enter a new evaluation context to insulate the lambda from any
1487 // cleanups from the enclosing full-expression.
1492 ExprEvalContexts.back().InImmediateFunctionContext =
1493 LSI->CallOperator->isConsteval();
1494 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
1495 getLangOpts().CPlusPlus20 && LSI->CallOperator->isImmediateEscalating();
1496}
1497
1499 bool IsInstantiation) {
1500 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(FunctionScopes.back());
1501
1502 // Leave the expression-evaluation context.
1505
1506 // Leave the context of the lambda.
1507 if (!IsInstantiation)
1509
1510 // Finalize the lambda.
1511 CXXRecordDecl *Class = LSI->Lambda;
1512 Class->setInvalidDecl();
1513 SmallVector<Decl*, 4> Fields(Class->fields());
1514 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
1516 CheckCompletedCXXClass(nullptr, Class);
1517
1519}
1520
1521template <typename Func>
1523 Sema &S, const FunctionProtoType &CallOpProto, Func F) {
1525 CallOpProto.isVariadic(), /*IsCXXMethod=*/false);
1527 CallOpProto.isVariadic(), /*IsCXXMethod=*/true);
1528 CallingConv CallOpCC = CallOpProto.getCallConv();
1529
1530 /// Implement emitting a version of the operator for many of the calling
1531 /// conventions for MSVC, as described here:
1532 /// https://devblogs.microsoft.com/oldnewthing/20150220-00/?p=44623.
1533 /// Experimentally, we determined that cdecl, stdcall, fastcall, and
1534 /// vectorcall are generated by MSVC when it is supported by the target.
1535 /// Additionally, we are ensuring that the default-free/default-member and
1536 /// call-operator calling convention are generated as well.
1537 /// NOTE: We intentionally generate a 'thiscall' on Win32 implicitly from the
1538 /// 'member default', despite MSVC not doing so. We do this in order to ensure
1539 /// that someone who intentionally places 'thiscall' on the lambda call
1540 /// operator will still get that overload, since we don't have the a way of
1541 /// detecting the attribute by the time we get here.
1542 if (S.getLangOpts().MSVCCompat) {
1543 CallingConv Convs[] = {
1545 DefaultFree, DefaultMember, CallOpCC};
1546 llvm::sort(Convs);
1547 llvm::iterator_range<CallingConv *> Range(
1548 std::begin(Convs), std::unique(std::begin(Convs), std::end(Convs)));
1549 const TargetInfo &TI = S.getASTContext().getTargetInfo();
1550
1551 for (CallingConv C : Range) {
1553 F(C);
1554 }
1555 return;
1556 }
1557
1558 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree) {
1559 F(DefaultFree);
1560 F(DefaultMember);
1561 } else {
1562 F(CallOpCC);
1563 }
1564}
1565
1566// Returns the 'standard' calling convention to be used for the lambda
1567// conversion function, that is, the 'free' function calling convention unless
1568// it is overridden by a non-default calling convention attribute.
1569static CallingConv
1571 const FunctionProtoType *CallOpProto) {
1573 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
1575 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
1576 CallingConv CallOpCC = CallOpProto->getCallConv();
1577
1578 // If the call-operator hasn't been changed, return both the 'free' and
1579 // 'member' function calling convention.
1580 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree)
1581 return DefaultFree;
1582 return CallOpCC;
1583}
1584
1586 const FunctionProtoType *CallOpProto, CallingConv CC) {
1587 const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
1588 CallOpProto->getExtProtoInfo();
1589 FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
1590 InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
1591 InvokerExtInfo.TypeQuals = Qualifiers();
1592 assert(InvokerExtInfo.RefQualifier == RQ_None &&
1593 "Lambda's call operator should not have a reference qualifier");
1594 return Context.getFunctionType(CallOpProto->getReturnType(),
1595 CallOpProto->getParamTypes(), InvokerExtInfo);
1596}
1597
1598/// Add a lambda's conversion to function pointer, as described in
1599/// C++11 [expr.prim.lambda]p6.
1600static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange,
1602 CXXMethodDecl *CallOperator,
1603 QualType InvokerFunctionTy) {
1604 // This conversion is explicitly disabled if the lambda's function has
1605 // pass_object_size attributes on any of its parameters.
1606 auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) {
1607 return P->hasAttr<PassObjectSizeAttr>();
1608 };
1609 if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr))
1610 return;
1611
1612 // Add the conversion to function pointer.
1613 QualType PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
1614
1615 // Create the type of the conversion function.
1618 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1619 // The conversion function is always const and noexcept.
1620 ConvExtInfo.TypeQuals = Qualifiers();
1621 ConvExtInfo.TypeQuals.addConst();
1622 ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept;
1623 QualType ConvTy =
1624 S.Context.getFunctionType(PtrToFunctionTy, std::nullopt, ConvExtInfo);
1625
1626 SourceLocation Loc = IntroducerRange.getBegin();
1627 DeclarationName ConversionName
1629 S.Context.getCanonicalType(PtrToFunctionTy));
1630 // Construct a TypeSourceInfo for the conversion function, and wire
1631 // all the parameters appropriately for the FunctionProtoTypeLoc
1632 // so that everything works during transformation/instantiation of
1633 // generic lambdas.
1634 // The main reason for wiring up the parameters of the conversion
1635 // function with that of the call operator is so that constructs
1636 // like the following work:
1637 // auto L = [](auto b) { <-- 1
1638 // return [](auto a) -> decltype(a) { <-- 2
1639 // return a;
1640 // };
1641 // };
1642 // int (*fp)(int) = L(5);
1643 // Because the trailing return type can contain DeclRefExprs that refer
1644 // to the original call operator's variables, we hijack the call
1645 // operators ParmVarDecls below.
1646 TypeSourceInfo *ConvNamePtrToFunctionTSI =
1647 S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
1648 DeclarationNameLoc ConvNameLoc =
1649 DeclarationNameLoc::makeNamedTypeLoc(ConvNamePtrToFunctionTSI);
1650
1651 // The conversion function is a conversion to a pointer-to-function.
1652 TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
1653 FunctionProtoTypeLoc ConvTL =
1655 // Get the result of the conversion function which is a pointer-to-function.
1656 PointerTypeLoc PtrToFunctionTL =
1657 ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
1658 // Do the same for the TypeSourceInfo that is used to name the conversion
1659 // operator.
1660 PointerTypeLoc ConvNamePtrToFunctionTL =
1661 ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
1662
1663 // Get the underlying function types that the conversion function will
1664 // be converting to (should match the type of the call operator).
1665 FunctionProtoTypeLoc CallOpConvTL =
1666 PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1667 FunctionProtoTypeLoc CallOpConvNameTL =
1668 ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1669
1670 // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1671 // These parameter's are essentially used to transform the name and
1672 // the type of the conversion operator. By using the same parameters
1673 // as the call operator's we don't have to fix any back references that
1674 // the trailing return type of the call operator's uses (such as
1675 // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1676 // - we can simply use the return type of the call operator, and
1677 // everything should work.
1678 SmallVector<ParmVarDecl *, 4> InvokerParams;
1679 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1680 ParmVarDecl *From = CallOperator->getParamDecl(I);
1681
1682 InvokerParams.push_back(ParmVarDecl::Create(
1683 S.Context,
1684 // Temporarily add to the TU. This is set to the invoker below.
1686 From->getLocation(), From->getIdentifier(), From->getType(),
1687 From->getTypeSourceInfo(), From->getStorageClass(),
1688 /*DefArg=*/nullptr));
1689 CallOpConvTL.setParam(I, From);
1690 CallOpConvNameTL.setParam(I, From);
1691 }
1692
1694 S.Context, Class, Loc,
1695 DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), ConvTy, ConvTSI,
1697 /*isInline=*/true, ExplicitSpecifier(),
1700 CallOperator->getBody()->getEndLoc());
1701 Conversion->setAccess(AS_public);
1702 Conversion->setImplicit(true);
1703
1704 // A non-generic lambda may still be a templated entity. We need to preserve
1705 // constraints when converting the lambda to a function pointer. See GH63181.
1706 if (Expr *Requires = CallOperator->getTrailingRequiresClause())
1707 Conversion->setTrailingRequiresClause(Requires);
1708
1709 if (Class->isGenericLambda()) {
1710 // Create a template version of the conversion operator, using the template
1711 // parameter list of the function call operator.
1712 FunctionTemplateDecl *TemplateCallOperator =
1713 CallOperator->getDescribedFunctionTemplate();
1714 FunctionTemplateDecl *ConversionTemplate =
1716 Loc, ConversionName,
1717 TemplateCallOperator->getTemplateParameters(),
1718 Conversion);
1719 ConversionTemplate->setAccess(AS_public);
1720 ConversionTemplate->setImplicit(true);
1721 Conversion->setDescribedFunctionTemplate(ConversionTemplate);
1722 Class->addDecl(ConversionTemplate);
1723 } else
1724 Class->addDecl(Conversion);
1725
1726 // If the lambda is not static, we need to add a static member
1727 // function that will be the result of the conversion with a
1728 // certain unique ID.
1729 // When it is static we just return the static call operator instead.
1730 if (CallOperator->isImplicitObjectMemberFunction()) {
1731 DeclarationName InvokerName =
1733 // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1734 // we should get a prebuilt TrivialTypeSourceInfo from Context
1735 // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1736 // then rewire the parameters accordingly, by hoisting up the InvokeParams
1737 // loop below and then use its Params to set Invoke->setParams(...) below.
1738 // This would avoid the 'const' qualifier of the calloperator from
1739 // contaminating the type of the invoker, which is currently adjusted
1740 // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the
1741 // trailing return type of the invoker would require a visitor to rebuild
1742 // the trailing return type and adjusting all back DeclRefExpr's to refer
1743 // to the new static invoker parameters - not the call operator's.
1745 S.Context, Class, Loc, DeclarationNameInfo(InvokerName, Loc),
1746 InvokerFunctionTy, CallOperator->getTypeSourceInfo(), SC_Static,
1748 /*isInline=*/true, CallOperator->getConstexprKind(),
1749 CallOperator->getBody()->getEndLoc());
1750 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
1751 InvokerParams[I]->setOwningFunction(Invoke);
1752 Invoke->setParams(InvokerParams);
1753 Invoke->setAccess(AS_private);
1754 Invoke->setImplicit(true);
1755 if (Class->isGenericLambda()) {
1756 FunctionTemplateDecl *TemplateCallOperator =
1757 CallOperator->getDescribedFunctionTemplate();
1758 FunctionTemplateDecl *StaticInvokerTemplate =
1760 S.Context, Class, Loc, InvokerName,
1761 TemplateCallOperator->getTemplateParameters(), Invoke);
1762 StaticInvokerTemplate->setAccess(AS_private);
1763 StaticInvokerTemplate->setImplicit(true);
1764 Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1765 Class->addDecl(StaticInvokerTemplate);
1766 } else
1767 Class->addDecl(Invoke);
1768 }
1769}
1770
1771/// Add a lambda's conversion to function pointers, as described in
1772/// C++11 [expr.prim.lambda]p6. Note that in most cases, this should emit only a
1773/// single pointer conversion. In the event that the default calling convention
1774/// for free and member functions is different, it will emit both conventions.
1775static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange,
1777 CXXMethodDecl *CallOperator) {
1778 const FunctionProtoType *CallOpProto =
1779 CallOperator->getType()->castAs<FunctionProtoType>();
1780
1782 S, *CallOpProto, [&](CallingConv CC) {
1783 QualType InvokerFunctionTy =
1784 S.getLambdaConversionFunctionResultType(CallOpProto, CC);
1785 addFunctionPointerConversion(S, IntroducerRange, Class, CallOperator,
1786 InvokerFunctionTy);
1787 });
1788}
1789
1790/// Add a lambda's conversion to block pointer.
1792 SourceRange IntroducerRange,
1794 CXXMethodDecl *CallOperator) {
1795 const FunctionProtoType *CallOpProto =
1796 CallOperator->getType()->castAs<FunctionProtoType>();
1798 CallOpProto, getLambdaConversionFunctionCallConv(S, CallOpProto));
1799 QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
1800
1801 FunctionProtoType::ExtProtoInfo ConversionEPI(
1803 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1804 ConversionEPI.TypeQuals = Qualifiers();
1805 ConversionEPI.TypeQuals.addConst();
1806 QualType ConvTy =
1807 S.Context.getFunctionType(BlockPtrTy, std::nullopt, ConversionEPI);
1808
1809 SourceLocation Loc = IntroducerRange.getBegin();
1810 DeclarationName Name
1812 S.Context.getCanonicalType(BlockPtrTy));
1814 S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc));
1816 S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), ConvTy,
1817 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
1820 CallOperator->getBody()->getEndLoc());
1821 Conversion->setAccess(AS_public);
1822 Conversion->setImplicit(true);
1823 Class->addDecl(Conversion);
1824}
1825
1827 SourceLocation ImplicitCaptureLoc,
1828 bool IsOpenMPMapping) {
1829 // VLA captures don't have a stored initialization expression.
1830 if (Cap.isVLATypeCapture())
1831 return ExprResult();
1832
1833 // An init-capture is initialized directly from its stored initializer.
1834 if (Cap.isInitCapture())
1835 return cast<VarDecl>(Cap.getVariable())->getInit();
1836
1837 // For anything else, build an initialization expression. For an implicit
1838 // capture, the capture notionally happens at the capture-default, so use
1839 // that location here.
1840 SourceLocation Loc =
1841 ImplicitCaptureLoc.isValid() ? ImplicitCaptureLoc : Cap.getLocation();
1842
1843 // C++11 [expr.prim.lambda]p21:
1844 // When the lambda-expression is evaluated, the entities that
1845 // are captured by copy are used to direct-initialize each
1846 // corresponding non-static data member of the resulting closure
1847 // object. (For array members, the array elements are
1848 // direct-initialized in increasing subscript order.) These
1849 // initializations are performed in the (unspecified) order in
1850 // which the non-static data members are declared.
1851
1852 // C++ [expr.prim.lambda]p12:
1853 // An entity captured by a lambda-expression is odr-used (3.2) in
1854 // the scope containing the lambda-expression.
1856 IdentifierInfo *Name = nullptr;
1857 if (Cap.isThisCapture()) {
1858 QualType ThisTy = getCurrentThisType();
1859 Expr *This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.isValid());
1860 if (Cap.isCopyCapture())
1861 Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
1862 else
1863 Init = This;
1864 } else {
1865 assert(Cap.isVariableCapture() && "unknown kind of capture");
1866 ValueDecl *Var = Cap.getVariable();
1867 Name = Var->getIdentifier();
1869 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
1870 }
1871
1872 // In OpenMP, the capture kind doesn't actually describe how to capture:
1873 // variables are "mapped" onto the device in a process that does not formally
1874 // make a copy, even for a "copy capture".
1875 if (IsOpenMPMapping)
1876 return Init;
1877
1878 if (Init.isInvalid())
1879 return ExprError();
1880
1881 Expr *InitExpr = Init.get();
1883 Name, Cap.getCaptureType(), Loc);
1884 InitializationKind InitKind =
1885 InitializationKind::CreateDirect(Loc, Loc, Loc);
1886 InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr);
1887 return InitSeq.Perform(*this, Entity, InitKind, InitExpr);
1888}
1889
1891 LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back());
1893 return BuildLambdaExpr(StartLoc, Body->getEndLoc(), &LSI);
1894}
1895
1898 switch (ICS) {
1900 return LCD_None;
1902 return LCD_ByCopy;
1905 return LCD_ByRef;
1907 llvm_unreachable("block capture in lambda");
1908 }
1909 llvm_unreachable("Unknown implicit capture style");
1910}
1911
1913 if (From.isInitCapture()) {
1914 Expr *Init = cast<VarDecl>(From.getVariable())->getInit();
1915 if (Init && Init->HasSideEffects(Context))
1916 return true;
1917 }
1918
1919 if (!From.isCopyCapture())
1920 return false;
1921
1922 const QualType T = From.isThisCapture()
1924 : From.getCaptureType();
1925
1926 if (T.isVolatileQualified())
1927 return true;
1928
1929 const Type *BaseT = T->getBaseElementTypeUnsafe();
1930 if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl())
1931 return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() ||
1932 !RD->hasTrivialDestructor();
1933
1934 return false;
1935}
1936
1938 const Capture &From) {
1939 if (CaptureHasSideEffects(From))
1940 return false;
1941
1942 if (From.isVLATypeCapture())
1943 return false;
1944
1945 // FIXME: maybe we should warn on these if we can find a sensible diagnostic
1946 // message
1947 if (From.isInitCapture() &&
1949 return false;
1950
1951 auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture);
1952 if (From.isThisCapture())
1953 diag << "'this'";
1954 else
1955 diag << From.getVariable();
1956 diag << From.isNonODRUsed();
1957 diag << FixItHint::CreateRemoval(CaptureRange);
1958 return true;
1959}
1960
1961/// Create a field within the lambda class or captured statement record for the
1962/// given capture.
1964 const sema::Capture &Capture) {
1966 QualType FieldType = Capture.getCaptureType();
1967
1968 TypeSourceInfo *TSI = nullptr;
1969 if (Capture.isVariableCapture()) {
1970 const auto *Var = dyn_cast_or_null<VarDecl>(Capture.getVariable());
1971 if (Var && Var->isInitCapture())
1972 TSI = Var->getTypeSourceInfo();
1973 }
1974
1975 // FIXME: Should we really be doing this? A null TypeSourceInfo seems more
1976 // appropriate, at least for an implicit capture.
1977 if (!TSI)
1978 TSI = Context.getTrivialTypeSourceInfo(FieldType, Loc);
1979
1980 // Build the non-static data member.
1981 FieldDecl *Field =
1982 FieldDecl::Create(Context, RD, /*StartLoc=*/Loc, /*IdLoc=*/Loc,
1983 /*Id=*/nullptr, FieldType, TSI, /*BW=*/nullptr,
1984 /*Mutable=*/false, ICIS_NoInit);
1985 // If the variable being captured has an invalid type, mark the class as
1986 // invalid as well.
1987 if (!FieldType->isDependentType()) {
1988 if (RequireCompleteSizedType(Loc, FieldType,
1989 diag::err_field_incomplete_or_sizeless)) {
1990 RD->setInvalidDecl();
1991 Field->setInvalidDecl();
1992 } else {
1993 NamedDecl *Def;
1994 FieldType->isIncompleteType(&Def);
1995 if (Def && Def->isInvalidDecl()) {
1996 RD->setInvalidDecl();
1997 Field->setInvalidDecl();
1998 }
1999 }
2000 }
2001 Field->setImplicit(true);
2002 Field->setAccess(AS_private);
2003 RD->addDecl(Field);
2004
2006 Field->setCapturedVLAType(Capture.getCapturedVLAType());
2007
2008 return Field;
2009}
2010
2012 LambdaScopeInfo *LSI) {
2013 // Collect information from the lambda scope.
2015 SmallVector<Expr *, 4> CaptureInits;
2016 SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc;
2017 LambdaCaptureDefault CaptureDefault =
2020 CXXMethodDecl *CallOperator;
2021 SourceRange IntroducerRange;
2022 bool ExplicitParams;
2023 bool ExplicitResultType;
2024 CleanupInfo LambdaCleanup;
2025 bool ContainsUnexpandedParameterPack;
2026 bool IsGenericLambda;
2027 {
2028 CallOperator = LSI->CallOperator;
2029 Class = LSI->Lambda;
2030 IntroducerRange = LSI->IntroducerRange;
2031 ExplicitParams = LSI->ExplicitParams;
2032 ExplicitResultType = !LSI->HasImplicitReturnType;
2033 LambdaCleanup = LSI->Cleanup;
2034 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
2035 IsGenericLambda = Class->isGenericLambda();
2036
2037 CallOperator->setLexicalDeclContext(Class);
2038 Decl *TemplateOrNonTemplateCallOperatorDecl =
2039 CallOperator->getDescribedFunctionTemplate()
2040 ? CallOperator->getDescribedFunctionTemplate()
2041 : cast<Decl>(CallOperator);
2042
2043 // FIXME: Is this really the best choice? Keeping the lexical decl context
2044 // set as CurContext seems more faithful to the source.
2045 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
2046
2048
2049 // True if the current capture has a used capture or default before it.
2050 bool CurHasPreviousCapture = CaptureDefault != LCD_None;
2051 SourceLocation PrevCaptureLoc = CurHasPreviousCapture ?
2052 CaptureDefaultLoc : IntroducerRange.getBegin();
2053
2054 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
2055 const Capture &From = LSI->Captures[I];
2056
2057 if (From.isInvalid())
2058 return ExprError();
2059
2060 assert(!From.isBlockCapture() && "Cannot capture __block variables");
2061 bool IsImplicit = I >= LSI->NumExplicitCaptures;
2062 SourceLocation ImplicitCaptureLoc =
2063 IsImplicit ? CaptureDefaultLoc : SourceLocation();
2064
2065 // Use source ranges of explicit captures for fixits where available.
2066 SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I];
2067
2068 // Warn about unused explicit captures.
2069 bool IsCaptureUsed = true;
2070 if (!CurContext->isDependentContext() && !IsImplicit &&
2071 !From.isODRUsed()) {
2072 // Initialized captures that are non-ODR used may not be eliminated.
2073 // FIXME: Where did the IsGenericLambda here come from?
2074 bool NonODRUsedInitCapture =
2075 IsGenericLambda && From.isNonODRUsed() && From.isInitCapture();
2076 if (!NonODRUsedInitCapture) {
2077 bool IsLast = (I + 1) == LSI->NumExplicitCaptures;
2078 SourceRange FixItRange;
2079 if (CaptureRange.isValid()) {
2080 if (!CurHasPreviousCapture && !IsLast) {
2081 // If there are no captures preceding this capture, remove the
2082 // following comma.
2083 FixItRange = SourceRange(CaptureRange.getBegin(),
2084 getLocForEndOfToken(CaptureRange.getEnd()));
2085 } else {
2086 // Otherwise, remove the comma since the last used capture.
2087 FixItRange = SourceRange(getLocForEndOfToken(PrevCaptureLoc),
2088 CaptureRange.getEnd());
2089 }
2090 }
2091
2092 IsCaptureUsed = !DiagnoseUnusedLambdaCapture(FixItRange, From);
2093 }
2094 }
2095
2096 if (CaptureRange.isValid()) {
2097 CurHasPreviousCapture |= IsCaptureUsed;
2098 PrevCaptureLoc = CaptureRange.getEnd();
2099 }
2100
2101 // Map the capture to our AST representation.
2102 LambdaCapture Capture = [&] {
2103 if (From.isThisCapture()) {
2104 // Capturing 'this' implicitly with a default of '[=]' is deprecated,
2105 // because it results in a reference capture. Don't warn prior to
2106 // C++2a; there's nothing that can be done about it before then.
2107 if (getLangOpts().CPlusPlus20 && IsImplicit &&
2108 CaptureDefault == LCD_ByCopy) {
2109 Diag(From.getLocation(), diag::warn_deprecated_this_capture);
2110 Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture)
2112 getLocForEndOfToken(CaptureDefaultLoc), ", this");
2113 }
2114 return LambdaCapture(From.getLocation(), IsImplicit,
2116 } else if (From.isVLATypeCapture()) {
2117 return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType);
2118 } else {
2119 assert(From.isVariableCapture() && "unknown kind of capture");
2120 ValueDecl *Var = From.getVariable();
2121 LambdaCaptureKind Kind =
2123 return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var,
2124 From.getEllipsisLoc());
2125 }
2126 }();
2127
2128 // Form the initializer for the capture field.
2129 ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc);
2130
2131 // FIXME: Skip this capture if the capture is not used, the initializer
2132 // has no side-effects, the type of the capture is trivial, and the
2133 // lambda is not externally visible.
2134
2135 // Add a FieldDecl for the capture and form its initializer.
2136 BuildCaptureField(Class, From);
2137 Captures.push_back(Capture);
2138 CaptureInits.push_back(Init.get());
2139
2140 if (LangOpts.CUDA)
2141 CUDA().CheckLambdaCapture(CallOperator, From);
2142 }
2143
2144 Class->setCaptures(Context, Captures);
2145
2146 // C++11 [expr.prim.lambda]p6:
2147 // The closure type for a lambda-expression with no lambda-capture
2148 // has a public non-virtual non-explicit const conversion function
2149 // to pointer to function having the same parameter and return
2150 // types as the closure type's function call operator.
2151 if (Captures.empty() && CaptureDefault == LCD_None)
2152 addFunctionPointerConversions(*this, IntroducerRange, Class,
2153 CallOperator);
2154
2155 // Objective-C++:
2156 // The closure type for a lambda-expression has a public non-virtual
2157 // non-explicit const conversion function to a block pointer having the
2158 // same parameter and return types as the closure type's function call
2159 // operator.
2160 // FIXME: Fix generic lambda to block conversions.
2161 if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda)
2162 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
2163
2164 // Finalize the lambda class.
2165 SmallVector<Decl*, 4> Fields(Class->fields());
2166 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
2168 CheckCompletedCXXClass(nullptr, Class);
2169 }
2170
2171 Cleanup.mergeFrom(LambdaCleanup);
2172
2173 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
2174 CaptureDefault, CaptureDefaultLoc,
2175 ExplicitParams, ExplicitResultType,
2176 CaptureInits, EndLoc,
2177 ContainsUnexpandedParameterPack);
2178 // If the lambda expression's call operator is not explicitly marked constexpr
2179 // and we are not in a dependent context, analyze the call operator to infer
2180 // its constexpr-ness, suppressing diagnostics while doing so.
2181 if (getLangOpts().CPlusPlus17 && !CallOperator->isInvalidDecl() &&
2182 !CallOperator->isConstexpr() &&
2183 !isa<CoroutineBodyStmt>(CallOperator->getBody()) &&
2184 !Class->getDeclContext()->isDependentContext()) {
2185 CallOperator->setConstexprKind(
2190 }
2191
2192 // Emit delayed shadowing warnings now that the full capture list is known.
2194
2196 switch (ExprEvalContexts.back().Context) {
2197 // C++11 [expr.prim.lambda]p2:
2198 // A lambda-expression shall not appear in an unevaluated operand
2199 // (Clause 5).
2203 // C++1y [expr.const]p2:
2204 // A conditional-expression e is a core constant expression unless the
2205 // evaluation of e, following the rules of the abstract machine, would
2206 // evaluate [...] a lambda-expression.
2207 //
2208 // This is technically incorrect, there are some constant evaluated contexts
2209 // where this should be allowed. We should probably fix this when DR1607 is
2210 // ratified, it lays out the exact set of conditions where we shouldn't
2211 // allow a lambda-expression.
2214 // We don't actually diagnose this case immediately, because we
2215 // could be within a context where we might find out later that
2216 // the expression is potentially evaluated (e.g., for typeid).
2217 ExprEvalContexts.back().Lambdas.push_back(Lambda);
2218 break;
2219
2223 break;
2224 }
2225 }
2226
2227 return MaybeBindToTemporary(Lambda);
2228}
2229
2231 SourceLocation ConvLocation,
2232 CXXConversionDecl *Conv,
2233 Expr *Src) {
2234 // Make sure that the lambda call operator is marked used.
2235 CXXRecordDecl *Lambda = Conv->getParent();
2236 CXXMethodDecl *CallOperator
2237 = cast<CXXMethodDecl>(
2238 Lambda->lookup(
2240 CallOperator->setReferenced();
2241 CallOperator->markUsed(Context);
2242
2245 CurrentLocation, Src);
2246 if (!Init.isInvalid())
2247 Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
2248
2249 if (Init.isInvalid())
2250 return ExprError();
2251
2252 // Create the new block to be returned.
2254
2255 // Set the type information.
2256 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
2257 Block->setIsVariadic(CallOperator->isVariadic());
2258 Block->setBlockMissingReturnType(false);
2259
2260 // Add parameters.
2262 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
2263 ParmVarDecl *From = CallOperator->getParamDecl(I);
2264 BlockParams.push_back(ParmVarDecl::Create(
2265 Context, Block, From->getBeginLoc(), From->getLocation(),
2266 From->getIdentifier(), From->getType(), From->getTypeSourceInfo(),
2267 From->getStorageClass(),
2268 /*DefArg=*/nullptr));
2269 }
2270 Block->setParams(BlockParams);
2271
2272 Block->setIsConversionFromLambda(true);
2273
2274 // Add capture. The capture uses a fake variable, which doesn't correspond
2275 // to any actual memory location. However, the initializer copy-initializes
2276 // the lambda object.
2277 TypeSourceInfo *CapVarTSI =
2279 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
2280 ConvLocation, nullptr,
2281 Src->getType(), CapVarTSI,
2282 SC_None);
2283 BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false,
2284 /*nested=*/false, /*copy=*/Init.get());
2285 Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false);
2286
2287 // Add a fake function body to the block. IR generation is responsible
2288 // for filling in the actual body, which cannot be expressed as an AST.
2289 Block->setBody(new (Context) CompoundStmt(ConvLocation));
2290
2291 // Create the block literal expression.
2292 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
2293 ExprCleanupObjects.push_back(Block);
2295
2296 return BuildBlock;
2297}
2298
2303 return FD;
2304 }
2305
2307 return FD->getInstantiatedFromDecl();
2308
2310 if (!FTD)
2311 return nullptr;
2312
2315
2316 return FTD->getTemplatedDecl();
2317}
2318
2322 LocalInstantiationScope &Scope, bool ShouldAddDeclsFromParentScope)
2323 : FunctionScopeRAII(SemaRef) {
2324 if (!isLambdaCallOperator(FD)) {
2326 return;
2327 }
2328
2329 SemaRef.RebuildLambdaScopeInfo(cast<CXXMethodDecl>(FD));
2330
2331 FunctionDecl *Pattern = getPatternFunctionDecl(FD);
2332 if (Pattern) {
2333 SemaRef.addInstantiatedCapturesToScope(FD, Pattern, Scope, MLTAL);
2334
2335 FunctionDecl *ParentFD = FD;
2336 while (ShouldAddDeclsFromParentScope) {
2337
2338 ParentFD =
2339 dyn_cast<FunctionDecl>(getLambdaAwareParentOfDeclContext(ParentFD));
2340 Pattern =
2341 dyn_cast<FunctionDecl>(getLambdaAwareParentOfDeclContext(Pattern));
2342
2343 if (!FD || !Pattern)
2344 break;
2345
2346 SemaRef.addInstantiatedParametersToScope(ParentFD, Pattern, Scope, MLTAL);
2347 SemaRef.addInstantiatedLocalVarsToScope(ParentFD, Pattern, Scope);
2348 }
2349 }
2350}
#define V(N, I)
Definition: ASTContext.h:3284
int Id
Definition: ASTDiff.cpp:190
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
Defines the clang::Expr interface and subclasses for C++ expressions.
This file declares semantic analysis for CUDA constructs.
static LambdaCaptureDefault mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS)
static CallingConv getLambdaConversionFunctionCallConv(Sema &S, const FunctionProtoType *CallOpProto)
static EnumDecl * findEnumForBlockReturn(Expr *E)
If this expression is an enumerator-like expression of some type T, return the type T; otherwise,...
Definition: SemaLambda.cpp:530
static EnumDecl * findCommonEnumForBlockReturns(ArrayRef< ReturnStmt * > returns)
Attempt to find a common type T for which all of the returned expressions in a block are enumerator-l...
Definition: SemaLambda.cpp:602
static TypeSourceInfo * getLambdaType(Sema &S, LambdaIntroducer &Intro, Declarator &ParamInfo, Scope *CurScope, SourceLocation Loc, bool &ExplicitResultType)
Definition: SemaLambda.cpp:876
static std::optional< unsigned > getStackIndexOfNearestEnclosingCaptureReadyLambda(ArrayRef< const clang::sema::FunctionScopeInfo * > FunctionScopes, ValueDecl *VarToCapture)
Examines the FunctionScopeInfo stack to determine the nearest enclosing lambda (to the current lambda...
Definition: SemaLambda.cpp:67
static FunctionDecl * getPatternFunctionDecl(FunctionDecl *FD)
static LambdaScopeInfo * getCurrentLambdaScopeUnsafe(Sema &S)
Definition: SemaLambda.cpp:844
static void adjustBlockReturnsToEnum(Sema &S, ArrayRef< ReturnStmt * > returns, QualType returnType)
Adjust the given return statements so that they formally return the given type.
Definition: SemaLambda.cpp:623
static TemplateParameterList * getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef)
Definition: SemaLambda.cpp:233
static void addBlockPointerConversion(Sema &S, SourceRange IntroducerRange, CXXRecordDecl *Class, CXXMethodDecl *CallOperator)
Add a lambda's conversion to block pointer.
static void buildLambdaScopeReturnType(Sema &S, LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, bool ExplicitResultType)
Definition: SemaLambda.cpp:468
static TypeSourceInfo * getDummyLambdaType(Sema &S, SourceLocation Loc=SourceLocation())
Definition: SemaLambda.cpp:850
static QualType buildTypeForLambdaCallOperator(Sema &S, clang::CXXRecordDecl *Class, TemplateParameterList *TemplateParams, TypeSourceInfo *MethodTypeInfo)
Definition: SemaLambda.cpp:363
static bool isInInlineFunction(const DeclContext *DC)
Determine whether the given context is or is enclosed in an inline function.
Definition: SemaLambda.cpp:267
static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange, CXXRecordDecl *Class, CXXMethodDecl *CallOperator)
Add a lambda's conversion to function pointers, as described in C++11 [expr.prim.lambda]p6.
static void repeatForLambdaConversionFunctionCallingConvs(Sema &S, const FunctionProtoType &CallOpProto, Func F)
static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange, CXXRecordDecl *Class, CXXMethodDecl *CallOperator, QualType InvokerFunctionTy)
Add a lambda's conversion to function pointer, as described in C++11 [expr.prim.lambda]p6.
This file provides some common utility functions for processing Lambdas.
This file declares semantic analysis for OpenMP constructs and clauses.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1073
CanQualType getCanonicalFunctionResultType(QualType ResultType) const
Adjust the given function result type.
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:648
QualType getRecordType(const RecordDecl *Decl) const
QualType getPackExpansionType(QualType Pattern, std::optional< unsigned > NumExpansions, bool ExpectPackInType=true)
Form a pack expansion type with the given pattern.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2574
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2590
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1119
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:1590
IdentifierTable & Idents
Definition: ASTContext.h:644
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
CanQualType VoidTy
Definition: ASTContext.h:1091
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1568
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:757
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1188
PtrTy get() const
Definition: Ownership.h:170
Attr - This represents one attribute.
Definition: Attr.h:42
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3840
A binding in a decomposition declaration.
Definition: DeclCXX.h:4107
A class which contains all the information about a particular captured value.
Definition: Decl.h:4501
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4495
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5418
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6173
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2862
static CXXConversionDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2890
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2902
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition: DeclCXX.cpp:2462
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2274
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
void setLambdaTypeInfo(TypeSourceInfo *TS)
Definition: DeclCXX.h:1866
void setLambdaIsGeneric(bool IsGeneric)
Definition: DeclCXX.h:1877
static CXXRecordDecl * CreateLambda(const ASTContext &C, DeclContext *DC, TypeSourceInfo *Info, SourceLocation Loc, unsigned DependencyKind, bool IsGeneric, LambdaCaptureDefault CaptureDefault)
Definition: DeclCXX.cpp:148
bool isCapturelessLambda() const
Definition: DeclCXX.h:1068
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:73
void mergeFrom(CleanupInfo Rhs)
Definition: CleanupInfo.h:38
void setExprNeedsCleanups(bool SideEffects)
Definition: CleanupInfo.h:28
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1606
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4179
reference front() const
Definition: DeclBase.h:1392
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2191
bool isFileContext() const
Definition: DeclBase.h:2137
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1264
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2082
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1784
bool isTranslationUnit() const
Definition: DeclBase.h:2142
bool isRecord() const
Definition: DeclBase.h:2146
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1698
bool isFunctionOrMethod() const
Definition: DeclBase.h:2118
Simple template class for restricting typo correction candidates to ones having a single Decl* of the...
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
Captures information about "declaration specifiers".
Definition: DeclSpec.h:246
SCS getStorageClassSpec() const
Definition: DeclSpec.h:497
bool SetTypeQual(TQ T, SourceLocation Loc)
Definition: DeclSpec.cpp:1013
ConstexprSpecKind getConstexprSpecifier() const
Definition: DeclSpec.h:828
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
void addAttr(Attr *A)
Definition: DeclBase.cpp:975
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:220
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:545
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:262
bool isInvalidDecl() const
Definition: DeclBase.h:594
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:508
SourceLocation getLocation() const
Definition: DeclBase.h:445
void setImplicit(bool I=true)
Definition: DeclBase.h:600
void setReferenced(bool R=true)
Definition: DeclBase.h:629
void setLocation(SourceLocation L)
Definition: DeclBase.h:446
DeclContext * getDeclContext()
Definition: DeclBase.h:454
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:340
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeNamedTypeLoc(TypeSourceInfo *TInfo)
Construct location information for a constructor, destructor or conversion operator.
static DeclarationNameLoc makeCXXOperatorNameLoc(SourceLocation BeginLoc, SourceLocation EndLoc)
Construct location information for a non-literal C++ operator.
DeclarationName getCXXConversionFunctionName(CanQualType Ty)
Returns the name of a C++ conversion function for the given Type.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
void setInnerLocStart(SourceLocation L)
Definition: Decl.h:814
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:822
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:805
void setTrailingRequiresClause(Expr *TrailingRequiresClause)
Definition: Decl.cpp:2016
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:846
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:799
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1898
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition: DeclSpec.h:2454
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2396
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2045
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition: DeclSpec.h:2631
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2392
bool isExplicitObjectMemberFunction()
Definition: DeclSpec.cpp:424
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:2080
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2485
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:5943
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3298
Represents an enum.
Definition: Decl.h:3868
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5571
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1897
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition: ExprCXX.h:3443
This represents one expression.
Definition: Expr.h:110
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3055
QualType getType() const
Definition: Expr.h:142
Represents difference between two FPOptions values.
Definition: LangOptions.h:915
bool isFPConstrained() const
Definition: LangOptions.h:843
Represents a member of a struct/union/class.
Definition: Decl.h:3058
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition: Decl.cpp:4547
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:97
void setSubExpr(Expr *E)
As with any mutator of the AST, be very careful when modifying an existing AST to preserve its invari...
Definition: Expr.h:1057
const Expr * getSubExpr() const
Definition: Expr.h:1052
Represents a function declaration or definition.
Definition: Decl.h:1971
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2707
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3236
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2439
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:4047
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4042
QualType getReturnType() const
Definition: Decl.h:2755
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2684
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4162
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3089
@ TK_MemberSpecialization
Definition: Decl.h:1983
@ TK_DependentNonTemplate
Definition: Decl.h:1992
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3993
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2433
bool isImmediateEscalating() const
Definition: Decl.cpp:3268
FunctionDecl * getInstantiatedFromDecl() const
Definition: Decl.cpp:4066
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2436
bool isConsteval() const
Definition: Decl.h:2445
void setStorageClass(StorageClass SClass)
Sets the storage class as written in the source.
Definition: Decl.h:2803
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4014
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3692
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.h:2715
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4652
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5008
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4896
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4892
Declaration of a template function.
Definition: DeclTemplate.h:958
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
TypeLoc getReturnLoc() const
Definition: TypeLoc.h:1509
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4478
CallingConv getCallConv() const
Definition: Type.h:4580
QualType getReturnType() const
Definition: Type.h:4569
One of these records is kept for each identifier that is lexed.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3655
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2074
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
Describes the sequence of initializations required to initialize a given object or reference with a s...
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Definition: SemaInit.cpp:8591
Describes an entity that is being initialized.
static InitializedEntity InitializeLambdaToBlock(SourceLocation BlockVarLoc, QualType Type)
static InitializedEntity InitializeLambdaCapture(IdentifierInfo *VarID, QualType FieldType, SourceLocation Loc)
Create the initialization entity for a lambda capture.
Describes the capture of a variable or of this, or of a C++1y init-capture.
Definition: LambdaCapture.h:25
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1948
static LambdaExpr * Create(const ASTContext &C, CXXRecordDecl *Class, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, bool ExplicitParams, bool ExplicitResultType, ArrayRef< Expr * > CaptureInits, SourceLocation ClosingBrace, bool ContainsUnexpandedParameterPack)
Construct a new lambda expression.
Definition: ExprCXX.cpp:1244
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:365
Represents the results of name lookup.
Definition: Lookup.h:46
DeclClass * getAsSingle() const
Definition: Lookup.h:556
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
bool isAmbiguous() const
Definition: Lookup.h:324
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
virtual unsigned getDeviceManglingNumber(const CXXMethodDecl *)
Retrieve the mangling number of a new lambda expression with the given call operator within the devic...
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:76
This represents a decl that may have a name.
Definition: Decl.h:249
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition: Decl.cpp:1082
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
PtrTy get() const
Definition: Ownership.h:80
Represents a pack expansion of types.
Definition: Type.h:6565
Expr ** getExprs()
Definition: Expr.h:5664
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5653
Represents a parameter to a function.
Definition: Decl.h:1761
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2915
Wrapper for source info for pointers.
Definition: TypeLoc.h:1301
A (possibly-)qualified type.
Definition: Type.h:940
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition: Type.h:1291
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7481
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:7556
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7449
The collection of all-type qualifiers we support.
Definition: Type.h:318
void addAddressSpace(LangAS space)
Definition: Type.h:583
void addConst()
Definition: Type.h:446
Represents a struct/union/class.
Definition: Decl.h:4169
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3019
void setRetValue(Expr *E)
Definition: Stmt.h:3052
SourceLocation getBeginLoc() const
Definition: Stmt.h:3076
Expr * getRetValue()
Definition: Stmt.h:3050
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:267
Scope * getTemplateParamParent()
Definition: Scope.h:312
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:56
Sema & SemaRef
Definition: SemaBase.h:40
void CheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture)
Definition: SemaCUDA.cpp:952
void SetLambdaAttrs(CXXMethodDecl *Method)
Set device or host device attributes on the given lambda operator() method.
Definition: SemaCUDA.cpp:997
void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D)
Act on D, a function definition inside of an omp [begin/end] assumes.
A RAII object to temporarily push a declaration context.
Definition: Sema.h:2544
LambdaScopeForCallOperatorInstantiationRAII(Sema &SemasRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL, LocalInstantiationScope &Scope, bool ShouldAddDeclsFromParentScope=true)
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:457
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
Definition: SemaDecl.cpp:11101
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:698
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args=std::nullopt, DeclContext *LookupCtx=nullptr, TypoExpr **Out=nullptr)
Diagnose an empty lookup.
Definition: SemaExpr.cpp:2476
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15753
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition: Sema.h:6365
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7376
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:13044
VarDecl * createLambdaInitCaptureVarDecl(SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc, IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx)
Create a dummy variable within the declcontext of the lambda's call operator, for name lookup purpose...
Definition: SemaLambda.cpp:809
ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body)
ActOnLambdaExpr - This is called when the body of a lambda expression was successfully completed.
SemaOpenMP & OpenMP()
Definition: Sema.h:1013
ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, sema::LambdaScopeInfo *LSI)
Complete a lambda-expression having processed and attached the lambda body.
CXXRecordDecl * createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, unsigned LambdaDependencyKind, LambdaCaptureDefault CaptureDefault)
Create a new lambda closure type.
Definition: SemaLambda.cpp:247
SemaCUDA & CUDA()
Definition: Sema.h:998
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:17673
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:807
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition: Sema.cpp:2245
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit=false, bool BuildAndDiagnose=true, const unsigned *const FunctionScopeIndexToStopAt=nullptr, bool ByCopy=false)
Make sure the value of 'this' is actually available in the current context, if it is a potentially ev...
void ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro, Scope *CurContext)
Once the Lambdas capture are known, we can start to create the closure, call operator method,...
void AddTemplateParametersToLambdaCallOperator(CXXMethodDecl *CallOperator, CXXRecordDecl *Class, TemplateParameterList *TemplateParams)
Definition: SemaLambda.cpp:957
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor,...
void AddRangeBasedOptnone(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based o...
Definition: SemaAttr.cpp:1177
void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef)
Add an init-capture to a lambda scope.
Definition: SemaLambda.cpp:835
FieldDecl * BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture)
Build a FieldDecl suitable to hold the given capture.
sema::LambdaScopeInfo * RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator)
Definition: SemaDecl.cpp:15654
ASTContext & Context
Definition: Sema.h:858
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1521
ASTContext & getASTContext() const
Definition: Sema.h:527
bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt)
Try to capture the given variable.
Definition: SemaExpr.cpp:19194
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:18099
sema::LambdaScopeInfo * getCurGenericLambda()
Retrieve the current generic lambda info, if any.
Definition: Sema.cpp:2385
void handleLambdaNumbering(CXXRecordDecl *Class, CXXMethodDecl *Method, std::optional< CXXRecordDecl::LambdaNumbering > NumberingOverride=std::nullopt)
Number lambda for linkage purposes if necessary.
Definition: SemaLambda.cpp:415
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition: Sema.cpp:1518
ExprResult BuildCaptureInit(const sema::Capture &Capture, SourceLocation ImplicitCaptureLoc, bool IsOpenMPMapping=false)
Initialize the given capture with a suitable expression.
FPOptions & getCurFPFeatures()
Definition: Sema.h:522
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:63
@ UPPC_Initializer
An initializer.
Definition: Sema.h:10824
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition: Sema.h:10797
void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, bool ExplicitParams, bool Mutable)
Endow the lambda scope info with the relevant properties.
Definition: SemaLambda.cpp:482
const LangOptions & getLangOpts() const
Definition: Sema.h:520
bool CaptureHasSideEffects(const sema::Capture &From)
Does copying/destroying the captured variable have side effects?
void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, Declarator &ParamInfo, const DeclSpec &DS)
ActOnStartOfLambdaDefinition - This is called just before we start parsing the body of a lambda; it a...
void ActOnLambdaClosureParameters(Scope *LambdaScope, MutableArrayRef< DeclaratorChunk::ParamInfo > ParamInfo)
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
void DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method)
Definition: SemaLambda.cpp:391
const LangOptions & LangOpts
Definition: Sema.h:856
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2360
bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, const sema::Capture &From)
Diagnose if an explicit lambda capture is unused.
QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, std::optional< unsigned > NumExpansions, IdentifierInfo *Id, bool DirectInit, Expr *&Init)
Definition: SemaLambda.cpp:743
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:5188
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
Definition: SemaDecl.cpp:8492
Expr * BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit)
Build a CXXThisExpr and mark it referenced in the current context.
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
Definition: SemaType.cpp:2273
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3432
void DiagPlaceholderVariableDefinition(SourceLocation Loc)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:996
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:10484
TryCaptureKind
Definition: Sema.h:5275
@ TryCapture_Implicit
Definition: Sema.h:5276
@ TryCapture_ExplicitByVal
Definition: Sema.h:5277
@ TryCapture_ExplicitByRef
Definition: Sema.h:5278
void ActOnLambdaExplicitTemplateParameterList(LambdaIntroducer &Intro, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > TParams, SourceLocation RAngleLoc, ExprResult RequiresClause)
This is called after parsing the explicit template parameter list on a lambda (if it exists) in C++2a...
Definition: SemaLambda.cpp:504
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
Definition: SemaDecl.cpp:16022
void ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro, SourceLocation MutableLoc)
void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, bool IsInstantiation=false)
ActOnLambdaError - If there is an error parsing a lambda, this callback is invoked to pop the informa...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:227
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
Definition: SemaDecl.cpp:8374
@ Normal
A normal translation unit fragment.
Definition: Sema.h:612
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition: Sema.h:5192
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
@ DiscardedStatement
The current expression occurs within a discarded statement.
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:6122
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9276
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:19320
void CheckExplicitObjectLambda(Declarator &D)
QualType getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType, CallingConv CC)
Get the return type to use for a lambda's conversion function(s) to function pointer type,...
void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:18177
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:6438
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1328
CXXMethodDecl * CreateLambdaCallOperator(SourceRange IntroducerRange, CXXRecordDecl *Class)
Definition: SemaLambda.cpp:932
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
Definition: SemaLambda.cpp:650
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:10662
void PopDeclContext()
Definition: SemaDecl.cpp:1335
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
Definition: SemaLambda.cpp:280
void CompleteLambdaCallOperator(CXXMethodDecl *Method, SourceLocation LambdaLoc, SourceLocation CallOperatorLoc, Expr *TrailingRequiresClause, TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind, StorageClass SC, ArrayRef< ParmVarDecl * > Params, bool HasExplicitResultType)
Definition: SemaLambda.cpp:968
void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI)
Note that we have finished the explicit captures for the given lambda.
Definition: SemaLambda.cpp:500
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
void NoteTemplateParameterLocation(const NamedDecl &Decl)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:6733
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:4383
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3809
Exposes information about the current target.
Definition: TargetInfo.h:214
virtual CallingConvCheckResult checkCallingConvention(CallingConv CC) const
Determines whether a given calling convention is valid for the target.
Definition: TargetInfo.h:1659
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
ArrayRef< NamedDecl * > asArray()
Definition: DeclTemplate.h:139
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:89
A container of type source information.
Definition: Type.h:7326
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7337
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
The base class of the type hierarchy.
Definition: Type.h:1813
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1870
bool isVoidType() const
Definition: Type.h:7901
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2059
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8186
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:694
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2649
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2320
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8069
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8035
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2350
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8119
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4610
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
void setType(QualType newType)
Definition: Decl.h:718
QualType getType() const
Definition: Decl.h:717
VarDecl * getPotentiallyDecomposedVarDecl()
Definition: DeclCXX.cpp:3324
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.cpp:5373
Represents a variable declaration or definition.
Definition: Decl.h:918
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2148
void setInitStyle(InitializationStyle Style)
Definition: Decl.h:1432
void setInitCapture(bool IC)
Definition: Decl.h:1561
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1558
InitializationStyle
Initialization styles.
Definition: Decl.h:921
@ ListInit
Direct list-initialization (C++11)
Definition: Decl.h:929
@ CInit
C-style initialization with assignment.
Definition: Decl.h:923
@ CallInit
Call-style initialization (C++98)
Definition: Decl.h:926
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1171
void setInit(Expr *I)
Definition: Decl.cpp:2454
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1155
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2663
ValueDecl * getVariable() const
Definition: ScopeInfo.h:675
bool isVariableCapture() const
Definition: ScopeInfo.h:650
bool isBlockCapture() const
Definition: ScopeInfo.h:656
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition: ScopeInfo.h:686
bool isNonODRUsed() const
Definition: ScopeInfo.h:667
bool isODRUsed() const
Definition: ScopeInfo.h:666
bool isInitCapture() const
Determine whether this capture is an init-capture.
Definition: ScopeInfo.cpp:222
bool isInvalid() const
Definition: ScopeInfo.h:661
bool isVLATypeCapture() const
Definition: ScopeInfo.h:657
SourceLocation getEllipsisLoc() const
Retrieve the source location of the ellipsis, whose presence indicates that the capture is a pack exp...
Definition: ScopeInfo.h:690
bool isThisCapture() const
Definition: ScopeInfo.h:649
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Definition: ScopeInfo.h:695
bool isCopyCapture() const
Definition: ScopeInfo.h:654
const VariableArrayType * getCapturedVLAType() const
Definition: ScopeInfo.h:680
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:729
bool isCaptured(ValueDecl *Var) const
Determine whether the given variable has been captured.
Definition: ScopeInfo.h:758
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition: ScopeInfo.h:721
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:708
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
Definition: ScopeInfo.h:752
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition: ScopeInfo.h:749
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition: ScopeInfo.h:731
SmallVector< ReturnStmt *, 4 > Returns
The list of return statements that occur within the function or block, if there is any chance of appl...
Definition: ScopeInfo.h:214
SourceLocation PotentialThisCaptureLocation
Definition: ScopeInfo.h:950
void finishedExplicitCaptures()
Note when all explicit captures have been added.
Definition: ScopeInfo.h:958
bool ContainsUnexpandedParameterPack
Whether the lambda contains an unexpanded parameter pack.
Definition: ScopeInfo.h:899
SmallVector< NamedDecl *, 4 > LocalPacks
Packs introduced by this lambda, if any.
Definition: ScopeInfo.h:902
CleanupInfo Cleanup
Whether any of the capture expressions requires cleanups.
Definition: ScopeInfo.h:896
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition: ScopeInfo.h:878
bool ExplicitParams
Whether the (empty) parameter list is explicit.
Definition: ScopeInfo.h:893
TemplateParameterList * GLTemplateParameterList
If this is a generic lambda, and the template parameter list has been created (from the TemplateParam...
Definition: ScopeInfo.h:915
ExprResult RequiresClause
The requires-clause immediately following the explicit template parameter list, if any.
Definition: ScopeInfo.h:910
SourceRange ExplicitTemplateParamsRange
Source range covering the explicit template parameter list (if it exists).
Definition: ScopeInfo.h:905
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:865
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition: ScopeInfo.h:886
SourceLocation CaptureDefaultLoc
Source location of the '&' or '=' specifying the default capture type, if any.
Definition: ScopeInfo.h:882
llvm::DenseMap< unsigned, SourceRange > ExplicitCaptureRanges
A map of explicit capture indices to their introducer source ranges.
Definition: ScopeInfo.h:939
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition: ScopeInfo.h:873
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:868
bool Mutable
Whether this is a mutable lambda.
Definition: ScopeInfo.h:890
Defines the clang::TargetInfo interface.
The JSON file list parser is used to communicate input to InstallAPI.
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus14
Definition: LangStandard.h:57
@ CPlusPlus17
Definition: LangStandard.h:58
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:95
std::optional< unsigned > getStackIndexOfNearestEnclosingCaptureCapableLambda(ArrayRef< const sema::FunctionScopeInfo * > FunctionScopes, ValueDecl *VarToCapture, Sema &S)
Examines the FunctionScopeInfo stack to determine the nearest enclosing lambda (to the current lambda...
Definition: SemaLambda.cpp:178
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition: Specifiers.h:35
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:269
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1762
LambdaCaptureKind
The different capture forms in a lambda introducer.
Definition: Lambda.h:33
@ LCK_ByCopy
Capturing by copy (a.k.a., by value)
Definition: Lambda.h:36
@ LCK_ByRef
Capturing by reference.
Definition: Lambda.h:37
@ LCK_VLAType
Capturing variable-length array type.
Definition: Lambda.h:38
@ LCK_StarThis
Capturing the *this object by copy.
Definition: Lambda.h:35
@ LCK_This
Capturing the *this object by reference.
Definition: Lambda.h:34
bool isLambdaCallWithExplicitObjectParameter(const DeclContext *DC)
Definition: ASTLambda.h:38
StorageClass
Storage classes.
Definition: Specifiers.h:245
@ SC_Auto
Definition: Specifiers.h:253
@ SC_Static
Definition: Specifiers.h:249
@ SC_None
Definition: Specifiers.h:247
bool FTIHasSingleVoidParameter(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:29
@ CopyInit
[a = b], [a = {b}]
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
@ Result
The result type of a method or function.
bool hasWeakerNullability(NullabilityKind L, NullabilityKind R)
Return true if L has a weaker nullability annotation than R.
Definition: Specifiers.h:354
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
ExprResult ExprError()
Definition: Ownership.h:264
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
LambdaCaptureDefault
The default, if any, capture method for a lambda expression.
Definition: Lambda.h:22
@ LCD_ByRef
Definition: Lambda.h:25
@ LCD_None
Definition: Lambda.h:23
@ LCD_ByCopy
Definition: Lambda.h:24
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
StringRef getLambdaStaticInvokerName()
Definition: ASTLambda.h:22
const FunctionProtoType * T
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
@ CC_C
Definition: Specifiers.h:276
@ CC_X86VectorCall
Definition: Specifiers.h:280
@ CC_X86StdCall
Definition: Specifiers.h:277
@ CC_X86FastCall
Definition: Specifiers.h:278
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ EST_BasicNoexcept
noexcept
@ AS_public
Definition: Specifiers.h:121
@ AS_private
Definition: Specifiers.h:123
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:258
Information about how a lambda is numbered within its context.
Definition: DeclCXX.h:1798
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getTrailingReturnTypeLoc() const
Get the trailing-return-type location for this function declarator.
Definition: DeclSpec.h:1591
bool hasTrailingReturnType() const
Determine whether this function declarator had a trailing-return-type.
Definition: DeclSpec.h:1582
ParsedType getTrailingReturnType() const
Get the trailing-return-type for this function declarator.
Definition: DeclSpec.h:1585
bool hasMutableQualifier() const
Determine whether this lambda-declarator contains a 'mutable' qualifier.
Definition: DeclSpec.h:1554
ParamInfo - An array of paraminfo objects is allocated whenever a function declarator is parsed.
Definition: DeclSpec.h:1329
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:4705
Extra information about a function prototype.
Definition: Type.h:4731
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:4738
FunctionType::ExtInfo ExtInfo
Definition: Type.h:4732
unsigned NumExplicitTemplateParams
The number of parameters in the template parameter list that were explicitly specified by the user,...
Definition: DeclSpec.h:2881
SmallVector< NamedDecl *, 4 > TemplateParams
Store the list of the template parameters for a generic lambda or an abbreviated function template.
Definition: DeclSpec.h:2894
Represents a complete lambda introducer.
Definition: DeclSpec.h:2830
SmallVector< LambdaCapture, 4 > Captures
Definition: DeclSpec.h:2855
SourceLocation DefaultLoc
Definition: DeclSpec.h:2853
LambdaCaptureDefault Default
Definition: DeclSpec.h:2854
An RAII helper that pops function a function scope on exit.
Definition: Sema.h:878