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