Debian Codegraph @

clang/lib/Sema/SemaLambda.cpp

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