clang 22.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"
19#include "clang/Sema/DeclSpec.h"
21#include "clang/Sema/Lookup.h"
22#include "clang/Sema/Scope.h"
24#include "clang/Sema/SemaARM.h"
25#include "clang/Sema/SemaCUDA.h"
28#include "clang/Sema/SemaSYCL.h"
29#include "clang/Sema/Template.h"
30#include "llvm/ADT/STLExtras.h"
31#include <optional>
32using namespace clang;
33using namespace sema;
34
35/// Examines the FunctionScopeInfo stack to determine the nearest
36/// enclosing lambda (to the current lambda) that is 'capture-ready' for
37/// the variable referenced in the current lambda (i.e. \p VarToCapture).
38/// If successful, returns the index into Sema's FunctionScopeInfo stack
39/// of the capture-ready lambda's LambdaScopeInfo.
40///
41/// Climbs down the stack of lambdas (deepest nested lambda - i.e. current
42/// lambda - is on top) to determine the index of the nearest enclosing/outer
43/// lambda that is ready to capture the \p VarToCapture being referenced in
44/// the current lambda.
45/// As we climb down the stack, we want the index of the first such lambda -
46/// that is the lambda with the highest index that is 'capture-ready'.
47///
48/// A lambda 'L' is capture-ready for 'V' (var or this) if:
49/// - its enclosing context is non-dependent
50/// - and if the chain of lambdas between L and the lambda in which
51/// V is potentially used (i.e. the lambda at the top of the scope info
52/// stack), can all capture or have already captured V.
53/// If \p VarToCapture is 'null' then we are trying to capture 'this'.
54///
55/// Note that a lambda that is deemed 'capture-ready' still needs to be checked
56/// for whether it is 'capture-capable' (see
57/// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly
58/// capture.
59///
60/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
61/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
62/// is at the top of the stack and has the highest index.
63/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
64///
65/// \returns An UnsignedOrNone Index that if evaluates to 'true'
66/// contains the index (into Sema's FunctionScopeInfo stack) of the innermost
67/// lambda which is capture-ready. If the return value evaluates to 'false'
68/// then no lambda is capture-ready for \p VarToCapture.
69
72 ValueDecl *VarToCapture) {
73 // Label failure to capture.
74 const UnsignedOrNone NoLambdaIsCaptureReady = std::nullopt;
75
76 // Ignore all inner captured regions.
77 unsigned CurScopeIndex = FunctionScopes.size() - 1;
78 while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>(
79 FunctionScopes[CurScopeIndex]))
80 --CurScopeIndex;
81 assert(
82 isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) &&
83 "The function on the top of sema's function-info stack must be a lambda");
84
85 // If VarToCapture is null, we are attempting to capture 'this'.
86 const bool IsCapturingThis = !VarToCapture;
87 const bool IsCapturingVariable = !IsCapturingThis;
88
89 // Start with the current lambda at the top of the stack (highest index).
90 DeclContext *EnclosingDC =
91 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
92
93 do {
95 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
96 // IF we have climbed down to an intervening enclosing lambda that contains
97 // the variable declaration - it obviously can/must not capture the
98 // variable.
99 // Since its enclosing DC is dependent, all the lambdas between it and the
100 // innermost nested lambda are dependent (otherwise we wouldn't have
101 // arrived here) - so we don't yet have a lambda that can capture the
102 // variable.
103 if (IsCapturingVariable &&
104 VarToCapture->getDeclContext()->Equals(EnclosingDC))
105 return NoLambdaIsCaptureReady;
106
107 // For an enclosing lambda to be capture ready for an entity, all
108 // intervening lambda's have to be able to capture that entity. If even
109 // one of the intervening lambda's is not capable of capturing the entity
110 // then no enclosing lambda can ever capture that entity.
111 // For e.g.
112 // const int x = 10;
113 // [=](auto a) { #1
114 // [](auto b) { #2 <-- an intervening lambda that can never capture 'x'
115 // [=](auto c) { #3
116 // f(x, c); <-- can not lead to x's speculative capture by #1 or #2
117 // }; }; };
118 // If they do not have a default implicit capture, check to see
119 // if the entity has already been explicitly captured.
120 // If even a single dependent enclosing lambda lacks the capability
121 // to ever capture this variable, there is no further enclosing
122 // non-dependent lambda that can capture this variable.
124 if (IsCapturingVariable && !LSI->isCaptured(VarToCapture))
125 return NoLambdaIsCaptureReady;
126 if (IsCapturingThis && !LSI->isCXXThisCaptured())
127 return NoLambdaIsCaptureReady;
128 }
129 EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);
130
131 assert(CurScopeIndex);
132 --CurScopeIndex;
133 } while (!EnclosingDC->isTranslationUnit() &&
134 EnclosingDC->isDependentContext() &&
135 isLambdaCallOperator(EnclosingDC));
136
137 assert(CurScopeIndex < (FunctionScopes.size() - 1));
138 // If the enclosingDC is not dependent, then the immediately nested lambda
139 // (one index above) is capture-ready.
140 if (!EnclosingDC->isDependentContext())
141 return CurScopeIndex + 1;
142 return NoLambdaIsCaptureReady;
143}
144
145/// Examines the FunctionScopeInfo stack to determine the nearest
146/// enclosing lambda (to the current lambda) that is 'capture-capable' for
147/// the variable referenced in the current lambda (i.e. \p VarToCapture).
148/// If successful, returns the index into Sema's FunctionScopeInfo stack
149/// of the capture-capable lambda's LambdaScopeInfo.
150///
151/// Given the current stack of lambdas being processed by Sema and
152/// the variable of interest, to identify the nearest enclosing lambda (to the
153/// current lambda at the top of the stack) that can truly capture
154/// a variable, it has to have the following two properties:
155/// a) 'capture-ready' - be the innermost lambda that is 'capture-ready':
156/// - climb down the stack (i.e. starting from the innermost and examining
157/// each outer lambda step by step) checking if each enclosing
158/// lambda can either implicitly or explicitly capture the variable.
159/// Record the first such lambda that is enclosed in a non-dependent
160/// context. If no such lambda currently exists return failure.
161/// b) 'capture-capable' - make sure the 'capture-ready' lambda can truly
162/// capture the variable by checking all its enclosing lambdas:
163/// - check if all outer lambdas enclosing the 'capture-ready' lambda
164/// identified above in 'a' can also capture the variable (this is done
165/// via tryCaptureVariable for variables and CheckCXXThisCapture for
166/// 'this' by passing in the index of the Lambda identified in step 'a')
167///
168/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
169/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
170/// is at the top of the stack.
171///
172/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
173///
174///
175/// \returns An UnsignedOrNone Index that if evaluates to 'true'
176/// contains the index (into Sema's FunctionScopeInfo stack) of the innermost
177/// lambda which is capture-capable. If the return value evaluates to 'false'
178/// then no lambda is capture-capable for \p VarToCapture.
179
182 ValueDecl *VarToCapture, Sema &S) {
183
184 const UnsignedOrNone NoLambdaIsCaptureCapable = std::nullopt;
185
186 const UnsignedOrNone OptionalStackIndex =
188 VarToCapture);
189 if (!OptionalStackIndex)
190 return NoLambdaIsCaptureCapable;
191
192 const unsigned IndexOfCaptureReadyLambda = *OptionalStackIndex;
193 assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||
194 S.getCurGenericLambda()) &&
195 "The capture ready lambda for a potential capture can only be the "
196 "current lambda if it is a generic lambda");
197
198 const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
199 cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);
200
201 // If VarToCapture is null, we are attempting to capture 'this'
202 const bool IsCapturingThis = !VarToCapture;
203 const bool IsCapturingVariable = !IsCapturingThis;
204
205 if (IsCapturingVariable) {
206 // Check if the capture-ready lambda can truly capture the variable, by
207 // checking whether all enclosing lambdas of the capture-ready lambda allow
208 // the capture - i.e. make sure it is capture-capable.
209 QualType CaptureType, DeclRefType;
210 const bool CanCaptureVariable = !S.tryCaptureVariable(
211 VarToCapture,
212 /*ExprVarIsUsedInLoc*/ SourceLocation(), TryCaptureKind::Implicit,
213 /*EllipsisLoc*/ SourceLocation(),
214 /*BuildAndDiagnose*/ false, CaptureType, DeclRefType,
215 &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()) {
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
253 bool IsGenericLambda =
255 // Start constructing the lambda class.
257 Context, DC, Info, IntroducerRange.getBegin(), LambdaDependencyKind,
258 IsGenericLambda, CaptureDefault);
259 DC->addDecl(Class);
260
261 return Class;
262}
263
264/// Determine whether the given context is or is enclosed in an inline
265/// function.
266static bool isInInlineFunction(const DeclContext *DC) {
267 while (!DC->isFileContext()) {
268 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
269 if (FD->isInlined())
270 return true;
271
272 DC = DC->getLexicalParent();
273 }
274
275 return false;
276}
277
278std::tuple<MangleNumberingContext *, Decl *>
280 // Compute the context for allocating mangling numbers in the current
281 // expression, if the ABI requires them.
282 Decl *ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
283
284 enum ContextKind {
285 Normal,
287 DataMember,
288 InlineVariable,
289 TemplatedVariable,
290 Concept,
291 NonInlineInModulePurview
292 } Kind = Normal;
293
294 bool IsInNonspecializedTemplate =
295 inTemplateInstantiation() || CurContext->isDependentContext();
296
297 // Default arguments of member function parameters that appear in a class
298 // definition, as well as the initializers of data members, receive special
299 // treatment. Identify them.
300 Kind = [&]() {
301 if (auto *ND = dyn_cast<NamedDecl>(ManglingContextDecl ? ManglingContextDecl
302 : cast<Decl>(DC))) {
303 // See discussion in https://github.com/itanium-cxx-abi/cxx-abi/issues/186
304 //
305 // zygoloid:
306 // Yeah, I think the only cases left where lambdas don't need a
307 // mangling are when they have (effectively) internal linkage or appear
308 // in a non-inline function in a non-module translation unit.
309 Module *M = ND->getOwningModule();
310 if (M && M->getTopLevelModule()->isNamedModuleUnit() &&
311 ND->isExternallyVisible())
312 return NonInlineInModulePurview;
313 }
314
315 if (!ManglingContextDecl)
316 return Normal;
317
318 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
319 if (const DeclContext *LexicalDC
320 = Param->getDeclContext()->getLexicalParent())
321 if (LexicalDC->isRecord())
322 return DefaultArgument;
323 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
324 if (Var->getMostRecentDecl()->isInline())
325 return InlineVariable;
326
327 if (Var->getDeclContext()->isRecord() && IsInNonspecializedTemplate)
328 return TemplatedVariable;
329
330 if (Var->getDescribedVarTemplate())
331 return TemplatedVariable;
332
333 if (auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
334 if (!VTS->isExplicitSpecialization())
335 return TemplatedVariable;
336 }
337 } else if (isa<FieldDecl>(ManglingContextDecl)) {
338 return DataMember;
339 } else if (isa<ImplicitConceptSpecializationDecl>(ManglingContextDecl)) {
340 return Concept;
341 }
342
343 return Normal;
344 }();
345
346 // Itanium ABI [5.1.7]:
347 // In the following contexts [...] the one-definition rule requires closure
348 // types in different translation units to "correspond":
349 switch (Kind) {
350 case Normal: {
351 // -- the bodies of inline or templated functions
352 if ((IsInNonspecializedTemplate &&
353 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
355 while (auto *CD = dyn_cast<CapturedDecl>(DC))
356 DC = CD->getParent();
357 return std::make_tuple(&Context.getManglingNumberContext(DC), nullptr);
358 }
359
360 return std::make_tuple(nullptr, nullptr);
361 }
362
363 case NonInlineInModulePurview:
364 case Concept:
365 // Concept definitions aren't code generated and thus aren't mangled,
366 // however the ManglingContextDecl is important for the purposes of
367 // re-forming the template argument list of the lambda for constraint
368 // evaluation.
369 case DataMember:
370 // -- default member initializers
371 case DefaultArgument:
372 // -- default arguments appearing in class definitions
373 case InlineVariable:
374 case TemplatedVariable:
375 // -- the initializers of inline or templated variables
376 return std::make_tuple(
377 &Context.getManglingNumberContext(ASTContext::NeedExtraManglingDecl,
378 ManglingContextDecl),
379 ManglingContextDecl);
380 }
381
382 llvm_unreachable("unexpected context");
383}
384
385static QualType
387 TemplateParameterList *TemplateParams,
388 TypeSourceInfo *MethodTypeInfo) {
389 assert(MethodTypeInfo && "expected a non null type");
390
391 QualType MethodType = MethodTypeInfo->getType();
392 // If a lambda appears in a dependent context or is a generic lambda (has
393 // template parameters) and has an 'auto' return type, deduce it to a
394 // dependent type.
395 if (Class->isDependentContext() || TemplateParams) {
396 const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
397 QualType Result = FPT->getReturnType();
398 if (Result->isUndeducedType()) {
399 Result = S.SubstAutoTypeDependent(Result);
400 MethodType = S.Context.getFunctionType(Result, FPT->getParamTypes(),
401 FPT->getExtProtoInfo());
402 }
403 }
404 return MethodType;
405}
406
407// [C++2b] [expr.prim.lambda.closure] p4
408// Given a lambda with a lambda-capture, the type of the explicit object
409// parameter, if any, of the lambda's function call operator (possibly
410// instantiated from a function call operator template) shall be either:
411// - the closure type,
412// - class type publicly and unambiguously derived from the closure type, or
413// - a reference to a possibly cv-qualified such type.
417 return false;
418 CXXRecordDecl *RD = Method->getParent();
419 if (Method->getType()->isDependentType())
420 return false;
421 if (RD->isCapturelessLambda())
422 return false;
423
424 ParmVarDecl *Param = Method->getParamDecl(0);
425 QualType ExplicitObjectParameterType = Param->getType()
426 .getNonReferenceType()
427 .getUnqualifiedType()
428 .getDesugaredType(getASTContext());
430 if (LambdaType == ExplicitObjectParameterType)
431 return false;
432
433 // Don't check the same instantiation twice.
434 //
435 // If this call operator is ill-formed, there is no point in issuing
436 // a diagnostic every time it is called because the problem is in the
437 // definition of the derived type, not at the call site.
438 //
439 // FIXME: Move this check to where we instantiate the method? This should
440 // be possible, but the naive approach of just marking the method as invalid
441 // leads to us emitting more diagnostics than we should have to for this case
442 // (1 error here *and* 1 error about there being no matching overload at the
443 // call site). It might be possible to avoid that by also checking if there
444 // is an empty cast path for the method stored in the context (signalling that
445 // we've already diagnosed it) and then just not building the call, but that
446 // doesn't really seem any simpler than diagnosing it at the call site...
447 auto [It, Inserted] = Context.LambdaCastPaths.try_emplace(Method);
448 if (!Inserted)
449 return It->second.empty();
450
451 CXXCastPath &Path = It->second;
452 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
453 /*DetectVirtual=*/false);
454 if (!IsDerivedFrom(RD->getLocation(), ExplicitObjectParameterType, LambdaType,
455 Paths)) {
456 Diag(Param->getLocation(), diag::err_invalid_explicit_object_type_in_lambda)
457 << ExplicitObjectParameterType;
458 return true;
459 }
460
461 if (Paths.isAmbiguous(LambdaType)) {
462 std::string PathsDisplay = getAmbiguousPathsDisplayString(Paths);
463 Diag(CallLoc, diag::err_explicit_object_lambda_ambiguous_base)
464 << LambdaType << PathsDisplay;
465 return true;
466 }
467
468 if (CheckBaseClassAccess(CallLoc, LambdaType, ExplicitObjectParameterType,
469 Paths.front(),
470 diag::err_explicit_object_lambda_inaccessible_base))
471 return true;
472
473 BuildBasePathArray(Paths, Path);
474 return false;
475}
476
479 std::optional<CXXRecordDecl::LambdaNumbering> NumberingOverride) {
480 if (NumberingOverride) {
481 Class->setLambdaNumbering(*NumberingOverride);
482 return;
483 }
484
485 ContextRAII ManglingContext(*this, Class->getDeclContext());
486
487 auto getMangleNumberingContext =
488 [this](CXXRecordDecl *Class,
489 Decl *ManglingContextDecl) -> MangleNumberingContext * {
490 // Get mangle numbering context if there's any extra decl context.
491 if (ManglingContextDecl)
492 return &Context.getManglingNumberContext(
493 ASTContext::NeedExtraManglingDecl, ManglingContextDecl);
494 // Otherwise, from that lambda's decl context.
495 auto DC = Class->getDeclContext();
496 while (auto *CD = dyn_cast<CapturedDecl>(DC))
497 DC = CD->getParent();
498 return &Context.getManglingNumberContext(DC);
499 };
500
503 std::tie(MCtx, Numbering.ContextDecl) =
504 getCurrentMangleNumberContext(Class->getDeclContext());
505 if (!MCtx && (getLangOpts().CUDA || getLangOpts().SYCLIsDevice ||
506 getLangOpts().SYCLIsHost)) {
507 // Force lambda numbering in CUDA/HIP as we need to name lambdas following
508 // ODR. Both device- and host-compilation need to have a consistent naming
509 // on kernel functions. As lambdas are potential part of these `__global__`
510 // function names, they needs numbering following ODR.
511 // Also force for SYCL, since we need this for the
512 // __builtin_sycl_unique_stable_name implementation, which depends on lambda
513 // mangling.
514 MCtx = getMangleNumberingContext(Class, Numbering.ContextDecl);
515 assert(MCtx && "Retrieving mangle numbering context failed!");
516 Numbering.HasKnownInternalLinkage = true;
517 }
518 if (MCtx) {
519 Numbering.IndexInContext = MCtx->getNextLambdaIndex();
520 Numbering.ManglingNumber = MCtx->getManglingNumber(Method);
522 Class->setLambdaNumbering(Numbering);
523
524 if (auto *Source =
525 dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
526 Source->AssignedLambdaNumbering(Class);
527 }
528}
529
531 CXXMethodDecl *CallOperator,
532 bool ExplicitResultType) {
533 if (ExplicitResultType) {
534 LSI->HasImplicitReturnType = false;
535 LSI->ReturnType = CallOperator->getReturnType();
536 if (!LSI->ReturnType->isDependentType() && !LSI->ReturnType->isVoidType())
537 S.RequireCompleteType(CallOperator->getBeginLoc(), LSI->ReturnType,
538 diag::err_lambda_incomplete_result);
539 } else {
540 LSI->HasImplicitReturnType = true;
541 }
542}
543
545 SourceRange IntroducerRange,
546 LambdaCaptureDefault CaptureDefault,
547 SourceLocation CaptureDefaultLoc,
548 bool ExplicitParams, bool Mutable) {
549 LSI->CallOperator = CallOperator;
550 CXXRecordDecl *LambdaClass = CallOperator->getParent();
551 LSI->Lambda = LambdaClass;
552 if (CaptureDefault == LCD_ByCopy)
553 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
554 else if (CaptureDefault == LCD_ByRef)
555 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
556 LSI->CaptureDefaultLoc = CaptureDefaultLoc;
557 LSI->IntroducerRange = IntroducerRange;
558 LSI->ExplicitParams = ExplicitParams;
559 LSI->Mutable = Mutable;
560}
561
565
567 LambdaIntroducer &Intro, SourceLocation LAngleLoc,
568 ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc,
569 ExprResult RequiresClause) {
571 assert(LSI && "Expected a lambda scope");
572 assert(LSI->NumExplicitTemplateParams == 0 &&
573 "Already acted on explicit template parameters");
574 assert(LSI->TemplateParams.empty() &&
575 "Explicit template parameters should come "
576 "before invented (auto) ones");
577 assert(!TParams.empty() &&
578 "No template parameters to act on");
579 LSI->TemplateParams.append(TParams.begin(), TParams.end());
580 LSI->NumExplicitTemplateParams = TParams.size();
581 LSI->ExplicitTemplateParamsRange = {LAngleLoc, RAngleLoc};
582 LSI->RequiresClause = RequiresClause;
583}
584
585/// If this expression is an enumerator-like expression of some type
586/// T, return the type T; otherwise, return null.
587///
588/// Pointer comparisons on the result here should always work because
589/// it's derived from either the parent of an EnumConstantDecl
590/// (i.e. the definition) or the declaration returned by
591/// EnumType::getDecl() (i.e. the definition).
593 // An expression is an enumerator-like expression of type T if,
594 // ignoring parens and parens-like expressions:
595 E = E->IgnoreParens();
596
597 // - it is an enumerator whose enum type is T or
598 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
599 if (EnumConstantDecl *D
600 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
601 return cast<EnumDecl>(D->getDeclContext());
602 }
603 return nullptr;
604 }
605
606 // - it is a comma expression whose RHS is an enumerator-like
607 // expression of type T or
608 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
609 if (BO->getOpcode() == BO_Comma)
610 return findEnumForBlockReturn(BO->getRHS());
611 return nullptr;
612 }
613
614 // - it is a statement-expression whose value expression is an
615 // enumerator-like expression of type T or
616 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
617 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
618 return findEnumForBlockReturn(last);
619 return nullptr;
620 }
621
622 // - it is a ternary conditional operator (not the GNU ?:
623 // extension) whose second and third operands are
624 // enumerator-like expressions of type T or
625 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
626 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
627 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
628 return ED;
629 return nullptr;
630 }
631
632 // (implicitly:)
633 // - it is an implicit integral conversion applied to an
634 // enumerator-like expression of type T or
635 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
636 // We can sometimes see integral conversions in valid
637 // enumerator-like expressions.
638 if (ICE->getCastKind() == CK_IntegralCast)
639 return findEnumForBlockReturn(ICE->getSubExpr());
640
641 // Otherwise, just rely on the type.
642 }
643
644 // - it is an expression of that formal enum type.
645 if (auto *ED = E->getType()->getAsEnumDecl())
646 return ED;
647
648 // Otherwise, nope.
649 return nullptr;
650}
651
652/// Attempt to find a type T for which the returned expression of the
653/// given statement is an enumerator-like expression of that type.
655 if (Expr *retValue = ret->getRetValue())
656 return findEnumForBlockReturn(retValue);
657 return nullptr;
658}
659
660/// Attempt to find a common type T for which all of the returned
661/// expressions in a block are enumerator-like expressions of that
662/// type.
664 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
665
666 // Try to find one for the first return.
668 if (!ED) return nullptr;
669
670 // Check that the rest of the returns have the same enum.
671 for (++i; i != e; ++i) {
672 if (findEnumForBlockReturn(*i) != ED)
673 return nullptr;
674 }
675
676 // Never infer an anonymous enum type.
677 if (!ED->hasNameForLinkage()) return nullptr;
678
679 return ED;
680}
681
682/// Adjust the given return statements so that they formally return
683/// the given type. It should require, at most, an IntegralCast.
685 QualType returnType) {
687 i = returns.begin(), e = returns.end(); i != e; ++i) {
688 ReturnStmt *ret = *i;
689 Expr *retValue = ret->getRetValue();
690 if (S.Context.hasSameType(retValue->getType(), returnType))
691 continue;
692
693 // Right now we only support integral fixup casts.
694 assert(returnType->isIntegralOrUnscopedEnumerationType());
695 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
696
697 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
698
699 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
700 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast, E,
701 /*base path*/ nullptr, VK_PRValue,
703 if (cleanups) {
704 cleanups->setSubExpr(E);
705 } else {
706 ret->setRetValue(E);
707 }
708 }
709}
710
712 assert(CSI.HasImplicitReturnType);
713 // If it was ever a placeholder, it had to been deduced to DependentTy.
714 assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
715 assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) &&
716 "lambda expressions use auto deduction in C++14 onwards");
717
718 // C++ core issue 975:
719 // If a lambda-expression does not include a trailing-return-type,
720 // it is as if the trailing-return-type denotes the following type:
721 // - if there are no return statements in the compound-statement,
722 // or all return statements return either an expression of type
723 // void or no expression or braced-init-list, the type void;
724 // - otherwise, if all return statements return an expression
725 // and the types of the returned expressions after
726 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
727 // array-to-pointer conversion (4.2 [conv.array]), and
728 // function-to-pointer conversion (4.3 [conv.func]) are the
729 // same, that common type;
730 // - otherwise, the program is ill-formed.
731 //
732 // C++ core issue 1048 additionally removes top-level cv-qualifiers
733 // from the types of returned expressions to match the C++14 auto
734 // deduction rules.
735 //
736 // In addition, in blocks in non-C++ modes, if all of the return
737 // statements are enumerator-like expressions of some type T, where
738 // T has a name for linkage, then we infer the return type of the
739 // block to be that type.
740
741 // First case: no return statements, implicit void return type.
742 ASTContext &Ctx = getASTContext();
743 if (CSI.Returns.empty()) {
744 // It's possible there were simply no /valid/ return statements.
745 // In this case, the first one we found may have at least given us a type.
746 if (CSI.ReturnType.isNull())
747 CSI.ReturnType = Ctx.VoidTy;
748 return;
749 }
750
751 // Second case: at least one return statement has dependent type.
752 // Delay type checking until instantiation.
753 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
754 if (CSI.ReturnType->isDependentType())
755 return;
756
757 // Try to apply the enum-fuzz rule.
758 if (!getLangOpts().CPlusPlus) {
759 assert(isa<BlockScopeInfo>(CSI));
761 if (ED) {
762 CSI.ReturnType = Context.getCanonicalTagType(ED);
764 return;
765 }
766 }
767
768 // Third case: only one return statement. Don't bother doing extra work!
769 if (CSI.Returns.size() == 1)
770 return;
771
772 // General case: many return statements.
773 // Check that they all have compatible return types.
774
775 // We require the return types to strictly match here.
776 // Note that we've already done the required promotions as part of
777 // processing the return statement.
778 for (const ReturnStmt *RS : CSI.Returns) {
779 const Expr *RetE = RS->getRetValue();
780
781 QualType ReturnType =
782 (RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType();
783 if (Context.getCanonicalFunctionResultType(ReturnType) ==
784 Context.getCanonicalFunctionResultType(CSI.ReturnType)) {
785 // Use the return type with the strictest possible nullability annotation.
786 auto RetTyNullability = ReturnType->getNullability();
787 auto BlockNullability = CSI.ReturnType->getNullability();
788 if (BlockNullability &&
789 (!RetTyNullability ||
790 hasWeakerNullability(*RetTyNullability, *BlockNullability)))
791 CSI.ReturnType = ReturnType;
792 continue;
793 }
794
795 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
796 // TODO: It's possible that the *first* return is the divergent one.
797 Diag(RS->getBeginLoc(),
798 diag::err_typecheck_missing_return_type_incompatible)
799 << ReturnType << CSI.ReturnType << isa<LambdaScopeInfo>(CSI);
800 // Continue iterating so that we keep emitting diagnostics.
801 }
802}
803
805 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
806 UnsignedOrNone NumExpansions, IdentifierInfo *Id, bool IsDirectInit,
807 Expr *&Init) {
808 // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
809 // deduce against.
810 QualType DeductType = Context.getAutoDeductType();
811 TypeLocBuilder TLB;
812 AutoTypeLoc TL = TLB.push<AutoTypeLoc>(DeductType);
813 TL.setNameLoc(Loc);
814 if (ByRef) {
815 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
816 assert(!DeductType.isNull() && "can't build reference to auto");
817 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
818 }
819 if (EllipsisLoc.isValid()) {
820 if (Init->containsUnexpandedParameterPack()) {
821 Diag(EllipsisLoc, getLangOpts().CPlusPlus20
822 ? diag::warn_cxx17_compat_init_capture_pack
823 : diag::ext_init_capture_pack);
824 DeductType = Context.getPackExpansionType(DeductType, NumExpansions,
825 /*ExpectPackInType=*/false);
826 TLB.push<PackExpansionTypeLoc>(DeductType).setEllipsisLoc(EllipsisLoc);
827 } else {
828 // Just ignore the ellipsis for now and form a non-pack variable. We'll
829 // diagnose this later when we try to capture it.
830 }
831 }
832 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
833
834 // Deduce the type of the init capture.
836 /*VarDecl*/nullptr, DeclarationName(Id), DeductType, TSI,
837 SourceRange(Loc, Loc), IsDirectInit, Init);
838 if (DeducedType.isNull())
839 return QualType();
840
841 // Are we a non-list direct initialization?
842 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
843
844 // Perform initialization analysis and ensure any implicit conversions
845 // (such as lvalue-to-rvalue) are enforced.
846 InitializedEntity Entity =
847 InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc);
848 InitializationKind Kind =
849 IsDirectInit
850 ? (CXXDirectInit ? InitializationKind::CreateDirect(
851 Loc, Init->getBeginLoc(), Init->getEndLoc())
853 : InitializationKind::CreateCopy(Loc, Init->getBeginLoc());
854
855 MultiExprArg Args = Init;
856 if (CXXDirectInit)
857 Args =
858 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
859 QualType DclT;
860 InitializationSequence InitSeq(*this, Entity, Kind, Args);
861 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
862
863 if (Result.isInvalid())
864 return QualType();
865
866 Init = Result.getAs<Expr>();
867 return DeducedType;
868}
869
871 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
872 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx) {
873 // FIXME: Retain the TypeSourceInfo from buildLambdaInitCaptureInitialization
874 // rather than reconstructing it here.
875 TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType, Loc);
876 if (auto PETL = TSI->getTypeLoc().getAs<PackExpansionTypeLoc>())
877 PETL.setEllipsisLoc(EllipsisLoc);
878
879 // Create a dummy variable representing the init-capture. This is not actually
880 // used as a variable, and only exists as a way to name and refer to the
881 // init-capture.
882 // FIXME: Pass in separate source locations for '&' and identifier.
883 VarDecl *NewVD = VarDecl::Create(Context, DeclCtx, Loc, Loc, Id,
884 InitCaptureType, TSI, SC_Auto);
885 NewVD->setInitCapture(true);
886 NewVD->setReferenced(true);
887 // FIXME: Pass in a VarDecl::InitializationStyle.
888 NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));
889 NewVD->markUsed(Context);
890 NewVD->setInit(Init);
891 if (NewVD->isParameterPack())
892 getCurLambda()->LocalPacks.push_back(NewVD);
893 return NewVD;
894}
895
896void Sema::addInitCapture(LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef) {
897 assert(Var->isInitCapture() && "init capture flag should be set");
898 LSI->addCapture(Var, /*isBlock=*/false, ByRef,
899 /*isNested=*/false, Var->getLocation(), SourceLocation(),
900 Var->getType(), /*Invalid=*/false);
901}
902
903// Unlike getCurLambda, getCurrentLambdaScopeUnsafe doesn't
904// check that the current lambda is in a consistent or fully constructed state.
906 assert(!S.FunctionScopes.empty());
908}
909
910static TypeSourceInfo *
912 // C++11 [expr.prim.lambda]p4:
913 // If a lambda-expression does not include a lambda-declarator, it is as
914 // if the lambda-declarator were ().
916 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
917 EPI.HasTrailingReturn = true;
918 EPI.TypeQuals.addConst();
920 if (AS != LangAS::Default)
922
923 // C++1y [expr.prim.lambda]:
924 // The lambda return type is 'auto', which is replaced by the
925 // trailing-return type if provided and/or deduced from 'return'
926 // statements
927 // We don't do this before C++1y, because we don't support deduced return
928 // types there.
929 QualType DefaultTypeForNoTrailingReturn = S.getLangOpts().CPlusPlus14
932 QualType MethodTy =
933 S.Context.getFunctionType(DefaultTypeForNoTrailingReturn, {}, EPI);
934 return S.Context.getTrivialTypeSourceInfo(MethodTy, Loc);
935}
936
938 Declarator &ParamInfo, Scope *CurScope,
939 SourceLocation Loc,
940 bool &ExplicitResultType) {
941
942 ExplicitResultType = false;
943
944 assert(
945 (ParamInfo.getDeclSpec().getStorageClassSpec() ==
948 "Unexpected storage specifier");
949 bool IsLambdaStatic =
951
952 TypeSourceInfo *MethodTyInfo;
953
954 if (ParamInfo.getNumTypeObjects() == 0) {
955 MethodTyInfo = getDummyLambdaType(S, Loc);
956 } else {
957 // Check explicit parameters
958 S.CheckExplicitObjectLambda(ParamInfo);
959
961
962 bool HasExplicitObjectParameter =
964
965 ExplicitResultType = FTI.hasTrailingReturnType();
966 if (!FTI.hasMutableQualifier() && !IsLambdaStatic &&
967 !HasExplicitObjectParameter)
969
970 if (ExplicitResultType && S.getLangOpts().HLSL) {
971 QualType RetTy = FTI.getTrailingReturnType().get();
972 if (!RetTy.isNull()) {
973 // HLSL does not support specifying an address space on a lambda return
974 // type.
975 LangAS AddressSpace = RetTy.getAddressSpace();
976 if (AddressSpace != LangAS::Default)
978 diag::err_return_value_with_address_space);
979 }
980 }
981
982 MethodTyInfo = S.GetTypeForDeclarator(ParamInfo);
983 assert(MethodTyInfo && "no type from lambda-declarator");
984
985 // Check for unexpanded parameter packs in the method type.
986 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
987 S.DiagnoseUnexpandedParameterPack(Intro.Range.getBegin(), MethodTyInfo,
989 }
990 return MethodTyInfo;
991}
992
995
996 // C++20 [expr.prim.lambda.closure]p3:
997 // The closure type for a lambda-expression has a public inline function
998 // call operator (for a non-generic lambda) or function call operator
999 // template (for a generic lambda) whose parameters and return type are
1000 // described by the lambda-expression's parameter-declaration-clause
1001 // and trailing-return-type respectively.
1002 DeclarationName MethodName =
1003 Context.DeclarationNames.getCXXOperatorName(OO_Call);
1004 DeclarationNameLoc MethodNameLoc =
1008 DeclarationNameInfo(MethodName, IntroducerRange.getBegin(),
1009 MethodNameLoc),
1010 QualType(), /*Tinfo=*/nullptr, SC_None,
1011 getCurFPFeatures().isFPConstrained(),
1012 /*isInline=*/true, ConstexprSpecKind::Unspecified, SourceLocation(),
1013 /*TrailingRequiresClause=*/{});
1014 Method->setAccess(AS_public);
1015 return Method;
1016}
1017
1019 CXXMethodDecl *CallOperator, CXXRecordDecl *Class,
1020 TemplateParameterList *TemplateParams) {
1021 assert(TemplateParams && "no template parameters");
1023 Context, Class, CallOperator->getLocation(), CallOperator->getDeclName(),
1024 TemplateParams, CallOperator);
1025 TemplateMethod->setAccess(AS_public);
1026 CallOperator->setDescribedFunctionTemplate(TemplateMethod);
1027}
1028
1031 SourceLocation CallOperatorLoc,
1032 const AssociatedConstraint &TrailingRequiresClause,
1033 TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind,
1035 bool HasExplicitResultType) {
1036
1038
1039 if (TrailingRequiresClause)
1040 Method->setTrailingRequiresClause(TrailingRequiresClause);
1041
1042 TemplateParameterList *TemplateParams =
1044
1045 DeclContext *DC = Method->getLexicalDeclContext();
1046 // DeclContext::addDecl() assumes that the DeclContext we're adding to is the
1047 // lexical context of the Method. Do so.
1048 Method->setLexicalDeclContext(LSI->Lambda);
1049 if (TemplateParams) {
1050 FunctionTemplateDecl *TemplateMethod =
1051 Method->getDescribedFunctionTemplate();
1052 assert(TemplateMethod &&
1053 "AddTemplateParametersToLambdaCallOperator should have been called");
1054
1055 LSI->Lambda->addDecl(TemplateMethod);
1056 TemplateMethod->setLexicalDeclContext(DC);
1057 } else {
1058 LSI->Lambda->addDecl(Method);
1059 }
1060 LSI->Lambda->setLambdaIsGeneric(TemplateParams);
1061 LSI->Lambda->setLambdaTypeInfo(MethodTyInfo);
1062
1063 Method->setLexicalDeclContext(DC);
1064 Method->setLocation(LambdaLoc);
1065 Method->setInnerLocStart(CallOperatorLoc);
1066 Method->setTypeSourceInfo(MethodTyInfo);
1067 Method->setType(buildTypeForLambdaCallOperator(*this, LSI->Lambda,
1068 TemplateParams, MethodTyInfo));
1069 Method->setConstexprKind(ConstexprKind);
1070 Method->setStorageClass(SC);
1071 if (!Params.empty()) {
1072 CheckParmsForFunctionDef(Params, /*CheckParameterNames=*/false);
1073 Method->setParams(Params);
1074 for (auto P : Method->parameters()) {
1075 assert(P && "null in a parameter list");
1076 P->setOwningFunction(Method);
1077 }
1078 }
1079
1080 buildLambdaScopeReturnType(*this, LSI, Method, HasExplicitResultType);
1081}
1082
1084 Scope *CurrentScope) {
1085
1087 assert(LSI && "LambdaScopeInfo should be on stack!");
1088
1089 if (Intro.Default == LCD_ByCopy)
1090 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
1091 else if (Intro.Default == LCD_ByRef)
1092 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
1093 LSI->CaptureDefaultLoc = Intro.DefaultLoc;
1094 LSI->IntroducerRange = Intro.Range;
1095 LSI->AfterParameterList = false;
1096
1097 assert(LSI->NumExplicitTemplateParams == 0);
1098
1099 // Determine if we're within a context where we know that the lambda will
1100 // be dependent, because there are template parameters in scope.
1101 CXXRecordDecl::LambdaDependencyKind LambdaDependencyKind =
1103 if (CurScope->getTemplateParamParent() != nullptr) {
1104 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
1105 } else if (Scope *ParentScope = CurScope->getParent()) {
1106 // Given a lambda defined inside a requires expression,
1107 //
1108 // struct S {
1109 // S(auto var) requires requires { [&] -> decltype(var) { }; }
1110 // {}
1111 // };
1112 //
1113 // The parameter var is not injected into the function Decl at the point of
1114 // parsing lambda. In such scenarios, perceiving it as dependent could
1115 // result in the constraint being evaluated, which matches what GCC does.
1116 Scope *LookupScope = ParentScope;
1117 while (LookupScope->getEntity() &&
1118 LookupScope->getEntity()->isRequiresExprBody())
1119 LookupScope = LookupScope->getParent();
1120
1121 if (LookupScope != ParentScope &&
1122 LookupScope->isFunctionDeclarationScope() &&
1123 llvm::any_of(LookupScope->decls(), [](Decl *D) {
1124 return isa<ParmVarDecl>(D) &&
1125 cast<ParmVarDecl>(D)->getType()->isTemplateTypeParmType();
1126 }))
1127 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
1128 }
1129
1131 Intro.Range, /*Info=*/nullptr, LambdaDependencyKind, Intro.Default);
1132 LSI->Lambda = Class;
1133
1135 LSI->CallOperator = Method;
1136 // Temporarily set the lexical declaration context to the current
1137 // context, so that the Scope stack matches the lexical nesting.
1138 Method->setLexicalDeclContext(CurContext);
1139
1140 PushDeclContext(CurScope, Method);
1141
1142 bool ContainsUnexpandedParameterPack = false;
1143
1144 // Distinct capture names, for diagnostics.
1145 llvm::DenseMap<IdentifierInfo *, ValueDecl *> CaptureNames;
1146
1147 // Handle explicit captures.
1148 SourceLocation PrevCaptureLoc =
1149 Intro.Default == LCD_None ? Intro.Range.getBegin() : Intro.DefaultLoc;
1150 for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;
1151 PrevCaptureLoc = C->Loc, ++C) {
1152 if (C->Kind == LCK_This || C->Kind == LCK_StarThis) {
1153 if (C->Kind == LCK_StarThis)
1154 Diag(C->Loc, !getLangOpts().CPlusPlus17
1155 ? diag::ext_star_this_lambda_capture_cxx17
1156 : diag::warn_cxx14_compat_star_this_lambda_capture);
1157
1158 // C++11 [expr.prim.lambda]p8:
1159 // An identifier or this shall not appear more than once in a
1160 // lambda-capture.
1161 if (LSI->isCXXThisCaptured()) {
1162 Diag(C->Loc, diag::err_capture_more_than_once)
1163 << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())
1165 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1166 continue;
1167 }
1168
1169 // C++20 [expr.prim.lambda]p8:
1170 // If a lambda-capture includes a capture-default that is =,
1171 // each simple-capture of that lambda-capture shall be of the form
1172 // "&identifier", "this", or "* this". [ Note: The form [&,this] is
1173 // redundant but accepted for compatibility with ISO C++14. --end note ]
1174 if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis)
1175 Diag(C->Loc, !getLangOpts().CPlusPlus20
1176 ? diag::ext_equals_this_lambda_capture_cxx20
1177 : diag::warn_cxx17_compat_equals_this_lambda_capture);
1178
1179 // C++11 [expr.prim.lambda]p12:
1180 // If this is captured by a local lambda expression, its nearest
1181 // enclosing function shall be a non-static member function.
1182 QualType ThisCaptureType = getCurrentThisType();
1183 if (ThisCaptureType.isNull()) {
1184 Diag(C->Loc, diag::err_this_capture) << true;
1185 continue;
1186 }
1187
1188 CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true,
1189 /*FunctionScopeIndexToStopAtPtr*/ nullptr,
1190 C->Kind == LCK_StarThis);
1191 if (!LSI->Captures.empty())
1192 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1193 continue;
1194 }
1195
1196 assert(C->Id && "missing identifier for capture");
1197
1198 if (C->Init.isInvalid())
1199 continue;
1200
1201 ValueDecl *Var = nullptr;
1202 if (C->Init.isUsable()) {
1204 ? diag::warn_cxx11_compat_init_capture
1205 : diag::ext_init_capture);
1206
1207 // If the initializer expression is usable, but the InitCaptureType
1208 // is not, then an error has occurred - so ignore the capture for now.
1209 // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
1210 // FIXME: we should create the init capture variable and mark it invalid
1211 // in this case.
1212 if (C->InitCaptureType.get().isNull())
1213 continue;
1214
1215 if (C->Init.get()->containsUnexpandedParameterPack() &&
1216 !C->InitCaptureType.get()->getAs<PackExpansionType>())
1218
1219 unsigned InitStyle;
1220 switch (C->InitKind) {
1222 llvm_unreachable("not an init-capture?");
1224 InitStyle = VarDecl::CInit;
1225 break;
1227 InitStyle = VarDecl::CallInit;
1228 break;
1230 InitStyle = VarDecl::ListInit;
1231 break;
1232 }
1233 Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
1234 C->EllipsisLoc, C->Id, InitStyle,
1235 C->Init.get(), Method);
1236 assert(Var && "createLambdaInitCaptureVarDecl returned a null VarDecl?");
1237 if (auto *V = dyn_cast<VarDecl>(Var))
1238 CheckShadow(CurrentScope, V);
1239 PushOnScopeChains(Var, CurrentScope, false);
1240 } else {
1241 assert(C->InitKind == LambdaCaptureInitKind::NoInit &&
1242 "init capture has valid but null init?");
1243
1244 // C++11 [expr.prim.lambda]p8:
1245 // If a lambda-capture includes a capture-default that is &, the
1246 // identifiers in the lambda-capture shall not be preceded by &.
1247 // If a lambda-capture includes a capture-default that is =, [...]
1248 // each identifier it contains shall be preceded by &.
1249 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
1250 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
1252 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1253 continue;
1254 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
1255 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
1257 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1258 continue;
1259 }
1260
1261 // C++11 [expr.prim.lambda]p10:
1262 // The identifiers in a capture-list are looked up using the usual
1263 // rules for unqualified name lookup (3.4.1)
1264 DeclarationNameInfo Name(C->Id, C->Loc);
1265 LookupResult R(*this, Name, LookupOrdinaryName);
1266 LookupName(R, CurScope);
1267 if (R.isAmbiguous())
1268 continue;
1269 if (R.empty()) {
1270 // FIXME: Disable corrections that would add qualification?
1271 CXXScopeSpec ScopeSpec;
1272 DeclFilterCCC<VarDecl> Validator{};
1273 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
1274 continue;
1275 }
1276
1277 if (auto *BD = R.getAsSingle<BindingDecl>())
1278 Var = BD;
1279 else if (R.getAsSingle<FieldDecl>()) {
1280 Diag(C->Loc, diag::err_capture_class_member_does_not_name_variable)
1281 << C->Id;
1282 continue;
1283 } else
1284 Var = R.getAsSingle<VarDecl>();
1285 if (Var && DiagnoseUseOfDecl(Var, C->Loc))
1286 continue;
1287 }
1288
1289 // C++11 [expr.prim.lambda]p10:
1290 // [...] each such lookup shall find a variable with automatic storage
1291 // duration declared in the reaching scope of the local lambda expression.
1292 // Note that the 'reaching scope' check happens in tryCaptureVariable().
1293 if (!Var) {
1294 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
1295 continue;
1296 }
1297
1298 // C++11 [expr.prim.lambda]p8:
1299 // An identifier or this shall not appear more than once in a
1300 // lambda-capture.
1301 if (auto [It, Inserted] = CaptureNames.insert(std::pair{C->Id, Var});
1302 !Inserted) {
1303 if (C->InitKind == LambdaCaptureInitKind::NoInit &&
1304 !Var->isInitCapture()) {
1305 Diag(C->Loc, diag::err_capture_more_than_once)
1306 << C->Id << It->second->getBeginLoc()
1308 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1309 Var->setInvalidDecl();
1310 } else if (Var && Var->isPlaceholderVar(getLangOpts())) {
1312 } else {
1313 // Previous capture captured something different (one or both was
1314 // an init-capture): no fixit.
1315 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
1316 continue;
1317 }
1318 }
1319
1320 // Ignore invalid decls; they'll just confuse the code later.
1321 if (Var->isInvalidDecl())
1322 continue;
1323
1324 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
1325
1326 if (!Underlying->hasLocalStorage()) {
1327 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
1328 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
1329 continue;
1330 }
1331
1332 // C++11 [expr.prim.lambda]p23:
1333 // A capture followed by an ellipsis is a pack expansion (14.5.3).
1334 SourceLocation EllipsisLoc;
1335 if (C->EllipsisLoc.isValid()) {
1336 if (Var->isParameterPack()) {
1337 EllipsisLoc = C->EllipsisLoc;
1338 } else {
1339 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1340 << (C->Init.isUsable() ? C->Init.get()->getSourceRange()
1341 : SourceRange(C->Loc));
1342
1343 // Just ignore the ellipsis.
1344 }
1345 } else if (Var->isParameterPack()) {
1346 ContainsUnexpandedParameterPack = true;
1347 }
1348
1349 if (C->Init.isUsable()) {
1350 addInitCapture(LSI, cast<VarDecl>(Var), C->Kind == LCK_ByRef);
1351 } else {
1352 TryCaptureKind Kind = C->Kind == LCK_ByRef
1355 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
1356 }
1357 if (!LSI->Captures.empty())
1358 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1359 }
1361 LSI->ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
1363}
1364
1366 SourceLocation MutableLoc) {
1367
1369 LSI->Mutable = MutableLoc.isValid();
1370 ContextRAII Context(*this, LSI->CallOperator, /*NewThisContext*/ false);
1371
1372 // C++11 [expr.prim.lambda]p9:
1373 // A lambda-expression whose smallest enclosing scope is a block scope is a
1374 // local lambda expression; any other lambda expression shall not have a
1375 // capture-default or simple-capture in its lambda-introducer.
1376 //
1377 // For simple-captures, this is covered by the check below that any named
1378 // entity is a variable that can be captured.
1379 //
1380 // For DR1632, we also allow a capture-default in any context where we can
1381 // odr-use 'this' (in particular, in a default initializer for a non-static
1382 // data member).
1383 if (Intro.Default != LCD_None &&
1384 !LSI->Lambda->getParent()->isFunctionOrMethod() &&
1385 (getCurrentThisType().isNull() ||
1386 CheckCXXThisCapture(SourceLocation(), /*Explicit=*/true,
1387 /*BuildAndDiagnose=*/false)))
1388 Diag(Intro.DefaultLoc, diag::err_capture_default_non_local);
1389}
1390
1394 PushDeclContext(LambdaScope, LSI->CallOperator);
1395
1396 for (const DeclaratorChunk::ParamInfo &P : Params) {
1397 auto *Param = cast<ParmVarDecl>(P.Param);
1398 Param->setOwningFunction(LSI->CallOperator);
1399 if (Param->getIdentifier())
1400 PushOnScopeChains(Param, LambdaScope, false);
1401 }
1402
1403 // After the parameter list, we may parse a noexcept/requires/trailing return
1404 // type which need to know whether the call operator constiture a dependent
1405 // context, so we need to setup the FunctionTemplateDecl of generic lambdas
1406 // now.
1407 TemplateParameterList *TemplateParams =
1409 if (TemplateParams) {
1411 TemplateParams);
1412 LSI->Lambda->setLambdaIsGeneric(true);
1414 TemplateParams->containsUnexpandedParameterPack();
1415 }
1416 LSI->AfterParameterList = true;
1417}
1418
1420 Declarator &ParamInfo,
1421 const DeclSpec &DS) {
1422
1425
1427 bool ExplicitResultType;
1428
1429 SourceLocation TypeLoc, CallOperatorLoc;
1430 if (ParamInfo.getNumTypeObjects() == 0) {
1431 CallOperatorLoc = TypeLoc = Intro.Range.getEnd();
1432 } else {
1433 unsigned Index;
1434 ParamInfo.isFunctionDeclarator(Index);
1435 const auto &Object = ParamInfo.getTypeObject(Index);
1436 TypeLoc =
1437 Object.Loc.isValid() ? Object.Loc : ParamInfo.getSourceRange().getEnd();
1438 CallOperatorLoc = ParamInfo.getSourceRange().getEnd();
1439 }
1440
1441 CXXRecordDecl *Class = LSI->Lambda;
1443
1444 TypeSourceInfo *MethodTyInfo = getLambdaType(
1445 *this, Intro, ParamInfo, getCurScope(), TypeLoc, ExplicitResultType);
1446
1447 if (ParamInfo.isFunctionDeclarator() != 0) {
1448 const auto &FTI = ParamInfo.getFunctionTypeInfo();
1449 LSI->ExplicitParams = FTI.getLParenLoc().isValid();
1450 if (!FTIHasSingleVoidParameter(FTI)) {
1451 Params.reserve(Params.size());
1452 for (unsigned I = 0; I < FTI.NumParams; ++I) {
1453 auto *Param = cast<ParmVarDecl>(FTI.Params[I].Param);
1454 Param->setScopeInfo(0, Params.size());
1455 Params.push_back(Param);
1456 }
1457 }
1458 }
1459
1460 bool IsLambdaStatic =
1462
1464 Method, Intro.Range.getBegin(), CallOperatorLoc,
1465 AssociatedConstraint(ParamInfo.getTrailingRequiresClause()), MethodTyInfo,
1466 ParamInfo.getDeclSpec().getConstexprSpecifier(),
1467 IsLambdaStatic ? SC_Static : SC_None, Params, ExplicitResultType);
1468
1470
1471 // This represents the function body for the lambda function, check if we
1472 // have to apply optnone due to a pragma.
1474
1475 // code_seg attribute on lambda apply to the method.
1477 Method, /*IsDefinition=*/true))
1478 Method->addAttr(A);
1479
1480 // Attributes on the lambda apply to the method.
1481 ProcessDeclAttributes(CurScope, Method, ParamInfo);
1482
1483 if (Context.getTargetInfo().getTriple().isAArch64())
1485
1486 // CUDA lambdas get implicit host and device attributes.
1487 if (getLangOpts().CUDA)
1489
1490 // OpenMP lambdas might get assumumption attributes.
1491 if (LangOpts.OpenMP)
1493
1495
1496 for (auto &&C : LSI->Captures) {
1497 if (!C.isVariableCapture())
1498 continue;
1499 ValueDecl *Var = C.getVariable();
1500 if (Var && Var->isInitCapture()) {
1501 PushOnScopeChains(Var, CurScope, false);
1502 }
1503 }
1504
1505 auto CheckRedefinition = [&](ParmVarDecl *Param) {
1506 for (const auto &Capture : Intro.Captures) {
1507 if (Capture.Id == Param->getIdentifier()) {
1508 Diag(Param->getLocation(), diag::err_parameter_shadow_capture);
1509 Diag(Capture.Loc, diag::note_var_explicitly_captured_here)
1510 << Capture.Id << true;
1511 return false;
1512 }
1513 }
1514 return true;
1515 };
1516
1517 for (ParmVarDecl *P : Params) {
1518 if (!P->getIdentifier())
1519 continue;
1520 if (CheckRedefinition(P))
1521 CheckShadow(CurScope, P);
1522 PushOnScopeChains(P, CurScope);
1523 }
1524
1525 // C++23 [expr.prim.lambda.capture]p5:
1526 // If an identifier in a capture appears as the declarator-id of a parameter
1527 // of the lambda-declarator's parameter-declaration-clause or as the name of a
1528 // template parameter of the lambda-expression's template-parameter-list, the
1529 // program is ill-formed.
1530 TemplateParameterList *TemplateParams =
1532 if (TemplateParams) {
1533 for (const auto *TP : TemplateParams->asArray()) {
1534 if (!TP->getIdentifier())
1535 continue;
1536 for (const auto &Capture : Intro.Captures) {
1537 if (Capture.Id == TP->getIdentifier()) {
1538 Diag(Capture.Loc, diag::err_template_param_shadow) << Capture.Id;
1540 }
1541 }
1542 }
1543 }
1544
1545 // C++20: dcl.decl.general p4:
1546 // The optional requires-clause ([temp.pre]) in an init-declarator or
1547 // member-declarator shall be present only if the declarator declares a
1548 // templated function ([dcl.fct]).
1549 if (const AssociatedConstraint &TRC = Method->getTrailingRequiresClause()) {
1550 // [temp.pre]/8:
1551 // An entity is templated if it is
1552 // - a template,
1553 // - an entity defined ([basic.def]) or created ([class.temporary]) in a
1554 // templated entity,
1555 // - a member of a templated entity,
1556 // - an enumerator for an enumeration that is a templated entity, or
1557 // - the closure type of a lambda-expression ([expr.prim.lambda.closure])
1558 // appearing in the declaration of a templated entity. [Note 6: A local
1559 // class, a local or block variable, or a friend function defined in a
1560 // templated entity is a templated entity. — end note]
1561 //
1562 // A templated function is a function template or a function that is
1563 // templated. A templated class is a class template or a class that is
1564 // templated. A templated variable is a variable template or a variable
1565 // that is templated.
1566
1567 // Note: we only have to check if this is defined in a template entity, OR
1568 // if we are a template, since the rest don't apply. The requires clause
1569 // applies to the call operator, which we already know is a member function,
1570 // AND defined.
1571 if (!Method->getDescribedFunctionTemplate() && !Method->isTemplated()) {
1572 Diag(TRC.ConstraintExpr->getBeginLoc(),
1573 diag::err_constrained_non_templated_function);
1574 }
1575 }
1576
1577 // Enter a new evaluation context to insulate the lambda from any
1578 // cleanups from the enclosing full-expression.
1581}
1582
1584 bool IsInstantiation) {
1586
1587 // Leave the expression-evaluation context.
1590
1591 // Leave the context of the lambda.
1592 if (!IsInstantiation)
1594
1595 // Finalize the lambda.
1596 CXXRecordDecl *Class = LSI->Lambda;
1597 Class->setInvalidDecl();
1598 SmallVector<Decl*, 4> Fields(Class->fields());
1599 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
1601 CheckCompletedCXXClass(nullptr, Class);
1602
1604}
1605
1606template <typename Func>
1608 Sema &S, const FunctionProtoType &CallOpProto, Func F) {
1610 CallOpProto.isVariadic(), /*IsCXXMethod=*/false);
1612 CallOpProto.isVariadic(), /*IsCXXMethod=*/true);
1613 CallingConv CallOpCC = CallOpProto.getCallConv();
1614
1615 /// Implement emitting a version of the operator for many of the calling
1616 /// conventions for MSVC, as described here:
1617 /// https://devblogs.microsoft.com/oldnewthing/20150220-00/?p=44623.
1618 /// Experimentally, we determined that cdecl, stdcall, fastcall, and
1619 /// vectorcall are generated by MSVC when it is supported by the target.
1620 /// Additionally, we are ensuring that the default-free/default-member and
1621 /// call-operator calling convention are generated as well.
1622 /// NOTE: We intentionally generate a 'thiscall' on Win32 implicitly from the
1623 /// 'member default', despite MSVC not doing so. We do this in order to ensure
1624 /// that someone who intentionally places 'thiscall' on the lambda call
1625 /// operator will still get that overload, since we don't have the a way of
1626 /// detecting the attribute by the time we get here.
1627 if (S.getLangOpts().MSVCCompat) {
1628 CallingConv Convs[] = {
1630 DefaultFree, DefaultMember, CallOpCC};
1631 llvm::sort(Convs);
1632 llvm::iterator_range<CallingConv *> Range(std::begin(Convs),
1633 llvm::unique(Convs));
1634 const TargetInfo &TI = S.getASTContext().getTargetInfo();
1635
1636 for (CallingConv C : Range) {
1638 F(C);
1639 }
1640 return;
1641 }
1642
1643 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree) {
1644 F(DefaultFree);
1645 F(DefaultMember);
1646 } else {
1647 F(CallOpCC);
1648 }
1649}
1650
1651// Returns the 'standard' calling convention to be used for the lambda
1652// conversion function, that is, the 'free' function calling convention unless
1653// it is overridden by a non-default calling convention attribute.
1654static CallingConv
1656 const FunctionProtoType *CallOpProto) {
1658 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
1660 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
1661 CallingConv CallOpCC = CallOpProto->getCallConv();
1662
1663 // If the call-operator hasn't been changed, return both the 'free' and
1664 // 'member' function calling convention.
1665 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree)
1666 return DefaultFree;
1667 return CallOpCC;
1668}
1669
1671 const FunctionProtoType *CallOpProto, CallingConv CC) {
1672 const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
1673 CallOpProto->getExtProtoInfo();
1674 FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
1675 InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
1676 InvokerExtInfo.TypeQuals = Qualifiers();
1677 assert(InvokerExtInfo.RefQualifier == RQ_None &&
1678 "Lambda's call operator should not have a reference qualifier");
1679 return Context.getFunctionType(CallOpProto->getReturnType(),
1680 CallOpProto->getParamTypes(), InvokerExtInfo);
1681}
1682
1683/// Add a lambda's conversion to function pointer, as described in
1684/// C++11 [expr.prim.lambda]p6.
1685static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange,
1686 CXXRecordDecl *Class,
1687 CXXMethodDecl *CallOperator,
1688 QualType InvokerFunctionTy) {
1689 // This conversion is explicitly disabled if the lambda's function has
1690 // pass_object_size attributes on any of its parameters.
1691 auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) {
1692 return P->hasAttr<PassObjectSizeAttr>();
1693 };
1694 if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr))
1695 return;
1696
1697 // Add the conversion to function pointer.
1698 QualType PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
1699
1700 // Create the type of the conversion function.
1703 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1704 // The conversion function is always const and noexcept.
1705 ConvExtInfo.TypeQuals = Qualifiers();
1706 ConvExtInfo.TypeQuals.addConst();
1707 ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept;
1708 QualType ConvTy = S.Context.getFunctionType(PtrToFunctionTy, {}, ConvExtInfo);
1709
1710 SourceLocation Loc = IntroducerRange.getBegin();
1711 DeclarationName ConversionName
1713 S.Context.getCanonicalType(PtrToFunctionTy));
1714 // Construct a TypeSourceInfo for the conversion function, and wire
1715 // all the parameters appropriately for the FunctionProtoTypeLoc
1716 // so that everything works during transformation/instantiation of
1717 // generic lambdas.
1718 // The main reason for wiring up the parameters of the conversion
1719 // function with that of the call operator is so that constructs
1720 // like the following work:
1721 // auto L = [](auto b) { <-- 1
1722 // return [](auto a) -> decltype(a) { <-- 2
1723 // return a;
1724 // };
1725 // };
1726 // int (*fp)(int) = L(5);
1727 // Because the trailing return type can contain DeclRefExprs that refer
1728 // to the original call operator's variables, we hijack the call
1729 // operators ParmVarDecls below.
1730 TypeSourceInfo *ConvNamePtrToFunctionTSI =
1731 S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
1732 DeclarationNameLoc ConvNameLoc =
1733 DeclarationNameLoc::makeNamedTypeLoc(ConvNamePtrToFunctionTSI);
1734
1735 // The conversion function is a conversion to a pointer-to-function.
1736 TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
1737 FunctionProtoTypeLoc ConvTL =
1739 // Get the result of the conversion function which is a pointer-to-function.
1740 PointerTypeLoc PtrToFunctionTL =
1741 ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
1742 // Do the same for the TypeSourceInfo that is used to name the conversion
1743 // operator.
1744 PointerTypeLoc ConvNamePtrToFunctionTL =
1745 ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
1746
1747 // Get the underlying function types that the conversion function will
1748 // be converting to (should match the type of the call operator).
1749 FunctionProtoTypeLoc CallOpConvTL =
1750 PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1751 FunctionProtoTypeLoc CallOpConvNameTL =
1752 ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1753
1754 // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1755 // These parameter's are essentially used to transform the name and
1756 // the type of the conversion operator. By using the same parameters
1757 // as the call operator's we don't have to fix any back references that
1758 // the trailing return type of the call operator's uses (such as
1759 // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1760 // - we can simply use the return type of the call operator, and
1761 // everything should work.
1762 SmallVector<ParmVarDecl *, 4> InvokerParams;
1763 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1764 ParmVarDecl *From = CallOperator->getParamDecl(I);
1765
1766 InvokerParams.push_back(ParmVarDecl::Create(
1767 S.Context,
1768 // Temporarily add to the TU. This is set to the invoker below.
1770 From->getLocation(), From->getIdentifier(), From->getType(),
1771 From->getTypeSourceInfo(), From->getStorageClass(),
1772 /*DefArg=*/nullptr));
1773 CallOpConvTL.setParam(I, From);
1774 CallOpConvNameTL.setParam(I, From);
1775 }
1776
1778 S.Context, Class, Loc,
1779 DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), ConvTy, ConvTSI,
1781 /*isInline=*/true, ExplicitSpecifier(),
1784 CallOperator->getBody()->getEndLoc());
1785 Conversion->setAccess(AS_public);
1786 Conversion->setImplicit(true);
1787
1788 // A non-generic lambda may still be a templated entity. We need to preserve
1789 // constraints when converting the lambda to a function pointer. See GH63181.
1790 if (const AssociatedConstraint &Requires =
1791 CallOperator->getTrailingRequiresClause())
1792 Conversion->setTrailingRequiresClause(Requires);
1793
1794 if (Class->isGenericLambda()) {
1795 // Create a template version of the conversion operator, using the template
1796 // parameter list of the function call operator.
1797 FunctionTemplateDecl *TemplateCallOperator =
1798 CallOperator->getDescribedFunctionTemplate();
1799 FunctionTemplateDecl *ConversionTemplate =
1801 Loc, ConversionName,
1802 TemplateCallOperator->getTemplateParameters(),
1803 Conversion);
1804 ConversionTemplate->setAccess(AS_public);
1805 ConversionTemplate->setImplicit(true);
1806 Conversion->setDescribedFunctionTemplate(ConversionTemplate);
1807 Class->addDecl(ConversionTemplate);
1808 } else
1809 Class->addDecl(Conversion);
1810
1811 // If the lambda is not static, we need to add a static member
1812 // function that will be the result of the conversion with a
1813 // certain unique ID.
1814 // When it is static we just return the static call operator instead.
1815 if (CallOperator->isImplicitObjectMemberFunction()) {
1816 DeclarationName InvokerName =
1818 // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1819 // we should get a prebuilt TrivialTypeSourceInfo from Context
1820 // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1821 // then rewire the parameters accordingly, by hoisting up the InvokeParams
1822 // loop below and then use its Params to set Invoke->setParams(...) below.
1823 // This would avoid the 'const' qualifier of the calloperator from
1824 // contaminating the type of the invoker, which is currently adjusted
1825 // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the
1826 // trailing return type of the invoker would require a visitor to rebuild
1827 // the trailing return type and adjusting all back DeclRefExpr's to refer
1828 // to the new static invoker parameters - not the call operator's.
1830 S.Context, Class, Loc, DeclarationNameInfo(InvokerName, Loc),
1831 InvokerFunctionTy, CallOperator->getTypeSourceInfo(), SC_Static,
1833 /*isInline=*/true, CallOperator->getConstexprKind(),
1834 CallOperator->getBody()->getEndLoc());
1835 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
1836 InvokerParams[I]->setOwningFunction(Invoke);
1837 Invoke->setParams(InvokerParams);
1838 Invoke->setAccess(AS_private);
1839 Invoke->setImplicit(true);
1840 if (Class->isGenericLambda()) {
1841 FunctionTemplateDecl *TemplateCallOperator =
1842 CallOperator->getDescribedFunctionTemplate();
1843 FunctionTemplateDecl *StaticInvokerTemplate =
1845 S.Context, Class, Loc, InvokerName,
1846 TemplateCallOperator->getTemplateParameters(), Invoke);
1847 StaticInvokerTemplate->setAccess(AS_private);
1848 StaticInvokerTemplate->setImplicit(true);
1849 Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1850 Class->addDecl(StaticInvokerTemplate);
1851 } else
1852 Class->addDecl(Invoke);
1853 }
1854}
1855
1856/// Add a lambda's conversion to function pointers, as described in
1857/// C++11 [expr.prim.lambda]p6. Note that in most cases, this should emit only a
1858/// single pointer conversion. In the event that the default calling convention
1859/// for free and member functions is different, it will emit both conventions.
1860static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange,
1861 CXXRecordDecl *Class,
1862 CXXMethodDecl *CallOperator) {
1863 const FunctionProtoType *CallOpProto =
1864 CallOperator->getType()->castAs<FunctionProtoType>();
1865
1867 S, *CallOpProto, [&](CallingConv CC) {
1868 QualType InvokerFunctionTy =
1869 S.getLambdaConversionFunctionResultType(CallOpProto, CC);
1870 addFunctionPointerConversion(S, IntroducerRange, Class, CallOperator,
1871 InvokerFunctionTy);
1872 });
1873}
1874
1875/// Add a lambda's conversion to block pointer.
1877 SourceRange IntroducerRange,
1878 CXXRecordDecl *Class,
1879 CXXMethodDecl *CallOperator) {
1880 const FunctionProtoType *CallOpProto =
1881 CallOperator->getType()->castAs<FunctionProtoType>();
1883 CallOpProto, getLambdaConversionFunctionCallConv(S, CallOpProto));
1884 QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
1885
1886 FunctionProtoType::ExtProtoInfo ConversionEPI(
1888 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1889 ConversionEPI.TypeQuals = Qualifiers();
1890 ConversionEPI.TypeQuals.addConst();
1891 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, {}, ConversionEPI);
1892
1893 SourceLocation Loc = IntroducerRange.getBegin();
1894 DeclarationName Name
1896 S.Context.getCanonicalType(BlockPtrTy));
1898 S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc));
1900 S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), ConvTy,
1901 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
1904 CallOperator->getBody()->getEndLoc());
1905 Conversion->setAccess(AS_public);
1906 Conversion->setImplicit(true);
1907 Class->addDecl(Conversion);
1908}
1909
1911 SourceLocation ImplicitCaptureLoc,
1912 bool IsOpenMPMapping) {
1913 // VLA captures don't have a stored initialization expression.
1914 if (Cap.isVLATypeCapture())
1915 return ExprResult();
1916
1917 // An init-capture is initialized directly from its stored initializer.
1918 if (Cap.isInitCapture())
1919 return cast<VarDecl>(Cap.getVariable())->getInit();
1920
1921 // For anything else, build an initialization expression. For an implicit
1922 // capture, the capture notionally happens at the capture-default, so use
1923 // that location here.
1924 SourceLocation Loc =
1925 ImplicitCaptureLoc.isValid() ? ImplicitCaptureLoc : Cap.getLocation();
1926
1927 // C++11 [expr.prim.lambda]p21:
1928 // When the lambda-expression is evaluated, the entities that
1929 // are captured by copy are used to direct-initialize each
1930 // corresponding non-static data member of the resulting closure
1931 // object. (For array members, the array elements are
1932 // direct-initialized in increasing subscript order.) These
1933 // initializations are performed in the (unspecified) order in
1934 // which the non-static data members are declared.
1935
1936 // C++ [expr.prim.lambda]p12:
1937 // An entity captured by a lambda-expression is odr-used (3.2) in
1938 // the scope containing the lambda-expression.
1940 IdentifierInfo *Name = nullptr;
1941 if (Cap.isThisCapture()) {
1942 QualType ThisTy = getCurrentThisType();
1943 Expr *This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.isValid());
1944 if (Cap.isCopyCapture())
1945 Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
1946 else
1947 Init = This;
1948 } else {
1949 assert(Cap.isVariableCapture() && "unknown kind of capture");
1950 ValueDecl *Var = Cap.getVariable();
1951 Name = Var->getIdentifier();
1953 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
1954 }
1955
1956 // In OpenMP, the capture kind doesn't actually describe how to capture:
1957 // variables are "mapped" onto the device in a process that does not formally
1958 // make a copy, even for a "copy capture".
1959 if (IsOpenMPMapping)
1960 return Init;
1961
1962 if (Init.isInvalid())
1963 return ExprError();
1964
1965 Expr *InitExpr = Init.get();
1967 Name, Cap.getCaptureType(), Loc);
1968 InitializationKind InitKind =
1969 InitializationKind::CreateDirect(Loc, Loc, Loc);
1970 InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr);
1971 return InitSeq.Perform(*this, Entity, InitKind, InitExpr);
1972}
1973
1976
1977 if (LSI.CallOperator->hasAttr<SYCLKernelEntryPointAttr>())
1979
1980 ActOnFinishFunctionBody(LSI.CallOperator, Body, /*IsInstantiation=*/false,
1981 /*RetainFunctionScopeInfo=*/true);
1982
1983 return BuildLambdaExpr(StartLoc, Body->getEndLoc());
1984}
1985
1988 switch (ICS) {
1990 return LCD_None;
1992 return LCD_ByCopy;
1995 return LCD_ByRef;
1997 llvm_unreachable("block capture in lambda");
1998 }
1999 llvm_unreachable("Unknown implicit capture style");
2000}
2001
2003 if (From.isInitCapture()) {
2004 Expr *Init = cast<VarDecl>(From.getVariable())->getInit();
2005 if (Init && Init->HasSideEffects(Context))
2006 return true;
2007 }
2008
2009 if (!From.isCopyCapture())
2010 return false;
2011
2012 const QualType T = From.isThisCapture()
2014 : From.getCaptureType();
2015
2016 if (T.isVolatileQualified())
2017 return true;
2018
2019 const Type *BaseT = T->getBaseElementTypeUnsafe();
2020 if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl())
2021 return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() ||
2022 !RD->hasTrivialDestructor();
2023
2024 return false;
2025}
2026
2028 SourceRange FixItRange,
2029 const Capture &From) {
2030 if (CaptureHasSideEffects(From))
2031 return false;
2032
2033 if (From.isVLATypeCapture())
2034 return false;
2035
2036 // FIXME: maybe we should warn on these if we can find a sensible diagnostic
2037 // message
2038 if (From.isInitCapture() &&
2040 return false;
2041
2042 auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture);
2043 if (From.isThisCapture())
2044 diag << "'this'";
2045 else
2046 diag << From.getVariable();
2047 diag << From.isNonODRUsed();
2048 // If we were able to resolve the fixit range we'll create a fixit,
2049 // otherwise we just use the raw capture range for the diagnostic.
2050 if (FixItRange.isValid())
2051 diag << FixItHint::CreateRemoval(FixItRange);
2052 else
2053 diag << CaptureRange;
2054 return true;
2055}
2056
2057/// Create a field within the lambda class or captured statement record for the
2058/// given capture.
2060 const sema::Capture &Capture) {
2062 QualType FieldType = Capture.getCaptureType();
2063
2064 TypeSourceInfo *TSI = nullptr;
2065 if (Capture.isVariableCapture()) {
2066 const auto *Var = dyn_cast_or_null<VarDecl>(Capture.getVariable());
2067 if (Var && Var->isInitCapture())
2068 TSI = Var->getTypeSourceInfo();
2069 }
2070
2071 // FIXME: Should we really be doing this? A null TypeSourceInfo seems more
2072 // appropriate, at least for an implicit capture.
2073 if (!TSI)
2074 TSI = Context.getTrivialTypeSourceInfo(FieldType, Loc);
2075
2076 // Build the non-static data member.
2077 FieldDecl *Field =
2078 FieldDecl::Create(Context, RD, /*StartLoc=*/Loc, /*IdLoc=*/Loc,
2079 /*Id=*/nullptr, FieldType, TSI, /*BW=*/nullptr,
2080 /*Mutable=*/false, ICIS_NoInit);
2081 // If the variable being captured has an invalid type, mark the class as
2082 // invalid as well.
2083 if (!FieldType->isDependentType()) {
2084 if (RequireCompleteSizedType(Loc, FieldType,
2085 diag::err_field_incomplete_or_sizeless)) {
2086 RD->setInvalidDecl();
2087 Field->setInvalidDecl();
2088 } else {
2089 NamedDecl *Def;
2090 FieldType->isIncompleteType(&Def);
2091 if (Def && Def->isInvalidDecl()) {
2092 RD->setInvalidDecl();
2093 Field->setInvalidDecl();
2094 }
2095 }
2096 }
2097 Field->setImplicit(true);
2098 Field->setAccess(AS_private);
2099 RD->addDecl(Field);
2100
2102 Field->setCapturedVLAType(Capture.getCapturedVLAType());
2103
2104 return Field;
2105}
2106
2107static SourceRange
2109 SourceLocation PrevCaptureLoc,
2110 bool CurHasPreviousCapture, bool IsLast) {
2111 if (!CaptureRange.isValid())
2112 return SourceRange();
2113
2114 auto GetTrailingEndLocation = [&](SourceLocation StartPoint) {
2115 SourceRange NextToken = S.getRangeForNextToken(
2116 StartPoint, /*IncludeMacros=*/false, /*IncludeComments=*/true);
2117 if (!NextToken.isValid())
2118 return SourceLocation();
2119 // Return the last location preceding the next token
2120 return NextToken.getBegin().getLocWithOffset(-1);
2121 };
2122
2123 if (!CurHasPreviousCapture && !IsLast) {
2124 // If there are no captures preceding this capture, remove the
2125 // trailing comma and anything up to the next token
2126 SourceRange CommaRange =
2127 S.getRangeForNextToken(CaptureRange.getEnd(), /*IncludeMacros=*/false,
2128 /*IncludeComments=*/false, tok::comma);
2129 SourceLocation FixItEnd = GetTrailingEndLocation(CommaRange.getBegin());
2130 return SourceRange(CaptureRange.getBegin(), FixItEnd);
2131 }
2132
2133 // Otherwise, remove the comma since the last used capture, and
2134 // anything up to the next token
2135 SourceLocation FixItStart = S.getLocForEndOfToken(PrevCaptureLoc);
2136 SourceLocation FixItEnd = GetTrailingEndLocation(CaptureRange.getEnd());
2137 return SourceRange(FixItStart, FixItEnd);
2138}
2139
2141 SourceLocation EndLoc) {
2143 // Collect information from the lambda scope.
2145 SmallVector<Expr *, 4> CaptureInits;
2146 SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc;
2147 LambdaCaptureDefault CaptureDefault =
2149 CXXRecordDecl *Class = LSI->Lambda;
2150 CXXMethodDecl *CallOperator = LSI->CallOperator;
2151 SourceRange IntroducerRange = LSI->IntroducerRange;
2152 bool ExplicitParams = LSI->ExplicitParams;
2153 bool ExplicitResultType = !LSI->HasImplicitReturnType;
2154 CleanupInfo LambdaCleanup = LSI->Cleanup;
2155 bool ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
2156 bool IsGenericLambda = Class->isGenericLambda();
2157
2158 CallOperator->setLexicalDeclContext(Class);
2159 Decl *TemplateOrNonTemplateCallOperatorDecl =
2160 CallOperator->getDescribedFunctionTemplate()
2161 ? CallOperator->getDescribedFunctionTemplate()
2162 : cast<Decl>(CallOperator);
2163
2164 // FIXME: Is this really the best choice? Keeping the lexical decl context
2165 // set as CurContext seems more faithful to the source.
2166 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
2167
2169
2171 AnalysisWarnings.getPolicyInEffectAt(EndLoc);
2172 // We cannot release LSI until we finish computing captures, which
2173 // requires the scope to be popped.
2175
2176 // True if the current capture has a used capture or default before it.
2177 bool CurHasPreviousCapture = CaptureDefault != LCD_None;
2178 SourceLocation PrevCaptureLoc =
2179 CurHasPreviousCapture ? CaptureDefaultLoc : IntroducerRange.getBegin();
2180
2181 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
2182 const Capture &From = LSI->Captures[I];
2183
2184 if (From.isInvalid())
2185 return ExprError();
2186
2187 assert(!From.isBlockCapture() && "Cannot capture __block variables");
2188 bool IsImplicit = I >= LSI->NumExplicitCaptures;
2189 SourceLocation ImplicitCaptureLoc =
2190 IsImplicit ? CaptureDefaultLoc : SourceLocation();
2191
2192 // Use source ranges of explicit captures for fixits where available.
2193 SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I];
2194
2195 // Warn about unused explicit captures.
2196 bool IsCaptureUsed = true;
2197 if (!CurContext->isDependentContext() && !IsImplicit && !From.isODRUsed()) {
2198 // Initialized captures that are non-ODR used may not be eliminated.
2199 // FIXME: Where did the IsGenericLambda here come from?
2200 bool NonODRUsedInitCapture =
2201 IsGenericLambda && From.isNonODRUsed() && From.isInitCapture();
2202 if (!NonODRUsedInitCapture) {
2203 bool IsLast = (I + 1) == LSI->NumExplicitCaptures;
2205 *this, CaptureRange, PrevCaptureLoc, CurHasPreviousCapture, IsLast);
2206 IsCaptureUsed =
2207 !DiagnoseUnusedLambdaCapture(CaptureRange, FixItRange, From);
2208 }
2209 }
2210
2211 if (CaptureRange.isValid()) {
2212 CurHasPreviousCapture |= IsCaptureUsed;
2213 PrevCaptureLoc = CaptureRange.getEnd();
2214 }
2215
2216 // Map the capture to our AST representation.
2217 LambdaCapture Capture = [&] {
2218 if (From.isThisCapture()) {
2219 // Capturing 'this' implicitly with a default of '[=]' is deprecated,
2220 // because it results in a reference capture. Don't warn prior to
2221 // C++2a; there's nothing that can be done about it before then.
2222 if (getLangOpts().CPlusPlus20 && IsImplicit &&
2223 CaptureDefault == LCD_ByCopy) {
2224 Diag(From.getLocation(), diag::warn_deprecated_this_capture);
2225 Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture)
2227 getLocForEndOfToken(CaptureDefaultLoc), ", this");
2228 }
2229 return LambdaCapture(From.getLocation(), IsImplicit,
2231 } else if (From.isVLATypeCapture()) {
2232 return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType);
2233 } else {
2234 assert(From.isVariableCapture() && "unknown kind of capture");
2235 ValueDecl *Var = From.getVariable();
2237 return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var,
2238 From.getEllipsisLoc());
2239 }
2240 }();
2241
2242 // Form the initializer for the capture field.
2243 ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc);
2244
2245 // FIXME: Skip this capture if the capture is not used, the initializer
2246 // has no side-effects, the type of the capture is trivial, and the
2247 // lambda is not externally visible.
2248
2249 // Add a FieldDecl for the capture and form its initializer.
2250 BuildCaptureField(Class, From);
2251 Captures.push_back(Capture);
2252 CaptureInits.push_back(Init.get());
2253
2254 if (LangOpts.CUDA)
2255 CUDA().CheckLambdaCapture(CallOperator, From);
2256 }
2257
2258 Class->setCaptures(Context, Captures);
2259
2260 // C++11 [expr.prim.lambda]p6:
2261 // The closure type for a lambda-expression with no lambda-capture
2262 // has a public non-virtual non-explicit const conversion function
2263 // to pointer to function having the same parameter and return
2264 // types as the closure type's function call operator.
2265 if (Captures.empty() && CaptureDefault == LCD_None)
2266 addFunctionPointerConversions(*this, IntroducerRange, Class, CallOperator);
2267
2268 // Objective-C++:
2269 // The closure type for a lambda-expression has a public non-virtual
2270 // non-explicit const conversion function to a block pointer having the
2271 // same parameter and return types as the closure type's function call
2272 // operator.
2273 // FIXME: Fix generic lambda to block conversions.
2274 if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda)
2275 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
2276
2277 // Finalize the lambda class.
2278 SmallVector<Decl *, 4> Fields(Class->fields());
2279 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
2281 CheckCompletedCXXClass(nullptr, Class);
2282
2283 Cleanup.mergeFrom(LambdaCleanup);
2284
2285 LambdaExpr *Lambda =
2286 LambdaExpr::Create(Context, Class, IntroducerRange, CaptureDefault,
2287 CaptureDefaultLoc, ExplicitParams, ExplicitResultType,
2288 CaptureInits, EndLoc, ContainsUnexpandedParameterPack);
2289
2290 // If the lambda expression's call operator is not explicitly marked constexpr
2291 // and is not dependent, analyze the call operator to infer
2292 // its constexpr-ness, suppressing diagnostics while doing so.
2293 if (getLangOpts().CPlusPlus17 && !CallOperator->isInvalidDecl() &&
2294 !CallOperator->isConstexpr() &&
2295 !isa<CoroutineBodyStmt>(CallOperator->getBody()) &&
2296 !Class->isDependentContext()) {
2297 CallOperator->setConstexprKind(
2302 }
2303
2304 // Emit delayed shadowing warnings now that the full capture list is known.
2306
2307 if (!CurContext->isDependentContext()) {
2308 switch (ExprEvalContexts.back().Context) {
2309 // C++11 [expr.prim.lambda]p2:
2310 // A lambda-expression shall not appear in an unevaluated operand
2311 // (Clause 5).
2315 // C++1y [expr.const]p2:
2316 // A conditional-expression e is a core constant expression unless the
2317 // evaluation of e, following the rules of the abstract machine, would
2318 // evaluate [...] a lambda-expression.
2319 //
2320 // This is technically incorrect, there are some constant evaluated contexts
2321 // where this should be allowed. We should probably fix this when DR1607 is
2322 // ratified, it lays out the exact set of conditions where we shouldn't
2323 // allow a lambda-expression.
2326 // We don't actually diagnose this case immediately, because we
2327 // could be within a context where we might find out later that
2328 // the expression is potentially evaluated (e.g., for typeid).
2329 ExprEvalContexts.back().Lambdas.push_back(Lambda);
2330 break;
2331
2335 break;
2336 }
2338 }
2339
2340 return MaybeBindToTemporary(Lambda);
2341}
2342
2344 SourceLocation ConvLocation,
2345 CXXConversionDecl *Conv,
2346 Expr *Src) {
2347 // Make sure that the lambda call operator is marked used.
2348 CXXRecordDecl *Lambda = Conv->getParent();
2349 CXXMethodDecl *CallOperator
2351 Lambda->lookup(
2352 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
2353 CallOperator->setReferenced();
2354 CallOperator->markUsed(Context);
2355
2358 CurrentLocation, Src);
2359 if (!Init.isInvalid())
2360 Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
2361
2362 if (Init.isInvalid())
2363 return ExprError();
2364
2365 // Create the new block to be returned.
2367
2368 // Set the type information.
2369 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
2370 Block->setIsVariadic(CallOperator->isVariadic());
2371 Block->setBlockMissingReturnType(false);
2372
2373 // Add parameters.
2375 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
2376 ParmVarDecl *From = CallOperator->getParamDecl(I);
2377 BlockParams.push_back(ParmVarDecl::Create(
2378 Context, Block, From->getBeginLoc(), From->getLocation(),
2379 From->getIdentifier(), From->getType(), From->getTypeSourceInfo(),
2380 From->getStorageClass(),
2381 /*DefArg=*/nullptr));
2382 }
2383 Block->setParams(BlockParams);
2384
2385 Block->setIsConversionFromLambda(true);
2386
2387 // Add capture. The capture uses a fake variable, which doesn't correspond
2388 // to any actual memory location. However, the initializer copy-initializes
2389 // the lambda object.
2390 TypeSourceInfo *CapVarTSI =
2391 Context.getTrivialTypeSourceInfo(Src->getType());
2392 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
2393 ConvLocation, nullptr,
2394 Src->getType(), CapVarTSI,
2395 SC_None);
2396 BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false,
2397 /*nested=*/false, /*copy=*/Init.get());
2398 Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false);
2399
2400 // Add a fake function body to the block. IR generation is responsible
2401 // for filling in the actual body, which cannot be expressed as an AST.
2402 Block->setBody(new (Context) CompoundStmt(ConvLocation));
2403
2404 // Create the block literal expression.
2405 // TODO: Do we ever get here if we have unexpanded packs in the lambda???
2406 Expr *BuildBlock =
2408 /*ContainsUnexpandedParameterPack=*/false);
2409 ExprCleanupObjects.push_back(Block);
2410 Cleanup.setExprNeedsCleanups(true);
2411
2412 return BuildBlock;
2413}
2414
2419 return FD;
2420 }
2421
2423 return FD->getInstantiatedFromDecl();
2424
2426 if (!FTD)
2427 return nullptr;
2428
2431
2432 return FTD->getTemplatedDecl();
2433}
2434
2435bool Sema::addInstantiatedCapturesToScope(
2436 FunctionDecl *Function, const FunctionDecl *PatternDecl,
2438 const MultiLevelTemplateArgumentList &TemplateArgs) {
2439 const auto *LambdaClass = cast<CXXMethodDecl>(Function)->getParent();
2440 const auto *LambdaPattern = cast<CXXMethodDecl>(PatternDecl)->getParent();
2441
2442 unsigned Instantiated = 0;
2443
2444 // FIXME: This is a workaround for not having deferred lambda body
2445 // instantiation.
2446 // When transforming a lambda's body, if we encounter another call to a
2447 // nested lambda that contains a constraint expression, we add all of the
2448 // outer lambda's instantiated captures to the current instantiation scope to
2449 // facilitate constraint evaluation. However, these captures don't appear in
2450 // the CXXRecordDecl until after the lambda expression is rebuilt, so we
2451 // pull them out from the corresponding LSI.
2452 LambdaScopeInfo *InstantiatingScope = nullptr;
2453 if (LambdaPattern->capture_size() && !LambdaClass->capture_size()) {
2454 for (FunctionScopeInfo *Scope : llvm::reverse(FunctionScopes)) {
2455 auto *LSI = dyn_cast<LambdaScopeInfo>(Scope);
2456 if (!LSI || getPatternFunctionDecl(LSI->CallOperator) != PatternDecl)
2457 continue;
2458 InstantiatingScope = LSI;
2459 break;
2460 }
2461 assert(InstantiatingScope);
2462 }
2463
2464 auto AddSingleCapture = [&](const ValueDecl *CapturedPattern,
2465 unsigned Index) {
2466 ValueDecl *CapturedVar =
2467 InstantiatingScope ? InstantiatingScope->Captures[Index].getVariable()
2468 : LambdaClass->getCapture(Index)->getCapturedVar();
2469 assert(CapturedVar->isInitCapture());
2470 Scope.InstantiatedLocal(CapturedPattern, CapturedVar);
2471 };
2472
2473 for (const LambdaCapture &CapturePattern : LambdaPattern->captures()) {
2474 if (!CapturePattern.capturesVariable()) {
2475 Instantiated++;
2476 continue;
2477 }
2478 ValueDecl *CapturedPattern = CapturePattern.getCapturedVar();
2479
2480 if (!CapturedPattern->isInitCapture()) {
2481 Instantiated++;
2482 continue;
2483 }
2484
2485 if (!CapturedPattern->isParameterPack()) {
2486 AddSingleCapture(CapturedPattern, Instantiated++);
2487 } else {
2488 Scope.MakeInstantiatedLocalArgPack(CapturedPattern);
2489 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2490 SemaRef.collectUnexpandedParameterPacks(
2491 dyn_cast<VarDecl>(CapturedPattern)->getInit(), Unexpanded);
2492 auto NumArgumentsInExpansion =
2493 getNumArgumentsInExpansionFromUnexpanded(Unexpanded, TemplateArgs);
2494 if (!NumArgumentsInExpansion)
2495 continue;
2496 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg)
2497 AddSingleCapture(CapturedPattern, Instantiated++);
2498 }
2499 }
2500 return false;
2501}
2502
2506 LocalInstantiationScope &Scope, bool ShouldAddDeclsFromParentScope)
2508 if (!isLambdaCallOperator(FD)) {
2510 return;
2511 }
2512
2513 SemaRef.RebuildLambdaScopeInfo(cast<CXXMethodDecl>(FD));
2514
2515 FunctionDecl *FDPattern = getPatternFunctionDecl(FD);
2516 if (!FDPattern)
2517 return;
2518
2519 if (!ShouldAddDeclsFromParentScope)
2520 return;
2521
2523 InstantiationAndPatterns;
2524 while (FDPattern && FD) {
2525 InstantiationAndPatterns.emplace_back(FDPattern, FD);
2526
2527 FDPattern =
2528 dyn_cast<FunctionDecl>(getLambdaAwareParentOfDeclContext(FDPattern));
2529 FD = dyn_cast<FunctionDecl>(getLambdaAwareParentOfDeclContext(FD));
2530 }
2531
2532 // Add instantiated parameters and local vars to scopes, starting from the
2533 // outermost lambda to the innermost lambda. This ordering ensures that
2534 // the outer instantiations can be found when referenced from within inner
2535 // lambdas.
2536 //
2537 // auto L = [](auto... x) {
2538 // return [](decltype(x)... y) { }; // Instantiating y needs x
2539 // };
2540 //
2541
2542 for (auto [FDPattern, FD] : llvm::reverse(InstantiationAndPatterns)) {
2543 SemaRef.addInstantiatedParametersToScope(FD, FDPattern, Scope, MLTAL);
2544 SemaRef.addInstantiatedLocalVarsToScope(FD, FDPattern, Scope);
2545
2546 if (isLambdaCallOperator(FD))
2547 SemaRef.addInstantiatedCapturesToScope(FD, FDPattern, Scope, MLTAL);
2548 }
2549}
#define V(N, I)
This file provides some common utility functions for processing Lambda related AST Constructs.
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the clang::Expr interface and subclasses for C++ expressions.
This file declares semantic analysis functions specific to ARM.
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,...
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...
static TypeSourceInfo * getLambdaType(Sema &S, LambdaIntroducer &Intro, Declarator &ParamInfo, Scope *CurScope, SourceLocation Loc, bool &ExplicitResultType)
static FunctionDecl * getPatternFunctionDecl(FunctionDecl *FD)
static LambdaScopeInfo * getCurrentLambdaScopeUnsafe(Sema &S)
static UnsignedOrNone getStackIndexOfNearestEnclosingCaptureReadyLambda(ArrayRef< const clang::sema::FunctionScopeInfo * > FunctionScopes, ValueDecl *VarToCapture)
Examines the FunctionScopeInfo stack to determine the nearest enclosing lambda (to the current lambda...
static void adjustBlockReturnsToEnum(Sema &S, ArrayRef< ReturnStmt * > returns, QualType returnType)
Adjust the given return statements so that they formally return the given type.
static TemplateParameterList * getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef)
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)
static SourceRange ConstructFixItRangeForUnusedCapture(Sema &S, SourceRange CaptureRange, SourceLocation PrevCaptureLoc, bool CurHasPreviousCapture, bool IsLast)
static TypeSourceInfo * getDummyLambdaType(Sema &S, SourceLocation Loc=SourceLocation())
static QualType buildTypeForLambdaCallOperator(Sema &S, clang::CXXRecordDecl *Class, TemplateParameterList *TemplateParams, TypeSourceInfo *MethodTypeInfo)
static bool isInInlineFunction(const DeclContext *DC)
Determine whether the given context is or is enclosed in an inline function.
static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange, CXXRecordDecl *Class, CXXMethodDecl *CallOperator)
Add a lambda's conversion to function pointers, as described in C++11 [expr.prim.lambda]p6.
static void repeatForLambdaConversionFunctionCallingConvs(Sema &S, const FunctionProtoType &CallOpProto, Func F)
static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange, CXXRecordDecl *Class, CXXMethodDecl *CallOperator, QualType InvokerFunctionTy)
Add a lambda's conversion to function pointer, as described in C++11 [expr.prim.lambda]p6.
This file provides some common utility functions for processing Lambdas.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis for SYCL constructs.
a trap message and trap category.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
TranslationUnitDecl * getTranslationUnitDecl() const
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
DeclarationNameTable DeclarationNames
Definition ASTContext.h:794
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType DependentTy
IdentifierTable & Idents
Definition ASTContext.h:790
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType VoidTy
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:909
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType getCanonicalTagType(const TagDecl *TD) const
PtrTy get() const
Definition Ownership.h:171
Attr - This represents one attribute.
Definition Attr.h:45
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4038
A binding in a decomposition declaration.
Definition DeclCXX.h:4181
A class which contains all the information about a particular captured value.
Definition Decl.h:4677
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4671
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition Decl.cpp:5640
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6624
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
CXXBasePath & front()
bool isAmbiguous(CanQualType BaseType) const
Determine whether the path from the most-derived type to the given base type is ambiguous (i....
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2939
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, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3223
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:2979
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
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:2710
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, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:2488
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2255
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
void setLambdaTypeInfo(TypeSourceInfo *TS)
Definition DeclCXX.h:1864
void setLambdaIsGeneric(bool IsGeneric)
Definition DeclCXX.h:1875
static CXXRecordDecl * CreateLambda(const ASTContext &C, DeclContext *DC, TypeSourceInfo *Info, SourceLocation Loc, unsigned DependencyKind, bool IsGeneric, LambdaCaptureDefault CaptureDefault)
Definition DeclCXX.cpp:141
bool isCapturelessLambda() const
Definition DeclCXX.h:1064
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
ConditionalOperator - The ?
Definition Expr.h:4391
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2238
bool isRequiresExprBody() const
Definition DeclBase.h:2194
bool isFileContext() const
Definition DeclBase.h:2180
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2125
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool isTranslationUnit() const
Definition DeclBase.h:2185
void addDecl(Decl *D)
Add the declaration D into this context.
bool isFunctionOrMethod() const
Definition DeclBase.h:2161
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:1270
Captures information about "declaration specifiers".
Definition DeclSpec.h:217
SCS getStorageClassSpec() const
Definition DeclSpec.h:471
bool SetTypeQual(TQ T, SourceLocation Loc)
Definition DeclSpec.cpp:991
ConstexprSpecKind getConstexprSpecifier() const
Definition DeclSpec.h:802
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition DeclBase.cpp:590
bool isInvalidDecl() const
Definition DeclBase.h:588
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:502
SourceLocation getLocation() const
Definition DeclBase.h:439
void setImplicit(bool I=true)
Definition DeclBase.h:594
void setReferenced(bool R=true)
Definition DeclBase.h:623
DeclContext * getDeclContext()
Definition DeclBase.h:448
bool hasAttr() const
Definition DeclBase.h:577
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:386
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.
The name of a declaration.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:831
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:855
void setTrailingRequiresClause(const AssociatedConstraint &AC)
Definition Decl.cpp:2030
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1874
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2430
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2372
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2021
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition DeclSpec.h:2607
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2368
bool isExplicitObjectMemberFunction()
Definition DeclSpec.cpp:398
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2056
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2461
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3423
Represents an enum.
Definition Decl.h:4010
Store information needed for an explicit specifier.
Definition DeclCXX.h:1924
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition ExprCXX.h:3661
This represents one expression.
Definition Expr.h:112
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3085
QualType getType() const
Definition Expr.h:144
Represents difference between two FPOptions values.
bool isFPConstrained() const
Represents a member of a struct/union/class.
Definition Decl.h:3160
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:4700
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
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:103
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:1067
const Expr * getSubExpr() const
Definition Expr.h:1062
Represents a function declaration or definition.
Definition Decl.h:2000
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3279
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2476
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition Decl.cpp:4198
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4193
QualType getReturnType() const
Definition Decl.h:2845
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4313
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3133
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4144
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2470
FunctionDecl * getInstantiatedFromDecl() const
Definition Decl.cpp:4217
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2473
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4165
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3826
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition Decl.h:2805
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5269
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5673
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5558
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5554
Declaration of a template function.
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:1696
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4688
CallingConv getCallConv() const
Definition TypeBase.h:4820
QualType getReturnType() const
Definition TypeBase.h:4805
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:3853
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2072
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)
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.
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.
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1968
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:1312
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:369
void InstantiatedLocal(const Decl *D, Decl *Inst)
Represents the results of name lookup.
Definition Lookup.h:147
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...
Describes a module or submodule.
Definition Module.h:144
bool isNamedModuleUnit() const
Is this a C++20 named module unit.
Definition Module.h:676
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition Module.h:722
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:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1095
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
PtrTy get() const
Definition Ownership.h:81
Expr ** getExprs()
Definition Expr.h:6121
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition Expr.h:6110
Represents a parameter to a function.
Definition Decl.h:1790
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:2957
Wrapper for source info for pointers.
Definition TypeLoc.h:1484
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8418
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8386
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
void addAddressSpace(LangAS space)
Definition TypeBase.h:597
Represents a struct/union/class.
Definition Decl.h:4324
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3151
void setRetValue(Expr *E)
Definition Stmt.h:3180
SourceLocation getBeginLoc() const
Definition Stmt.h:3203
Expr * getRetValue()
Definition Stmt.h:3178
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:401
decl_range decls() const
Definition Scope.h:356
bool isFunctionDeclarationScope() const
isFunctionDeclarationScope - Return true if this scope is a function prototype scope.
Definition Scope.h:493
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:287
void CheckSMEFunctionDefAttributes(const FunctionDecl *FD)
Definition SemaARM.cpp:1417
Sema & SemaRef
Definition SemaBase.h:40
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
void CheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture)
void SetLambdaAttrs(CXXMethodDecl *Method)
Set device or host device attributes on the given lambda operator() method.
void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D)
Act on D, a function definition inside of an omp [begin/end] assumes.
void CheckSYCLEntryPointFunctionDecl(FunctionDecl *FD)
Definition SemaSYCL.cpp:270
A RAII object to temporarily push a declaration context.
Definition Sema.h:3472
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:855
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
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:1120
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition Sema.h:8240
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9327
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
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...
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:1503
CXXRecordDecl * createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, unsigned LambdaDependencyKind, LambdaCaptureDefault CaptureDefault)
Create a new lambda closure type.
SemaCUDA & CUDA()
Definition Sema.h:1443
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition Sema.h:1223
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)
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...
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation=false, bool RetainFunctionScopeInfo=false)
Performs semantic analysis at the end of a function body.
void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef)
Add an init-capture to a lambda scope.
FieldDecl * BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture)
Build a FieldDecl suitable to hold the given capture.
SemaSYCL & SYCL()
Definition Sema.h:1528
ASTContext & Context
Definition Sema.h:1283
SemaObjC & ObjC()
Definition Sema.h:1488
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
ASTContext & getASTContext() const
Definition Sema.h:926
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition Sema.h:1060
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.
void PopExpressionEvaluationContext()
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:2583
void handleLambdaNumbering(CXXRecordDecl *Class, CXXMethodDecl *Method, std::optional< CXXRecordDecl::LambdaNumbering > NumberingOverride=std::nullopt)
Number lambda for linkage purposes if necessary.
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition Sema.cpp:1673
ExprResult BuildCaptureInit(const sema::Capture &Capture, SourceLocation ImplicitCaptureLoc, bool IsOpenMPMapping=false)
Initialize the given capture with a suitable expression.
FPOptions & getCurFPFeatures()
Definition Sema.h:921
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:272
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
@ UPPC_Initializer
An initializer.
Definition Sema.h:14418
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14391
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.
const LangOptions & getLangOpts() const
Definition Sema.h:919
bool CaptureHasSideEffects(const sema::Capture &From)
Does copying/destroying the captured variable have side effects?
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2443
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 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args={}, DeclContext *LookupCtx=nullptr)
Diagnose an empty lookup.
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:1281
void PushExpressionEvaluationContextForFunction(ExpressionEvaluationContext NewContext, FunctionDecl *FD)
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2558
void CompleteLambdaCallOperator(CXXMethodDecl *Method, SourceLocation LambdaLoc, SourceLocation CallOperatorLoc, const AssociatedConstraint &TrailingRequiresClause, TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind, StorageClass SC, ArrayRef< ParmVarDecl * > Params, bool HasExplicitResultType)
void maybeAddDeclWithEffects(FuncOrBlockDecl *D)
Inline checks from the start of maybeAddDeclWithEffects, to minimize performance impact on code not u...
Definition Sema.h:15661
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:6957
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
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.
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
void DiagPlaceholderVariableDefinition(SourceLocation Loc)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1416
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:13937
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...
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:224
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.
bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, SourceRange FixItRange, const sema::Capture &From)
Diagnose if an explicit lambda capture is unused.
QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, UnsignedOrNone NumExpansions, IdentifierInfo *Id, bool DirectInit, Expr *&Init)
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition Sema.h:6961
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1321
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
Definition Sema.h:6720
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
Definition Sema.h:6710
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6725
@ DiscardedStatement
The current expression occurs within a discarded statement.
Definition Sema.h:6715
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6735
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6704
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
Definition Sema.h:6730
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Definition Sema.h:6745
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
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()
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8313
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
CXXMethodDecl * CreateLambdaCallOperator(SourceRange IntroducerRange, CXXRecordDecl *Class)
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
friend class InitializationSequence
Definition Sema.h:1558
void PopDeclContext()
ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc)
Complete a lambda-expression having processed and attached the lambda body.
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)
SourceRange getRangeForNextToken(SourceLocation Loc, bool IncludeMacros, bool IncludeComments, std::optional< tok::TokenKind > ExpectedToken=std::nullopt)
Calls Lexer::findNextToken() to find the next token, and if the locations of both ends of the token c...
Definition Sema.cpp:88
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI)
Note that we have finished the explicit captures for the given lambda.
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
Definition Sema.h:6415
bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method, SourceLocation CallLoc)
Returns true if the explicit object parameter was invalid.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
UnsignedOrNone getNumArgumentsInExpansionFromUnexpanded(llvm::ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs)
void NoteTemplateParameterLocation(const NamedDecl &Decl)
SemaARM & ARM()
Definition Sema.h:1423
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8655
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition Expr.h:4595
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:362
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition Decl.h:3947
Exposes information about the current target.
Definition TargetInfo.h:226
virtual CallingConvCheckResult checkCallingConvention(CallingConv CC) const
Determines whether a given calling convention is valid for the target.
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Stores a list of template parameters for a TemplateDecl and its derived classes.
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
bool containsUnexpandedParameterPack() const
Determine whether this template parameter list contains an unexpanded parameter pack.
ArrayRef< NamedDecl * > asArray()
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 TypeBase.h:8263
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8274
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isVoidType() const
Definition TypeBase.h:8891
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2116
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9178
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:753
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2783
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2405
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9027
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2436
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5015
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5588
VarDecl * getPotentiallyDecomposedVarDecl()
Definition DeclCXX.cpp:3635
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.cpp:5582
Represents a variable declaration or definition.
Definition Decl.h:926
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2162
void setInitStyle(InitializationStyle Style)
Definition Decl.h:1452
void setInitCapture(bool IC)
Definition Decl.h:1581
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1578
InitializationStyle
Initialization styles.
Definition Decl.h:929
@ ListInit
Direct list-initialization (C++11)
Definition Decl.h:937
@ CInit
C-style initialization with assignment.
Definition Decl.h:931
@ CallInit
Call-style initialization (C++98)
Definition Decl.h:934
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1184
void setInit(Expr *I)
Definition Decl.cpp:2488
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1168
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.
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:732
bool isCaptured(ValueDecl *Var) const
Determine whether the given variable has been captured.
Definition ScopeInfo.h:764
bool ContainsUnexpandedParameterPack
Whether this contains an unexpanded parameter pack.
Definition ScopeInfo.h:728
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:758
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition ScopeInfo.h:755
SmallVector< NamedDecl *, 4 > LocalPacks
Packs introduced by this, if any.
Definition ScopeInfo.h:735
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition ScopeInfo.h:737
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:961
CleanupInfo Cleanup
Whether any of the capture expressions requires cleanups.
Definition ScopeInfo.h:902
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition ScopeInfo.h:884
bool ExplicitParams
Whether the (empty) parameter list is explicit.
Definition ScopeInfo.h:899
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:871
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition ScopeInfo.h:892
SourceLocation CaptureDefaultLoc
Source location of the '&' or '=' specifying the default capture type, if any.
Definition ScopeInfo.h:888
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:879
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:874
bool Mutable
Whether this is a mutable lambda.
Definition ScopeInfo.h:896
Defines the clang::TargetInfo interface.
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus14
@ CPlusPlus17
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition ASTLambda.h:102
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition Specifiers.h:35
TryCaptureKind
Definition Sema.h:652
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:272
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1782
UnsignedOrNone getStackIndexOfNearestEnclosingCaptureCapableLambda(ArrayRef< const sema::FunctionScopeInfo * > FunctionScopes, ValueDecl *VarToCapture, Sema &S)
Examines the FunctionScopeInfo stack to determine the nearest enclosing lambda (to the current lambda...
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
@ AS_public
Definition Specifiers.h:124
@ AS_private
Definition Specifiers.h:126
bool isLambdaCallWithExplicitObjectParameter(const DeclContext *DC)
Definition ASTLambda.h:45
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)
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ CopyInit
[a = b], [a = {b}]
Definition DeclSpec.h:2800
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:905
const FunctionProtoType * T
bool hasWeakerNullability(NullabilityKind L, NullabilityKind R)
Return true if L has a weaker nullability annotation than R.
Definition Specifiers.h:369
ExprResult ExprError()
Definition Ownership.h:265
LangAS
Defines the address space values used by the address space qualifier of QualType.
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:23
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:149
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
@ CC_X86VectorCall
Definition Specifiers.h:283
@ CC_X86StdCall
Definition Specifiers.h:280
@ CC_X86FastCall
Definition Specifiers.h:281
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5879
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ EST_BasicNoexcept
noexcept
Information about how a lambda is numbered within its context.
Definition DeclCXX.h:1796
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:1565
bool hasTrailingReturnType() const
Determine whether this function declarator had a trailing-return-type.
Definition DeclSpec.h:1556
ParsedType getTrailingReturnType() const
Get the trailing-return-type for this function declarator.
Definition DeclSpec.h:1559
bool hasMutableQualifier() const
Determine whether this lambda-declarator contains a 'mutable' qualifier.
Definition DeclSpec.h:1528
ParamInfo - An array of paraminfo objects is allocated whenever a function declarator is parsed.
Definition DeclSpec.h:1303
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5328
Extra information about a function prototype.
Definition TypeBase.h:5354
unsigned NumExplicitTemplateParams
The number of parameters in the template parameter list that were explicitly specified by the user,...
Definition DeclSpec.h:2857
SmallVector< NamedDecl *, 4 > TemplateParams
Store the list of the template parameters for a generic lambda or an abbreviated function template.
Definition DeclSpec.h:2870
Represents a complete lambda introducer.
Definition DeclSpec.h:2806
SmallVector< LambdaCapture, 4 > Captures
Definition DeclSpec.h:2831
SourceLocation DefaultLoc
Definition DeclSpec.h:2829
LambdaCaptureDefault Default
Definition DeclSpec.h:2830