clang 20.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"
16#include "clang/AST/ExprCXX.h"
18#include "clang/Sema/DeclSpec.h"
20#include "clang/Sema/Lookup.h"
21#include "clang/Sema/Scope.h"
23#include "clang/Sema/SemaCUDA.h"
26#include "clang/Sema/Template.h"
27#include "llvm/ADT/STLExtras.h"
28#include <optional>
29using namespace clang;
30using namespace sema;
31
32/// Examines the FunctionScopeInfo stack to determine the nearest
33/// enclosing lambda (to the current lambda) that is 'capture-ready' for
34/// the variable referenced in the current lambda (i.e. \p VarToCapture).
35/// If successful, returns the index into Sema's FunctionScopeInfo stack
36/// of the capture-ready lambda's LambdaScopeInfo.
37///
38/// Climbs down the stack of lambdas (deepest nested lambda - i.e. current
39/// lambda - is on top) to determine the index of the nearest enclosing/outer
40/// lambda that is ready to capture the \p VarToCapture being referenced in
41/// the current lambda.
42/// As we climb down the stack, we want the index of the first such lambda -
43/// that is the lambda with the highest index that is 'capture-ready'.
44///
45/// A lambda 'L' is capture-ready for 'V' (var or this) if:
46/// - its enclosing context is non-dependent
47/// - and if the chain of lambdas between L and the lambda in which
48/// V is potentially used (i.e. the lambda at the top of the scope info
49/// stack), can all capture or have already captured V.
50/// If \p VarToCapture is 'null' then we are trying to capture 'this'.
51///
52/// Note that a lambda that is deemed 'capture-ready' still needs to be checked
53/// for whether it is 'capture-capable' (see
54/// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly
55/// capture.
56///
57/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
58/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
59/// is at the top of the stack and has the highest index.
60/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
61///
62/// \returns An std::optional<unsigned> Index that if evaluates to 'true'
63/// contains the index (into Sema's FunctionScopeInfo stack) of the innermost
64/// lambda which is capture-ready. If the return value evaluates to 'false'
65/// then no lambda is capture-ready for \p VarToCapture.
66
67static inline std::optional<unsigned>
70 ValueDecl *VarToCapture) {
71 // Label failure to capture.
72 const std::optional<unsigned> NoLambdaIsCaptureReady;
73
74 // Ignore all inner captured regions.
75 unsigned CurScopeIndex = FunctionScopes.size() - 1;
76 while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>(
77 FunctionScopes[CurScopeIndex]))
78 --CurScopeIndex;
79 assert(
80 isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) &&
81 "The function on the top of sema's function-info stack must be a lambda");
82
83 // If VarToCapture is null, we are attempting to capture 'this'.
84 const bool IsCapturingThis = !VarToCapture;
85 const bool IsCapturingVariable = !IsCapturingThis;
86
87 // Start with the current lambda at the top of the stack (highest index).
88 DeclContext *EnclosingDC =
89 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
90
91 do {
93 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
94 // IF we have climbed down to an intervening enclosing lambda that contains
95 // the variable declaration - it obviously can/must not capture the
96 // variable.
97 // Since its enclosing DC is dependent, all the lambdas between it and the
98 // innermost nested lambda are dependent (otherwise we wouldn't have
99 // arrived here) - so we don't yet have a lambda that can capture the
100 // variable.
101 if (IsCapturingVariable &&
102 VarToCapture->getDeclContext()->Equals(EnclosingDC))
103 return NoLambdaIsCaptureReady;
104
105 // For an enclosing lambda to be capture ready for an entity, all
106 // intervening lambda's have to be able to capture that entity. If even
107 // one of the intervening lambda's is not capable of capturing the entity
108 // then no enclosing lambda can ever capture that entity.
109 // For e.g.
110 // const int x = 10;
111 // [=](auto a) { #1
112 // [](auto b) { #2 <-- an intervening lambda that can never capture 'x'
113 // [=](auto c) { #3
114 // f(x, c); <-- can not lead to x's speculative capture by #1 or #2
115 // }; }; };
116 // If they do not have a default implicit capture, check to see
117 // if the entity has already been explicitly captured.
118 // If even a single dependent enclosing lambda lacks the capability
119 // to ever capture this variable, there is no further enclosing
120 // non-dependent lambda that can capture this variable.
121 if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {
122 if (IsCapturingVariable && !LSI->isCaptured(VarToCapture))
123 return NoLambdaIsCaptureReady;
124 if (IsCapturingThis && !LSI->isCXXThisCaptured())
125 return NoLambdaIsCaptureReady;
126 }
127 EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);
128
129 assert(CurScopeIndex);
130 --CurScopeIndex;
131 } while (!EnclosingDC->isTranslationUnit() &&
132 EnclosingDC->isDependentContext() &&
133 isLambdaCallOperator(EnclosingDC));
134
135 assert(CurScopeIndex < (FunctionScopes.size() - 1));
136 // If the enclosingDC is not dependent, then the immediately nested lambda
137 // (one index above) is capture-ready.
138 if (!EnclosingDC->isDependentContext())
139 return CurScopeIndex + 1;
140 return NoLambdaIsCaptureReady;
141}
142
143/// Examines the FunctionScopeInfo stack to determine the nearest
144/// enclosing lambda (to the current lambda) that is 'capture-capable' for
145/// the variable referenced in the current lambda (i.e. \p VarToCapture).
146/// If successful, returns the index into Sema's FunctionScopeInfo stack
147/// of the capture-capable lambda's LambdaScopeInfo.
148///
149/// Given the current stack of lambdas being processed by Sema and
150/// the variable of interest, to identify the nearest enclosing lambda (to the
151/// current lambda at the top of the stack) that can truly capture
152/// a variable, it has to have the following two properties:
153/// a) 'capture-ready' - be the innermost lambda that is 'capture-ready':
154/// - climb down the stack (i.e. starting from the innermost and examining
155/// each outer lambda step by step) checking if each enclosing
156/// lambda can either implicitly or explicitly capture the variable.
157/// Record the first such lambda that is enclosed in a non-dependent
158/// context. If no such lambda currently exists return failure.
159/// b) 'capture-capable' - make sure the 'capture-ready' lambda can truly
160/// capture the variable by checking all its enclosing lambdas:
161/// - check if all outer lambdas enclosing the 'capture-ready' lambda
162/// identified above in 'a' can also capture the variable (this is done
163/// via tryCaptureVariable for variables and CheckCXXThisCapture for
164/// 'this' by passing in the index of the Lambda identified in step 'a')
165///
166/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
167/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
168/// is at the top of the stack.
169///
170/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
171///
172///
173/// \returns An std::optional<unsigned> Index that if evaluates to 'true'
174/// contains the index (into Sema's FunctionScopeInfo stack) of the innermost
175/// lambda which is capture-capable. If the return value evaluates to 'false'
176/// then no lambda is capture-capable for \p VarToCapture.
177
178std::optional<unsigned>
181 ValueDecl *VarToCapture, Sema &S) {
182
183 const std::optional<unsigned> NoLambdaIsCaptureCapable;
184
185 const std::optional<unsigned> OptionalStackIndex =
187 VarToCapture);
188 if (!OptionalStackIndex)
189 return NoLambdaIsCaptureCapable;
190
191 const unsigned IndexOfCaptureReadyLambda = *OptionalStackIndex;
192 assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||
193 S.getCurGenericLambda()) &&
194 "The capture ready lambda for a potential capture can only be the "
195 "current lambda if it is a generic lambda");
196
197 const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
198 cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);
199
200 // If VarToCapture is null, we are attempting to capture 'this'
201 const bool IsCapturingThis = !VarToCapture;
202 const bool IsCapturingVariable = !IsCapturingThis;
203
204 if (IsCapturingVariable) {
205 // Check if the capture-ready lambda can truly capture the variable, by
206 // checking whether all enclosing lambdas of the capture-ready lambda allow
207 // the capture - i.e. make sure it is capture-capable.
208 QualType CaptureType, DeclRefType;
209 const bool CanCaptureVariable =
210 !S.tryCaptureVariable(VarToCapture,
211 /*ExprVarIsUsedInLoc*/ SourceLocation(),
213 /*EllipsisLoc*/ SourceLocation(),
214 /*BuildAndDiagnose*/ false, CaptureType,
215 DeclRefType, &IndexOfCaptureReadyLambda);
216 if (!CanCaptureVariable)
217 return NoLambdaIsCaptureCapable;
218 } else {
219 // Check if the capture-ready lambda can truly capture 'this' by checking
220 // whether all enclosing lambdas of the capture-ready lambda can capture
221 // 'this'.
222 const bool CanCaptureThis =
224 CaptureReadyLambdaLSI->PotentialThisCaptureLocation,
225 /*Explicit*/ false, /*BuildAndDiagnose*/ false,
226 &IndexOfCaptureReadyLambda);
227 if (!CanCaptureThis)
228 return NoLambdaIsCaptureCapable;
229 }
230 return IndexOfCaptureReadyLambda;
231}
232
233static inline TemplateParameterList *
235 if (!LSI->GLTemplateParameterList && !LSI->TemplateParams.empty()) {
236 LSI->GLTemplateParameterList = TemplateParameterList::Create(
237 SemaRef.Context,
238 /*Template kw loc*/ SourceLocation(),
239 /*L angle loc*/ LSI->ExplicitTemplateParamsRange.getBegin(),
240 LSI->TemplateParams,
241 /*R angle loc*/LSI->ExplicitTemplateParamsRange.getEnd(),
242 LSI->RequiresClause.get());
243 }
244 return LSI->GLTemplateParameterList;
245}
246
249 unsigned LambdaDependencyKind,
250 LambdaCaptureDefault CaptureDefault) {
252 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
253 DC = DC->getParent();
254
255 bool IsGenericLambda =
257 // Start constructing the lambda class.
259 Context, DC, Info, IntroducerRange.getBegin(), LambdaDependencyKind,
260 IsGenericLambda, CaptureDefault);
261 DC->addDecl(Class);
262
263 return Class;
264}
265
266/// Determine whether the given context is or is enclosed in an inline
267/// function.
268static bool isInInlineFunction(const DeclContext *DC) {
269 while (!DC->isFileContext()) {
270 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
271 if (FD->isInlined())
272 return true;
273
274 DC = DC->getLexicalParent();
275 }
276
277 return false;
278}
279
280std::tuple<MangleNumberingContext *, Decl *>
282 // Compute the context for allocating mangling numbers in the current
283 // expression, if the ABI requires them.
284 Decl *ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
285
286 enum ContextKind {
287 Normal,
289 DataMember,
290 InlineVariable,
291 TemplatedVariable,
292 Concept
293 } Kind = Normal;
294
295 bool IsInNonspecializedTemplate =
297
298 // Default arguments of member function parameters that appear in a class
299 // definition, as well as the initializers of data members, receive special
300 // treatment. Identify them.
301 if (ManglingContextDecl) {
302 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
303 if (const DeclContext *LexicalDC
304 = Param->getDeclContext()->getLexicalParent())
305 if (LexicalDC->isRecord())
306 Kind = DefaultArgument;
307 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
308 if (Var->getMostRecentDecl()->isInline())
309 Kind = InlineVariable;
310 else if (Var->getDeclContext()->isRecord() && IsInNonspecializedTemplate)
311 Kind = TemplatedVariable;
312 else if (Var->getDescribedVarTemplate())
313 Kind = TemplatedVariable;
314 else if (auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
315 if (!VTS->isExplicitSpecialization())
316 Kind = TemplatedVariable;
317 }
318 } else if (isa<FieldDecl>(ManglingContextDecl)) {
319 Kind = DataMember;
320 } else if (isa<ImplicitConceptSpecializationDecl>(ManglingContextDecl)) {
321 Kind = Concept;
322 }
323 }
324
325 // Itanium ABI [5.1.7]:
326 // In the following contexts [...] the one-definition rule requires closure
327 // types in different translation units to "correspond":
328 switch (Kind) {
329 case Normal: {
330 // -- the bodies of inline or templated functions
331 if ((IsInNonspecializedTemplate &&
332 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
334 while (auto *CD = dyn_cast<CapturedDecl>(DC))
335 DC = CD->getParent();
336 return std::make_tuple(&Context.getManglingNumberContext(DC), nullptr);
337 }
338
339 return std::make_tuple(nullptr, nullptr);
340 }
341
342 case Concept:
343 // Concept definitions aren't code generated and thus aren't mangled,
344 // however the ManglingContextDecl is important for the purposes of
345 // re-forming the template argument list of the lambda for constraint
346 // evaluation.
347 case DataMember:
348 // -- default member initializers
349 case DefaultArgument:
350 // -- default arguments appearing in class definitions
351 case InlineVariable:
352 case TemplatedVariable:
353 // -- the initializers of inline or templated variables
354 return std::make_tuple(
356 ManglingContextDecl),
357 ManglingContextDecl);
358 }
359
360 llvm_unreachable("unexpected context");
361}
362
363static QualType
365 TemplateParameterList *TemplateParams,
366 TypeSourceInfo *MethodTypeInfo) {
367 assert(MethodTypeInfo && "expected a non null type");
368
369 QualType MethodType = MethodTypeInfo->getType();
370 // If a lambda appears in a dependent context or is a generic lambda (has
371 // template parameters) and has an 'auto' return type, deduce it to a
372 // dependent type.
373 if (Class->isDependentContext() || TemplateParams) {
374 const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
376 if (Result->isUndeducedType()) {
378 MethodType = S.Context.getFunctionType(Result, FPT->getParamTypes(),
379 FPT->getExtProtoInfo());
380 }
381 }
382 return MethodType;
383}
384
385// [C++2b] [expr.prim.lambda.closure] p4
386// Given a lambda with a lambda-capture, the type of the explicit object
387// parameter, if any, of the lambda's function call operator (possibly
388// instantiated from a function call operator template) shall be either:
389// - the closure type,
390// - class type publicly and unambiguously derived from the closure type, or
391// - a reference to a possibly cv-qualified such type.
393 CXXMethodDecl *Method, SourceLocation CallLoc) {
395 return false;
396 CXXRecordDecl *RD = Method->getParent();
397 if (Method->getType()->isDependentType())
398 return false;
399 if (RD->isCapturelessLambda())
400 return false;
401
402 ParmVarDecl *Param = Method->getParamDecl(0);
403 QualType ExplicitObjectParameterType = Param->getType()
407 QualType LambdaType = getASTContext().getRecordType(RD);
408 if (LambdaType == ExplicitObjectParameterType)
409 return false;
410
411 // Don't check the same instantiation twice.
412 //
413 // If this call operator is ill-formed, there is no point in issuing
414 // a diagnostic every time it is called because the problem is in the
415 // definition of the derived type, not at the call site.
416 //
417 // FIXME: Move this check to where we instantiate the method? This should
418 // be possible, but the naive approach of just marking the method as invalid
419 // leads to us emitting more diagnostics than we should have to for this case
420 // (1 error here *and* 1 error about there being no matching overload at the
421 // call site). It might be possible to avoid that by also checking if there
422 // is an empty cast path for the method stored in the context (signalling that
423 // we've already diagnosed it) and then just not building the call, but that
424 // doesn't really seem any simpler than diagnosing it at the call site...
425 if (auto It = Context.LambdaCastPaths.find(Method);
426 It != Context.LambdaCastPaths.end())
427 return It->second.empty();
428
430 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
431 /*DetectVirtual=*/false);
432 if (!IsDerivedFrom(RD->getLocation(), ExplicitObjectParameterType, LambdaType,
433 Paths)) {
434 Diag(Param->getLocation(), diag::err_invalid_explicit_object_type_in_lambda)
435 << ExplicitObjectParameterType;
436 return true;
437 }
438
439 if (Paths.isAmbiguous(LambdaType->getCanonicalTypeUnqualified())) {
440 std::string PathsDisplay = getAmbiguousPathsDisplayString(Paths);
441 Diag(CallLoc, diag::err_explicit_object_lambda_ambiguous_base)
442 << LambdaType << PathsDisplay;
443 return true;
444 }
445
446 if (CheckBaseClassAccess(CallLoc, LambdaType, ExplicitObjectParameterType,
447 Paths.front(),
448 diag::err_explicit_object_lambda_inaccessible_base))
449 return true;
450
451 BuildBasePathArray(Paths, Path);
452 return false;
453}
454
457 std::optional<CXXRecordDecl::LambdaNumbering> NumberingOverride) {
458 if (NumberingOverride) {
459 Class->setLambdaNumbering(*NumberingOverride);
460 return;
461 }
462
463 ContextRAII ManglingContext(*this, Class->getDeclContext());
464
465 auto getMangleNumberingContext =
466 [this](CXXRecordDecl *Class,
467 Decl *ManglingContextDecl) -> MangleNumberingContext * {
468 // Get mangle numbering context if there's any extra decl context.
469 if (ManglingContextDecl)
471 ASTContext::NeedExtraManglingDecl, ManglingContextDecl);
472 // Otherwise, from that lambda's decl context.
473 auto DC = Class->getDeclContext();
474 while (auto *CD = dyn_cast<CapturedDecl>(DC))
475 DC = CD->getParent();
477 };
478
481 std::tie(MCtx, Numbering.ContextDecl) =
482 getCurrentMangleNumberContext(Class->getDeclContext());
483 if (!MCtx && (getLangOpts().CUDA || getLangOpts().SYCLIsDevice ||
484 getLangOpts().SYCLIsHost)) {
485 // Force lambda numbering in CUDA/HIP as we need to name lambdas following
486 // ODR. Both device- and host-compilation need to have a consistent naming
487 // on kernel functions. As lambdas are potential part of these `__global__`
488 // function names, they needs numbering following ODR.
489 // Also force for SYCL, since we need this for the
490 // __builtin_sycl_unique_stable_name implementation, which depends on lambda
491 // mangling.
492 MCtx = getMangleNumberingContext(Class, Numbering.ContextDecl);
493 assert(MCtx && "Retrieving mangle numbering context failed!");
494 Numbering.HasKnownInternalLinkage = true;
495 }
496 if (MCtx) {
497 Numbering.IndexInContext = MCtx->getNextLambdaIndex();
498 Numbering.ManglingNumber = MCtx->getManglingNumber(Method);
499 Numbering.DeviceManglingNumber = MCtx->getDeviceManglingNumber(Method);
500 Class->setLambdaNumbering(Numbering);
501
502 if (auto *Source =
503 dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
504 Source->AssignedLambdaNumbering(Class);
505 }
506}
507
509 CXXMethodDecl *CallOperator,
510 bool ExplicitResultType) {
511 if (ExplicitResultType) {
512 LSI->HasImplicitReturnType = false;
513 LSI->ReturnType = CallOperator->getReturnType();
514 if (!LSI->ReturnType->isDependentType() && !LSI->ReturnType->isVoidType())
515 S.RequireCompleteType(CallOperator->getBeginLoc(), LSI->ReturnType,
516 diag::err_lambda_incomplete_result);
517 } else {
518 LSI->HasImplicitReturnType = true;
519 }
520}
521
523 SourceRange IntroducerRange,
524 LambdaCaptureDefault CaptureDefault,
525 SourceLocation CaptureDefaultLoc,
526 bool ExplicitParams, bool Mutable) {
527 LSI->CallOperator = CallOperator;
528 CXXRecordDecl *LambdaClass = CallOperator->getParent();
529 LSI->Lambda = LambdaClass;
530 if (CaptureDefault == LCD_ByCopy)
531 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
532 else if (CaptureDefault == LCD_ByRef)
533 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
534 LSI->CaptureDefaultLoc = CaptureDefaultLoc;
535 LSI->IntroducerRange = IntroducerRange;
536 LSI->ExplicitParams = ExplicitParams;
537 LSI->Mutable = Mutable;
538}
539
542}
543
545 LambdaIntroducer &Intro, SourceLocation LAngleLoc,
546 ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc,
547 ExprResult RequiresClause) {
549 assert(LSI && "Expected a lambda scope");
550 assert(LSI->NumExplicitTemplateParams == 0 &&
551 "Already acted on explicit template parameters");
552 assert(LSI->TemplateParams.empty() &&
553 "Explicit template parameters should come "
554 "before invented (auto) ones");
555 assert(!TParams.empty() &&
556 "No template parameters to act on");
557 LSI->TemplateParams.append(TParams.begin(), TParams.end());
558 LSI->NumExplicitTemplateParams = TParams.size();
559 LSI->ExplicitTemplateParamsRange = {LAngleLoc, RAngleLoc};
560 LSI->RequiresClause = RequiresClause;
561}
562
563/// If this expression is an enumerator-like expression of some type
564/// T, return the type T; otherwise, return null.
565///
566/// Pointer comparisons on the result here should always work because
567/// it's derived from either the parent of an EnumConstantDecl
568/// (i.e. the definition) or the declaration returned by
569/// EnumType::getDecl() (i.e. the definition).
571 // An expression is an enumerator-like expression of type T if,
572 // ignoring parens and parens-like expressions:
573 E = E->IgnoreParens();
574
575 // - it is an enumerator whose enum type is T or
576 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
578 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
579 return cast<EnumDecl>(D->getDeclContext());
580 }
581 return nullptr;
582 }
583
584 // - it is a comma expression whose RHS is an enumerator-like
585 // expression of type T or
586 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
587 if (BO->getOpcode() == BO_Comma)
588 return findEnumForBlockReturn(BO->getRHS());
589 return nullptr;
590 }
591
592 // - it is a statement-expression whose value expression is an
593 // enumerator-like expression of type T or
594 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
595 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
596 return findEnumForBlockReturn(last);
597 return nullptr;
598 }
599
600 // - it is a ternary conditional operator (not the GNU ?:
601 // extension) whose second and third operands are
602 // enumerator-like expressions of type T or
603 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
604 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
605 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
606 return ED;
607 return nullptr;
608 }
609
610 // (implicitly:)
611 // - it is an implicit integral conversion applied to an
612 // enumerator-like expression of type T or
613 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
614 // We can sometimes see integral conversions in valid
615 // enumerator-like expressions.
616 if (ICE->getCastKind() == CK_IntegralCast)
617 return findEnumForBlockReturn(ICE->getSubExpr());
618
619 // Otherwise, just rely on the type.
620 }
621
622 // - it is an expression of that formal enum type.
623 if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
624 return ET->getDecl();
625 }
626
627 // Otherwise, nope.
628 return nullptr;
629}
630
631/// Attempt to find a type T for which the returned expression of the
632/// given statement is an enumerator-like expression of that type.
634 if (Expr *retValue = ret->getRetValue())
635 return findEnumForBlockReturn(retValue);
636 return nullptr;
637}
638
639/// Attempt to find a common type T for which all of the returned
640/// expressions in a block are enumerator-like expressions of that
641/// type.
643 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
644
645 // Try to find one for the first return.
647 if (!ED) return nullptr;
648
649 // Check that the rest of the returns have the same enum.
650 for (++i; i != e; ++i) {
651 if (findEnumForBlockReturn(*i) != ED)
652 return nullptr;
653 }
654
655 // Never infer an anonymous enum type.
656 if (!ED->hasNameForLinkage()) return nullptr;
657
658 return ED;
659}
660
661/// Adjust the given return statements so that they formally return
662/// the given type. It should require, at most, an IntegralCast.
664 QualType returnType) {
666 i = returns.begin(), e = returns.end(); i != e; ++i) {
667 ReturnStmt *ret = *i;
668 Expr *retValue = ret->getRetValue();
669 if (S.Context.hasSameType(retValue->getType(), returnType))
670 continue;
671
672 // Right now we only support integral fixup casts.
673 assert(returnType->isIntegralOrUnscopedEnumerationType());
674 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
675
676 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
677
678 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
679 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast, E,
680 /*base path*/ nullptr, VK_PRValue,
682 if (cleanups) {
683 cleanups->setSubExpr(E);
684 } else {
685 ret->setRetValue(E);
686 }
687 }
688}
689
691 assert(CSI.HasImplicitReturnType);
692 // If it was ever a placeholder, it had to been deduced to DependentTy.
693 assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
694 assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) &&
695 "lambda expressions use auto deduction in C++14 onwards");
696
697 // C++ core issue 975:
698 // If a lambda-expression does not include a trailing-return-type,
699 // it is as if the trailing-return-type denotes the following type:
700 // - if there are no return statements in the compound-statement,
701 // or all return statements return either an expression of type
702 // void or no expression or braced-init-list, the type void;
703 // - otherwise, if all return statements return an expression
704 // and the types of the returned expressions after
705 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
706 // array-to-pointer conversion (4.2 [conv.array]), and
707 // function-to-pointer conversion (4.3 [conv.func]) are the
708 // same, that common type;
709 // - otherwise, the program is ill-formed.
710 //
711 // C++ core issue 1048 additionally removes top-level cv-qualifiers
712 // from the types of returned expressions to match the C++14 auto
713 // deduction rules.
714 //
715 // In addition, in blocks in non-C++ modes, if all of the return
716 // statements are enumerator-like expressions of some type T, where
717 // T has a name for linkage, then we infer the return type of the
718 // block to be that type.
719
720 // First case: no return statements, implicit void return type.
721 ASTContext &Ctx = getASTContext();
722 if (CSI.Returns.empty()) {
723 // It's possible there were simply no /valid/ return statements.
724 // In this case, the first one we found may have at least given us a type.
725 if (CSI.ReturnType.isNull())
726 CSI.ReturnType = Ctx.VoidTy;
727 return;
728 }
729
730 // Second case: at least one return statement has dependent type.
731 // Delay type checking until instantiation.
732 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
733 if (CSI.ReturnType->isDependentType())
734 return;
735
736 // Try to apply the enum-fuzz rule.
737 if (!getLangOpts().CPlusPlus) {
738 assert(isa<BlockScopeInfo>(CSI));
740 if (ED) {
743 return;
744 }
745 }
746
747 // Third case: only one return statement. Don't bother doing extra work!
748 if (CSI.Returns.size() == 1)
749 return;
750
751 // General case: many return statements.
752 // Check that they all have compatible return types.
753
754 // We require the return types to strictly match here.
755 // Note that we've already done the required promotions as part of
756 // processing the return statement.
757 for (const ReturnStmt *RS : CSI.Returns) {
758 const Expr *RetE = RS->getRetValue();
759
760 QualType ReturnType =
761 (RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType();
762 if (Context.getCanonicalFunctionResultType(ReturnType) ==
764 // Use the return type with the strictest possible nullability annotation.
765 auto RetTyNullability = ReturnType->getNullability();
766 auto BlockNullability = CSI.ReturnType->getNullability();
767 if (BlockNullability &&
768 (!RetTyNullability ||
769 hasWeakerNullability(*RetTyNullability, *BlockNullability)))
770 CSI.ReturnType = ReturnType;
771 continue;
772 }
773
774 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
775 // TODO: It's possible that the *first* return is the divergent one.
776 Diag(RS->getBeginLoc(),
777 diag::err_typecheck_missing_return_type_incompatible)
778 << ReturnType << CSI.ReturnType << isa<LambdaScopeInfo>(CSI);
779 // Continue iterating so that we keep emitting diagnostics.
780 }
781}
782
784 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
785 std::optional<unsigned> NumExpansions, IdentifierInfo *Id,
786 bool IsDirectInit, Expr *&Init) {
787 // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
788 // deduce against.
789 QualType DeductType = Context.getAutoDeductType();
790 TypeLocBuilder TLB;
791 AutoTypeLoc TL = TLB.push<AutoTypeLoc>(DeductType);
792 TL.setNameLoc(Loc);
793 if (ByRef) {
794 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
795 assert(!DeductType.isNull() && "can't build reference to auto");
796 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
797 }
798 if (EllipsisLoc.isValid()) {
799 if (Init->containsUnexpandedParameterPack()) {
800 Diag(EllipsisLoc, getLangOpts().CPlusPlus20
801 ? diag::warn_cxx17_compat_init_capture_pack
802 : diag::ext_init_capture_pack);
803 DeductType = Context.getPackExpansionType(DeductType, NumExpansions,
804 /*ExpectPackInType=*/false);
805 TLB.push<PackExpansionTypeLoc>(DeductType).setEllipsisLoc(EllipsisLoc);
806 } else {
807 // Just ignore the ellipsis for now and form a non-pack variable. We'll
808 // diagnose this later when we try to capture it.
809 }
810 }
811 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
812
813 // Deduce the type of the init capture.
815 /*VarDecl*/nullptr, DeclarationName(Id), DeductType, TSI,
816 SourceRange(Loc, Loc), IsDirectInit, Init);
817 if (DeducedType.isNull())
818 return QualType();
819
820 // Are we a non-list direct initialization?
821 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
822
823 // Perform initialization analysis and ensure any implicit conversions
824 // (such as lvalue-to-rvalue) are enforced.
825 InitializedEntity Entity =
827 InitializationKind Kind =
828 IsDirectInit
829 ? (CXXDirectInit ? InitializationKind::CreateDirect(
830 Loc, Init->getBeginLoc(), Init->getEndLoc())
832 : InitializationKind::CreateCopy(Loc, Init->getBeginLoc());
833
834 MultiExprArg Args = Init;
835 if (CXXDirectInit)
836 Args =
837 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
838 QualType DclT;
839 InitializationSequence InitSeq(*this, Entity, Kind, Args);
840 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
841
842 if (Result.isInvalid())
843 return QualType();
844
845 Init = Result.getAs<Expr>();
846 return DeducedType;
847}
848
850 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
851 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx) {
852 // FIXME: Retain the TypeSourceInfo from buildLambdaInitCaptureInitialization
853 // rather than reconstructing it here.
854 TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType, Loc);
855 if (auto PETL = TSI->getTypeLoc().getAs<PackExpansionTypeLoc>())
856 PETL.setEllipsisLoc(EllipsisLoc);
857
858 // Create a dummy variable representing the init-capture. This is not actually
859 // used as a variable, and only exists as a way to name and refer to the
860 // init-capture.
861 // FIXME: Pass in separate source locations for '&' and identifier.
862 VarDecl *NewVD = VarDecl::Create(Context, DeclCtx, Loc, Loc, Id,
863 InitCaptureType, TSI, SC_Auto);
864 NewVD->setInitCapture(true);
865 NewVD->setReferenced(true);
866 // FIXME: Pass in a VarDecl::InitializationStyle.
867 NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));
868 NewVD->markUsed(Context);
869 NewVD->setInit(Init);
870 if (NewVD->isParameterPack())
871 getCurLambda()->LocalPacks.push_back(NewVD);
872 return NewVD;
873}
874
875void Sema::addInitCapture(LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef) {
876 assert(Var->isInitCapture() && "init capture flag should be set");
877 LSI->addCapture(Var, /*isBlock=*/false, ByRef,
878 /*isNested=*/false, Var->getLocation(), SourceLocation(),
879 Var->getType(), /*Invalid=*/false);
880}
881
882// Unlike getCurLambda, getCurrentLambdaScopeUnsafe doesn't
883// check that the current lambda is in a consistent or fully constructed state.
885 assert(!S.FunctionScopes.empty());
886 return cast<LambdaScopeInfo>(S.FunctionScopes[S.FunctionScopes.size() - 1]);
887}
888
889static TypeSourceInfo *
891 // C++11 [expr.prim.lambda]p4:
892 // If a lambda-expression does not include a lambda-declarator, it is as
893 // if the lambda-declarator were ().
895 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
896 EPI.HasTrailingReturn = true;
897 EPI.TypeQuals.addConst();
899 if (AS != LangAS::Default)
901
902 // C++1y [expr.prim.lambda]:
903 // The lambda return type is 'auto', which is replaced by the
904 // trailing-return type if provided and/or deduced from 'return'
905 // statements
906 // We don't do this before C++1y, because we don't support deduced return
907 // types there.
908 QualType DefaultTypeForNoTrailingReturn = S.getLangOpts().CPlusPlus14
911 QualType MethodTy = S.Context.getFunctionType(DefaultTypeForNoTrailingReturn,
912 std::nullopt, EPI);
913 return S.Context.getTrivialTypeSourceInfo(MethodTy, Loc);
914}
915
917 Declarator &ParamInfo, Scope *CurScope,
919 bool &ExplicitResultType) {
920
921 ExplicitResultType = false;
922
923 assert(
924 (ParamInfo.getDeclSpec().getStorageClassSpec() ==
927 "Unexpected storage specifier");
928 bool IsLambdaStatic =
930
931 TypeSourceInfo *MethodTyInfo;
932
933 if (ParamInfo.getNumTypeObjects() == 0) {
934 MethodTyInfo = getDummyLambdaType(S, Loc);
935 } else {
936 // Check explicit parameters
937 S.CheckExplicitObjectLambda(ParamInfo);
938
940
941 bool HasExplicitObjectParameter =
943
944 ExplicitResultType = FTI.hasTrailingReturnType();
945 if (!FTI.hasMutableQualifier() && !IsLambdaStatic &&
946 !HasExplicitObjectParameter)
948
949 if (ExplicitResultType && S.getLangOpts().HLSL) {
950 QualType RetTy = FTI.getTrailingReturnType().get();
951 if (!RetTy.isNull()) {
952 // HLSL does not support specifying an address space on a lambda return
953 // type.
954 LangAS AddressSpace = RetTy.getAddressSpace();
955 if (AddressSpace != LangAS::Default)
957 diag::err_return_value_with_address_space);
958 }
959 }
960
961 MethodTyInfo = S.GetTypeForDeclarator(ParamInfo);
962 assert(MethodTyInfo && "no type from lambda-declarator");
963
964 // Check for unexpanded parameter packs in the method type.
965 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
966 S.DiagnoseUnexpandedParameterPack(Intro.Range.getBegin(), MethodTyInfo,
968 }
969 return MethodTyInfo;
970}
971
974
975 // C++20 [expr.prim.lambda.closure]p3:
976 // The closure type for a lambda-expression has a public inline function
977 // call operator (for a non-generic lambda) or function call operator
978 // template (for a generic lambda) whose parameters and return type are
979 // described by the lambda-expression's parameter-declaration-clause
980 // and trailing-return-type respectively.
981 DeclarationName MethodName =
983 DeclarationNameLoc MethodNameLoc =
987 DeclarationNameInfo(MethodName, IntroducerRange.getBegin(),
988 MethodNameLoc),
989 QualType(), /*Tinfo=*/nullptr, SC_None,
990 getCurFPFeatures().isFPConstrained(),
992 /*TrailingRequiresClause=*/nullptr);
993 Method->setAccess(AS_public);
994 return Method;
995}
996
998 CXXMethodDecl *CallOperator, CXXRecordDecl *Class,
999 TemplateParameterList *TemplateParams) {
1000 assert(TemplateParams && "no template parameters");
1002 Context, Class, CallOperator->getLocation(), CallOperator->getDeclName(),
1003 TemplateParams, CallOperator);
1004 TemplateMethod->setAccess(AS_public);
1005 CallOperator->setDescribedFunctionTemplate(TemplateMethod);
1006}
1007
1009 CXXMethodDecl *Method, SourceLocation LambdaLoc,
1010 SourceLocation CallOperatorLoc, Expr *TrailingRequiresClause,
1011 TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind,
1013 bool HasExplicitResultType) {
1014
1016
1017 if (TrailingRequiresClause)
1018 Method->setTrailingRequiresClause(TrailingRequiresClause);
1019
1020 TemplateParameterList *TemplateParams =
1022
1023 DeclContext *DC = Method->getLexicalDeclContext();
1024 // DeclContext::addDecl() assumes that the DeclContext we're adding to is the
1025 // lexical context of the Method. Do so.
1026 Method->setLexicalDeclContext(LSI->Lambda);
1027 if (TemplateParams) {
1028 FunctionTemplateDecl *TemplateMethod =
1030 assert(TemplateMethod &&
1031 "AddTemplateParametersToLambdaCallOperator should have been called");
1032
1033 LSI->Lambda->addDecl(TemplateMethod);
1034 TemplateMethod->setLexicalDeclContext(DC);
1035 } else {
1036 LSI->Lambda->addDecl(Method);
1037 }
1038 LSI->Lambda->setLambdaIsGeneric(TemplateParams);
1039 LSI->Lambda->setLambdaTypeInfo(MethodTyInfo);
1040
1041 Method->setLexicalDeclContext(DC);
1042 Method->setLocation(LambdaLoc);
1043 Method->setInnerLocStart(CallOperatorLoc);
1044 Method->setTypeSourceInfo(MethodTyInfo);
1045 Method->setType(buildTypeForLambdaCallOperator(*this, LSI->Lambda,
1046 TemplateParams, MethodTyInfo));
1047 Method->setConstexprKind(ConstexprKind);
1048 Method->setStorageClass(SC);
1049 if (!Params.empty()) {
1050 CheckParmsForFunctionDef(Params, /*CheckParameterNames=*/false);
1051 Method->setParams(Params);
1052 for (auto P : Method->parameters()) {
1053 assert(P && "null in a parameter list");
1054 P->setOwningFunction(Method);
1055 }
1056 }
1057
1058 buildLambdaScopeReturnType(*this, LSI, Method, HasExplicitResultType);
1059}
1060
1062 Scope *CurrentScope) {
1063
1065 assert(LSI && "LambdaScopeInfo should be on stack!");
1066
1067 if (Intro.Default == LCD_ByCopy)
1068 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
1069 else if (Intro.Default == LCD_ByRef)
1070 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
1071 LSI->CaptureDefaultLoc = Intro.DefaultLoc;
1072 LSI->IntroducerRange = Intro.Range;
1073 LSI->AfterParameterList = false;
1074
1075 assert(LSI->NumExplicitTemplateParams == 0);
1076
1077 // Determine if we're within a context where we know that the lambda will
1078 // be dependent, because there are template parameters in scope.
1079 CXXRecordDecl::LambdaDependencyKind LambdaDependencyKind =
1081 if (CurScope->getTemplateParamParent() != nullptr) {
1082 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
1083 } else if (Scope *P = CurScope->getParent()) {
1084 // Given a lambda defined inside a requires expression,
1085 //
1086 // struct S {
1087 // S(auto var) requires requires { [&] -> decltype(var) { }; }
1088 // {}
1089 // };
1090 //
1091 // The parameter var is not injected into the function Decl at the point of
1092 // parsing lambda. In such scenarios, perceiving it as dependent could
1093 // result in the constraint being evaluated, which matches what GCC does.
1094 while (P->getEntity() && P->getEntity()->isRequiresExprBody())
1095 P = P->getParent();
1096 if (P->isFunctionDeclarationScope() &&
1097 llvm::any_of(P->decls(), [](Decl *D) {
1098 return isa<ParmVarDecl>(D) &&
1099 cast<ParmVarDecl>(D)->getType()->isTemplateTypeParmType();
1100 }))
1101 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
1102 }
1103
1105 Intro.Range, /*Info=*/nullptr, LambdaDependencyKind, Intro.Default);
1106 LSI->Lambda = Class;
1107
1109 LSI->CallOperator = Method;
1110 // Temporarily set the lexical declaration context to the current
1111 // context, so that the Scope stack matches the lexical nesting.
1113
1114 PushDeclContext(CurScope, Method);
1115
1116 bool ContainsUnexpandedParameterPack = false;
1117
1118 // Distinct capture names, for diagnostics.
1119 llvm::DenseMap<IdentifierInfo *, ValueDecl *> CaptureNames;
1120
1121 // Handle explicit captures.
1122 SourceLocation PrevCaptureLoc =
1123 Intro.Default == LCD_None ? Intro.Range.getBegin() : Intro.DefaultLoc;
1124 for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;
1125 PrevCaptureLoc = C->Loc, ++C) {
1126 if (C->Kind == LCK_This || C->Kind == LCK_StarThis) {
1127 if (C->Kind == LCK_StarThis)
1128 Diag(C->Loc, !getLangOpts().CPlusPlus17
1129 ? diag::ext_star_this_lambda_capture_cxx17
1130 : diag::warn_cxx14_compat_star_this_lambda_capture);
1131
1132 // C++11 [expr.prim.lambda]p8:
1133 // An identifier or this shall not appear more than once in a
1134 // lambda-capture.
1135 if (LSI->isCXXThisCaptured()) {
1136 Diag(C->Loc, diag::err_capture_more_than_once)
1137 << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())
1139 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1140 continue;
1141 }
1142
1143 // C++20 [expr.prim.lambda]p8:
1144 // If a lambda-capture includes a capture-default that is =,
1145 // each simple-capture of that lambda-capture shall be of the form
1146 // "&identifier", "this", or "* this". [ Note: The form [&,this] is
1147 // redundant but accepted for compatibility with ISO C++14. --end note ]
1148 if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis)
1149 Diag(C->Loc, !getLangOpts().CPlusPlus20
1150 ? diag::ext_equals_this_lambda_capture_cxx20
1151 : diag::warn_cxx17_compat_equals_this_lambda_capture);
1152
1153 // C++11 [expr.prim.lambda]p12:
1154 // If this is captured by a local lambda expression, its nearest
1155 // enclosing function shall be a non-static member function.
1156 QualType ThisCaptureType = getCurrentThisType();
1157 if (ThisCaptureType.isNull()) {
1158 Diag(C->Loc, diag::err_this_capture) << true;
1159 continue;
1160 }
1161
1162 CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true,
1163 /*FunctionScopeIndexToStopAtPtr*/ nullptr,
1164 C->Kind == LCK_StarThis);
1165 if (!LSI->Captures.empty())
1166 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1167 continue;
1168 }
1169
1170 assert(C->Id && "missing identifier for capture");
1171
1172 if (C->Init.isInvalid())
1173 continue;
1174
1175 ValueDecl *Var = nullptr;
1176 if (C->Init.isUsable()) {
1178 ? diag::warn_cxx11_compat_init_capture
1179 : diag::ext_init_capture);
1180
1181 // If the initializer expression is usable, but the InitCaptureType
1182 // is not, then an error has occurred - so ignore the capture for now.
1183 // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
1184 // FIXME: we should create the init capture variable and mark it invalid
1185 // in this case.
1186 if (C->InitCaptureType.get().isNull())
1187 continue;
1188
1189 if (C->Init.get()->containsUnexpandedParameterPack() &&
1190 !C->InitCaptureType.get()->getAs<PackExpansionType>())
1192
1193 unsigned InitStyle;
1194 switch (C->InitKind) {
1196 llvm_unreachable("not an init-capture?");
1198 InitStyle = VarDecl::CInit;
1199 break;
1201 InitStyle = VarDecl::CallInit;
1202 break;
1204 InitStyle = VarDecl::ListInit;
1205 break;
1206 }
1207 Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
1208 C->EllipsisLoc, C->Id, InitStyle,
1209 C->Init.get(), Method);
1210 assert(Var && "createLambdaInitCaptureVarDecl returned a null VarDecl?");
1211 if (auto *V = dyn_cast<VarDecl>(Var))
1212 CheckShadow(CurrentScope, V);
1213 PushOnScopeChains(Var, CurrentScope, false);
1214 } else {
1215 assert(C->InitKind == LambdaCaptureInitKind::NoInit &&
1216 "init capture has valid but null init?");
1217
1218 // C++11 [expr.prim.lambda]p8:
1219 // If a lambda-capture includes a capture-default that is &, the
1220 // identifiers in the lambda-capture shall not be preceded by &.
1221 // If a lambda-capture includes a capture-default that is =, [...]
1222 // each identifier it contains shall be preceded by &.
1223 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
1224 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
1226 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1227 continue;
1228 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
1229 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
1231 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1232 continue;
1233 }
1234
1235 // C++11 [expr.prim.lambda]p10:
1236 // The identifiers in a capture-list are looked up using the usual
1237 // rules for unqualified name lookup (3.4.1)
1238 DeclarationNameInfo Name(C->Id, C->Loc);
1239 LookupResult R(*this, Name, LookupOrdinaryName);
1240 LookupName(R, CurScope);
1241 if (R.isAmbiguous())
1242 continue;
1243 if (R.empty()) {
1244 // FIXME: Disable corrections that would add qualification?
1245 CXXScopeSpec ScopeSpec;
1246 DeclFilterCCC<VarDecl> Validator{};
1247 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
1248 continue;
1249 }
1250
1251 if (auto *BD = R.getAsSingle<BindingDecl>())
1252 Var = BD;
1253 else if (R.getAsSingle<FieldDecl>()) {
1254 Diag(C->Loc, diag::err_capture_class_member_does_not_name_variable)
1255 << C->Id;
1256 continue;
1257 } else
1258 Var = R.getAsSingle<VarDecl>();
1259 if (Var && DiagnoseUseOfDecl(Var, C->Loc))
1260 continue;
1261 }
1262
1263 // C++11 [expr.prim.lambda]p10:
1264 // [...] each such lookup shall find a variable with automatic storage
1265 // duration declared in the reaching scope of the local lambda expression.
1266 // Note that the 'reaching scope' check happens in tryCaptureVariable().
1267 if (!Var) {
1268 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
1269 continue;
1270 }
1271
1272 // C++11 [expr.prim.lambda]p8:
1273 // An identifier or this shall not appear more than once in a
1274 // lambda-capture.
1275 if (auto [It, Inserted] = CaptureNames.insert(std::pair{C->Id, Var});
1276 !Inserted) {
1277 if (C->InitKind == LambdaCaptureInitKind::NoInit &&
1278 !Var->isInitCapture()) {
1279 Diag(C->Loc, diag::err_capture_more_than_once)
1280 << C->Id << It->second->getBeginLoc()
1282 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1283 Var->setInvalidDecl();
1284 } else if (Var && Var->isPlaceholderVar(getLangOpts())) {
1286 } else {
1287 // Previous capture captured something different (one or both was
1288 // an init-capture): no fixit.
1289 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
1290 continue;
1291 }
1292 }
1293
1294 // Ignore invalid decls; they'll just confuse the code later.
1295 if (Var->isInvalidDecl())
1296 continue;
1297
1298 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
1299
1300 if (!Underlying->hasLocalStorage()) {
1301 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
1302 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
1303 continue;
1304 }
1305
1306 // C++11 [expr.prim.lambda]p23:
1307 // A capture followed by an ellipsis is a pack expansion (14.5.3).
1308 SourceLocation EllipsisLoc;
1309 if (C->EllipsisLoc.isValid()) {
1310 if (Var->isParameterPack()) {
1311 EllipsisLoc = C->EllipsisLoc;
1312 } else {
1313 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1314 << (C->Init.isUsable() ? C->Init.get()->getSourceRange()
1315 : SourceRange(C->Loc));
1316
1317 // Just ignore the ellipsis.
1318 }
1319 } else if (Var->isParameterPack()) {
1320 ContainsUnexpandedParameterPack = true;
1321 }
1322
1323 if (C->Init.isUsable()) {
1324 addInitCapture(LSI, cast<VarDecl>(Var), C->Kind == LCK_ByRef);
1325 PushOnScopeChains(Var, CurScope, false);
1326 } else {
1329 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
1330 }
1331 if (!LSI->Captures.empty())
1332 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1333 }
1335 LSI->ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
1337}
1338
1340 SourceLocation MutableLoc) {
1341
1343 LSI->Mutable = MutableLoc.isValid();
1344 ContextRAII Context(*this, LSI->CallOperator, /*NewThisContext*/ false);
1345
1346 // C++11 [expr.prim.lambda]p9:
1347 // A lambda-expression whose smallest enclosing scope is a block scope is a
1348 // local lambda expression; any other lambda expression shall not have a
1349 // capture-default or simple-capture in its lambda-introducer.
1350 //
1351 // For simple-captures, this is covered by the check below that any named
1352 // entity is a variable that can be captured.
1353 //
1354 // For DR1632, we also allow a capture-default in any context where we can
1355 // odr-use 'this' (in particular, in a default initializer for a non-static
1356 // data member).
1357 if (Intro.Default != LCD_None &&
1358 !LSI->Lambda->getParent()->isFunctionOrMethod() &&
1359 (getCurrentThisType().isNull() ||
1360 CheckCXXThisCapture(SourceLocation(), /*Explicit=*/true,
1361 /*BuildAndDiagnose=*/false)))
1362 Diag(Intro.DefaultLoc, diag::err_capture_default_non_local);
1363}
1364
1368 PushDeclContext(LambdaScope, LSI->CallOperator);
1369
1370 for (const DeclaratorChunk::ParamInfo &P : Params) {
1371 auto *Param = cast<ParmVarDecl>(P.Param);
1372 Param->setOwningFunction(LSI->CallOperator);
1373 if (Param->getIdentifier())
1374 PushOnScopeChains(Param, LambdaScope, false);
1375 }
1376
1377 // After the parameter list, we may parse a noexcept/requires/trailing return
1378 // type which need to know whether the call operator constiture a dependent
1379 // context, so we need to setup the FunctionTemplateDecl of generic lambdas
1380 // now.
1381 TemplateParameterList *TemplateParams =
1383 if (TemplateParams) {
1385 TemplateParams);
1386 LSI->Lambda->setLambdaIsGeneric(true);
1388 TemplateParams->containsUnexpandedParameterPack();
1389 }
1390 LSI->AfterParameterList = true;
1391}
1392
1394 Declarator &ParamInfo,
1395 const DeclSpec &DS) {
1396
1399
1401 bool ExplicitResultType;
1402
1403 SourceLocation TypeLoc, CallOperatorLoc;
1404 if (ParamInfo.getNumTypeObjects() == 0) {
1405 CallOperatorLoc = TypeLoc = Intro.Range.getEnd();
1406 } else {
1407 unsigned Index;
1408 ParamInfo.isFunctionDeclarator(Index);
1409 const auto &Object = ParamInfo.getTypeObject(Index);
1410 TypeLoc =
1411 Object.Loc.isValid() ? Object.Loc : ParamInfo.getSourceRange().getEnd();
1412 CallOperatorLoc = ParamInfo.getSourceRange().getEnd();
1413 }
1414
1415 CXXRecordDecl *Class = LSI->Lambda;
1416 CXXMethodDecl *Method = LSI->CallOperator;
1417
1418 TypeSourceInfo *MethodTyInfo = getLambdaType(
1419 *this, Intro, ParamInfo, getCurScope(), TypeLoc, ExplicitResultType);
1420
1421 LSI->ExplicitParams = ParamInfo.getNumTypeObjects() != 0;
1422
1423 if (ParamInfo.isFunctionDeclarator() != 0 &&
1425 const auto &FTI = ParamInfo.getFunctionTypeInfo();
1426 Params.reserve(Params.size());
1427 for (unsigned I = 0; I < FTI.NumParams; ++I) {
1428 auto *Param = cast<ParmVarDecl>(FTI.Params[I].Param);
1429 Param->setScopeInfo(0, Params.size());
1430 Params.push_back(Param);
1431 }
1432 }
1433
1434 bool IsLambdaStatic =
1436
1438 Method, Intro.Range.getBegin(), CallOperatorLoc,
1439 ParamInfo.getTrailingRequiresClause(), MethodTyInfo,
1440 ParamInfo.getDeclSpec().getConstexprSpecifier(),
1441 IsLambdaStatic ? SC_Static : SC_None, Params, ExplicitResultType);
1442
1444
1445 // This represents the function body for the lambda function, check if we
1446 // have to apply optnone due to a pragma.
1447 AddRangeBasedOptnone(Method);
1448
1449 // code_seg attribute on lambda apply to the method.
1451 Method, /*IsDefinition=*/true))
1452 Method->addAttr(A);
1453
1454 // Attributes on the lambda apply to the method.
1455 ProcessDeclAttributes(CurScope, Method, ParamInfo);
1456
1457 // CUDA lambdas get implicit host and device attributes.
1458 if (getLangOpts().CUDA)
1459 CUDA().SetLambdaAttrs(Method);
1460
1461 // OpenMP lambdas might get assumumption attributes.
1462 if (LangOpts.OpenMP)
1464
1466
1467 for (auto &&C : LSI->Captures) {
1468 if (!C.isVariableCapture())
1469 continue;
1470 ValueDecl *Var = C.getVariable();
1471 if (Var && Var->isInitCapture()) {
1472 PushOnScopeChains(Var, CurScope, false);
1473 }
1474 }
1475
1476 auto CheckRedefinition = [&](ParmVarDecl *Param) {
1477 for (const auto &Capture : Intro.Captures) {
1478 if (Capture.Id == Param->getIdentifier()) {
1479 Diag(Param->getLocation(), diag::err_parameter_shadow_capture);
1480 Diag(Capture.Loc, diag::note_var_explicitly_captured_here)
1481 << Capture.Id << true;
1482 return false;
1483 }
1484 }
1485 return true;
1486 };
1487
1488 for (ParmVarDecl *P : Params) {
1489 if (!P->getIdentifier())
1490 continue;
1491 if (CheckRedefinition(P))
1492 CheckShadow(CurScope, P);
1493 PushOnScopeChains(P, CurScope);
1494 }
1495
1496 // C++23 [expr.prim.lambda.capture]p5:
1497 // If an identifier in a capture appears as the declarator-id of a parameter
1498 // of the lambda-declarator's parameter-declaration-clause or as the name of a
1499 // template parameter of the lambda-expression's template-parameter-list, the
1500 // program is ill-formed.
1501 TemplateParameterList *TemplateParams =
1503 if (TemplateParams) {
1504 for (const auto *TP : TemplateParams->asArray()) {
1505 if (!TP->getIdentifier())
1506 continue;
1507 for (const auto &Capture : Intro.Captures) {
1508 if (Capture.Id == TP->getIdentifier()) {
1509 Diag(Capture.Loc, diag::err_template_param_shadow) << Capture.Id;
1511 }
1512 }
1513 }
1514 }
1515
1516 // C++20: dcl.decl.general p4:
1517 // The optional requires-clause ([temp.pre]) in an init-declarator or
1518 // member-declarator shall be present only if the declarator declares a
1519 // templated function ([dcl.fct]).
1520 if (Expr *TRC = Method->getTrailingRequiresClause()) {
1521 // [temp.pre]/8:
1522 // An entity is templated if it is
1523 // - a template,
1524 // - an entity defined ([basic.def]) or created ([class.temporary]) in a
1525 // templated entity,
1526 // - a member of a templated entity,
1527 // - an enumerator for an enumeration that is a templated entity, or
1528 // - the closure type of a lambda-expression ([expr.prim.lambda.closure])
1529 // appearing in the declaration of a templated entity. [Note 6: A local
1530 // class, a local or block variable, or a friend function defined in a
1531 // templated entity is a templated entity. — end note]
1532 //
1533 // A templated function is a function template or a function that is
1534 // templated. A templated class is a class template or a class that is
1535 // templated. A templated variable is a variable template or a variable
1536 // that is templated.
1537
1538 // Note: we only have to check if this is defined in a template entity, OR
1539 // if we are a template, since the rest don't apply. The requires clause
1540 // applies to the call operator, which we already know is a member function,
1541 // AND defined.
1542 if (!Method->getDescribedFunctionTemplate() && !Method->isTemplated()) {
1543 Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
1544 }
1545 }
1546
1547 // Enter a new evaluation context to insulate the lambda from any
1548 // cleanups from the enclosing full-expression.
1553 ExprEvalContexts.back().InImmediateFunctionContext =
1554 LSI->CallOperator->isConsteval();
1555 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
1556 getLangOpts().CPlusPlus20 && LSI->CallOperator->isImmediateEscalating();
1557}
1558
1560 bool IsInstantiation) {
1561 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(FunctionScopes.back());
1562
1563 // Leave the expression-evaluation context.
1566
1567 // Leave the context of the lambda.
1568 if (!IsInstantiation)
1570
1571 // Finalize the lambda.
1572 CXXRecordDecl *Class = LSI->Lambda;
1573 Class->setInvalidDecl();
1574 SmallVector<Decl*, 4> Fields(Class->fields());
1575 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
1577 CheckCompletedCXXClass(nullptr, Class);
1578
1580}
1581
1582template <typename Func>
1584 Sema &S, const FunctionProtoType &CallOpProto, Func F) {
1586 CallOpProto.isVariadic(), /*IsCXXMethod=*/false);
1588 CallOpProto.isVariadic(), /*IsCXXMethod=*/true);
1589 CallingConv CallOpCC = CallOpProto.getCallConv();
1590
1591 /// Implement emitting a version of the operator for many of the calling
1592 /// conventions for MSVC, as described here:
1593 /// https://devblogs.microsoft.com/oldnewthing/20150220-00/?p=44623.
1594 /// Experimentally, we determined that cdecl, stdcall, fastcall, and
1595 /// vectorcall are generated by MSVC when it is supported by the target.
1596 /// Additionally, we are ensuring that the default-free/default-member and
1597 /// call-operator calling convention are generated as well.
1598 /// NOTE: We intentionally generate a 'thiscall' on Win32 implicitly from the
1599 /// 'member default', despite MSVC not doing so. We do this in order to ensure
1600 /// that someone who intentionally places 'thiscall' on the lambda call
1601 /// operator will still get that overload, since we don't have the a way of
1602 /// detecting the attribute by the time we get here.
1603 if (S.getLangOpts().MSVCCompat) {
1604 CallingConv Convs[] = {
1606 DefaultFree, DefaultMember, CallOpCC};
1607 llvm::sort(Convs);
1608 llvm::iterator_range<CallingConv *> Range(
1609 std::begin(Convs), std::unique(std::begin(Convs), std::end(Convs)));
1610 const TargetInfo &TI = S.getASTContext().getTargetInfo();
1611
1612 for (CallingConv C : Range) {
1614 F(C);
1615 }
1616 return;
1617 }
1618
1619 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree) {
1620 F(DefaultFree);
1621 F(DefaultMember);
1622 } else {
1623 F(CallOpCC);
1624 }
1625}
1626
1627// Returns the 'standard' calling convention to be used for the lambda
1628// conversion function, that is, the 'free' function calling convention unless
1629// it is overridden by a non-default calling convention attribute.
1630static CallingConv
1632 const FunctionProtoType *CallOpProto) {
1634 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
1636 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
1637 CallingConv CallOpCC = CallOpProto->getCallConv();
1638
1639 // If the call-operator hasn't been changed, return both the 'free' and
1640 // 'member' function calling convention.
1641 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree)
1642 return DefaultFree;
1643 return CallOpCC;
1644}
1645
1647 const FunctionProtoType *CallOpProto, CallingConv CC) {
1648 const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
1649 CallOpProto->getExtProtoInfo();
1650 FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
1651 InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
1652 InvokerExtInfo.TypeQuals = Qualifiers();
1653 assert(InvokerExtInfo.RefQualifier == RQ_None &&
1654 "Lambda's call operator should not have a reference qualifier");
1655 return Context.getFunctionType(CallOpProto->getReturnType(),
1656 CallOpProto->getParamTypes(), InvokerExtInfo);
1657}
1658
1659/// Add a lambda's conversion to function pointer, as described in
1660/// C++11 [expr.prim.lambda]p6.
1661static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange,
1663 CXXMethodDecl *CallOperator,
1664 QualType InvokerFunctionTy) {
1665 // This conversion is explicitly disabled if the lambda's function has
1666 // pass_object_size attributes on any of its parameters.
1667 auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) {
1668 return P->hasAttr<PassObjectSizeAttr>();
1669 };
1670 if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr))
1671 return;
1672
1673 // Add the conversion to function pointer.
1674 QualType PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
1675
1676 // Create the type of the conversion function.
1679 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1680 // The conversion function is always const and noexcept.
1681 ConvExtInfo.TypeQuals = Qualifiers();
1682 ConvExtInfo.TypeQuals.addConst();
1683 ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept;
1684 QualType ConvTy =
1685 S.Context.getFunctionType(PtrToFunctionTy, std::nullopt, ConvExtInfo);
1686
1687 SourceLocation Loc = IntroducerRange.getBegin();
1688 DeclarationName ConversionName
1690 S.Context.getCanonicalType(PtrToFunctionTy));
1691 // Construct a TypeSourceInfo for the conversion function, and wire
1692 // all the parameters appropriately for the FunctionProtoTypeLoc
1693 // so that everything works during transformation/instantiation of
1694 // generic lambdas.
1695 // The main reason for wiring up the parameters of the conversion
1696 // function with that of the call operator is so that constructs
1697 // like the following work:
1698 // auto L = [](auto b) { <-- 1
1699 // return [](auto a) -> decltype(a) { <-- 2
1700 // return a;
1701 // };
1702 // };
1703 // int (*fp)(int) = L(5);
1704 // Because the trailing return type can contain DeclRefExprs that refer
1705 // to the original call operator's variables, we hijack the call
1706 // operators ParmVarDecls below.
1707 TypeSourceInfo *ConvNamePtrToFunctionTSI =
1708 S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
1709 DeclarationNameLoc ConvNameLoc =
1710 DeclarationNameLoc::makeNamedTypeLoc(ConvNamePtrToFunctionTSI);
1711
1712 // The conversion function is a conversion to a pointer-to-function.
1713 TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
1714 FunctionProtoTypeLoc ConvTL =
1716 // Get the result of the conversion function which is a pointer-to-function.
1717 PointerTypeLoc PtrToFunctionTL =
1718 ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
1719 // Do the same for the TypeSourceInfo that is used to name the conversion
1720 // operator.
1721 PointerTypeLoc ConvNamePtrToFunctionTL =
1722 ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
1723
1724 // Get the underlying function types that the conversion function will
1725 // be converting to (should match the type of the call operator).
1726 FunctionProtoTypeLoc CallOpConvTL =
1727 PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1728 FunctionProtoTypeLoc CallOpConvNameTL =
1729 ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1730
1731 // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1732 // These parameter's are essentially used to transform the name and
1733 // the type of the conversion operator. By using the same parameters
1734 // as the call operator's we don't have to fix any back references that
1735 // the trailing return type of the call operator's uses (such as
1736 // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1737 // - we can simply use the return type of the call operator, and
1738 // everything should work.
1739 SmallVector<ParmVarDecl *, 4> InvokerParams;
1740 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1741 ParmVarDecl *From = CallOperator->getParamDecl(I);
1742
1743 InvokerParams.push_back(ParmVarDecl::Create(
1744 S.Context,
1745 // Temporarily add to the TU. This is set to the invoker below.
1747 From->getLocation(), From->getIdentifier(), From->getType(),
1748 From->getTypeSourceInfo(), From->getStorageClass(),
1749 /*DefArg=*/nullptr));
1750 CallOpConvTL.setParam(I, From);
1751 CallOpConvNameTL.setParam(I, From);
1752 }
1753
1755 S.Context, Class, Loc,
1756 DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), ConvTy, ConvTSI,
1758 /*isInline=*/true, ExplicitSpecifier(),
1761 CallOperator->getBody()->getEndLoc());
1762 Conversion->setAccess(AS_public);
1763 Conversion->setImplicit(true);
1764
1765 // A non-generic lambda may still be a templated entity. We need to preserve
1766 // constraints when converting the lambda to a function pointer. See GH63181.
1767 if (Expr *Requires = CallOperator->getTrailingRequiresClause())
1768 Conversion->setTrailingRequiresClause(Requires);
1769
1770 if (Class->isGenericLambda()) {
1771 // Create a template version of the conversion operator, using the template
1772 // parameter list of the function call operator.
1773 FunctionTemplateDecl *TemplateCallOperator =
1774 CallOperator->getDescribedFunctionTemplate();
1775 FunctionTemplateDecl *ConversionTemplate =
1777 Loc, ConversionName,
1778 TemplateCallOperator->getTemplateParameters(),
1779 Conversion);
1780 ConversionTemplate->setAccess(AS_public);
1781 ConversionTemplate->setImplicit(true);
1782 Conversion->setDescribedFunctionTemplate(ConversionTemplate);
1783 Class->addDecl(ConversionTemplate);
1784 } else
1785 Class->addDecl(Conversion);
1786
1787 // If the lambda is not static, we need to add a static member
1788 // function that will be the result of the conversion with a
1789 // certain unique ID.
1790 // When it is static we just return the static call operator instead.
1791 if (CallOperator->isImplicitObjectMemberFunction()) {
1792 DeclarationName InvokerName =
1794 // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1795 // we should get a prebuilt TrivialTypeSourceInfo from Context
1796 // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1797 // then rewire the parameters accordingly, by hoisting up the InvokeParams
1798 // loop below and then use its Params to set Invoke->setParams(...) below.
1799 // This would avoid the 'const' qualifier of the calloperator from
1800 // contaminating the type of the invoker, which is currently adjusted
1801 // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the
1802 // trailing return type of the invoker would require a visitor to rebuild
1803 // the trailing return type and adjusting all back DeclRefExpr's to refer
1804 // to the new static invoker parameters - not the call operator's.
1806 S.Context, Class, Loc, DeclarationNameInfo(InvokerName, Loc),
1807 InvokerFunctionTy, CallOperator->getTypeSourceInfo(), SC_Static,
1809 /*isInline=*/true, CallOperator->getConstexprKind(),
1810 CallOperator->getBody()->getEndLoc());
1811 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
1812 InvokerParams[I]->setOwningFunction(Invoke);
1813 Invoke->setParams(InvokerParams);
1814 Invoke->setAccess(AS_private);
1815 Invoke->setImplicit(true);
1816 if (Class->isGenericLambda()) {
1817 FunctionTemplateDecl *TemplateCallOperator =
1818 CallOperator->getDescribedFunctionTemplate();
1819 FunctionTemplateDecl *StaticInvokerTemplate =
1821 S.Context, Class, Loc, InvokerName,
1822 TemplateCallOperator->getTemplateParameters(), Invoke);
1823 StaticInvokerTemplate->setAccess(AS_private);
1824 StaticInvokerTemplate->setImplicit(true);
1825 Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1826 Class->addDecl(StaticInvokerTemplate);
1827 } else
1828 Class->addDecl(Invoke);
1829 }
1830}
1831
1832/// Add a lambda's conversion to function pointers, as described in
1833/// C++11 [expr.prim.lambda]p6. Note that in most cases, this should emit only a
1834/// single pointer conversion. In the event that the default calling convention
1835/// for free and member functions is different, it will emit both conventions.
1836static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange,
1838 CXXMethodDecl *CallOperator) {
1839 const FunctionProtoType *CallOpProto =
1840 CallOperator->getType()->castAs<FunctionProtoType>();
1841
1843 S, *CallOpProto, [&](CallingConv CC) {
1844 QualType InvokerFunctionTy =
1845 S.getLambdaConversionFunctionResultType(CallOpProto, CC);
1846 addFunctionPointerConversion(S, IntroducerRange, Class, CallOperator,
1847 InvokerFunctionTy);
1848 });
1849}
1850
1851/// Add a lambda's conversion to block pointer.
1853 SourceRange IntroducerRange,
1855 CXXMethodDecl *CallOperator) {
1856 const FunctionProtoType *CallOpProto =
1857 CallOperator->getType()->castAs<FunctionProtoType>();
1859 CallOpProto, getLambdaConversionFunctionCallConv(S, CallOpProto));
1860 QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
1861
1862 FunctionProtoType::ExtProtoInfo ConversionEPI(
1864 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1865 ConversionEPI.TypeQuals = Qualifiers();
1866 ConversionEPI.TypeQuals.addConst();
1867 QualType ConvTy =
1868 S.Context.getFunctionType(BlockPtrTy, std::nullopt, ConversionEPI);
1869
1870 SourceLocation Loc = IntroducerRange.getBegin();
1871 DeclarationName Name
1873 S.Context.getCanonicalType(BlockPtrTy));
1875 S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc));
1877 S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), ConvTy,
1881 CallOperator->getBody()->getEndLoc());
1882 Conversion->setAccess(AS_public);
1883 Conversion->setImplicit(true);
1884 Class->addDecl(Conversion);
1885}
1886
1888 SourceLocation ImplicitCaptureLoc,
1889 bool IsOpenMPMapping) {
1890 // VLA captures don't have a stored initialization expression.
1891 if (Cap.isVLATypeCapture())
1892 return ExprResult();
1893
1894 // An init-capture is initialized directly from its stored initializer.
1895 if (Cap.isInitCapture())
1896 return cast<VarDecl>(Cap.getVariable())->getInit();
1897
1898 // For anything else, build an initialization expression. For an implicit
1899 // capture, the capture notionally happens at the capture-default, so use
1900 // that location here.
1902 ImplicitCaptureLoc.isValid() ? ImplicitCaptureLoc : Cap.getLocation();
1903
1904 // C++11 [expr.prim.lambda]p21:
1905 // When the lambda-expression is evaluated, the entities that
1906 // are captured by copy are used to direct-initialize each
1907 // corresponding non-static data member of the resulting closure
1908 // object. (For array members, the array elements are
1909 // direct-initialized in increasing subscript order.) These
1910 // initializations are performed in the (unspecified) order in
1911 // which the non-static data members are declared.
1912
1913 // C++ [expr.prim.lambda]p12:
1914 // An entity captured by a lambda-expression is odr-used (3.2) in
1915 // the scope containing the lambda-expression.
1917 IdentifierInfo *Name = nullptr;
1918 if (Cap.isThisCapture()) {
1919 QualType ThisTy = getCurrentThisType();
1920 Expr *This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.isValid());
1921 if (Cap.isCopyCapture())
1922 Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
1923 else
1924 Init = This;
1925 } else {
1926 assert(Cap.isVariableCapture() && "unknown kind of capture");
1927 ValueDecl *Var = Cap.getVariable();
1928 Name = Var->getIdentifier();
1931 }
1932
1933 // In OpenMP, the capture kind doesn't actually describe how to capture:
1934 // variables are "mapped" onto the device in a process that does not formally
1935 // make a copy, even for a "copy capture".
1936 if (IsOpenMPMapping)
1937 return Init;
1938
1939 if (Init.isInvalid())
1940 return ExprError();
1941
1942 Expr *InitExpr = Init.get();
1944 Name, Cap.getCaptureType(), Loc);
1945 InitializationKind InitKind =
1947 InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr);
1948 return InitSeq.Perform(*this, Entity, InitKind, InitExpr);
1949}
1950
1952 LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back());
1954 return BuildLambdaExpr(StartLoc, Body->getEndLoc(), &LSI);
1955}
1956
1959 switch (ICS) {
1961 return LCD_None;
1963 return LCD_ByCopy;
1966 return LCD_ByRef;
1968 llvm_unreachable("block capture in lambda");
1969 }
1970 llvm_unreachable("Unknown implicit capture style");
1971}
1972
1974 if (From.isInitCapture()) {
1975 Expr *Init = cast<VarDecl>(From.getVariable())->getInit();
1976 if (Init && Init->HasSideEffects(Context))
1977 return true;
1978 }
1979
1980 if (!From.isCopyCapture())
1981 return false;
1982
1983 const QualType T = From.isThisCapture()
1985 : From.getCaptureType();
1986
1987 if (T.isVolatileQualified())
1988 return true;
1989
1990 const Type *BaseT = T->getBaseElementTypeUnsafe();
1991 if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl())
1992 return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() ||
1993 !RD->hasTrivialDestructor();
1994
1995 return false;
1996}
1997
1999 const Capture &From) {
2000 if (CaptureHasSideEffects(From))
2001 return false;
2002
2003 if (From.isVLATypeCapture())
2004 return false;
2005
2006 // FIXME: maybe we should warn on these if we can find a sensible diagnostic
2007 // message
2008 if (From.isInitCapture() &&
2010 return false;
2011
2012 auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture);
2013 if (From.isThisCapture())
2014 diag << "'this'";
2015 else
2016 diag << From.getVariable();
2017 diag << From.isNonODRUsed();
2018 diag << FixItHint::CreateRemoval(CaptureRange);
2019 return true;
2020}
2021
2022/// Create a field within the lambda class or captured statement record for the
2023/// given capture.
2025 const sema::Capture &Capture) {
2027 QualType FieldType = Capture.getCaptureType();
2028
2029 TypeSourceInfo *TSI = nullptr;
2030 if (Capture.isVariableCapture()) {
2031 const auto *Var = dyn_cast_or_null<VarDecl>(Capture.getVariable());
2032 if (Var && Var->isInitCapture())
2033 TSI = Var->getTypeSourceInfo();
2034 }
2035
2036 // FIXME: Should we really be doing this? A null TypeSourceInfo seems more
2037 // appropriate, at least for an implicit capture.
2038 if (!TSI)
2039 TSI = Context.getTrivialTypeSourceInfo(FieldType, Loc);
2040
2041 // Build the non-static data member.
2042 FieldDecl *Field =
2043 FieldDecl::Create(Context, RD, /*StartLoc=*/Loc, /*IdLoc=*/Loc,
2044 /*Id=*/nullptr, FieldType, TSI, /*BW=*/nullptr,
2045 /*Mutable=*/false, ICIS_NoInit);
2046 // If the variable being captured has an invalid type, mark the class as
2047 // invalid as well.
2048 if (!FieldType->isDependentType()) {
2049 if (RequireCompleteSizedType(Loc, FieldType,
2050 diag::err_field_incomplete_or_sizeless)) {
2051 RD->setInvalidDecl();
2052 Field->setInvalidDecl();
2053 } else {
2054 NamedDecl *Def;
2055 FieldType->isIncompleteType(&Def);
2056 if (Def && Def->isInvalidDecl()) {
2057 RD->setInvalidDecl();
2058 Field->setInvalidDecl();
2059 }
2060 }
2061 }
2062 Field->setImplicit(true);
2063 Field->setAccess(AS_private);
2064 RD->addDecl(Field);
2065
2067 Field->setCapturedVLAType(Capture.getCapturedVLAType());
2068
2069 return Field;
2070}
2071
2073 LambdaScopeInfo *LSI) {
2074 // Collect information from the lambda scope.
2076 SmallVector<Expr *, 4> CaptureInits;
2077 SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc;
2078 LambdaCaptureDefault CaptureDefault =
2081 CXXMethodDecl *CallOperator;
2082 SourceRange IntroducerRange;
2083 bool ExplicitParams;
2084 bool ExplicitResultType;
2085 CleanupInfo LambdaCleanup;
2086 bool ContainsUnexpandedParameterPack;
2087 bool IsGenericLambda;
2088 {
2089 CallOperator = LSI->CallOperator;
2090 Class = LSI->Lambda;
2091 IntroducerRange = LSI->IntroducerRange;
2092 ExplicitParams = LSI->ExplicitParams;
2093 ExplicitResultType = !LSI->HasImplicitReturnType;
2094 LambdaCleanup = LSI->Cleanup;
2095 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
2096 IsGenericLambda = Class->isGenericLambda();
2097
2098 CallOperator->setLexicalDeclContext(Class);
2099 Decl *TemplateOrNonTemplateCallOperatorDecl =
2100 CallOperator->getDescribedFunctionTemplate()
2101 ? CallOperator->getDescribedFunctionTemplate()
2102 : cast<Decl>(CallOperator);
2103
2104 // FIXME: Is this really the best choice? Keeping the lexical decl context
2105 // set as CurContext seems more faithful to the source.
2106 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
2107
2109
2110 // True if the current capture has a used capture or default before it.
2111 bool CurHasPreviousCapture = CaptureDefault != LCD_None;
2112 SourceLocation PrevCaptureLoc = CurHasPreviousCapture ?
2113 CaptureDefaultLoc : IntroducerRange.getBegin();
2114
2115 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
2116 const Capture &From = LSI->Captures[I];
2117
2118 if (From.isInvalid())
2119 return ExprError();
2120
2121 assert(!From.isBlockCapture() && "Cannot capture __block variables");
2122 bool IsImplicit = I >= LSI->NumExplicitCaptures;
2123 SourceLocation ImplicitCaptureLoc =
2124 IsImplicit ? CaptureDefaultLoc : SourceLocation();
2125
2126 // Use source ranges of explicit captures for fixits where available.
2127 SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I];
2128
2129 // Warn about unused explicit captures.
2130 bool IsCaptureUsed = true;
2131 if (!CurContext->isDependentContext() && !IsImplicit &&
2132 !From.isODRUsed()) {
2133 // Initialized captures that are non-ODR used may not be eliminated.
2134 // FIXME: Where did the IsGenericLambda here come from?
2135 bool NonODRUsedInitCapture =
2136 IsGenericLambda && From.isNonODRUsed() && From.isInitCapture();
2137 if (!NonODRUsedInitCapture) {
2138 bool IsLast = (I + 1) == LSI->NumExplicitCaptures;
2139 SourceRange FixItRange;
2140 if (CaptureRange.isValid()) {
2141 if (!CurHasPreviousCapture && !IsLast) {
2142 // If there are no captures preceding this capture, remove the
2143 // following comma.
2144 FixItRange = SourceRange(CaptureRange.getBegin(),
2145 getLocForEndOfToken(CaptureRange.getEnd()));
2146 } else {
2147 // Otherwise, remove the comma since the last used capture.
2148 FixItRange = SourceRange(getLocForEndOfToken(PrevCaptureLoc),
2149 CaptureRange.getEnd());
2150 }
2151 }
2152
2153 IsCaptureUsed = !DiagnoseUnusedLambdaCapture(FixItRange, From);
2154 }
2155 }
2156
2157 if (CaptureRange.isValid()) {
2158 CurHasPreviousCapture |= IsCaptureUsed;
2159 PrevCaptureLoc = CaptureRange.getEnd();
2160 }
2161
2162 // Map the capture to our AST representation.
2163 LambdaCapture Capture = [&] {
2164 if (From.isThisCapture()) {
2165 // Capturing 'this' implicitly with a default of '[=]' is deprecated,
2166 // because it results in a reference capture. Don't warn prior to
2167 // C++2a; there's nothing that can be done about it before then.
2168 if (getLangOpts().CPlusPlus20 && IsImplicit &&
2169 CaptureDefault == LCD_ByCopy) {
2170 Diag(From.getLocation(), diag::warn_deprecated_this_capture);
2171 Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture)
2173 getLocForEndOfToken(CaptureDefaultLoc), ", this");
2174 }
2175 return LambdaCapture(From.getLocation(), IsImplicit,
2177 } else if (From.isVLATypeCapture()) {
2178 return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType);
2179 } else {
2180 assert(From.isVariableCapture() && "unknown kind of capture");
2181 ValueDecl *Var = From.getVariable();
2182 LambdaCaptureKind Kind =
2184 return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var,
2185 From.getEllipsisLoc());
2186 }
2187 }();
2188
2189 // Form the initializer for the capture field.
2190 ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc);
2191
2192 // FIXME: Skip this capture if the capture is not used, the initializer
2193 // has no side-effects, the type of the capture is trivial, and the
2194 // lambda is not externally visible.
2195
2196 // Add a FieldDecl for the capture and form its initializer.
2197 BuildCaptureField(Class, From);
2198 Captures.push_back(Capture);
2199 CaptureInits.push_back(Init.get());
2200
2201 if (LangOpts.CUDA)
2202 CUDA().CheckLambdaCapture(CallOperator, From);
2203 }
2204
2205 Class->setCaptures(Context, Captures);
2206
2207 // C++11 [expr.prim.lambda]p6:
2208 // The closure type for a lambda-expression with no lambda-capture
2209 // has a public non-virtual non-explicit const conversion function
2210 // to pointer to function having the same parameter and return
2211 // types as the closure type's function call operator.
2212 if (Captures.empty() && CaptureDefault == LCD_None)
2213 addFunctionPointerConversions(*this, IntroducerRange, Class,
2214 CallOperator);
2215
2216 // Objective-C++:
2217 // The closure type for a lambda-expression has a public non-virtual
2218 // non-explicit const conversion function to a block pointer having the
2219 // same parameter and return types as the closure type's function call
2220 // operator.
2221 // FIXME: Fix generic lambda to block conversions.
2222 if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda)
2223 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
2224
2225 // Finalize the lambda class.
2226 SmallVector<Decl*, 4> Fields(Class->fields());
2227 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
2229 CheckCompletedCXXClass(nullptr, Class);
2230 }
2231
2232 Cleanup.mergeFrom(LambdaCleanup);
2233
2234 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
2235 CaptureDefault, CaptureDefaultLoc,
2236 ExplicitParams, ExplicitResultType,
2237 CaptureInits, EndLoc,
2238 ContainsUnexpandedParameterPack);
2239 // If the lambda expression's call operator is not explicitly marked constexpr
2240 // and we are not in a dependent context, analyze the call operator to infer
2241 // its constexpr-ness, suppressing diagnostics while doing so.
2242 if (getLangOpts().CPlusPlus17 && !CallOperator->isInvalidDecl() &&
2243 !CallOperator->isConstexpr() &&
2244 !isa<CoroutineBodyStmt>(CallOperator->getBody()) &&
2245 !Class->getDeclContext()->isDependentContext()) {
2246 CallOperator->setConstexprKind(
2251 }
2252
2253 // Emit delayed shadowing warnings now that the full capture list is known.
2255
2257 switch (ExprEvalContexts.back().Context) {
2258 // C++11 [expr.prim.lambda]p2:
2259 // A lambda-expression shall not appear in an unevaluated operand
2260 // (Clause 5).
2264 // C++1y [expr.const]p2:
2265 // A conditional-expression e is a core constant expression unless the
2266 // evaluation of e, following the rules of the abstract machine, would
2267 // evaluate [...] a lambda-expression.
2268 //
2269 // This is technically incorrect, there are some constant evaluated contexts
2270 // where this should be allowed. We should probably fix this when DR1607 is
2271 // ratified, it lays out the exact set of conditions where we shouldn't
2272 // allow a lambda-expression.
2275 // We don't actually diagnose this case immediately, because we
2276 // could be within a context where we might find out later that
2277 // the expression is potentially evaluated (e.g., for typeid).
2278 ExprEvalContexts.back().Lambdas.push_back(Lambda);
2279 break;
2280
2284 break;
2285 }
2286 }
2287
2288 return MaybeBindToTemporary(Lambda);
2289}
2290
2292 SourceLocation ConvLocation,
2293 CXXConversionDecl *Conv,
2294 Expr *Src) {
2295 // Make sure that the lambda call operator is marked used.
2296 CXXRecordDecl *Lambda = Conv->getParent();
2297 CXXMethodDecl *CallOperator
2298 = cast<CXXMethodDecl>(
2299 Lambda->lookup(
2301 CallOperator->setReferenced();
2302 CallOperator->markUsed(Context);
2303
2306 CurrentLocation, Src);
2307 if (!Init.isInvalid())
2308 Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
2309
2310 if (Init.isInvalid())
2311 return ExprError();
2312
2313 // Create the new block to be returned.
2315
2316 // Set the type information.
2317 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
2318 Block->setIsVariadic(CallOperator->isVariadic());
2319 Block->setBlockMissingReturnType(false);
2320
2321 // Add parameters.
2323 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
2324 ParmVarDecl *From = CallOperator->getParamDecl(I);
2325 BlockParams.push_back(ParmVarDecl::Create(
2326 Context, Block, From->getBeginLoc(), From->getLocation(),
2327 From->getIdentifier(), From->getType(), From->getTypeSourceInfo(),
2328 From->getStorageClass(),
2329 /*DefArg=*/nullptr));
2330 }
2331 Block->setParams(BlockParams);
2332
2333 Block->setIsConversionFromLambda(true);
2334
2335 // Add capture. The capture uses a fake variable, which doesn't correspond
2336 // to any actual memory location. However, the initializer copy-initializes
2337 // the lambda object.
2338 TypeSourceInfo *CapVarTSI =
2340 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
2341 ConvLocation, nullptr,
2342 Src->getType(), CapVarTSI,
2343 SC_None);
2344 BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false,
2345 /*nested=*/false, /*copy=*/Init.get());
2346 Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false);
2347
2348 // Add a fake function body to the block. IR generation is responsible
2349 // for filling in the actual body, which cannot be expressed as an AST.
2350 Block->setBody(new (Context) CompoundStmt(ConvLocation));
2351
2352 // Create the block literal expression.
2353 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
2354 ExprCleanupObjects.push_back(Block);
2356
2357 return BuildBlock;
2358}
2359
2364 return FD;
2365 }
2366
2368 return FD->getInstantiatedFromDecl();
2369
2371 if (!FTD)
2372 return nullptr;
2373
2376
2377 return FTD->getTemplatedDecl();
2378}
2379
2383 LocalInstantiationScope &Scope, bool ShouldAddDeclsFromParentScope)
2384 : FunctionScopeRAII(SemaRef) {
2385 if (!isLambdaCallOperator(FD)) {
2387 return;
2388 }
2389
2390 SemaRef.RebuildLambdaScopeInfo(cast<CXXMethodDecl>(FD));
2391
2392 FunctionDecl *FDPattern = getPatternFunctionDecl(FD);
2393 if (!FDPattern)
2394 return;
2395
2396 if (!ShouldAddDeclsFromParentScope)
2397 return;
2398
2399 FunctionDecl *InnermostFD = FD, *InnermostFDPattern = FDPattern;
2401 ParentInstantiations;
2402 while (true) {
2403 FDPattern =
2404 dyn_cast<FunctionDecl>(getLambdaAwareParentOfDeclContext(FDPattern));
2405 FD = dyn_cast<FunctionDecl>(getLambdaAwareParentOfDeclContext(FD));
2406
2407 if (!FDPattern || !FD)
2408 break;
2409
2410 ParentInstantiations.emplace_back(FDPattern, FD);
2411 }
2412
2413 // Add instantiated parameters and local vars to scopes, starting from the
2414 // outermost lambda to the innermost lambda. This ordering ensures that
2415 // parameters in inner lambdas can correctly depend on those defined
2416 // in outer lambdas, e.g. auto L = [](auto... x) {
2417 // return [](decltype(x)... y) { }; // `y` depends on `x`
2418 // };
2419
2420 for (const auto &[FDPattern, FD] : llvm::reverse(ParentInstantiations)) {
2421 SemaRef.addInstantiatedParametersToScope(FD, FDPattern, Scope, MLTAL);
2422 SemaRef.addInstantiatedLocalVarsToScope(FD, FDPattern, Scope);
2423
2424 if (isLambdaCallOperator(FD))
2425 SemaRef.addInstantiatedCapturesToScope(FD, FDPattern, Scope, MLTAL);
2426 }
2427
2428 SemaRef.addInstantiatedCapturesToScope(InnermostFD, InnermostFDPattern, Scope,
2429 MLTAL);
2430}
#define V(N, I)
Definition: ASTContext.h:3341
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
const Decl * D
IndirectLocalPath & Path
Expr * E
Defines the clang::Expr interface and subclasses for C++ expressions.
uint32_t Id
Definition: SemaARM.cpp:1143
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:570
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:642
static TypeSourceInfo * getLambdaType(Sema &S, LambdaIntroducer &Intro, Declarator &ParamInfo, Scope *CurScope, SourceLocation Loc, bool &ExplicitResultType)
Definition: SemaLambda.cpp:916
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:68
static FunctionDecl * getPatternFunctionDecl(FunctionDecl *FD)
static LambdaScopeInfo * getCurrentLambdaScopeUnsafe(Sema &S)
Definition: SemaLambda.cpp:884
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:663
static TemplateParameterList * getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef)
Definition: SemaLambda.cpp:234
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:508
static TypeSourceInfo * getDummyLambdaType(Sema &S, SourceLocation Loc=SourceLocation())
Definition: SemaLambda.cpp:890
static QualType buildTypeForLambdaCallOperator(Sema &S, clang::CXXRecordDecl *Class, TemplateParameterList *TemplateParams, TypeSourceInfo *MethodTypeInfo)
Definition: SemaLambda.cpp:364
static bool isInInlineFunction(const DeclContext *DC)
Determine whether the given context is or is enclosed in an inline function.
Definition: SemaLambda.cpp:268
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.
SourceRange Range
Definition: SemaObjC.cpp:757
SourceLocation Loc
Definition: SemaObjC.cpp:758
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:187
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1101
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:664
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:2628
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2644
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:1147
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:1637
IdentifierTable & Idents
Definition: ASTContext.h:660
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
llvm::DenseMap< const CXXMethodDecl *, CXXCastPath > LambdaCastPaths
For capturing lambdas with an explicit object parameter whose type is derived from the lambda type,...
Definition: ASTContext.h:1209
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
CanQualType VoidTy
Definition: ASTContext.h:1119
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:1615
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:779
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:1227
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:3860
A binding in a decomposition declaration.
Definition: DeclCXX.h:4111
A class which contains all the information about a particular captured value.
Definition: Decl.h:4473
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4467
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5402
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6355
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2866
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:2928
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2906
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2064
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:2500
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2190
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:2312
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
void setLambdaTypeInfo(TypeSourceInfo *TS)
Definition: DeclCXX.h:1870
void setLambdaIsGeneric(bool IsGeneric)
Definition: DeclCXX.h:1881
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:1069
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
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:4203
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:2090
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2219
bool isFileContext() const
Definition: DeclBase.h:2161
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1333
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2106
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1852
bool isTranslationUnit() const
Definition: DeclBase.h:2166
bool isRecord() const
Definition: DeclBase.h:2170
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1766
bool isFunctionOrMethod() const
Definition: DeclBase.h:2142
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:1265
Captures information about "declaration specifiers".
Definition: DeclSpec.h:247
SCS getStorageClassSpec() const
Definition: DeclSpec.h:501
bool SetTypeQual(TQ T, SourceLocation Loc)
Definition: DeclSpec.cpp:1020
ConstexprSpecKind getConstexprSpecifier() const
Definition: DeclSpec.h:832
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
void addAttr(Attr *A)
Definition: DeclBase.cpp:1013
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:242
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:154
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:567
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:284
bool isInvalidDecl() const
Definition: DeclBase.h:595
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:509
SourceLocation getLocation() const
Definition: DeclBase.h:446
void setImplicit(bool I=true)
Definition: DeclBase.h:601
void setReferenced(bool R=true)
Definition: DeclBase.h:630
void setLocation(SourceLocation L)
Definition: DeclBase.h:447
DeclContext * getDeclContext()
Definition: DeclBase.h:455
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:362
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:775
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:783
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:766
void setTrailingRequiresClause(Expr *TrailingRequiresClause)
Definition: Decl.cpp:2001
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:807
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:760
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1903
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition: DeclSpec.h:2459
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2401
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2050
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition: DeclSpec.h:2636
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2397
bool isExplicitObjectMemberFunction()
Definition: DeclSpec.cpp:427
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:2085
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2490
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6341
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3270
Represents an enum.
Definition: Decl.h:3840
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5991
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1901
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition: ExprCXX.h:3473
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:3066
QualType getType() const
Definition: Expr.h:142
Represents difference between two FPOptions values.
Definition: LangOptions.h:919
bool isFPConstrained() const
Definition: LangOptions.h:847
Represents a member of a struct/union/class.
Definition: Decl.h:3030
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:4531
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:1062
const Expr * getSubExpr() const
Definition: Expr.h:1057
Represents a function declaration or definition.
Definition: Decl.h:1932
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2669
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3224
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2401
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:4033
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4028
QualType getReturnType() const
Definition: Decl.h:2717
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2646
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4148
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3077
@ TK_MemberSpecialization
Definition: Decl.h:1944
@ TK_DependentNonTemplate
Definition: Decl.h:1953
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3979
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2395
bool isImmediateEscalating() const
Definition: Decl.cpp:3256
FunctionDecl * getInstantiatedFromDecl() const
Definition: Decl.cpp:4052
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2398
bool isConsteval() const
Definition: Decl.h:2407
void setStorageClass(StorageClass SClass)
Sets the storage class as written in the source.
Definition: Decl.h:2765
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4000
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3678
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.h:2677
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5002
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5379
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5266
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5262
Declaration of a template function.
Definition: DeclTemplate.h:957
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:4534
CallingConv getCallConv() const
Definition: Type.h:4641
QualType getReturnType() const
Definition: Type.h:4630
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:3675
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:7521
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:1954
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:1294
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:558
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:1089
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:6960
Expr ** getExprs()
Definition: Expr.h:5846
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5835
Represents a parameter to a function.
Definition: Decl.h:1722
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:2903
Wrapper for source info for pointers.
Definition: TypeLoc.h:1301
A (possibly-)qualified type.
Definition: Type.h:941
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition: Type.h:1303
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7876
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:7951
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7844
The collection of all-type qualifiers we support.
Definition: Type.h:319
void addAddressSpace(LangAS space)
Definition: Type.h:584
void addConst()
Definition: Type.h:447
Represents a struct/union/class.
Definition: Decl.h:4141
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3024
void setRetValue(Expr *E)
Definition: Stmt.h:3057
SourceLocation getBeginLoc() const
Definition: Stmt.h:3081
Expr * getRetValue()
Definition: Stmt.h:3055
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:270
Scope * getTemplateParamParent()
Definition: Scope.h:315
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
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:3011
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:535
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:10905
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:803
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:2434
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15276
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition: Sema.h:7858
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:9000
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:12813
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:849
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:1219
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:248
SemaCUDA & CUDA()
Definition: Sema.h:1164
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:17170
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:940
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:2295
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:997
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:1162
void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef)
Add an init-capture to a lambda scope.
Definition: SemaLambda.cpp:875
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:15380
ASTContext & Context
Definition: Sema.h:1002
SemaObjC & ObjC()
Definition: Sema.h:1204
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1495
ASTContext & getASTContext() const
Definition: Sema.h:600
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:18684
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:17591
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths)
Builds a string representing ambiguous paths from a specific derived class to different subobjects of...
sema::LambdaScopeInfo * getCurGenericLambda()
Retrieve the current generic lambda info, if any.
Definition: Sema.cpp:2433
void handleLambdaNumbering(CXXRecordDecl *Class, CXXMethodDecl *Method, std::optional< CXXRecordDecl::LambdaNumbering > NumberingOverride=std::nullopt)
Number lambda for linkage purposes if necessary.
Definition: SemaLambda.cpp:455
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition: Sema.cpp:1585
ExprResult BuildCaptureInit(const sema::Capture &Capture, SourceLocation ImplicitCaptureLoc, bool IsOpenMPMapping=false)
Initialize the given capture with a suitable expression.
FPOptions & getCurFPFeatures()
Definition: Sema.h:595
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:83
@ UPPC_Initializer
An initializer.
Definition: Sema.h:13905
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition: Sema.h:13878
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:522
const LangOptions & getLangOpts() const
Definition: Sema.h:593
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)
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck=false, bool ForceUnprivileged=false)
Checks access for a hierarchy conversion.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
const LangOptions & LangOpts
Definition: Sema.h:1000
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2408
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:783
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:6472
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
Definition: SemaDecl.cpp:8302
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:1842
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3163
void DiagPlaceholderVariableDefinition(SourceLocation Loc)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1137
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:13472
TryCaptureKind
Definition: Sema.h:6598
@ TryCapture_Implicit
Definition: Sema.h:6599
@ TryCapture_ExplicitByVal
Definition: Sema.h:6600
@ TryCapture_ExplicitByRef
Definition: Sema.h:6601
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:544
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
Definition: SemaDecl.cpp:15736
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:215
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:8186
@ Normal
A normal translation unit fragment.
Definition: Sema.h:690
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition: Sema.h:6476
@ 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:5651
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8905
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:18852
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:17669
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7931
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1306
CXXMethodDecl * CreateLambdaCallOperator(SourceRange IntroducerRange, CXXRecordDecl *Class)
Definition: SemaLambda.cpp:972
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:690
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9655
void PopDeclContext()
Definition: SemaDecl.cpp:1313
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:281
void CompleteLambdaCallOperator(CXXMethodDecl *Method, SourceLocation LambdaLoc, SourceLocation CallOperatorLoc, Expr *TrailingRequiresClause, TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind, StorageClass SC, ArrayRef< ParmVarDecl * > Params, bool HasExplicitResultType)
void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI)
Note that we have finished the explicit captures for the given lambda.
Definition: SemaLambda.cpp:540
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 DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method, SourceLocation CallLoc)
Returns true if the explicit object parameter was invalid.
Definition: SemaLambda.cpp:392
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:8278
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:4407
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:3781
Exposes information about the current target.
Definition: TargetInfo.h:218
virtual CallingConvCheckResult checkCallingConvention(CallingConv CC) const
Determines whether a given calling convention is valid for the target.
Definition: TargetInfo.h:1694
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
bool containsUnexpandedParameterPack() const
Determine whether this template parameter list contains an unexpanded parameter pack.
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:7721
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:7732
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
The base class of the type hierarchy.
Definition: Type.h:1829
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
bool isVoidType() const
Definition: Type.h:8319
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2071
CanQualType getCanonicalTypeUnqualified() const
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8607
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2695
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2354
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8490
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8453
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2362
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8540
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4693
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:667
void setType(QualType newType)
Definition: Decl.h:679
QualType getType() const
Definition: Decl.h:678
VarDecl * getPotentiallyDecomposedVarDecl()
Definition: DeclCXX.cpp:3339
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.cpp:5357
Represents a variable declaration or definition.
Definition: Decl.h:879
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2133
void setInitStyle(InitializationStyle Style)
Definition: Decl.h:1393
void setInitCapture(bool IC)
Definition: Decl.h:1522
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1519
InitializationStyle
Initialization styles.
Definition: Decl.h:882
@ ListInit
Direct list-initialization (C++11)
Definition: Decl.h:890
@ CInit
C-style initialization with assignment.
Definition: Decl.h:884
@ CallInit
Call-style initialization (C++98)
Definition: Decl.h:887
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1132
void setInit(Expr *I)
Definition: Decl.cpp:2442
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1116
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2651
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:223
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:60
@ CPlusPlus
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:58
@ CPlusPlus17
Definition: LangStandard.h:59
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:179
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition: Specifiers.h:35
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:272
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1778
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:248
@ SC_Auto
Definition: Specifiers.h:256
@ SC_Static
Definition: Specifiers.h:252
@ SC_None
Definition: Specifiers.h:250
bool FTIHasSingleVoidParameter(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:25
@ 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:357
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:135
StringRef getLambdaStaticInvokerName()
Definition: ASTLambda.h:22
const FunctionProtoType * T
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
@ CC_C
Definition: Specifiers.h:279
@ CC_X86VectorCall
Definition: Specifiers.h:283
@ CC_X86StdCall
Definition: Specifiers.h:280
@ CC_X86FastCall
Definition: Specifiers.h:281
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ EST_BasicNoexcept
noexcept
@ AS_public
Definition: Specifiers.h:124
@ AS_private
Definition: Specifiers.h:126
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:258
Information about how a lambda is numbered within its context.
Definition: DeclCXX.h:1802
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:1595
bool hasTrailingReturnType() const
Determine whether this function declarator had a trailing-return-type.
Definition: DeclSpec.h:1586
ParsedType getTrailingReturnType() const
Get the trailing-return-type for this function declarator.
Definition: DeclSpec.h:1589
bool hasMutableQualifier() const
Determine whether this lambda-declarator contains a 'mutable' qualifier.
Definition: DeclSpec.h:1558
ParamInfo - An array of paraminfo objects is allocated whenever a function declarator is parsed.
Definition: DeclSpec.h:1333
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5061
Extra information about a function prototype.
Definition: Type.h:5087
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5094
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5088
unsigned NumExplicitTemplateParams
The number of parameters in the template parameter list that were explicitly specified by the user,...
Definition: DeclSpec.h:2886
SmallVector< NamedDecl *, 4 > TemplateParams
Store the list of the template parameters for a generic lambda or an abbreviated function template.
Definition: DeclSpec.h:2899
Represents a complete lambda introducer.
Definition: DeclSpec.h:2835
SmallVector< LambdaCapture, 4 > Captures
Definition: DeclSpec.h:2860
SourceLocation DefaultLoc
Definition: DeclSpec.h:2858
LambdaCaptureDefault Default
Definition: DeclSpec.h:2859
An RAII helper that pops function a function scope on exit.
Definition: Sema.h:1022