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//===----------------------------------------------------------------------===//
12#include "clang/Sema/SemaLambda.h"
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTLambda.h"
15#include "clang/AST/CXXInheritance.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/MangleNumberingContext.h"
18#include "clang/Basic/TargetInfo.h"
19#include "clang/Sema/DeclSpec.h"
20#include "clang/Sema/Initialization.h"
21#include "clang/Sema/Lookup.h"
22#include "clang/Sema/Scope.h"
23#include "clang/Sema/ScopeInfo.h"
24#include "clang/Sema/SemaARM.h"
25#include "clang/Sema/SemaCUDA.h"
26#include "clang/Sema/SemaInternal.h"
27#include "clang/Sema/SemaOpenMP.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
70static inline UnsignedOrNone getStackIndexOfNearestEnclosingCaptureReadyLambda(
71 ArrayRef<const clang::sema::FunctionScopeInfo *> FunctionScopes,
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 Val: 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>(Val: FunctionScopes[CurScopeIndex])->CallOperator;
92
93 do {
94 const clang::sema::LambdaScopeInfo *LSI =
95 cast<sema::LambdaScopeInfo>(Val: 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(DC: 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.
123 if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {
124 if (IsCapturingVariable && !LSI->isCaptured(Var: VarToCapture))
125 return NoLambdaIsCaptureReady;
126 if (IsCapturingThis && !LSI->isCXXThisCaptured())
127 return NoLambdaIsCaptureReady;
128 }
129 EnclosingDC = getLambdaAwareParentOfDeclContext(DC: EnclosingDC);
130
131 assert(CurScopeIndex);
132 --CurScopeIndex;
133 } while (!EnclosingDC->isTranslationUnit() &&
134 EnclosingDC->isDependentContext() &&
135 isLambdaCallOperator(DC: 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
180UnsignedOrNone clang::getStackIndexOfNearestEnclosingCaptureCapableLambda(
181 ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes,
182 ValueDecl *VarToCapture, Sema &S) {
183
184 const UnsignedOrNone NoLambdaIsCaptureCapable = std::nullopt;
185
186 const UnsignedOrNone OptionalStackIndex =
187 getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes,
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>(Val: 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 Var: VarToCapture,
212 /*ExprVarIsUsedInLoc*/ Loc: SourceLocation(), Kind: TryCaptureKind::Implicit,
213 /*EllipsisLoc*/ SourceLocation(),
214 /*BuildAndDiagnose*/ false, CaptureType, DeclRefType,
215 FunctionScopeIndexToStopAt: &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 =
223 !S.CheckCXXThisCapture(
224 Loc: CaptureReadyLambdaLSI->PotentialThisCaptureLocation,
225 /*Explicit*/ false, /*BuildAndDiagnose*/ false,
226 FunctionScopeIndexToStopAt: &IndexOfCaptureReadyLambda);
227 if (!CanCaptureThis)
228 return NoLambdaIsCaptureCapable;
229 }
230 return IndexOfCaptureReadyLambda;
231}
232
233static inline TemplateParameterList *
234getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {
235 if (!LSI->GLTemplateParameterList && !LSI->TemplateParams.empty()) {
236 LSI->GLTemplateParameterList = TemplateParameterList::Create(
237 C: SemaRef.Context,
238 /*Begin loc of the lambda expression*/ TemplateLoc: LSI->IntroducerRange.getBegin(),
239 /*L angle loc*/ LAngleLoc: LSI->ExplicitTemplateParamsRange.getBegin(),
240 Params: LSI->TemplateParams,
241 /*R angle loc*/ RAngleLoc: LSI->ExplicitTemplateParamsRange.getEnd(),
242 RequiresClause: LSI->RequiresClause.get());
243 }
244 return LSI->GLTemplateParameterList;
245}
246
247CXXRecordDecl *
248Sema::createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info,
249 unsigned LambdaDependencyKind,
250 LambdaCaptureDefault CaptureDefault) {
251 DeclContext *DC = CurContext;
252
253 bool IsGenericLambda =
254 Info && getGenericLambdaTemplateParameterList(LSI: getCurLambda(), SemaRef&: *this);
255 // Start constructing the lambda class.
256 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(
257 C: Context, DC, Info, Loc: IntroducerRange.getBegin(), DependencyKind: LambdaDependencyKind,
258 IsGeneric: IsGenericLambda, CaptureDefault);
259 DC->addDecl(D: 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>(Val: DC))
269 if (FD->isInlined())
270 return true;
271
272 DC = DC->getLexicalParent();
273 }
274
275 return false;
276}
277
278std::tuple<MangleNumberingContext *, Decl *>
279Sema::getCurrentMangleNumberContext(const DeclContext *DC) {
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,
286 DefaultArgument,
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 // See discussion in https://github.com/itanium-cxx-abi/cxx-abi/issues/186
302 //
303 // zygoloid:
304 // Yeah, I think the only cases left where lambdas don't need a
305 // mangling are when they have (effectively) internal linkage or appear
306 // in a non-inline function in a non-module translation unit.
307 if (auto *ND = dyn_cast<NamedDecl>(Val: ManglingContextDecl ? ManglingContextDecl
308 : cast<Decl>(Val: DC));
309 ND && (ND->isInNamedModule() || ND->isFromGlobalModule()) &&
310 ND->isExternallyVisible()) {
311 if (!ManglingContextDecl)
312 ManglingContextDecl = const_cast<Decl *>(cast<Decl>(Val: DC));
313 return NonInlineInModulePurview;
314 }
315
316 if (!ManglingContextDecl)
317 return Normal;
318
319 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Val: ManglingContextDecl)) {
320 if (const DeclContext *LexicalDC
321 = Param->getDeclContext()->getLexicalParent())
322 if (LexicalDC->isRecord())
323 return DefaultArgument;
324 } else if (VarDecl *Var = dyn_cast<VarDecl>(Val: ManglingContextDecl)) {
325 if (Var->getMostRecentDecl()->isInline())
326 return InlineVariable;
327
328 if (Var->getDeclContext()->isRecord() && IsInNonspecializedTemplate)
329 return TemplatedVariable;
330
331 if (Var->getDescribedVarTemplate())
332 return TemplatedVariable;
333
334 if (auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Val: Var)) {
335 if (!VTS->isExplicitSpecialization())
336 return TemplatedVariable;
337 }
338 } else if (isa<FieldDecl>(Val: ManglingContextDecl)) {
339 return DataMember;
340 } else if (isa<ImplicitConceptSpecializationDecl>(Val: ManglingContextDecl)) {
341 return Concept;
342 }
343
344 return Normal;
345 }();
346
347 // Itanium ABI [5.1.7]:
348 // In the following contexts [...] the one-definition rule requires closure
349 // types in different translation units to "correspond":
350 switch (Kind) {
351 case Normal: {
352 // -- the bodies of inline or templated functions
353 if ((IsInNonspecializedTemplate &&
354 !(ManglingContextDecl && isa<ParmVarDecl>(Val: ManglingContextDecl))) ||
355 isInInlineFunction(DC: CurContext)) {
356 while (auto *CD = dyn_cast<CapturedDecl>(Val: DC))
357 DC = CD->getParent();
358 return std::make_tuple(args: &Context.getManglingNumberContext(DC), args: nullptr);
359 }
360
361 return std::make_tuple(args: nullptr, args: nullptr);
362 }
363
364 case NonInlineInModulePurview:
365 case Concept:
366 // Concept definitions aren't code generated and thus aren't mangled,
367 // however the ManglingContextDecl is important for the purposes of
368 // re-forming the template argument list of the lambda for constraint
369 // evaluation.
370 case DataMember:
371 // -- default member initializers
372 case DefaultArgument:
373 // -- default arguments appearing in class definitions
374 case InlineVariable:
375 case TemplatedVariable:
376 // -- the initializers of inline or templated variables
377 return std::make_tuple(
378 args: &Context.getManglingNumberContext(ASTContext::NeedExtraManglingDecl,
379 D: ManglingContextDecl),
380 args&: ManglingContextDecl);
381 }
382
383 llvm_unreachable("unexpected context");
384}
385
386static QualType
387buildTypeForLambdaCallOperator(Sema &S, clang::CXXRecordDecl *Class,
388 TemplateParameterList *TemplateParams,
389 TypeSourceInfo *MethodTypeInfo) {
390 assert(MethodTypeInfo && "expected a non null type");
391
392 QualType MethodType = MethodTypeInfo->getType();
393 // If a lambda appears in a dependent context or is a generic lambda (has
394 // template parameters) and has an 'auto' return type, deduce it to a
395 // dependent type.
396 if (Class->isDependentContext() || TemplateParams) {
397 const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
398 QualType Result = FPT->getReturnType();
399 if (Result->isUndeducedType()) {
400 Result = S.SubstAutoTypeDependent(TypeWithAuto: Result);
401 MethodType = S.Context.getFunctionType(ResultTy: Result, Args: FPT->getParamTypes(),
402 EPI: FPT->getExtProtoInfo());
403 }
404 }
405 return MethodType;
406}
407
408// [C++2b] [expr.prim.lambda.closure] p4
409// Given a lambda with a lambda-capture, the type of the explicit object
410// parameter, if any, of the lambda's function call operator (possibly
411// instantiated from a function call operator template) shall be either:
412// - the closure type,
413// - class type publicly and unambiguously derived from the closure type, or
414// - a reference to a possibly cv-qualified such type.
415bool Sema::DiagnoseInvalidExplicitObjectParameterInLambda(
416 CXXMethodDecl *Method, SourceLocation CallLoc) {
417 if (!isLambdaCallWithExplicitObjectParameter(DC: Method))
418 return false;
419 CXXRecordDecl *RD = Method->getParent();
420 if (Method->getType()->isDependentType())
421 return false;
422 if (RD->isCapturelessLambda())
423 return false;
424
425 ParmVarDecl *Param = Method->getParamDecl(i: 0);
426 QualType ExplicitObjectParameterType = Param->getType()
427 .getNonReferenceType()
428 .getUnqualifiedType()
429 .getDesugaredType(Context: getASTContext());
430 CanQualType LambdaType = getASTContext().getCanonicalTagType(TD: RD);
431 if (LambdaType == ExplicitObjectParameterType)
432 return false;
433
434 // Don't check the same instantiation twice.
435 //
436 // If this call operator is ill-formed, there is no point in issuing
437 // a diagnostic every time it is called because the problem is in the
438 // definition of the derived type, not at the call site.
439 //
440 // FIXME: Move this check to where we instantiate the method? This should
441 // be possible, but the naive approach of just marking the method as invalid
442 // leads to us emitting more diagnostics than we should have to for this case
443 // (1 error here *and* 1 error about there being no matching overload at the
444 // call site). It might be possible to avoid that by also checking if there
445 // is an empty cast path for the method stored in the context (signalling that
446 // we've already diagnosed it) and then just not building the call, but that
447 // doesn't really seem any simpler than diagnosing it at the call site...
448 auto [It, Inserted] = Context.LambdaCastPaths.try_emplace(Key: Method);
449 if (!Inserted)
450 return It->second.empty();
451
452 CXXCastPath &Path = It->second;
453 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
454 /*DetectVirtual=*/false);
455 if (!IsDerivedFrom(Loc: RD->getLocation(), Derived: ExplicitObjectParameterType, Base: LambdaType,
456 Paths)) {
457 Diag(Loc: Param->getLocation(), DiagID: diag::err_invalid_explicit_object_type_in_lambda)
458 << ExplicitObjectParameterType;
459 return true;
460 }
461
462 if (Paths.isAmbiguous(BaseType: LambdaType)) {
463 std::string PathsDisplay = getAmbiguousPathsDisplayString(Paths);
464 Diag(Loc: CallLoc, DiagID: diag::err_explicit_object_lambda_ambiguous_base)
465 << LambdaType << PathsDisplay;
466 return true;
467 }
468
469 if (CheckBaseClassAccess(AccessLoc: CallLoc, Base: LambdaType, Derived: ExplicitObjectParameterType,
470 Path: Paths.front(),
471 DiagID: diag::err_explicit_object_lambda_inaccessible_base))
472 return true;
473
474 BuildBasePathArray(Paths, BasePath&: Path);
475 return false;
476}
477
478void Sema::handleLambdaNumbering(
479 CXXRecordDecl *Class, CXXMethodDecl *Method,
480 std::optional<CXXRecordDecl::LambdaNumbering> NumberingOverride) {
481 if (NumberingOverride) {
482 Class->setLambdaNumbering(*NumberingOverride);
483 return;
484 }
485
486 ContextRAII ManglingContext(*this, Class->getDeclContext());
487
488 auto getMangleNumberingContext =
489 [this](CXXRecordDecl *Class,
490 Decl *ManglingContextDecl) -> MangleNumberingContext * {
491 // Get mangle numbering context if there's any extra decl context.
492 if (ManglingContextDecl)
493 return &Context.getManglingNumberContext(
494 ASTContext::NeedExtraManglingDecl, D: ManglingContextDecl);
495 // Otherwise, from that lambda's decl context.
496 auto DC = Class->getDeclContext();
497 while (auto *CD = dyn_cast<CapturedDecl>(Val: DC))
498 DC = CD->getParent();
499 return &Context.getManglingNumberContext(DC);
500 };
501
502 CXXRecordDecl::LambdaNumbering Numbering;
503 MangleNumberingContext *MCtx;
504 std::tie(args&: MCtx, args&: Numbering.ContextDecl) =
505 getCurrentMangleNumberContext(DC: Class->getDeclContext());
506 if (!MCtx && (getLangOpts().CUDA || getLangOpts().SYCLIsDevice ||
507 getLangOpts().SYCLIsHost)) {
508 // Force lambda numbering in CUDA/HIP as we need to name lambdas following
509 // ODR. Both device- and host-compilation need to have a consistent naming
510 // on kernel functions. As lambdas are potential part of these `__global__`
511 // function names, they needs numbering following ODR.
512 // Also force for SYCL, since we need this for the
513 // __builtin_sycl_unique_stable_name implementation, which depends on lambda
514 // mangling.
515 MCtx = getMangleNumberingContext(Class, Numbering.ContextDecl);
516 assert(MCtx && "Retrieving mangle numbering context failed!");
517 Numbering.HasKnownInternalLinkage = true;
518 }
519 if (MCtx) {
520 Numbering.IndexInContext = MCtx->getNextLambdaIndex();
521 Numbering.ManglingNumber = MCtx->getManglingNumber(CallOperator: Method);
522 Numbering.DeviceManglingNumber = MCtx->getDeviceManglingNumber(Method);
523 Class->setLambdaNumbering(Numbering);
524
525 if (auto *Source =
526 dyn_cast_or_null<ExternalSemaSource>(Val: Context.getExternalSource()))
527 Source->AssignedLambdaNumbering(Lambda: Class);
528 }
529}
530
531static void buildLambdaScopeReturnType(Sema &S, LambdaScopeInfo *LSI,
532 CXXMethodDecl *CallOperator,
533 bool ExplicitResultType) {
534 if (ExplicitResultType) {
535 LSI->HasImplicitReturnType = false;
536 LSI->ReturnType = CallOperator->getReturnType();
537 if (!LSI->ReturnType->isDependentType() && !LSI->ReturnType->isVoidType())
538 S.RequireCompleteType(Loc: CallOperator->getBeginLoc(), T: LSI->ReturnType,
539 DiagID: diag::err_lambda_incomplete_result);
540 } else {
541 LSI->HasImplicitReturnType = true;
542 }
543}
544
545void Sema::buildLambdaScope(LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator,
546 SourceRange IntroducerRange,
547 LambdaCaptureDefault CaptureDefault,
548 SourceLocation CaptureDefaultLoc,
549 bool ExplicitParams, bool Mutable) {
550 LSI->CallOperator = CallOperator;
551 CXXRecordDecl *LambdaClass = CallOperator->getParent();
552 LSI->Lambda = LambdaClass;
553 if (CaptureDefault == LCD_ByCopy)
554 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
555 else if (CaptureDefault == LCD_ByRef)
556 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
557 LSI->CaptureDefaultLoc = CaptureDefaultLoc;
558 LSI->IntroducerRange = IntroducerRange;
559 LSI->ExplicitParams = ExplicitParams;
560 LSI->Mutable = Mutable;
561}
562
563void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
564 LSI->finishedExplicitCaptures();
565}
566
567void Sema::ActOnLambdaExplicitTemplateParameterList(
568 LambdaIntroducer &Intro, SourceLocation LAngleLoc,
569 ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc,
570 ExprResult RequiresClause) {
571 LambdaScopeInfo *LSI = getCurLambda();
572 assert(LSI && "Expected a lambda scope");
573 assert(LSI->NumExplicitTemplateParams == 0 &&
574 "Already acted on explicit template parameters");
575 assert(LSI->TemplateParams.empty() &&
576 "Explicit template parameters should come "
577 "before invented (auto) ones");
578 assert(!TParams.empty() &&
579 "No template parameters to act on");
580 LSI->TemplateParams.append(in_start: TParams.begin(), in_end: TParams.end());
581 LSI->NumExplicitTemplateParams = TParams.size();
582 LSI->ExplicitTemplateParamsRange = {LAngleLoc, RAngleLoc};
583 LSI->RequiresClause = RequiresClause;
584}
585
586/// If this expression is an enumerator-like expression of some type
587/// T, return the type T; otherwise, return null.
588///
589/// Pointer comparisons on the result here should always work because
590/// it's derived from either the parent of an EnumConstantDecl
591/// (i.e. the definition) or the declaration returned by
592/// EnumType::getDecl() (i.e. the definition).
593static EnumDecl *findEnumForBlockReturn(Expr *E) {
594 // An expression is an enumerator-like expression of type T if,
595 // ignoring parens and parens-like expressions:
596 E = E->IgnoreParens();
597
598 // - it is an enumerator whose enum type is T or
599 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
600 if (EnumConstantDecl *D
601 = dyn_cast<EnumConstantDecl>(Val: DRE->getDecl())) {
602 return cast<EnumDecl>(Val: D->getDeclContext());
603 }
604 return nullptr;
605 }
606
607 // - it is a comma expression whose RHS is an enumerator-like
608 // expression of type T or
609 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
610 if (BO->getOpcode() == BO_Comma)
611 return findEnumForBlockReturn(E: BO->getRHS());
612 return nullptr;
613 }
614
615 // - it is a statement-expression whose value expression is an
616 // enumerator-like expression of type T or
617 if (StmtExpr *SE = dyn_cast<StmtExpr>(Val: E)) {
618 if (Expr *last = dyn_cast_or_null<Expr>(Val: SE->getSubStmt()->body_back()))
619 return findEnumForBlockReturn(E: last);
620 return nullptr;
621 }
622
623 // - it is a ternary conditional operator (not the GNU ?:
624 // extension) whose second and third operands are
625 // enumerator-like expressions of type T or
626 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
627 if (EnumDecl *ED = findEnumForBlockReturn(E: CO->getTrueExpr()))
628 if (ED == findEnumForBlockReturn(E: CO->getFalseExpr()))
629 return ED;
630 return nullptr;
631 }
632
633 // (implicitly:)
634 // - it is an implicit integral conversion applied to an
635 // enumerator-like expression of type T or
636 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
637 // We can sometimes see integral conversions in valid
638 // enumerator-like expressions.
639 if (ICE->getCastKind() == CK_IntegralCast)
640 return findEnumForBlockReturn(E: ICE->getSubExpr());
641
642 // Otherwise, just rely on the type.
643 }
644
645 // - it is an expression of that formal enum type.
646 if (auto *ED = E->getType()->getAsEnumDecl())
647 return ED;
648
649 // Otherwise, nope.
650 return nullptr;
651}
652
653/// Attempt to find a type T for which the returned expression of the
654/// given statement is an enumerator-like expression of that type.
655static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
656 if (Expr *retValue = ret->getRetValue())
657 return findEnumForBlockReturn(E: retValue);
658 return nullptr;
659}
660
661/// Attempt to find a common type T for which all of the returned
662/// expressions in a block are enumerator-like expressions of that
663/// type.
664static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
665 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
666
667 // Try to find one for the first return.
668 EnumDecl *ED = findEnumForBlockReturn(ret: *i);
669 if (!ED) return nullptr;
670
671 // Check that the rest of the returns have the same enum.
672 for (++i; i != e; ++i) {
673 if (findEnumForBlockReturn(ret: *i) != ED)
674 return nullptr;
675 }
676
677 // Never infer an anonymous enum type.
678 if (!ED->hasNameForLinkage()) return nullptr;
679
680 return ED;
681}
682
683/// Adjust the given return statements so that they formally return
684/// the given type. It should require, at most, an IntegralCast.
685static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
686 QualType returnType) {
687 for (ArrayRef<ReturnStmt*>::iterator
688 i = returns.begin(), e = returns.end(); i != e; ++i) {
689 ReturnStmt *ret = *i;
690 Expr *retValue = ret->getRetValue();
691 if (S.Context.hasSameType(T1: retValue->getType(), T2: returnType))
692 continue;
693
694 // Right now we only support integral fixup casts.
695 assert(returnType->isIntegralOrUnscopedEnumerationType());
696 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
697
698 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Val: retValue);
699
700 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
701 E = ImplicitCastExpr::Create(Context: S.Context, T: returnType, Kind: CK_IntegralCast, Operand: E,
702 /*base path*/ BasePath: nullptr, Cat: VK_PRValue,
703 FPO: FPOptionsOverride());
704 if (cleanups) {
705 cleanups->setSubExpr(E);
706 } else {
707 ret->setRetValue(E);
708 }
709 }
710}
711
712void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
713 assert(CSI.HasImplicitReturnType);
714 // If it was ever a placeholder, it had to been deduced to DependentTy.
715 assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
716 assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) &&
717 "lambda expressions use auto deduction in C++14 onwards");
718
719 // C++ core issue 975:
720 // If a lambda-expression does not include a trailing-return-type,
721 // it is as if the trailing-return-type denotes the following type:
722 // - if there are no return statements in the compound-statement,
723 // or all return statements return either an expression of type
724 // void or no expression or braced-init-list, the type void;
725 // - otherwise, if all return statements return an expression
726 // and the types of the returned expressions after
727 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
728 // array-to-pointer conversion (4.2 [conv.array]), and
729 // function-to-pointer conversion (4.3 [conv.func]) are the
730 // same, that common type;
731 // - otherwise, the program is ill-formed.
732 //
733 // C++ core issue 1048 additionally removes top-level cv-qualifiers
734 // from the types of returned expressions to match the C++14 auto
735 // deduction rules.
736 //
737 // In addition, in blocks in non-C++ modes, if all of the return
738 // statements are enumerator-like expressions of some type T, where
739 // T has a name for linkage, then we infer the return type of the
740 // block to be that type.
741
742 // First case: no return statements, implicit void return type.
743 ASTContext &Ctx = getASTContext();
744 if (CSI.Returns.empty()) {
745 // It's possible there were simply no /valid/ return statements.
746 // In this case, the first one we found may have at least given us a type.
747 if (CSI.ReturnType.isNull())
748 CSI.ReturnType = Ctx.VoidTy;
749 return;
750 }
751
752 // Second case: at least one return statement has dependent type.
753 // Delay type checking until instantiation.
754 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
755 if (CSI.ReturnType->isDependentType())
756 return;
757
758 // Try to apply the enum-fuzz rule.
759 if (!getLangOpts().CPlusPlus) {
760 assert(isa<BlockScopeInfo>(CSI));
761 const EnumDecl *ED = findCommonEnumForBlockReturns(returns: CSI.Returns);
762 if (ED) {
763 CSI.ReturnType = Context.getCanonicalTagType(TD: ED);
764 adjustBlockReturnsToEnum(S&: *this, returns: CSI.Returns, returnType: CSI.ReturnType);
765 return;
766 }
767 }
768
769 // Third case: only one return statement. Don't bother doing extra work!
770 if (CSI.Returns.size() == 1)
771 return;
772
773 // General case: many return statements.
774 // Check that they all have compatible return types.
775
776 // We require the return types to strictly match here.
777 // Note that we've already done the required promotions as part of
778 // processing the return statement.
779 for (const ReturnStmt *RS : CSI.Returns) {
780 const Expr *RetE = RS->getRetValue();
781
782 QualType ReturnType =
783 (RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType();
784 if (Context.getCanonicalFunctionResultType(ResultType: ReturnType) ==
785 Context.getCanonicalFunctionResultType(ResultType: CSI.ReturnType)) {
786 // Use the return type with the strictest possible nullability annotation.
787 auto RetTyNullability = ReturnType->getNullability();
788 auto BlockNullability = CSI.ReturnType->getNullability();
789 if (BlockNullability &&
790 (!RetTyNullability ||
791 hasWeakerNullability(L: *RetTyNullability, R: *BlockNullability)))
792 CSI.ReturnType = ReturnType;
793 continue;
794 }
795
796 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
797 // TODO: It's possible that the *first* return is the divergent one.
798 Diag(Loc: RS->getBeginLoc(),
799 DiagID: diag::err_typecheck_missing_return_type_incompatible)
800 << ReturnType << CSI.ReturnType << isa<LambdaScopeInfo>(Val: CSI);
801 // Continue iterating so that we keep emitting diagnostics.
802 }
803}
804
805QualType Sema::buildLambdaInitCaptureInitialization(
806 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
807 UnsignedOrNone NumExpansions, IdentifierInfo *Id, bool IsDirectInit,
808 Expr *&Init) {
809 // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
810 // deduce against.
811 QualType DeductType = Context.getAutoDeductType();
812 TypeLocBuilder TLB;
813 AutoTypeLoc TL = TLB.push<AutoTypeLoc>(T: DeductType);
814 TL.setNameLoc(Loc);
815 if (ByRef) {
816 DeductType = BuildReferenceType(T: DeductType, LValueRef: true, Loc, Entity: Id);
817 assert(!DeductType.isNull() && "can't build reference to auto");
818 TLB.push<ReferenceTypeLoc>(T: DeductType).setSigilLoc(Loc);
819 }
820 if (EllipsisLoc.isValid()) {
821 if (Init->containsUnexpandedParameterPack()) {
822 Diag(Loc: EllipsisLoc, DiagID: getLangOpts().CPlusPlus20
823 ? diag::warn_cxx17_compat_init_capture_pack
824 : diag::ext_init_capture_pack);
825 DeductType = Context.getPackExpansionType(Pattern: DeductType, NumExpansions,
826 /*ExpectPackInType=*/false);
827 TLB.push<PackExpansionTypeLoc>(T: DeductType).setEllipsisLoc(EllipsisLoc);
828 } else {
829 // Just ignore the ellipsis for now and form a non-pack variable. We'll
830 // diagnose this later when we try to capture it.
831 }
832 }
833 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, T: DeductType);
834
835 // Deduce the type of the init capture.
836 QualType DeducedType = deduceVarTypeFromInitializer(
837 /*VarDecl*/VDecl: nullptr, Name: DeclarationName(Id), Type: DeductType, TSI,
838 Range: SourceRange(Loc, Loc), DirectInit: IsDirectInit, Init);
839 if (DeducedType.isNull())
840 return QualType();
841
842 // Are we a non-list direct initialization?
843 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Val: Init);
844
845 // Perform initialization analysis and ensure any implicit conversions
846 // (such as lvalue-to-rvalue) are enforced.
847 InitializedEntity Entity =
848 InitializedEntity::InitializeLambdaCapture(VarID: Id, FieldType: DeducedType, Loc);
849 InitializationKind Kind =
850 IsDirectInit
851 ? (CXXDirectInit ? InitializationKind::CreateDirect(
852 InitLoc: Loc, LParenLoc: Init->getBeginLoc(), RParenLoc: Init->getEndLoc())
853 : InitializationKind::CreateDirectList(InitLoc: Loc))
854 : InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: Init->getBeginLoc());
855
856 MultiExprArg Args = Init;
857 if (CXXDirectInit)
858 Args =
859 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
860 QualType DclT;
861 InitializationSequence InitSeq(*this, Entity, Kind, Args);
862 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args, ResultType: &DclT);
863
864 if (Result.isInvalid())
865 return QualType();
866
867 Init = Result.getAs<Expr>();
868 return DeducedType;
869}
870
871VarDecl *Sema::createLambdaInitCaptureVarDecl(
872 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
873 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx) {
874 // FIXME: Retain the TypeSourceInfo from buildLambdaInitCaptureInitialization
875 // rather than reconstructing it here.
876 TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(T: InitCaptureType, Loc);
877 if (auto PETL = TSI->getTypeLoc().getAs<PackExpansionTypeLoc>())
878 PETL.setEllipsisLoc(EllipsisLoc);
879
880 // Create a dummy variable representing the init-capture. This is not actually
881 // used as a variable, and only exists as a way to name and refer to the
882 // init-capture.
883 // FIXME: Pass in separate source locations for '&' and identifier.
884 VarDecl *NewVD = VarDecl::Create(C&: Context, DC: DeclCtx, StartLoc: Loc, IdLoc: Loc, Id,
885 T: InitCaptureType, TInfo: TSI, S: SC_Auto);
886 NewVD->setInitCapture(true);
887 NewVD->setReferenced(true);
888 // FIXME: Pass in a VarDecl::InitializationStyle.
889 NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));
890 NewVD->markUsed(C&: Context);
891 NewVD->setInit(Init);
892 if (NewVD->isParameterPack())
893 getCurLambda()->LocalPacks.push_back(Elt: NewVD);
894 return NewVD;
895}
896
897void Sema::addInitCapture(LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef) {
898 assert(Var->isInitCapture() && "init capture flag should be set");
899 LSI->addCapture(Var, /*isBlock=*/false, isByref: ByRef,
900 /*isNested=*/false, Loc: Var->getLocation(), EllipsisLoc: SourceLocation(),
901 CaptureType: Var->getType(), /*Invalid=*/false);
902}
903
904// Unlike getCurLambda, getCurrentLambdaScopeUnsafe doesn't
905// check that the current lambda is in a consistent or fully constructed state.
906static LambdaScopeInfo *getCurrentLambdaScopeUnsafe(Sema &S) {
907 assert(!S.FunctionScopes.empty());
908 return cast<LambdaScopeInfo>(Val: S.FunctionScopes[S.FunctionScopes.size() - 1]);
909}
910
911static TypeSourceInfo *
912getDummyLambdaType(Sema &S, SourceLocation Loc = SourceLocation()) {
913 // C++11 [expr.prim.lambda]p4:
914 // If a lambda-expression does not include a lambda-declarator, it is as
915 // if the lambda-declarator were ().
916 FunctionProtoType::ExtProtoInfo EPI(S.Context.getDefaultCallingConvention(
917 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
918 EPI.HasTrailingReturn = true;
919 EPI.TypeQuals.addConst();
920 LangAS AS = S.getDefaultCXXMethodAddrSpace();
921 if (AS != LangAS::Default)
922 EPI.TypeQuals.addAddressSpace(space: AS);
923
924 // C++1y [expr.prim.lambda]:
925 // The lambda return type is 'auto', which is replaced by the
926 // trailing-return type if provided and/or deduced from 'return'
927 // statements
928 // We don't do this before C++1y, because we don't support deduced return
929 // types there.
930 QualType DefaultTypeForNoTrailingReturn = S.getLangOpts().CPlusPlus14
931 ? S.Context.getAutoDeductType()
932 : S.Context.DependentTy;
933 QualType MethodTy =
934 S.Context.getFunctionType(ResultTy: DefaultTypeForNoTrailingReturn, Args: {}, EPI);
935 return S.Context.getTrivialTypeSourceInfo(T: MethodTy, Loc);
936}
937
938static TypeSourceInfo *getLambdaType(Sema &S, LambdaIntroducer &Intro,
939 Declarator &ParamInfo, Scope *CurScope,
940 SourceLocation Loc,
941 bool &ExplicitResultType) {
942
943 ExplicitResultType = false;
944
945 assert(
946 (ParamInfo.getDeclSpec().getStorageClassSpec() ==
947 DeclSpec::SCS_unspecified ||
948 ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) &&
949 "Unexpected storage specifier");
950 bool IsLambdaStatic =
951 ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static;
952
953 TypeSourceInfo *MethodTyInfo;
954
955 if (ParamInfo.getNumTypeObjects() == 0) {
956 MethodTyInfo = getDummyLambdaType(S, Loc);
957 } else {
958 // Check explicit parameters
959 S.CheckExplicitObjectLambda(D&: ParamInfo);
960
961 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
962
963 bool HasExplicitObjectParameter =
964 ParamInfo.isExplicitObjectMemberFunction();
965
966 ExplicitResultType = FTI.hasTrailingReturnType();
967 if (!FTI.hasMutableQualifier() && !IsLambdaStatic &&
968 !HasExplicitObjectParameter)
969 FTI.getOrCreateMethodQualifiers().SetTypeQual(T: DeclSpec::TQ_const, Loc);
970
971 if (ExplicitResultType && S.getLangOpts().HLSL) {
972 QualType RetTy = FTI.getTrailingReturnType().get();
973 if (!RetTy.isNull()) {
974 // HLSL does not support specifying an address space on a lambda return
975 // type.
976 LangAS AddressSpace = RetTy.getAddressSpace();
977 if (AddressSpace != LangAS::Default)
978 S.Diag(Loc: FTI.getTrailingReturnTypeLoc(),
979 DiagID: diag::err_return_value_with_address_space);
980 }
981 }
982
983 MethodTyInfo = S.GetTypeForDeclarator(D&: ParamInfo);
984 assert(MethodTyInfo && "no type from lambda-declarator");
985
986 // Check for unexpanded parameter packs in the method type.
987 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
988 S.DiagnoseUnexpandedParameterPack(Loc: Intro.Range.getBegin(), T: MethodTyInfo,
989 UPPC: S.UPPC_DeclarationType);
990 }
991 return MethodTyInfo;
992}
993
994CXXMethodDecl *Sema::CreateLambdaCallOperator(SourceRange IntroducerRange,
995 CXXRecordDecl *Class) {
996
997 // C++20 [expr.prim.lambda.closure]p3:
998 // The closure type for a lambda-expression has a public inline function
999 // call operator (for a non-generic lambda) or function call operator
1000 // template (for a generic lambda) whose parameters and return type are
1001 // described by the lambda-expression's parameter-declaration-clause
1002 // and trailing-return-type respectively.
1003 DeclarationName MethodName =
1004 Context.DeclarationNames.getCXXOperatorName(Op: OO_Call);
1005 DeclarationNameLoc MethodNameLoc =
1006 DeclarationNameLoc::makeCXXOperatorNameLoc(Range: IntroducerRange.getBegin());
1007 CXXMethodDecl *Method = CXXMethodDecl::Create(
1008 C&: Context, RD: Class, StartLoc: SourceLocation(),
1009 NameInfo: DeclarationNameInfo(MethodName, IntroducerRange.getBegin(),
1010 MethodNameLoc),
1011 T: QualType(), /*Tinfo=*/TInfo: nullptr, SC: SC_None,
1012 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
1013 /*isInline=*/true, ConstexprKind: ConstexprSpecKind::Unspecified, EndLocation: SourceLocation(),
1014 /*TrailingRequiresClause=*/{});
1015 Method->setAccess(AS_public);
1016 return Method;
1017}
1018
1019void Sema::AddTemplateParametersToLambdaCallOperator(
1020 CXXMethodDecl *CallOperator, CXXRecordDecl *Class,
1021 TemplateParameterList *TemplateParams) {
1022 assert(TemplateParams && "no template parameters");
1023 FunctionTemplateDecl *TemplateMethod = FunctionTemplateDecl::Create(
1024 C&: Context, DC: Class, L: CallOperator->getLocation(), Name: CallOperator->getDeclName(),
1025 Params: TemplateParams, Decl: CallOperator);
1026 TemplateMethod->setAccess(AS_public);
1027 CallOperator->setDescribedFunctionTemplate(TemplateMethod);
1028}
1029
1030void Sema::CompleteLambdaCallOperator(
1031 CXXMethodDecl *Method, SourceLocation LambdaLoc,
1032 SourceLocation CallOperatorLoc,
1033 const AssociatedConstraint &TrailingRequiresClause,
1034 TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind,
1035 StorageClass SC, ArrayRef<ParmVarDecl *> Params,
1036 bool HasExplicitResultType) {
1037
1038 LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(S&: *this);
1039
1040 if (TrailingRequiresClause)
1041 Method->setTrailingRequiresClause(TrailingRequiresClause);
1042
1043 TemplateParameterList *TemplateParams =
1044 getGenericLambdaTemplateParameterList(LSI, SemaRef&: *this);
1045
1046 DeclContext *DC = Method->getLexicalDeclContext();
1047 // DeclContext::addDecl() assumes that the DeclContext we're adding to is the
1048 // lexical context of the Method. Do so.
1049 Method->setLexicalDeclContext(LSI->Lambda);
1050 if (TemplateParams) {
1051 FunctionTemplateDecl *TemplateMethod =
1052 Method->getDescribedFunctionTemplate();
1053 assert(TemplateMethod &&
1054 "AddTemplateParametersToLambdaCallOperator should have been called");
1055
1056 LSI->Lambda->addDecl(D: TemplateMethod);
1057 TemplateMethod->setLexicalDeclContext(DC);
1058 } else {
1059 LSI->Lambda->addDecl(D: Method);
1060 }
1061 LSI->Lambda->setLambdaIsGeneric(TemplateParams);
1062 LSI->Lambda->setLambdaTypeInfo(MethodTyInfo);
1063
1064 Method->setLexicalDeclContext(DC);
1065 Method->setLocation(LambdaLoc);
1066 Method->setInnerLocStart(CallOperatorLoc);
1067 Method->setTypeSourceInfo(MethodTyInfo);
1068 Method->setType(buildTypeForLambdaCallOperator(S&: *this, Class: LSI->Lambda,
1069 TemplateParams, MethodTypeInfo: MethodTyInfo));
1070 Method->setConstexprKind(ConstexprKind);
1071 Method->setStorageClass(SC);
1072 if (!Params.empty()) {
1073 CheckParmsForFunctionDef(Parameters: Params, /*CheckParameterNames=*/false);
1074 Method->setParams(Params);
1075 for (auto P : Method->parameters()) {
1076 assert(P && "null in a parameter list");
1077 P->setOwningFunction(Method);
1078 }
1079 }
1080
1081 buildLambdaScopeReturnType(S&: *this, LSI, CallOperator: Method, ExplicitResultType: HasExplicitResultType);
1082}
1083
1084void Sema::ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro,
1085 Scope *CurrentScope) {
1086
1087 LambdaScopeInfo *LSI = getCurLambda();
1088 assert(LSI && "LambdaScopeInfo should be on stack!");
1089
1090 if (Intro.Default == LCD_ByCopy)
1091 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
1092 else if (Intro.Default == LCD_ByRef)
1093 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
1094 LSI->CaptureDefaultLoc = Intro.DefaultLoc;
1095 LSI->IntroducerRange = Intro.Range;
1096 LSI->AfterParameterList = false;
1097
1098 assert(LSI->NumExplicitTemplateParams == 0);
1099
1100 // Determine if we're within a context where we know that the lambda will
1101 // be dependent, because there are template parameters in scope.
1102 CXXRecordDecl::LambdaDependencyKind LambdaDependencyKind =
1103 CXXRecordDecl::LDK_Unknown;
1104 if (CurScope->getTemplateParamParent() != nullptr) {
1105 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
1106 } else if (Scope *ParentScope = CurScope->getParent()) {
1107 // Given a lambda defined inside a requires expression,
1108 //
1109 // struct S {
1110 // S(auto var) requires requires { [&] -> decltype(var) { }; }
1111 // {}
1112 // };
1113 //
1114 // The parameter var is not injected into the function Decl at the point of
1115 // parsing lambda. In such scenarios, perceiving it as dependent could
1116 // result in the constraint being evaluated, which matches what GCC does.
1117 Scope *LookupScope = ParentScope;
1118 while (LookupScope->getEntity() &&
1119 LookupScope->getEntity()->isRequiresExprBody())
1120 LookupScope = LookupScope->getParent();
1121
1122 if (LookupScope != ParentScope &&
1123 LookupScope->isFunctionDeclarationScope() &&
1124 llvm::any_of(Range: LookupScope->decls(), P: [](Decl *D) {
1125 return isa<ParmVarDecl>(Val: D) &&
1126 cast<ParmVarDecl>(Val: D)->getType()->isTemplateTypeParmType();
1127 }))
1128 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
1129 }
1130
1131 CXXRecordDecl *Class = createLambdaClosureType(
1132 IntroducerRange: Intro.Range, /*Info=*/nullptr, LambdaDependencyKind, CaptureDefault: Intro.Default);
1133 LSI->Lambda = Class;
1134
1135 CXXMethodDecl *Method = CreateLambdaCallOperator(IntroducerRange: Intro.Range, Class);
1136 LSI->CallOperator = Method;
1137 // Temporarily set the lexical declaration context to the current
1138 // context, so that the Scope stack matches the lexical nesting.
1139 Method->setLexicalDeclContext(CurContext);
1140
1141 PushDeclContext(S: CurScope, DC: Method);
1142
1143 bool ContainsUnexpandedParameterPack = false;
1144
1145 // Distinct capture names, for diagnostics.
1146 llvm::DenseMap<IdentifierInfo *, ValueDecl *> CaptureNames;
1147
1148 // Handle explicit captures.
1149 SourceLocation PrevCaptureLoc =
1150 Intro.Default == LCD_None ? Intro.Range.getBegin() : Intro.DefaultLoc;
1151 for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;
1152 PrevCaptureLoc = C->Loc, ++C) {
1153 if (C->Kind == LCK_This || C->Kind == LCK_StarThis) {
1154 if (C->Kind == LCK_StarThis)
1155 Diag(Loc: C->Loc, DiagID: !getLangOpts().CPlusPlus17
1156 ? diag::ext_star_this_lambda_capture_cxx17
1157 : diag::warn_cxx14_compat_star_this_lambda_capture);
1158
1159 // C++11 [expr.prim.lambda]p8:
1160 // An identifier or this shall not appear more than once in a
1161 // lambda-capture.
1162 if (LSI->isCXXThisCaptured()) {
1163 Diag(Loc: C->Loc, DiagID: diag::err_capture_more_than_once)
1164 << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())
1165 << FixItHint::CreateRemoval(
1166 RemoveRange: SourceRange(getLocForEndOfToken(Loc: PrevCaptureLoc), C->Loc));
1167 continue;
1168 }
1169
1170 // C++20 [expr.prim.lambda]p8:
1171 // If a lambda-capture includes a capture-default that is =,
1172 // each simple-capture of that lambda-capture shall be of the form
1173 // "&identifier", "this", or "* this". [ Note: The form [&,this] is
1174 // redundant but accepted for compatibility with ISO C++14. --end note ]
1175 if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis)
1176 Diag(Loc: C->Loc, DiagID: !getLangOpts().CPlusPlus20
1177 ? diag::ext_equals_this_lambda_capture_cxx20
1178 : diag::warn_cxx17_compat_equals_this_lambda_capture);
1179
1180 // C++11 [expr.prim.lambda]p12:
1181 // If this is captured by a local lambda expression, its nearest
1182 // enclosing function shall be a non-static member function.
1183 QualType ThisCaptureType = getCurrentThisType();
1184 if (ThisCaptureType.isNull()) {
1185 Diag(Loc: C->Loc, DiagID: diag::err_this_capture) << true;
1186 continue;
1187 }
1188
1189 CheckCXXThisCapture(Loc: C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true,
1190 /*FunctionScopeIndexToStopAtPtr*/ FunctionScopeIndexToStopAt: nullptr,
1191 ByCopy: C->Kind == LCK_StarThis);
1192 if (!LSI->Captures.empty())
1193 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1194 continue;
1195 }
1196
1197 assert(C->Id && "missing identifier for capture");
1198
1199 if (C->Init.isInvalid())
1200 continue;
1201
1202 ValueDecl *Var = nullptr;
1203 if (C->Init.isUsable()) {
1204 Diag(Loc: C->Loc, DiagID: getLangOpts().CPlusPlus14
1205 ? diag::warn_cxx11_compat_init_capture
1206 : diag::ext_init_capture);
1207
1208 // If the initializer expression is usable, but the InitCaptureType
1209 // is not, then an error has occurred - so ignore the capture for now.
1210 // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
1211 // FIXME: we should create the init capture variable and mark it invalid
1212 // in this case.
1213 if (C->InitCaptureType.get().isNull())
1214 continue;
1215
1216 if (C->Init.get()->containsUnexpandedParameterPack() &&
1217 !C->InitCaptureType.get()->getAs<PackExpansionType>())
1218 DiagnoseUnexpandedParameterPack(E: C->Init.get(), UPPC: UPPC_Initializer);
1219
1220 unsigned InitStyle;
1221 switch (C->InitKind) {
1222 case LambdaCaptureInitKind::NoInit:
1223 llvm_unreachable("not an init-capture?");
1224 case LambdaCaptureInitKind::CopyInit:
1225 InitStyle = VarDecl::CInit;
1226 break;
1227 case LambdaCaptureInitKind::DirectInit:
1228 InitStyle = VarDecl::CallInit;
1229 break;
1230 case LambdaCaptureInitKind::ListInit:
1231 InitStyle = VarDecl::ListInit;
1232 break;
1233 }
1234 Var = createLambdaInitCaptureVarDecl(Loc: C->Loc, InitCaptureType: C->InitCaptureType.get(),
1235 EllipsisLoc: C->EllipsisLoc, Id: C->Id, InitStyle,
1236 Init: C->Init.get(), DeclCtx: Method);
1237 assert(Var && "createLambdaInitCaptureVarDecl returned a null VarDecl?");
1238 if (auto *V = dyn_cast<VarDecl>(Val: Var))
1239 CheckShadow(S: CurrentScope, D: V);
1240 PushOnScopeChains(D: Var, S: CurrentScope, AddToContext: false);
1241 } else {
1242 assert(C->InitKind == LambdaCaptureInitKind::NoInit &&
1243 "init capture has valid but null init?");
1244
1245 // C++11 [expr.prim.lambda]p8:
1246 // If a lambda-capture includes a capture-default that is &, the
1247 // identifiers in the lambda-capture shall not be preceded by &.
1248 // If a lambda-capture includes a capture-default that is =, [...]
1249 // each identifier it contains shall be preceded by &.
1250 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
1251 Diag(Loc: C->Loc, DiagID: diag::err_reference_capture_with_reference_default)
1252 << FixItHint::CreateRemoval(
1253 RemoveRange: SourceRange(getLocForEndOfToken(Loc: PrevCaptureLoc), C->Loc));
1254 continue;
1255 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
1256 Diag(Loc: C->Loc, DiagID: diag::err_copy_capture_with_copy_default)
1257 << FixItHint::CreateRemoval(
1258 RemoveRange: SourceRange(getLocForEndOfToken(Loc: PrevCaptureLoc), C->Loc));
1259 continue;
1260 }
1261
1262 // C++11 [expr.prim.lambda]p10:
1263 // The identifiers in a capture-list are looked up using the usual
1264 // rules for unqualified name lookup (3.4.1)
1265 DeclarationNameInfo Name(C->Id, C->Loc);
1266 LookupResult R(*this, Name, LookupOrdinaryName);
1267 LookupName(R, S: CurScope);
1268 if (R.isAmbiguous())
1269 continue;
1270 if (R.empty()) {
1271 // FIXME: Disable corrections that would add qualification?
1272 CXXScopeSpec ScopeSpec;
1273 DeclFilterCCC<VarDecl> Validator{};
1274 if (DiagnoseEmptyLookup(S: CurScope, SS&: ScopeSpec, R, CCC&: Validator))
1275 continue;
1276 }
1277
1278 if (auto *BD = R.getAsSingle<BindingDecl>())
1279 Var = BD;
1280 else if (R.getAsSingle<FieldDecl>()) {
1281 Diag(Loc: C->Loc, DiagID: diag::err_capture_class_member_does_not_name_variable)
1282 << C->Id;
1283 continue;
1284 } else
1285 Var = R.getAsSingle<VarDecl>();
1286 if (Var && DiagnoseUseOfDecl(D: Var, Locs: C->Loc))
1287 continue;
1288 }
1289
1290 // C++11 [expr.prim.lambda]p10:
1291 // [...] each such lookup shall find a variable with automatic storage
1292 // duration declared in the reaching scope of the local lambda expression.
1293 // Note that the 'reaching scope' check happens in tryCaptureVariable().
1294 if (!Var) {
1295 Diag(Loc: C->Loc, DiagID: diag::err_capture_does_not_name_variable) << C->Id;
1296 continue;
1297 }
1298
1299 // C++11 [expr.prim.lambda]p8:
1300 // An identifier or this shall not appear more than once in a
1301 // lambda-capture.
1302 if (auto [It, Inserted] = CaptureNames.insert(KV: std::pair{C->Id, Var});
1303 !Inserted) {
1304 if (C->InitKind == LambdaCaptureInitKind::NoInit &&
1305 !Var->isInitCapture()) {
1306 Diag(Loc: C->Loc, DiagID: diag::err_capture_more_than_once)
1307 << C->Id << It->second->getBeginLoc()
1308 << FixItHint::CreateRemoval(
1309 RemoveRange: SourceRange(getLocForEndOfToken(Loc: PrevCaptureLoc), C->Loc));
1310 Var->setInvalidDecl();
1311 } else if (Var && Var->isPlaceholderVar(LangOpts: getLangOpts())) {
1312 DiagPlaceholderVariableDefinition(Loc: C->Loc);
1313 } else {
1314 // Previous capture captured something different (one or both was
1315 // an init-capture): no fixit.
1316 Diag(Loc: C->Loc, DiagID: diag::err_capture_more_than_once) << C->Id;
1317 continue;
1318 }
1319 }
1320
1321 // Ignore invalid decls; they'll just confuse the code later.
1322 if (Var->isInvalidDecl())
1323 continue;
1324
1325 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
1326
1327 if (!Underlying->hasLocalStorage()) {
1328 Diag(Loc: C->Loc, DiagID: diag::err_capture_non_automatic_variable) << C->Id;
1329 Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << C->Id;
1330 continue;
1331 }
1332
1333 // C++11 [expr.prim.lambda]p23:
1334 // A capture followed by an ellipsis is a pack expansion (14.5.3).
1335 SourceLocation EllipsisLoc;
1336 if (C->EllipsisLoc.isValid()) {
1337 if (Var->isParameterPack()) {
1338 EllipsisLoc = C->EllipsisLoc;
1339 } else {
1340 Diag(Loc: C->EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
1341 << (C->Init.isUsable() ? C->Init.get()->getSourceRange()
1342 : SourceRange(C->Loc));
1343
1344 // Just ignore the ellipsis.
1345 }
1346 } else if (Var->isParameterPack()) {
1347 ContainsUnexpandedParameterPack = true;
1348 }
1349
1350 if (C->Init.isUsable()) {
1351 addInitCapture(LSI, Var: cast<VarDecl>(Val: Var), ByRef: C->Kind == LCK_ByRef);
1352 } else {
1353 TryCaptureKind Kind = C->Kind == LCK_ByRef
1354 ? TryCaptureKind::ExplicitByRef
1355 : TryCaptureKind::ExplicitByVal;
1356 tryCaptureVariable(Var, Loc: C->Loc, Kind, EllipsisLoc);
1357 }
1358 if (!LSI->Captures.empty())
1359 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1360 }
1361 finishLambdaExplicitCaptures(LSI);
1362 LSI->ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
1363 PopDeclContext();
1364}
1365
1366void Sema::ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro,
1367 SourceLocation MutableLoc) {
1368
1369 LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(S&: *this);
1370 LSI->Mutable = MutableLoc.isValid();
1371 ContextRAII Context(*this, LSI->CallOperator, /*NewThisContext*/ false);
1372
1373 // C++11 [expr.prim.lambda]p9:
1374 // A lambda-expression whose smallest enclosing scope is a block scope is a
1375 // local lambda expression; any other lambda expression shall not have a
1376 // capture-default or simple-capture in its lambda-introducer.
1377 //
1378 // For simple-captures, this is covered by the check below that any named
1379 // entity is a variable that can be captured.
1380 //
1381 // For DR1632, we also allow a capture-default in any context where we can
1382 // odr-use 'this' (in particular, in a default initializer for a non-static
1383 // data member).
1384 if (Intro.Default != LCD_None &&
1385 !LSI->Lambda->getParent()->isFunctionOrMethod() &&
1386 (getCurrentThisType().isNull() ||
1387 CheckCXXThisCapture(Loc: SourceLocation(), /*Explicit=*/true,
1388 /*BuildAndDiagnose=*/false)))
1389 Diag(Loc: Intro.DefaultLoc, DiagID: diag::err_capture_default_non_local);
1390}
1391
1392void Sema::ActOnLambdaClosureParameters(
1393 Scope *LambdaScope, MutableArrayRef<DeclaratorChunk::ParamInfo> Params) {
1394 LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(S&: *this);
1395 PushDeclContext(S: LambdaScope, DC: LSI->CallOperator);
1396
1397 for (const DeclaratorChunk::ParamInfo &P : Params) {
1398 auto *Param = cast<ParmVarDecl>(Val: P.Param);
1399 Param->setOwningFunction(LSI->CallOperator);
1400 if (Param->getIdentifier())
1401 PushOnScopeChains(D: Param, S: LambdaScope, AddToContext: false);
1402 }
1403
1404 // After the parameter list, we may parse a noexcept/requires/trailing return
1405 // type which need to know whether the call operator constiture a dependent
1406 // context, so we need to setup the FunctionTemplateDecl of generic lambdas
1407 // now.
1408 TemplateParameterList *TemplateParams =
1409 getGenericLambdaTemplateParameterList(LSI, SemaRef&: *this);
1410 if (TemplateParams) {
1411 AddTemplateParametersToLambdaCallOperator(CallOperator: LSI->CallOperator, Class: LSI->Lambda,
1412 TemplateParams);
1413 LSI->Lambda->setLambdaIsGeneric(true);
1414 LSI->ContainsUnexpandedParameterPack |=
1415 TemplateParams->containsUnexpandedParameterPack();
1416 }
1417 LSI->AfterParameterList = true;
1418}
1419
1420void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
1421 Declarator &ParamInfo,
1422 const DeclSpec &DS) {
1423
1424 LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(S&: *this);
1425 LSI->CallOperator->setConstexprKind(DS.getConstexprSpecifier());
1426
1427 SmallVector<ParmVarDecl *, 8> Params;
1428 bool ExplicitResultType;
1429
1430 SourceLocation TypeLoc, CallOperatorLoc;
1431 if (ParamInfo.getNumTypeObjects() == 0) {
1432 CallOperatorLoc = TypeLoc = Intro.Range.getEnd();
1433 } else {
1434 unsigned Index;
1435 ParamInfo.isFunctionDeclarator(idx&: Index);
1436 const auto &Object = ParamInfo.getTypeObject(i: Index);
1437 TypeLoc =
1438 Object.Loc.isValid() ? Object.Loc : ParamInfo.getSourceRange().getEnd();
1439 CallOperatorLoc = ParamInfo.getSourceRange().getEnd();
1440 }
1441
1442 CXXRecordDecl *Class = LSI->Lambda;
1443 CXXMethodDecl *Method = LSI->CallOperator;
1444
1445 TypeSourceInfo *MethodTyInfo = getLambdaType(
1446 S&: *this, Intro, ParamInfo, CurScope: getCurScope(), Loc: TypeLoc, ExplicitResultType);
1447
1448 if (ParamInfo.isFunctionDeclarator() != 0) {
1449 const auto &FTI = ParamInfo.getFunctionTypeInfo();
1450 LSI->ExplicitParams = FTI.getLParenLoc().isValid();
1451 if (!FTIHasSingleVoidParameter(FTI)) {
1452 Params.reserve(N: Params.size());
1453 for (unsigned I = 0; I < FTI.NumParams; ++I) {
1454 auto *Param = cast<ParmVarDecl>(Val: FTI.Params[I].Param);
1455 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
1456 Params.push_back(Elt: Param);
1457 }
1458 }
1459 }
1460
1461 bool IsLambdaStatic =
1462 ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static;
1463
1464 CompleteLambdaCallOperator(
1465 Method, LambdaLoc: Intro.Range.getBegin(), CallOperatorLoc,
1466 TrailingRequiresClause: AssociatedConstraint(ParamInfo.getTrailingRequiresClause()), MethodTyInfo,
1467 ConstexprKind: ParamInfo.getDeclSpec().getConstexprSpecifier(),
1468 SC: IsLambdaStatic ? SC_Static : SC_None, Params, HasExplicitResultType: ExplicitResultType);
1469
1470 CheckCXXDefaultArguments(FD: Method);
1471
1472 // This represents the function body for the lambda function, check if we
1473 // have to apply optnone due to a pragma.
1474 AddRangeBasedOptnone(FD: Method);
1475
1476 // code_seg attribute on lambda apply to the method.
1477 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(
1478 FD: Method, /*IsDefinition=*/true))
1479 Method->addAttr(A);
1480
1481 // Attributes on the lambda apply to the method.
1482 ProcessDeclAttributes(S: CurScope, D: Method, PD: ParamInfo);
1483
1484 if (Context.getTargetInfo().getTriple().isAArch64())
1485 ARM().CheckSMEFunctionDefAttributes(FD: Method);
1486
1487 // CUDA lambdas get implicit host and device attributes.
1488 if (getLangOpts().CUDA)
1489 CUDA().SetLambdaAttrs(Method);
1490
1491 // OpenMP lambdas might get assumumption attributes.
1492 if (LangOpts.OpenMP)
1493 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(D: Method);
1494
1495 handleLambdaNumbering(Class, Method);
1496
1497 for (auto &&C : LSI->Captures) {
1498 if (!C.isVariableCapture())
1499 continue;
1500 ValueDecl *Var = C.getVariable();
1501 if (Var && Var->isInitCapture()) {
1502 PushOnScopeChains(D: Var, S: CurScope, AddToContext: false);
1503 }
1504 }
1505
1506 auto CheckRedefinition = [&](ParmVarDecl *Param) {
1507 for (const auto &Capture : Intro.Captures) {
1508 if (Capture.Id == Param->getIdentifier()) {
1509 Diag(Loc: Param->getLocation(), DiagID: diag::err_parameter_shadow_capture);
1510 Diag(Loc: Capture.Loc, DiagID: diag::note_var_explicitly_captured_here)
1511 << Capture.Id << true;
1512 return false;
1513 }
1514 }
1515 return true;
1516 };
1517
1518 for (ParmVarDecl *P : Params) {
1519 if (!P->getIdentifier())
1520 continue;
1521 if (CheckRedefinition(P))
1522 CheckShadow(S: CurScope, D: P);
1523 PushOnScopeChains(D: P, S: CurScope);
1524 }
1525
1526 // C++23 [expr.prim.lambda.capture]p5:
1527 // If an identifier in a capture appears as the declarator-id of a parameter
1528 // of the lambda-declarator's parameter-declaration-clause or as the name of a
1529 // template parameter of the lambda-expression's template-parameter-list, the
1530 // program is ill-formed.
1531 TemplateParameterList *TemplateParams =
1532 getGenericLambdaTemplateParameterList(LSI, SemaRef&: *this);
1533 if (TemplateParams) {
1534 for (const auto *TP : TemplateParams->asArray()) {
1535 if (!TP->getIdentifier())
1536 continue;
1537 for (const auto &Capture : Intro.Captures) {
1538 if (Capture.Id == TP->getIdentifier()) {
1539 Diag(Loc: Capture.Loc, DiagID: diag::err_template_param_shadow) << Capture.Id;
1540 NoteTemplateParameterLocation(Decl: *TP);
1541 }
1542 }
1543 }
1544 }
1545
1546 // C++20: dcl.decl.general p4:
1547 // The optional requires-clause ([temp.pre]) in an init-declarator or
1548 // member-declarator shall be present only if the declarator declares a
1549 // templated function ([dcl.fct]).
1550 if (const AssociatedConstraint &TRC = Method->getTrailingRequiresClause()) {
1551 // [temp.pre]/8:
1552 // An entity is templated if it is
1553 // - a template,
1554 // - an entity defined ([basic.def]) or created ([class.temporary]) in a
1555 // templated entity,
1556 // - a member of a templated entity,
1557 // - an enumerator for an enumeration that is a templated entity, or
1558 // - the closure type of a lambda-expression ([expr.prim.lambda.closure])
1559 // appearing in the declaration of a templated entity. [Note 6: A local
1560 // class, a local or block variable, or a friend function defined in a
1561 // templated entity is a templated entity. — end note]
1562 //
1563 // A templated function is a function template or a function that is
1564 // templated. A templated class is a class template or a class that is
1565 // templated. A templated variable is a variable template or a variable
1566 // that is templated.
1567
1568 // Note: we only have to check if this is defined in a template entity, OR
1569 // if we are a template, since the rest don't apply. The requires clause
1570 // applies to the call operator, which we already know is a member function,
1571 // AND defined.
1572 if (!Method->getDescribedFunctionTemplate() && !Method->isTemplated()) {
1573 Diag(Loc: TRC.ConstraintExpr->getBeginLoc(),
1574 DiagID: diag::err_constrained_non_templated_function);
1575 }
1576 }
1577
1578 // Enter a new evaluation context to insulate the lambda from any
1579 // cleanups from the enclosing full-expression.
1580 PushExpressionEvaluationContextForFunction(
1581 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated, FD: LSI->CallOperator);
1582}
1583
1584void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
1585 bool IsInstantiation) {
1586 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: FunctionScopes.back());
1587
1588 // Leave the expression-evaluation context.
1589 DiscardCleanupsInEvaluationContext();
1590 PopExpressionEvaluationContext();
1591
1592 // Leave the context of the lambda.
1593 if (!IsInstantiation)
1594 PopDeclContext();
1595
1596 // Finalize the lambda.
1597 CXXRecordDecl *Class = LSI->Lambda;
1598 Class->setInvalidDecl();
1599 SmallVector<Decl*, 4> Fields(Class->fields());
1600 ActOnFields(S: nullptr, RecLoc: Class->getLocation(), TagDecl: Class, Fields, LBrac: SourceLocation(),
1601 RBrac: SourceLocation(), AttrList: ParsedAttributesView());
1602 CheckCompletedCXXClass(S: nullptr, Record: Class);
1603
1604 PopFunctionScopeInfo();
1605}
1606
1607template <typename Func>
1608static void repeatForLambdaConversionFunctionCallingConvs(
1609 Sema &S, const FunctionProtoType &CallOpProto, Func F) {
1610 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
1611 IsVariadic: CallOpProto.isVariadic(), /*IsCXXMethod=*/false);
1612 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
1613 IsVariadic: CallOpProto.isVariadic(), /*IsCXXMethod=*/true);
1614 CallingConv CallOpCC = CallOpProto.getCallConv();
1615
1616 /// Implement emitting a version of the operator for many of the calling
1617 /// conventions for MSVC, as described here:
1618 /// https://devblogs.microsoft.com/oldnewthing/20150220-00/?p=44623.
1619 /// Experimentally, we determined that cdecl, stdcall, fastcall, and
1620 /// vectorcall are generated by MSVC when it is supported by the target.
1621 /// Additionally, we are ensuring that the default-free/default-member and
1622 /// call-operator calling convention are generated as well.
1623 /// NOTE: We intentionally generate a 'thiscall' on Win32 implicitly from the
1624 /// 'member default', despite MSVC not doing so. We do this in order to ensure
1625 /// that someone who intentionally places 'thiscall' on the lambda call
1626 /// operator will still get that overload, since we don't have the a way of
1627 /// detecting the attribute by the time we get here.
1628 if (S.getLangOpts().MSVCCompat) {
1629 CallingConv Convs[] = {
1630 CC_C, CC_X86StdCall, CC_X86FastCall, CC_X86VectorCall,
1631 DefaultFree, DefaultMember, CallOpCC};
1632 llvm::sort(C&: Convs);
1633 llvm::iterator_range<CallingConv *> Range(std::begin(arr&: Convs),
1634 llvm::unique(R&: Convs));
1635 const TargetInfo &TI = S.getASTContext().getTargetInfo();
1636
1637 for (CallingConv C : Range) {
1638 if (TI.checkCallingConvention(CC: C) == TargetInfo::CCCR_OK)
1639 F(C);
1640 }
1641 return;
1642 }
1643
1644 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree) {
1645 F(DefaultFree);
1646 F(DefaultMember);
1647 } else {
1648 F(CallOpCC);
1649 }
1650}
1651
1652// Returns the 'standard' calling convention to be used for the lambda
1653// conversion function, that is, the 'free' function calling convention unless
1654// it is overridden by a non-default calling convention attribute.
1655static CallingConv
1656getLambdaConversionFunctionCallConv(Sema &S,
1657 const FunctionProtoType *CallOpProto) {
1658 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
1659 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
1660 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
1661 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
1662 CallingConv CallOpCC = CallOpProto->getCallConv();
1663
1664 // If the call-operator hasn't been changed, return both the 'free' and
1665 // 'member' function calling convention.
1666 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree)
1667 return DefaultFree;
1668 return CallOpCC;
1669}
1670
1671QualType Sema::getLambdaConversionFunctionResultType(
1672 const FunctionProtoType *CallOpProto, CallingConv CC) {
1673 const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
1674 CallOpProto->getExtProtoInfo();
1675 FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
1676 InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(cc: CC);
1677 InvokerExtInfo.TypeQuals = Qualifiers();
1678 assert(InvokerExtInfo.RefQualifier == RQ_None &&
1679 "Lambda's call operator should not have a reference qualifier");
1680 return Context.getFunctionType(ResultTy: CallOpProto->getReturnType(),
1681 Args: CallOpProto->getParamTypes(), EPI: InvokerExtInfo);
1682}
1683
1684/// Add a lambda's conversion to function pointer, as described in
1685/// C++11 [expr.prim.lambda]p6.
1686static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange,
1687 CXXRecordDecl *Class,
1688 CXXMethodDecl *CallOperator,
1689 QualType InvokerFunctionTy) {
1690 // This conversion is explicitly disabled if the lambda's function has
1691 // pass_object_size attributes on any of its parameters.
1692 auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) {
1693 return P->hasAttr<PassObjectSizeAttr>();
1694 };
1695 if (llvm::any_of(Range: CallOperator->parameters(), P: HasPassObjectSizeAttr))
1696 return;
1697
1698 // Add the conversion to function pointer.
1699 QualType PtrToFunctionTy = S.Context.getPointerType(T: InvokerFunctionTy);
1700
1701 // Create the type of the conversion function.
1702 FunctionProtoType::ExtProtoInfo ConvExtInfo(
1703 S.Context.getDefaultCallingConvention(
1704 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1705 // The conversion function is always const and noexcept.
1706 ConvExtInfo.TypeQuals = Qualifiers();
1707 ConvExtInfo.TypeQuals.addConst();
1708 ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept;
1709 QualType ConvTy = S.Context.getFunctionType(ResultTy: PtrToFunctionTy, Args: {}, EPI: ConvExtInfo);
1710
1711 SourceLocation Loc = IntroducerRange.getBegin();
1712 DeclarationName ConversionName
1713 = S.Context.DeclarationNames.getCXXConversionFunctionName(
1714 Ty: S.Context.getCanonicalType(T: PtrToFunctionTy));
1715 // Construct a TypeSourceInfo for the conversion function, and wire
1716 // all the parameters appropriately for the FunctionProtoTypeLoc
1717 // so that everything works during transformation/instantiation of
1718 // generic lambdas.
1719 // The main reason for wiring up the parameters of the conversion
1720 // function with that of the call operator is so that constructs
1721 // like the following work:
1722 // auto L = [](auto b) { <-- 1
1723 // return [](auto a) -> decltype(a) { <-- 2
1724 // return a;
1725 // };
1726 // };
1727 // int (*fp)(int) = L(5);
1728 // Because the trailing return type can contain DeclRefExprs that refer
1729 // to the original call operator's variables, we hijack the call
1730 // operators ParmVarDecls below.
1731 TypeSourceInfo *ConvNamePtrToFunctionTSI =
1732 S.Context.getTrivialTypeSourceInfo(T: PtrToFunctionTy, Loc);
1733 DeclarationNameLoc ConvNameLoc =
1734 DeclarationNameLoc::makeNamedTypeLoc(TInfo: ConvNamePtrToFunctionTSI);
1735
1736 // The conversion function is a conversion to a pointer-to-function.
1737 TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(T: ConvTy, Loc);
1738 FunctionProtoTypeLoc ConvTL =
1739 ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
1740 // Get the result of the conversion function which is a pointer-to-function.
1741 PointerTypeLoc PtrToFunctionTL =
1742 ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
1743 // Do the same for the TypeSourceInfo that is used to name the conversion
1744 // operator.
1745 PointerTypeLoc ConvNamePtrToFunctionTL =
1746 ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
1747
1748 // Get the underlying function types that the conversion function will
1749 // be converting to (should match the type of the call operator).
1750 FunctionProtoTypeLoc CallOpConvTL =
1751 PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1752 FunctionProtoTypeLoc CallOpConvNameTL =
1753 ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1754
1755 // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1756 // These parameter's are essentially used to transform the name and
1757 // the type of the conversion operator. By using the same parameters
1758 // as the call operator's we don't have to fix any back references that
1759 // the trailing return type of the call operator's uses (such as
1760 // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1761 // - we can simply use the return type of the call operator, and
1762 // everything should work.
1763 SmallVector<ParmVarDecl *, 4> InvokerParams;
1764 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1765 ParmVarDecl *From = CallOperator->getParamDecl(i: I);
1766
1767 InvokerParams.push_back(Elt: ParmVarDecl::Create(
1768 C&: S.Context,
1769 // Temporarily add to the TU. This is set to the invoker below.
1770 DC: S.Context.getTranslationUnitDecl(), StartLoc: From->getBeginLoc(),
1771 IdLoc: From->getLocation(), Id: From->getIdentifier(), T: From->getType(),
1772 TInfo: From->getTypeSourceInfo(), S: From->getStorageClass(),
1773 /*DefArg=*/nullptr));
1774 CallOpConvTL.setParam(i: I, VD: From);
1775 CallOpConvNameTL.setParam(i: I, VD: From);
1776 }
1777
1778 CXXConversionDecl *Conversion = CXXConversionDecl::Create(
1779 C&: S.Context, RD: Class, StartLoc: Loc,
1780 NameInfo: DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), T: ConvTy, TInfo: ConvTSI,
1781 UsesFPIntrin: S.getCurFPFeatures().isFPConstrained(),
1782 /*isInline=*/true, ES: ExplicitSpecifier(),
1783 ConstexprKind: S.getLangOpts().CPlusPlus17 ? ConstexprSpecKind::Constexpr
1784 : ConstexprSpecKind::Unspecified,
1785 EndLocation: CallOperator->getBody()->getEndLoc());
1786 Conversion->setAccess(AS_public);
1787 Conversion->setImplicit(true);
1788
1789 // A non-generic lambda may still be a templated entity. We need to preserve
1790 // constraints when converting the lambda to a function pointer. See GH63181.
1791 if (const AssociatedConstraint &Requires =
1792 CallOperator->getTrailingRequiresClause())
1793 Conversion->setTrailingRequiresClause(Requires);
1794
1795 if (Class->isGenericLambda()) {
1796 // Create a template version of the conversion operator, using the template
1797 // parameter list of the function call operator.
1798 FunctionTemplateDecl *TemplateCallOperator =
1799 CallOperator->getDescribedFunctionTemplate();
1800 FunctionTemplateDecl *ConversionTemplate =
1801 FunctionTemplateDecl::Create(C&: S.Context, DC: Class,
1802 L: Loc, Name: ConversionName,
1803 Params: TemplateCallOperator->getTemplateParameters(),
1804 Decl: Conversion);
1805 ConversionTemplate->setAccess(AS_public);
1806 ConversionTemplate->setImplicit(true);
1807 Conversion->setDescribedFunctionTemplate(ConversionTemplate);
1808 Class->addDecl(D: ConversionTemplate);
1809 } else
1810 Class->addDecl(D: Conversion);
1811
1812 // If the lambda is not static, we need to add a static member
1813 // function that will be the result of the conversion with a
1814 // certain unique ID.
1815 // When it is static we just return the static call operator instead.
1816 if (CallOperator->isImplicitObjectMemberFunction()) {
1817 DeclarationName InvokerName =
1818 &S.Context.Idents.get(Name: getLambdaStaticInvokerName());
1819 // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1820 // we should get a prebuilt TrivialTypeSourceInfo from Context
1821 // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1822 // then rewire the parameters accordingly, by hoisting up the InvokeParams
1823 // loop below and then use its Params to set Invoke->setParams(...) below.
1824 // This would avoid the 'const' qualifier of the calloperator from
1825 // contaminating the type of the invoker, which is currently adjusted
1826 // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the
1827 // trailing return type of the invoker would require a visitor to rebuild
1828 // the trailing return type and adjusting all back DeclRefExpr's to refer
1829 // to the new static invoker parameters - not the call operator's.
1830 CXXMethodDecl *Invoke = CXXMethodDecl::Create(
1831 C&: S.Context, RD: Class, StartLoc: Loc, NameInfo: DeclarationNameInfo(InvokerName, Loc),
1832 T: InvokerFunctionTy, TInfo: CallOperator->getTypeSourceInfo(), SC: SC_Static,
1833 UsesFPIntrin: S.getCurFPFeatures().isFPConstrained(),
1834 /*isInline=*/true, ConstexprKind: CallOperator->getConstexprKind(),
1835 EndLocation: CallOperator->getBody()->getEndLoc());
1836 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
1837 InvokerParams[I]->setOwningFunction(Invoke);
1838 Invoke->setParams(InvokerParams);
1839 Invoke->setAccess(AS_private);
1840 Invoke->setImplicit(true);
1841 if (Class->isGenericLambda()) {
1842 FunctionTemplateDecl *TemplateCallOperator =
1843 CallOperator->getDescribedFunctionTemplate();
1844 FunctionTemplateDecl *StaticInvokerTemplate =
1845 FunctionTemplateDecl::Create(
1846 C&: S.Context, DC: Class, L: Loc, Name: InvokerName,
1847 Params: TemplateCallOperator->getTemplateParameters(), Decl: Invoke);
1848 StaticInvokerTemplate->setAccess(AS_private);
1849 StaticInvokerTemplate->setImplicit(true);
1850 Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1851 Class->addDecl(D: StaticInvokerTemplate);
1852 } else
1853 Class->addDecl(D: Invoke);
1854 }
1855}
1856
1857/// Add a lambda's conversion to function pointers, as described in
1858/// C++11 [expr.prim.lambda]p6. Note that in most cases, this should emit only a
1859/// single pointer conversion. In the event that the default calling convention
1860/// for free and member functions is different, it will emit both conventions.
1861static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange,
1862 CXXRecordDecl *Class,
1863 CXXMethodDecl *CallOperator) {
1864 const FunctionProtoType *CallOpProto =
1865 CallOperator->getType()->castAs<FunctionProtoType>();
1866
1867 repeatForLambdaConversionFunctionCallingConvs(
1868 S, CallOpProto: *CallOpProto, F: [&](CallingConv CC) {
1869 QualType InvokerFunctionTy =
1870 S.getLambdaConversionFunctionResultType(CallOpProto, CC);
1871 addFunctionPointerConversion(S, IntroducerRange, Class, CallOperator,
1872 InvokerFunctionTy);
1873 });
1874}
1875
1876/// Add a lambda's conversion to block pointer.
1877static void addBlockPointerConversion(Sema &S,
1878 SourceRange IntroducerRange,
1879 CXXRecordDecl *Class,
1880 CXXMethodDecl *CallOperator) {
1881 const FunctionProtoType *CallOpProto =
1882 CallOperator->getType()->castAs<FunctionProtoType>();
1883 QualType FunctionTy = S.getLambdaConversionFunctionResultType(
1884 CallOpProto, CC: getLambdaConversionFunctionCallConv(S, CallOpProto));
1885 QualType BlockPtrTy = S.Context.getBlockPointerType(T: FunctionTy);
1886
1887 FunctionProtoType::ExtProtoInfo ConversionEPI(
1888 S.Context.getDefaultCallingConvention(
1889 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1890 ConversionEPI.TypeQuals = Qualifiers();
1891 ConversionEPI.TypeQuals.addConst();
1892 QualType ConvTy = S.Context.getFunctionType(ResultTy: BlockPtrTy, Args: {}, EPI: ConversionEPI);
1893
1894 SourceLocation Loc = IntroducerRange.getBegin();
1895 DeclarationName Name
1896 = S.Context.DeclarationNames.getCXXConversionFunctionName(
1897 Ty: S.Context.getCanonicalType(T: BlockPtrTy));
1898 DeclarationNameLoc NameLoc = DeclarationNameLoc::makeNamedTypeLoc(
1899 TInfo: S.Context.getTrivialTypeSourceInfo(T: BlockPtrTy, Loc));
1900 CXXConversionDecl *Conversion = CXXConversionDecl::Create(
1901 C&: S.Context, RD: Class, StartLoc: Loc, NameInfo: DeclarationNameInfo(Name, Loc, NameLoc), T: ConvTy,
1902 TInfo: S.Context.getTrivialTypeSourceInfo(T: ConvTy, Loc),
1903 UsesFPIntrin: S.getCurFPFeatures().isFPConstrained(),
1904 /*isInline=*/true, ES: ExplicitSpecifier(), ConstexprKind: ConstexprSpecKind::Unspecified,
1905 EndLocation: CallOperator->getBody()->getEndLoc());
1906 Conversion->setAccess(AS_public);
1907 Conversion->setImplicit(true);
1908 Class->addDecl(D: Conversion);
1909}
1910
1911ExprResult Sema::BuildCaptureInit(const Capture &Cap,
1912 SourceLocation ImplicitCaptureLoc,
1913 bool IsOpenMPMapping) {
1914 // VLA captures don't have a stored initialization expression.
1915 if (Cap.isVLATypeCapture())
1916 return ExprResult();
1917
1918 // An init-capture is initialized directly from its stored initializer.
1919 if (Cap.isInitCapture())
1920 return cast<VarDecl>(Val: Cap.getVariable())->getInit();
1921
1922 // For anything else, build an initialization expression. For an implicit
1923 // capture, the capture notionally happens at the capture-default, so use
1924 // that location here.
1925 SourceLocation Loc =
1926 ImplicitCaptureLoc.isValid() ? ImplicitCaptureLoc : Cap.getLocation();
1927
1928 // C++11 [expr.prim.lambda]p21:
1929 // When the lambda-expression is evaluated, the entities that
1930 // are captured by copy are used to direct-initialize each
1931 // corresponding non-static data member of the resulting closure
1932 // object. (For array members, the array elements are
1933 // direct-initialized in increasing subscript order.) These
1934 // initializations are performed in the (unspecified) order in
1935 // which the non-static data members are declared.
1936
1937 // C++ [expr.prim.lambda]p12:
1938 // An entity captured by a lambda-expression is odr-used (3.2) in
1939 // the scope containing the lambda-expression.
1940 ExprResult Init;
1941 IdentifierInfo *Name = nullptr;
1942 if (Cap.isThisCapture()) {
1943 QualType ThisTy = getCurrentThisType();
1944 Expr *This = BuildCXXThisExpr(Loc, Type: ThisTy, IsImplicit: ImplicitCaptureLoc.isValid());
1945 if (Cap.isCopyCapture())
1946 Init = CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: This);
1947 else
1948 Init = This;
1949 } else {
1950 assert(Cap.isVariableCapture() && "unknown kind of capture");
1951 ValueDecl *Var = Cap.getVariable();
1952 Name = Var->getIdentifier();
1953 Init = BuildDeclarationNameExpr(
1954 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(Var->getDeclName(), Loc), D: Var);
1955 }
1956
1957 // In OpenMP, the capture kind doesn't actually describe how to capture:
1958 // variables are "mapped" onto the device in a process that does not formally
1959 // make a copy, even for a "copy capture".
1960 if (IsOpenMPMapping)
1961 return Init;
1962
1963 if (Init.isInvalid())
1964 return ExprError();
1965
1966 Expr *InitExpr = Init.get();
1967 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
1968 VarID: Name, FieldType: Cap.getCaptureType(), Loc);
1969 InitializationKind InitKind =
1970 InitializationKind::CreateDirect(InitLoc: Loc, LParenLoc: Loc, RParenLoc: Loc);
1971 InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr);
1972 return InitSeq.Perform(S&: *this, Entity, Kind: InitKind, Args: InitExpr);
1973}
1974
1975ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body) {
1976 LambdaScopeInfo &LSI = *cast<LambdaScopeInfo>(Val: FunctionScopes.back());
1977
1978 if (LSI.CallOperator->hasAttr<SYCLKernelEntryPointAttr>())
1979 SYCL().CheckSYCLEntryPointFunctionDecl(FD: LSI.CallOperator);
1980
1981 ActOnFinishFunctionBody(Decl: LSI.CallOperator, Body, /*IsInstantiation=*/false,
1982 /*RetainFunctionScopeInfo=*/true);
1983
1984 return BuildLambdaExpr(StartLoc, EndLoc: Body->getEndLoc());
1985}
1986
1987static LambdaCaptureDefault
1988mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS) {
1989 switch (ICS) {
1990 case CapturingScopeInfo::ImpCap_None:
1991 return LCD_None;
1992 case CapturingScopeInfo::ImpCap_LambdaByval:
1993 return LCD_ByCopy;
1994 case CapturingScopeInfo::ImpCap_CapturedRegion:
1995 case CapturingScopeInfo::ImpCap_LambdaByref:
1996 return LCD_ByRef;
1997 case CapturingScopeInfo::ImpCap_Block:
1998 llvm_unreachable("block capture in lambda");
1999 }
2000 llvm_unreachable("Unknown implicit capture style");
2001}
2002
2003bool Sema::CaptureHasSideEffects(const Capture &From) {
2004 if (From.isInitCapture()) {
2005 Expr *Init = cast<VarDecl>(Val: From.getVariable())->getInit();
2006 if (Init && Init->HasSideEffects(Ctx: Context))
2007 return true;
2008 }
2009
2010 if (!From.isCopyCapture())
2011 return false;
2012
2013 const QualType T = From.isThisCapture()
2014 ? getCurrentThisType()->getPointeeType()
2015 : From.getCaptureType();
2016
2017 if (T.isVolatileQualified())
2018 return true;
2019
2020 const Type *BaseT = T->getBaseElementTypeUnsafe();
2021 if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl())
2022 return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() ||
2023 !RD->hasTrivialDestructor();
2024
2025 return false;
2026}
2027
2028bool Sema::DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
2029 SourceRange FixItRange,
2030 const Capture &From) {
2031 if (CaptureHasSideEffects(From))
2032 return false;
2033
2034 if (From.isVLATypeCapture())
2035 return false;
2036
2037 // FIXME: maybe we should warn on these if we can find a sensible diagnostic
2038 // message
2039 if (From.isInitCapture() &&
2040 From.getVariable()->isPlaceholderVar(LangOpts: getLangOpts()))
2041 return false;
2042
2043 auto diag = Diag(Loc: From.getLocation(), DiagID: diag::warn_unused_lambda_capture);
2044 if (From.isThisCapture())
2045 diag << "'this'";
2046 else
2047 diag << From.getVariable();
2048 diag << From.isNonODRUsed();
2049 // If we were able to resolve the fixit range we'll create a fixit,
2050 // otherwise we just use the raw capture range for the diagnostic.
2051 if (FixItRange.isValid())
2052 diag << FixItHint::CreateRemoval(RemoveRange: FixItRange);
2053 else
2054 diag << CaptureRange;
2055 return true;
2056}
2057
2058/// Create a field within the lambda class or captured statement record for the
2059/// given capture.
2060FieldDecl *Sema::BuildCaptureField(RecordDecl *RD,
2061 const sema::Capture &Capture) {
2062 SourceLocation Loc = Capture.getLocation();
2063 QualType FieldType = Capture.getCaptureType();
2064
2065 TypeSourceInfo *TSI = nullptr;
2066 if (Capture.isVariableCapture()) {
2067 const auto *Var = dyn_cast_or_null<VarDecl>(Val: Capture.getVariable());
2068 if (Var && Var->isInitCapture())
2069 TSI = Var->getTypeSourceInfo();
2070 }
2071
2072 // FIXME: Should we really be doing this? A null TypeSourceInfo seems more
2073 // appropriate, at least for an implicit capture.
2074 if (!TSI)
2075 TSI = Context.getTrivialTypeSourceInfo(T: FieldType, Loc);
2076
2077 // Build the non-static data member.
2078 FieldDecl *Field =
2079 FieldDecl::Create(C: Context, DC: RD, /*StartLoc=*/Loc, /*IdLoc=*/Loc,
2080 /*Id=*/nullptr, T: FieldType, TInfo: TSI, /*BW=*/nullptr,
2081 /*Mutable=*/false, InitStyle: ICIS_NoInit);
2082 // If the variable being captured has an invalid type, mark the class as
2083 // invalid as well.
2084 if (!FieldType->isDependentType()) {
2085 if (RequireCompleteSizedType(Loc, T: FieldType,
2086 DiagID: diag::err_field_incomplete_or_sizeless)) {
2087 RD->setInvalidDecl();
2088 Field->setInvalidDecl();
2089 } else {
2090 NamedDecl *Def;
2091 FieldType->isIncompleteType(Def: &Def);
2092 if (Def && Def->isInvalidDecl()) {
2093 RD->setInvalidDecl();
2094 Field->setInvalidDecl();
2095 }
2096 }
2097 }
2098 Field->setImplicit(true);
2099 Field->setAccess(AS_private);
2100 RD->addDecl(D: Field);
2101
2102 if (Capture.isVLATypeCapture())
2103 Field->setCapturedVLAType(Capture.getCapturedVLAType());
2104
2105 return Field;
2106}
2107
2108static SourceRange
2109ConstructFixItRangeForUnusedCapture(Sema &S, SourceRange CaptureRange,
2110 SourceLocation PrevCaptureLoc,
2111 bool CurHasPreviousCapture, bool IsLast) {
2112 if (!CaptureRange.isValid())
2113 return SourceRange();
2114
2115 auto GetTrailingEndLocation = [&](SourceLocation StartPoint) {
2116 SourceRange NextToken = S.getRangeForNextToken(
2117 Loc: StartPoint, /*IncludeMacros=*/false, /*IncludeComments=*/true);
2118 if (!NextToken.isValid())
2119 return SourceLocation();
2120 // Return the last location preceding the next token
2121 return NextToken.getBegin().getLocWithOffset(Offset: -1);
2122 };
2123
2124 if (!CurHasPreviousCapture && !IsLast) {
2125 // If there are no captures preceding this capture, remove the
2126 // trailing comma and anything up to the next token
2127 SourceRange CommaRange =
2128 S.getRangeForNextToken(Loc: CaptureRange.getEnd(), /*IncludeMacros=*/false,
2129 /*IncludeComments=*/false, ExpectedToken: tok::comma);
2130 SourceLocation FixItEnd = GetTrailingEndLocation(CommaRange.getBegin());
2131 return SourceRange(CaptureRange.getBegin(), FixItEnd);
2132 }
2133
2134 // Otherwise, remove the comma since the last used capture, and
2135 // anything up to the next token
2136 SourceLocation FixItStart = S.getLocForEndOfToken(Loc: PrevCaptureLoc);
2137 SourceLocation FixItEnd = GetTrailingEndLocation(CaptureRange.getEnd());
2138 return SourceRange(FixItStart, FixItEnd);
2139}
2140
2141ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc,
2142 SourceLocation EndLoc) {
2143 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: FunctionScopes.back());
2144 // Collect information from the lambda scope.
2145 SmallVector<LambdaCapture, 4> Captures;
2146 SmallVector<Expr *, 4> CaptureInits;
2147 SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc;
2148 LambdaCaptureDefault CaptureDefault =
2149 mapImplicitCaptureStyle(ICS: LSI->ImpCaptureStyle);
2150 CXXRecordDecl *Class = LSI->Lambda;
2151 CXXMethodDecl *CallOperator = LSI->CallOperator;
2152 SourceRange IntroducerRange = LSI->IntroducerRange;
2153 bool ExplicitParams = LSI->ExplicitParams;
2154 bool ExplicitResultType = !LSI->HasImplicitReturnType;
2155 CleanupInfo LambdaCleanup = LSI->Cleanup;
2156 bool ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
2157 bool IsGenericLambda = Class->isGenericLambda();
2158
2159 CallOperator->setLexicalDeclContext(Class);
2160 Decl *TemplateOrNonTemplateCallOperatorDecl =
2161 CallOperator->getDescribedFunctionTemplate()
2162 ? CallOperator->getDescribedFunctionTemplate()
2163 : cast<Decl>(Val: CallOperator);
2164
2165 // FIXME: Is this really the best choice? Keeping the lexical decl context
2166 // set as CurContext seems more faithful to the source.
2167 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
2168
2169 {
2170 // TreeTransform of immediate functions may call getCurLambda, which
2171 // requires both the paired LSI and the lambda DeclContext.
2172 ContextRAII SavedContext(*this, CallOperator, /*NewThisContext=*/false);
2173 PopExpressionEvaluationContext();
2174 }
2175
2176 sema::AnalysisBasedWarnings::Policy WP =
2177 AnalysisWarnings.getPolicyInEffectAt(Loc: EndLoc);
2178 // We cannot release LSI until we finish computing captures, which
2179 // requires the scope to be popped.
2180 Sema::PoppedFunctionScopePtr _ = PopFunctionScopeInfo(WP: &WP, D: LSI->CallOperator);
2181
2182 // True if the current capture has a used capture or default before it.
2183 bool CurHasPreviousCapture = CaptureDefault != LCD_None;
2184 SourceLocation PrevCaptureLoc =
2185 CurHasPreviousCapture ? CaptureDefaultLoc : IntroducerRange.getBegin();
2186
2187 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
2188 const Capture &From = LSI->Captures[I];
2189
2190 if (From.isInvalid())
2191 return ExprError();
2192
2193 assert(!From.isBlockCapture() && "Cannot capture __block variables");
2194 bool IsImplicit = I >= LSI->NumExplicitCaptures;
2195 SourceLocation ImplicitCaptureLoc =
2196 IsImplicit ? CaptureDefaultLoc : SourceLocation();
2197
2198 // Use source ranges of explicit captures for fixits where available.
2199 SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I];
2200
2201 // Warn about unused explicit captures.
2202 bool IsCaptureUsed = true;
2203 if (!CurContext->isDependentContext() && !IsImplicit && !From.isODRUsed()) {
2204 // Initialized captures that are non-ODR used may not be eliminated.
2205 // FIXME: Where did the IsGenericLambda here come from?
2206 bool NonODRUsedInitCapture =
2207 IsGenericLambda && From.isNonODRUsed() && From.isInitCapture();
2208 if (!NonODRUsedInitCapture) {
2209 bool IsLast = (I + 1) == LSI->NumExplicitCaptures;
2210 SourceRange FixItRange = ConstructFixItRangeForUnusedCapture(
2211 S&: *this, CaptureRange, PrevCaptureLoc, CurHasPreviousCapture, IsLast);
2212 IsCaptureUsed =
2213 !DiagnoseUnusedLambdaCapture(CaptureRange, FixItRange, From);
2214 }
2215 }
2216
2217 if (CaptureRange.isValid()) {
2218 CurHasPreviousCapture |= IsCaptureUsed;
2219 PrevCaptureLoc = CaptureRange.getEnd();
2220 }
2221
2222 // Map the capture to our AST representation.
2223 LambdaCapture Capture = [&] {
2224 if (From.isThisCapture()) {
2225 // Capturing 'this' implicitly with a default of '[=]' is deprecated,
2226 // because it results in a reference capture. Don't warn prior to
2227 // C++2a; there's nothing that can be done about it before then.
2228 if (getLangOpts().CPlusPlus20 && IsImplicit &&
2229 CaptureDefault == LCD_ByCopy) {
2230 Diag(Loc: From.getLocation(), DiagID: diag::warn_deprecated_this_capture);
2231 Diag(Loc: CaptureDefaultLoc, DiagID: diag::note_deprecated_this_capture)
2232 << FixItHint::CreateInsertion(
2233 InsertionLoc: getLocForEndOfToken(Loc: CaptureDefaultLoc), Code: ", this");
2234 }
2235 return LambdaCapture(From.getLocation(), IsImplicit,
2236 From.isCopyCapture() ? LCK_StarThis : LCK_This);
2237 } else if (From.isVLATypeCapture()) {
2238 return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType);
2239 } else {
2240 assert(From.isVariableCapture() && "unknown kind of capture");
2241 ValueDecl *Var = From.getVariable();
2242 LambdaCaptureKind Kind = From.isCopyCapture() ? LCK_ByCopy : LCK_ByRef;
2243 return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var,
2244 From.getEllipsisLoc());
2245 }
2246 }();
2247
2248 // Form the initializer for the capture field.
2249 ExprResult Init = BuildCaptureInit(Cap: From, ImplicitCaptureLoc);
2250
2251 // FIXME: Skip this capture if the capture is not used, the initializer
2252 // has no side-effects, the type of the capture is trivial, and the
2253 // lambda is not externally visible.
2254
2255 // Add a FieldDecl for the capture and form its initializer.
2256 BuildCaptureField(RD: Class, Capture: From);
2257 Captures.push_back(Elt: Capture);
2258 CaptureInits.push_back(Elt: Init.get());
2259
2260 if (LangOpts.CUDA)
2261 CUDA().CheckLambdaCapture(D: CallOperator, Capture: From);
2262 }
2263
2264 Class->setCaptures(Context, Captures);
2265
2266 // C++11 [expr.prim.lambda]p6:
2267 // The closure type for a lambda-expression with no lambda-capture
2268 // has a public non-virtual non-explicit const conversion function
2269 // to pointer to function having the same parameter and return
2270 // types as the closure type's function call operator.
2271 if (Captures.empty() && CaptureDefault == LCD_None)
2272 addFunctionPointerConversions(S&: *this, IntroducerRange, Class, CallOperator);
2273
2274 // Objective-C++:
2275 // The closure type for a lambda-expression has a public non-virtual
2276 // non-explicit const conversion function to a block pointer having the
2277 // same parameter and return types as the closure type's function call
2278 // operator.
2279 // FIXME: Fix generic lambda to block conversions.
2280 if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda)
2281 addBlockPointerConversion(S&: *this, IntroducerRange, Class, CallOperator);
2282
2283 // Finalize the lambda class.
2284 SmallVector<Decl *, 4> Fields(Class->fields());
2285 ActOnFields(S: nullptr, RecLoc: Class->getLocation(), TagDecl: Class, Fields, LBrac: SourceLocation(),
2286 RBrac: SourceLocation(), AttrList: ParsedAttributesView());
2287 CheckCompletedCXXClass(S: nullptr, Record: Class);
2288
2289 Cleanup.mergeFrom(Rhs: LambdaCleanup);
2290
2291 LambdaExpr *Lambda =
2292 LambdaExpr::Create(C: Context, Class, IntroducerRange, CaptureDefault,
2293 CaptureDefaultLoc, ExplicitParams, ExplicitResultType,
2294 CaptureInits, ClosingBrace: EndLoc, ContainsUnexpandedParameterPack);
2295
2296 // If the lambda expression's call operator is not explicitly marked constexpr
2297 // and is not dependent, analyze the call operator to infer
2298 // its constexpr-ness, suppressing diagnostics while doing so.
2299 if (getLangOpts().CPlusPlus17 && !CallOperator->isInvalidDecl() &&
2300 !CallOperator->isConstexpr() &&
2301 !isa<CoroutineBodyStmt>(Val: CallOperator->getBody()) &&
2302 !Class->isDependentContext()) {
2303 CallOperator->setConstexprKind(
2304 CheckConstexprFunctionDefinition(FD: CallOperator,
2305 Kind: CheckConstexprKind::CheckValid)
2306 ? ConstexprSpecKind::Constexpr
2307 : ConstexprSpecKind::Unspecified);
2308 }
2309
2310 // Emit delayed shadowing warnings now that the full capture list is known.
2311 DiagnoseShadowingLambdaDecls(LSI);
2312
2313 if (!CurContext->isDependentContext()) {
2314 switch (ExprEvalContexts.back().Context) {
2315 // C++11 [expr.prim.lambda]p2:
2316 // A lambda-expression shall not appear in an unevaluated operand
2317 // (Clause 5).
2318 case ExpressionEvaluationContext::Unevaluated:
2319 case ExpressionEvaluationContext::UnevaluatedList:
2320 case ExpressionEvaluationContext::UnevaluatedAbstract:
2321 // C++1y [expr.const]p2:
2322 // A conditional-expression e is a core constant expression unless the
2323 // evaluation of e, following the rules of the abstract machine, would
2324 // evaluate [...] a lambda-expression.
2325 //
2326 // This is technically incorrect, there are some constant evaluated contexts
2327 // where this should be allowed. We should probably fix this when DR1607 is
2328 // ratified, it lays out the exact set of conditions where we shouldn't
2329 // allow a lambda-expression.
2330 case ExpressionEvaluationContext::ConstantEvaluated:
2331 case ExpressionEvaluationContext::ImmediateFunctionContext:
2332 // We don't actually diagnose this case immediately, because we
2333 // could be within a context where we might find out later that
2334 // the expression is potentially evaluated (e.g., for typeid).
2335 ExprEvalContexts.back().Lambdas.push_back(Elt: Lambda);
2336 break;
2337
2338 case ExpressionEvaluationContext::DiscardedStatement:
2339 case ExpressionEvaluationContext::PotentiallyEvaluated:
2340 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
2341 break;
2342 }
2343 maybeAddDeclWithEffects(D: LSI->CallOperator);
2344 }
2345
2346 return MaybeBindToTemporary(E: Lambda);
2347}
2348
2349ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
2350 SourceLocation ConvLocation,
2351 CXXConversionDecl *Conv,
2352 Expr *Src) {
2353 // Make sure that the lambda call operator is marked used.
2354 CXXRecordDecl *Lambda = Conv->getParent();
2355 CXXMethodDecl *CallOperator
2356 = cast<CXXMethodDecl>(
2357 Val: Lambda->lookup(
2358 Name: Context.DeclarationNames.getCXXOperatorName(Op: OO_Call)).front());
2359 CallOperator->setReferenced();
2360 CallOperator->markUsed(C&: Context);
2361
2362 ExprResult Init = PerformCopyInitialization(
2363 Entity: InitializedEntity::InitializeLambdaToBlock(BlockVarLoc: ConvLocation, Type: Src->getType()),
2364 EqualLoc: CurrentLocation, Init: Src);
2365 if (!Init.isInvalid())
2366 Init = ActOnFinishFullExpr(Expr: Init.get(), /*DiscardedValue*/ false);
2367
2368 if (Init.isInvalid())
2369 return ExprError();
2370
2371 // Create the new block to be returned.
2372 BlockDecl *Block = BlockDecl::Create(C&: Context, DC: CurContext, L: ConvLocation);
2373
2374 // Set the type information.
2375 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
2376 Block->setIsVariadic(CallOperator->isVariadic());
2377 Block->setBlockMissingReturnType(false);
2378
2379 // Add parameters.
2380 SmallVector<ParmVarDecl *, 4> BlockParams;
2381 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
2382 ParmVarDecl *From = CallOperator->getParamDecl(i: I);
2383 BlockParams.push_back(Elt: ParmVarDecl::Create(
2384 C&: Context, DC: Block, StartLoc: From->getBeginLoc(), IdLoc: From->getLocation(),
2385 Id: From->getIdentifier(), T: From->getType(), TInfo: From->getTypeSourceInfo(),
2386 S: From->getStorageClass(),
2387 /*DefArg=*/nullptr));
2388 }
2389 Block->setParams(BlockParams);
2390
2391 Block->setIsConversionFromLambda(true);
2392
2393 // Add capture. The capture uses a fake variable, which doesn't correspond
2394 // to any actual memory location. However, the initializer copy-initializes
2395 // the lambda object.
2396 TypeSourceInfo *CapVarTSI =
2397 Context.getTrivialTypeSourceInfo(T: Src->getType());
2398 VarDecl *CapVar = VarDecl::Create(C&: Context, DC: Block, StartLoc: ConvLocation,
2399 IdLoc: ConvLocation, Id: nullptr,
2400 T: Src->getType(), TInfo: CapVarTSI,
2401 S: SC_None);
2402 BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false,
2403 /*nested=*/false, /*copy=*/Init.get());
2404 Block->setCaptures(Context, Captures: Capture, /*CapturesCXXThis=*/false);
2405
2406 // Add a fake function body to the block. IR generation is responsible
2407 // for filling in the actual body, which cannot be expressed as an AST.
2408 Block->setBody(new (Context) CompoundStmt(ConvLocation));
2409
2410 // Create the block literal expression.
2411 // TODO: Do we ever get here if we have unexpanded packs in the lambda???
2412 Expr *BuildBlock =
2413 new (Context) BlockExpr(Block, Conv->getConversionType(),
2414 /*ContainsUnexpandedParameterPack=*/false);
2415 ExprCleanupObjects.push_back(Elt: Block);
2416 Cleanup.setExprNeedsCleanups(true);
2417
2418 return BuildBlock;
2419}
2420
2421static FunctionDecl *getPatternFunctionDecl(FunctionDecl *FD) {
2422 if (FD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization) {
2423 while (FD->getInstantiatedFromMemberFunction())
2424 FD = FD->getInstantiatedFromMemberFunction();
2425 return FD;
2426 }
2427
2428 if (FD->getTemplatedKind() == FunctionDecl::TK_DependentNonTemplate)
2429 return FD->getInstantiatedFromDecl();
2430
2431 FunctionTemplateDecl *FTD = FD->getPrimaryTemplate();
2432 if (!FTD)
2433 return nullptr;
2434
2435 while (FTD->getInstantiatedFromMemberTemplate())
2436 FTD = FTD->getInstantiatedFromMemberTemplate();
2437
2438 return FTD->getTemplatedDecl();
2439}
2440
2441bool Sema::addInstantiatedCapturesToScope(
2442 FunctionDecl *Function, const FunctionDecl *PatternDecl,
2443 LocalInstantiationScope &Scope,
2444 const MultiLevelTemplateArgumentList &TemplateArgs) {
2445 const auto *LambdaClass = cast<CXXMethodDecl>(Val: Function)->getParent();
2446 const auto *LambdaPattern = cast<CXXMethodDecl>(Val: PatternDecl)->getParent();
2447
2448 unsigned Instantiated = 0;
2449
2450 // FIXME: This is a workaround for not having deferred lambda body
2451 // instantiation.
2452 // When transforming a lambda's body, if we encounter another call to a
2453 // nested lambda that contains a constraint expression, we add all of the
2454 // outer lambda's instantiated captures to the current instantiation scope to
2455 // facilitate constraint evaluation. However, these captures don't appear in
2456 // the CXXRecordDecl until after the lambda expression is rebuilt, so we
2457 // pull them out from the corresponding LSI.
2458 LambdaScopeInfo *InstantiatingScope = nullptr;
2459 if (LambdaPattern->capture_size() && !LambdaClass->capture_size()) {
2460 for (FunctionScopeInfo *Scope : llvm::reverse(C&: FunctionScopes)) {
2461 auto *LSI = dyn_cast<LambdaScopeInfo>(Val: Scope);
2462 if (!LSI || getPatternFunctionDecl(FD: LSI->CallOperator) != PatternDecl)
2463 continue;
2464 InstantiatingScope = LSI;
2465 break;
2466 }
2467 assert(InstantiatingScope);
2468 }
2469
2470 auto AddSingleCapture = [&](const ValueDecl *CapturedPattern,
2471 unsigned Index) {
2472 ValueDecl *CapturedVar =
2473 InstantiatingScope ? InstantiatingScope->Captures[Index].getVariable()
2474 : LambdaClass->getCapture(I: Index)->getCapturedVar();
2475 assert(CapturedVar->isInitCapture());
2476 Scope.InstantiatedLocal(D: CapturedPattern, Inst: CapturedVar);
2477 };
2478
2479 for (const LambdaCapture &CapturePattern : LambdaPattern->captures()) {
2480 if (!CapturePattern.capturesVariable()) {
2481 Instantiated++;
2482 continue;
2483 }
2484 ValueDecl *CapturedPattern = CapturePattern.getCapturedVar();
2485
2486 if (!CapturedPattern->isInitCapture()) {
2487 Instantiated++;
2488 continue;
2489 }
2490
2491 if (!CapturedPattern->isParameterPack()) {
2492 AddSingleCapture(CapturedPattern, Instantiated++);
2493 } else {
2494 Scope.MakeInstantiatedLocalArgPack(D: CapturedPattern);
2495 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2496 SemaRef.collectUnexpandedParameterPacks(
2497 E: dyn_cast<VarDecl>(Val: CapturedPattern)->getInit(), Unexpanded);
2498 auto NumArgumentsInExpansion =
2499 getNumArgumentsInExpansionFromUnexpanded(Unexpanded, TemplateArgs);
2500 if (!NumArgumentsInExpansion)
2501 continue;
2502 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg)
2503 AddSingleCapture(CapturedPattern, Instantiated++);
2504 }
2505 }
2506 return false;
2507}
2508
2509Sema::LambdaScopeForCallOperatorInstantiationRAII::
2510 LambdaScopeForCallOperatorInstantiationRAII(
2511 Sema &SemaRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL,
2512 LocalInstantiationScope &Scope, bool ShouldAddDeclsFromParentScope)
2513 : FunctionScopeRAII(SemaRef) {
2514 if (!isLambdaCallOperator(DC: FD)) {
2515 FunctionScopeRAII::disable();
2516 return;
2517 }
2518
2519 SemaRef.RebuildLambdaScopeInfo(CallOperator: cast<CXXMethodDecl>(Val: FD));
2520
2521 FunctionDecl *FDPattern = getPatternFunctionDecl(FD);
2522 if (!FDPattern)
2523 return;
2524
2525 if (!ShouldAddDeclsFromParentScope)
2526 return;
2527
2528 llvm::SmallVector<std::pair<FunctionDecl *, FunctionDecl *>, 4>
2529 InstantiationAndPatterns;
2530 while (FDPattern && FD) {
2531 InstantiationAndPatterns.emplace_back(Args&: FDPattern, Args&: FD);
2532
2533 FDPattern =
2534 dyn_cast<FunctionDecl>(Val: getLambdaAwareParentOfDeclContext(DC: FDPattern));
2535 FD = dyn_cast<FunctionDecl>(Val: getLambdaAwareParentOfDeclContext(DC: FD));
2536 }
2537
2538 // Add instantiated parameters and local vars to scopes, starting from the
2539 // outermost lambda to the innermost lambda. This ordering ensures that
2540 // the outer instantiations can be found when referenced from within inner
2541 // lambdas.
2542 //
2543 // auto L = [](auto... x) {
2544 // return [](decltype(x)... y) { }; // Instantiating y needs x
2545 // };
2546 //
2547
2548 for (auto [FDPattern, FD] : llvm::reverse(C&: InstantiationAndPatterns)) {
2549 SemaRef.addInstantiatedParametersToScope(Function: FD, PatternDecl: FDPattern, Scope, TemplateArgs: MLTAL);
2550 SemaRef.addInstantiatedLocalVarsToScope(Function: FD, PatternDecl: FDPattern, Scope);
2551
2552 if (isLambdaCallOperator(DC: FD))
2553 SemaRef.addInstantiatedCapturesToScope(Function: FD, PatternDecl: FDPattern, Scope, TemplateArgs: MLTAL);
2554 }
2555}
2556